Chain
*****

Chain-based trial assignment and network growth.

Chain trial makers discover available networks, apply chain
eligibility rules, then select one chain and resolve its head to the
node used for trial creation. Static trial makers reuse the
availability checks but adapt candidate networks to nodes before
filtering and selection.

Blocks are strict phases. "ChainTrialMaker._select_trial_node" is the
only place that moves a participant between blocks: it searches the
current block and moves on only when "should_finish_block" says so or
the block has nothing left to give. Within a block, the "chain_order"
/ "node_order" setting is either dynamic (""balanced"", ""random"":
decided by SQL at each trial) or planned (""listed"", a function:
decided once when the participant enters the block and stored on their
module state). A planned item, or the current chain when
"interleave_chains=False", is the participant's focus; selection waits
for it when it is busy rather than moving on.

class psynet.trial.chain.Candidate(value, network)

   Bases: "object"

   Connect a selection-hook value to its already-loaded network.

   "value" is the paradigm-specific object exposed to experiment
   authors: a network for chain trial makers and a node for static
   trial makers. "network" is the backing object used internally for
   capacity, asynchronous state, and block checks.

   Keeping both references together is intentional. In particular,
   static discovery must not recover the network through
   "node.network": that reverse ORM relationship is not populated when
   "network.head" is loaded and would issue lazy queries for every
   candidate.

class psynet.trial.chain.ChainNetwork(*args, **kwargs)

   Bases: "TrialNetwork"

   Implements a network in the form of a chain. Intended for use with
   "ChainTrialMaker". Typically the user won't have to override
   anything here, but they can optionally override "validate()".

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

      * **chain_type** -- Either ""within"" for within-participant
        chains, or ""across"" for across-participant chains.

      * **trials_per_node** -- Number of satisfactory trials to be
        received by the last node in the chain before another chain
        will be added. Most paradigms have this equal to 1.

      * **target_n_nodes** -- Indicates the target number of nodes for
        that network. In a network with one trial per node, the total
        number of nodes will generally be one greater than the total
        number of trials. This is because we start with one node,
        representing the random starting location of the chain, and
        each new trial takes us to a new node.

      * **participant** -- Optional participant with which to
        associate the network.

      * **id_within_participant** -- If "participant is not None",
        then this provides an optional ID for the network that is
        unique within a given participant.

      * **sync_group_type** (*Optional**[**str**]*) -- The
        "sync_group_type" attribute of the trial maker that owns this
        network.

      * **sync_group** (*Optional**[**SyncGroup**]*) -- The SyncGroup
        that owns this network (normally only relevant for within-
        style chains).

   target_n_trials

      Indicates the target number of trials for that network. Left
      empty by default, but can be set by custom "__init__" functions.

      Type:
         int or None

   var

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

      Type:
         "VarStore"

   participant_id

      The ID of the associated participant, or "None" if there is no
      such participant. Set by default in the "__init__" function.

      Type:
         int

   id_within_participant

      If "participant is not None", then this provides an optional ID
      for the network that is unique within a given participant. Set
      by default in the "__init__" function.

   chain_type

      Either ""within"" for within-participant chains, or ""across""
      for across-participant chains. Set by default in the "__init__"
      function.

   trials_per_node

      Number of satisfactory trials to be received by the last node in
      the chain before another chain will be added. Most paradigms
      have this equal to 1. Set by default in the "__init__" function.

   add_node(node)

      Adds a node to the network. This method is responsible for
      setting "self.full = True" if the network is full as a result.

   balance_across_networks(values)

      Chooses a value from a list, with choices being balanced across
      networks. Relies on the fact that network IDs are guaranteed to
      be consecutive. sequences of integers.

      Suppose we wish to assign our networks to colors, and we want to
      balance color assignment across networks. We might write the
      following:

         colors = ["red", "green", "blue"]
         chosen_color = self.balance_across_networks(colors)

      In across-participant chain designs, "balance_across_networks()"
      will ensure that the distribution of colors is maximally uniform
      across the experiment by assigning the first network to red, the
      second network to green, the third to blue, then the fourth to
      red, the fifth to green, the sixth to blue, and so on. This is
      achieved by referring to the network's "id" attribute. In
      within-participant chain designs, the same method is used but
      within participants, so that each participant's first network is
      assigned to red, their second network to green, their third to
      blue, then their fourth, fifth, and sixth to red, green, and
      blue respectively.

      Parameters:
         **values** ("list") -- The list of values from which to
         choose.

      Returns:
         * *Object* -- An object from the provided list.

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

   make_definition()

      Derives the definition for the network. This definition
      represents some collection of attributes that is shared by all
      nodes/trials in a network, but that may differ between networks.

      Suppose one wishes to have multiple networks in the experiment,
      each characterised by a different value of an attribute (e.g. a
      different color). One approach would be to sample randomly;
      however, this would not guarantee an even distribution of
      attribute values. In this case, a better approach is to use the
      "psynet.trial.chain.ChainNetwork.balance_across_networks()"
      method, as follows:

         colors = ["red", "green", "blue"]
         return {
             "color": self.balance_across_networks(colors)
         }

      See "psynet.trial.chain.ChainNetwork.balance_across_networks()"
      for details on how this balancing works.

      Returns:
         * *object* -- By default this returns an empty dictionary,
           but this can be customised by subclasses. The object should
           be suitable for serialisation to JSON.

   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.

   validate()

      Runs at the end of the constructor function to check that the
      network object has a legal structure. This can be useful for
      checking that the user hasn't passed illegal argument values.

   vars

class psynet.trial.chain.ChainNode(*args, **kwargs)

   Bases: "TrialNode"

   Represents a node in a chain network. In an experimental context,
   the node represents a state in the experiment; in particular, the
   last node in the chain represents a current state in the
   experiment.

   This class is intended for use with "ChainTrialMaker". It
   subclasses "dallinger.models.Node".

   The most important attribute is "definition". This is the core
   information that represents the current state of the node. In a
   transmission chain of drawings, this might be an (encoded) drawing;
   in a Markov Chain Monte Carlo with People paradigm, this might be
   the current state from the proposal is sampled.

   The user is required to override the following abstract methods:

   * "create_definition_from_seed()", which creates a node definition
     from the seed passed from the previous source or node in the
     chain;

   * "summarize_trials()", which summarizes the trials at a given node
     to produce a seed that can be passed to the next node in the
     chain.

   Parameters:
      * **seed** -- The seed which is used to initialize the node,
        potentially stochastically. This seed typically comes from
        either a "ChainSource" or from another "ChainNode" via the
        "create_seed()" method. For example, in a transmission chain
        of drawings, the seed might be a serialised version of the
        last drawn image.

      * **degree** -- The position of the node in the chain, where 0
        indicates the source, where 1 indicates the first node, 2 the
        second node, and so on.

      * **network** -- The network with which the node is to be
        associated.

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

      * **propagate_failure** -- If "True", the failure of a trial is
        propagated to other parts of the experiment (the nature of
        this propagation is left up to the implementation).

      * **participant** -- Optional participant with which to
        associate the node.

   degree

      See the "__init__" function.

   child_id

      See the "__init__" function.

   seed

      See the "__init__" function.

   definition

      This is the core information that represents the current state
      of the node. In a transmission chain of drawings, this might be
      an (encoded) drawing; in a Markov Chain Monte Carlo with People
      paradigm, this might be the current state from the proposal is
      sampled. It is set by the
      "ChainNode:create_definition_from_seed()" method.

   propagate_failure

      See the "__init__" function.

   var

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

      Type:
         "VarStore"

   child

      The node's child (i.e. direct descendant) in the chain, or
      "None" if no child exists.

   target_n_trials

      The target number of trials for the node, set from
      "psynet.trial.chain.ChainNetwork.trials_per_node".

   can_spawn

      Returns "True" if the node is structurally allowed to spawn a
      child. Dynamic readiness is computed live from trial state.

   complete_and_processed_trials

      Returns all completed trials associated with the node, excluding
      those that are awaiting some asynchronous processing. excludes
      failed nodes.

   completed_trials

      Returns all completed trials associated with the node. Excludes
      failed nodes and repeat trials.

   n_completed_trials

      Counts the number of completed trials associated with the node.
      Excludes failed nodes and repeat_trials.

   all_trials

      A list of all trials owned by that node.

      Type:
         list

   alive_trials

      A list of all non-failed trials owned by that node.

      Type:
         list

   failed_trials

      A list of all failed trials owned by that node.

      Type:
         list

   viable_trials

      Returns all viable trials associated with the node, i.e. all
      trials that have not failed.

   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.

   create_initial_seed(experiment, participant)

      Return the seed of a chain's first node when no definition was
      given.

   creation_time

      the time at which the Network was created.

   details

      a generic column for storing structured JSON data

   fail(reason=None)

      Fail this object, and potentially its related objects.

      Set "failed" to "True" and "time_of_death" to now.

      If a *reason* argument is passed, this will be stored in
      "failed_reason".

      Failure will then be propagated to related objects as defined by
      the *failure_cascade* property.

   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

      List of callables to determine which related objects to fail
      when "fail()" is called on this object.

      By default, no related objects are failed, but subclasses can
      provide a list of functions (typically bound instance methods)
      which will be called in order to retrieve additional objects on
      which to call "fail()".

      Example: The following implentation would cause "fail()" to be
      called on each value returned by "self.nodes()", and then on
      each value returned by "self.questions()":

      >>> @property
      >>> def failure_cascade(self):
      >>>     return [self.nodes, self.questions]

   id

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

   make_next_definition(experiment, participant)

      Creates the definition for the next node in the chain.

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

         * **participant** -- The participant who initiated the
           creation of the node (if relevant).

      Return type:
         "dict"

      Returns:
         * *dict* -- The definition for the next node in the chain.

   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.

   update_status()

      Hook method called when the node's status may need updating.

      This method is called when trials associated with the node are
      finalized or fail. Subclasses can override this to update
      derived status attributes. For example, "ChainNode" uses this to
      check whether the node is ready to spawn a child node.

   vars

class psynet.trial.chain.ChainTrial(*args, **kwargs)

   Bases: "Trial"

   Represents a trial in a "ChainNetwork". The user is expected to
   override the following methods:

   * "make_definition()", responsible for deciding on the content of
     the trial.

   * "show_trial()", determines how the trial is turned into a webpage
     for presentation to the participant.

   * "show_feedback()". defines an optional feedback page to be
     displayed after the trial.

   The user must also 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.

   The user may also wish to override the "async_post_trial()" method
   if they wish to implement asynchronous trial processing.

   This class subclasses "Trial". Trials are stored in the physical
   "trial" table, not Dallinger's "info" table. Custom trial classes
   use single-table polymorphism within "trial".

   Instances can be retrieved using *SQLAlchemy*; for example, the
   following command retrieves the "ChainTrial" object with an ID of
   1:

      ChainTrial.query.filter_by(id=1).one()

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

      * **node** -- An object of class "dallinger.models.Node" to
        which the "Trial" object should be attached. Complex
        experiments are often organised around networks of nodes, but
        in the simplest case one could just make one "Network" for
        each type of trial and one "Node" for each participant, and
        then assign the "Trial" to this "Node". Ask us if you want to
        use this simple use case - it would be worth adding it as a
        default to this implementation, but we haven't done that yet,
        because most people are using more complex designs.

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

      * **propagate_failure** (*bool*) -- Whether failure of a trial
        should be propagated to other parts of the experiment
        depending on that trial (for example, subsequent parts of a
        transmission chain).

      * **run_async_post_trial** (*bool*) -- Set this to "True" if you
        want the "async_post_trial()" method to run after the user
        responds to the trial.

   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

   node

      The class:*dallinger.models.Node* to which the "Trial" belongs.

   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

   propagate_failure

      Whether failure of a trial should be propagated to other parts
      of the experiment depending on that trial (for example,
      subsequent parts of a transmission chain).

      Type:
         bool

   var

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

      Type:
         "VarStore"

   definition

      An arbitrary Python object that somehow defines the content of a
      trial. Often this will be a dictionary comprising a few named
      parameters. The user should not typically change this directly,
      as it is instead determined by "make_definition()".

      Type:
         Object

   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.

   fail(reason=None)

      Fail this object, and potentially its related objects.

      Set "failed" to "True" and "time_of_death" to now.

      If a *reason* argument is passed, this will be stored in
      "failed_reason".

      Failure will then be propagated to related objects as defined by
      the *failure_cascade* property.

   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

      Fail "node.child" when this trial is finalized and already has
      one.

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

   make_definition(experiment, participant)

      Creates and returns a definition for the trial, which will be
      later stored in the "definition" attribute. This can be an
      arbitrary object as long as it is serialisable to JSON.

      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.

   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.

   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.chain.ChainTrialMaker(*, id_, trial_class, node_class, network_class=None, chain_type, expected_trials_per_participant, max_trials_per_participant=None, max_trials_per_block=None, max_nodes_per_chain=None, chains_per_participant=None, chains_per_experiment=None, trials_per_node=1, n_repeat_trials=0, target_n_participants=None, n_participants_completion='experiment', start_nodes=None, block_order='random', chain_order='random', interleave_chains=True, balance_across_chains=None, check_performance_at_end=False, check_performance_every_trial=False, recruit_mode=None, fail_trials_on_premature_exit=False, fail_trials_on_participant_performance_check=False, propagate_failure=True, wait_for_networks=False, allow_revisiting_networks_in_across_chains=False, 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: "NetworkTrialMaker"

   Administers a sequence of trials in a chain-based paradigm.

   "find_chains()" applies PsyNet's eligibility checks and returns all
   remaining chains. "select_chain()" then chooses one. Override
   "select_chain" to change assignment among eligible chains; override
   "custom_chain_filter" to change eligibility. Do not override
   "find_chains" unless you need to replace that whole procedure.

   Parameters:
      * **node_class** ("Type"["ChainNode"]) -- The class object for
        the networks used by this maker. This should subclass
        "ChainNode".

      * **trial_class** ("Type"["ChainTrial"]) -- The class object for
        trials administered by this maker (should subclass
        "ChainTrial").

      * **network_class** ("Optional"["Type"["ChainNetwork"]]) -- The
        class object for the networks used by this maker. This should
        subclass "ChainNetwork".

      * **chain_type** ("str") -- Either ""within"" for within-
        participant chains, or ""across"" for across-participant
        chains.

      * **expected_trials_per_participant** ("Union"["int", "str"]) --
        Expected number of trials that each participant will complete.
        This can either be an integer, or the string
        ""n_start_nodes"", which will be read as referring to the
        number of start nodes with which the trial maker is
        initialized (i.e. "len(start_nodes)", "chains_per_experiment",
        or "chains_per_participant" as appropriate). This is used for
        timeline/progress estimation purposes.

      * **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_start_nodes"", which will be
        read as referring to the number of start nodes with which the
        trial maker is initialized (i.e. "len(start_nodes)",
        "chains_per_experiment", or "chains_per_participant" as
        appropriate).

      * **chains_per_participant** ("Optional"["int"]) -- Number of
        chains to be created for each participant; only relevant if
        "chain_type="within"". Not required if "start_nodes" is
        provided.

      * **chains_per_experiment** ("Optional"["int"]) -- Number of
        chains to be created for the entire experiment; only relevant
        if "chain_type="across"". Not required if "start_nodes" is
        provided.

      * **max_nodes_per_chain** ("Optional"["int"]) -- Specifies chain
        length in terms of the number of data-collection iterations
        that are required to complete a chain. The number of
        successful participant trials required to complete the chain
        then corresponds to "trials_per_node * max_nodes_per_chain".

      * **max_nodes_per_chain** -- Maximum number of nodes in the
        chain before the chain is marked as full and no more nodes
        will be added.

      * **trials_per_node** ("int") -- Number of satisfactory trials
        to be received by the last node in the chain before another
        chain will be added. Most paradigms have this equal to 1.

      * **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 among the start 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.

      * **chain_order** ("Union"["str", "callable", "dict"]) -- The
        order in which the participant receives chains within a block:
        ""random"" (the default), ""balanced"" (chains with the fewest
        trials first), ""listed"" (the order of "start_nodes"), a
        function returning the planned chains, or a dict giving one of
        these values for every block. The function may take any of
        "participant", "experiment", "block" and "chains" (the block's
        "ChainNetwork" objects in start-node order). See Trial order.

      * **interleave_chains** ("bool") -- If "True" (the default),
        consecutive trials may come from different chains. If "False",
        the participant stays on one chain until it can give them no
        more trials, then moves to the next, waiting whenever that
        chain is busy. Needs "chain_type="within"" or
        "allow_revisiting_networks_in_across_chains=True".

      * **start_nodes** ("Union"["callable", "List"["ChainNode"],
        "None"]) -- A list of nodes that are used to initialize the
        chains. In an across-participant trial maker, this should be a
        simple list of instances of the class "node_class". In a
        within-participant trial maker, a fresh set of nodes should be
        created for each new participant. To achieve this,
        "start_nodes" should be a lambda function that returns a list
        of newly created nodes. This lambda function may accept
        "participant" as one of its arguments.

      * **check_performance_at_end** ("bool") -- If "True", the
        participant's performance is evaluated at the end of the
        series of trials.

      * **check_performance_every_trial** ("bool") -- If "True", the
        participant's performance is evaluated after each trial.

      * **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 giving "target_n_participants"
        with any other mode raises an error; ""n_trials"" recruits
        until every chain is full. 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"".

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

      * **fail_trials_on_participant_performance_check** ("bool") --
        See "TrialMaker". Defaults to "False" because failing
        completed trials can invalidate large amounts of downstream
        chain data.

      * **propagate_failure** ("bool") -- If "True", the failure of a
        trial is propagated to other parts of the experiment (the
        nature of this propagation is left up to the implementation).

      * **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.
        Defaults to "0".

      * **wait_for_networks** ("bool") -- If "True", then the
        participant will be made to wait if there are still more
        networks to participate in, but these networks are pending
        async jobs.

      * **allow_revisiting_networks_in_across_chains** (*bool*) -- If
        this is set to "True", then participants can revisit the same
        network in across-participant chains. The default is "False".

      * **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_max_wait_time** ("Union"["float", "Callable",
        "None"]) -- Acts on members waiting for their group at the
        trial maker's own barriers: the longest each may wait, in
        seconds, counted from their arrival, before
        "sync_group_max_wait_action" is applied to them. Defaults to
        45 seconds, or to no limit with "sync_group_late_after", which
        then moves slow members on; passing a number or a function
        together with "sync_group_late_after" raises an error. "None"
        means no limit.

      * **sync_group_max_wait_action** ("Literal"["'fail'",
        "'leave_group'"]) -- What happens to a member who waits longer
        than "sync_group_max_wait_time": ""fail"" (default) fails them
        and sends them to the end of the experiment; ""leave_group""
        removes them from the group, and they get no more trials from
        this trial maker, or skip the rest of it if they haven't
        finished a trial (see After leaving a group).

      * **sync_group_late_after** ("Optional"["float"]) -- Acts on
        members who haven't reached the trial maker's barrier yet: the
        longest each may take to reach it, in seconds, counted from
        the group's previous barrier pass or from when they joined the
        group, whichever is later, before "sync_group_late_action" is
        applied to them. "None" (default) never treats anyone as late.
        See "late_after" in "GroupBarrier".

      * **sync_group_late_action** ("Optional"["Literal"["'fail'",
        "'leave_group'"]]) -- What happens to a member who is later
        than "sync_group_late_after", which requires it: ""fail""
        fails them; ""leave_group"" removes them from the group, so
        the rest can go on without them (see After leaving a group).
        See "late_action" in "GroupBarrier".

      * **sync_group_also_leave** ("Optional"["Sequence"["str"]]) --
        With "sync_group_late_action="leave_group"", the other group
        types a late member also leaves, for example "["cohort"]". See
        "also_leave" in "GroupBarrier".

      * **sync_group_waiting_message** -- Message on the waiting
        indicator at the trial maker's own sync-group wait (trial
        preparation). If omitted, participants see "Waiting for other
        participants…". "Grouper" and "GroupBarrier" elements use
        their own "waiting_message"; pass the same text to them if the
        messages should match.

      * **sync_group_newcomer_max_wait** ("Optional"["float"]) -- 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
      = 300) (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

   before_selection(participant, experiment)

      Decide whether to look for a trial at all.

      PsyNet calls this hook before it searches the database for
      candidates. Return ""wait"" to show the waiting page, ""exit""
      to leave the trial maker, or "None" to continue with selection.
      Use it for decisions that depend only on the participant, such
      as waiting until a partner has finished, so that selection can
      stay in the database. It runs before PsyNet moves on from a
      finished block, so "participant.module_state.block" may be the
      block the participant is about to leave.

      Parameters:
         * **participant** -- The participant receiving the next
           trial.

         * **experiment** -- The current experiment.

      Return type:
         None, "wait", or "exit"

   chain_priority(participant, experiment)

      Return SQL expressions that rank eligible chains.

      PsyNet only considers chains in the participant's current block.
      It orders them by these expressions (ascending; use ".desc()" to
      reverse), then by balancing when "chain_order="balanced"", then
      randomly. The default "select_chain" takes the first chain in
      that order. Expressions may use columns of "self.network_class"
      and "self.node_class". Planned chain orders (""listed"" or a
      function) cannot be combined with this hook.

   check_initialization()

      Validate trial-maker hooks after construction.

   check_participant_groups(participant_groups)

      Require "choose_participant_group" when networks use non-default
      groups.

   choose_block_order(experiment, participant, blocks)

      Return the participant's block order.

      Pass "block_order" to the constructor rather than overriding
      this method. The default applies that argument: ""random""
      shuffles the blocks, ""listed"" keeps the order in which they
      first appear among the start nodes, a list is used as given, and
      a function is called with any of "participant", "experiment" and
      "blocks". In within-participant chains, which can give
      participants different blocks, a list skips blocks this
      participant does not have.

   custom_chain_filter(chains, participant, experiment)

      Filter eligible chains before selection.

      Override this to remove chains the participant must not receive.
      The default returns the original list, or applies a deprecated
      "custom_network_filter" override when that is the only filter
      present. Ranking among eligible chains belongs in
      "select_chain".

   custom_network_filter(candidates, participant)

      Deprecated list-based eligibility hook.

      Chain trial makers should override "custom_chain_filter()"
      instead. Static trial makers should override
      "custom_node_filter()". This method still receives candidate
      networks as keyword arguments ("candidates" and "participant")
      and must return a subset of those objects.

   filter_chains_query(query, participant, experiment)

      Narrow the database query that finds candidate chains.

      Override this to remove chains in SQL rather than in Python.
      "query" selects "self.network_class" joined to the chain's head
      node ("self.node_class") and already applies PsyNet's built-in
      checks. Add conditions with "query.filter(...)" on columns of
      either class and return the result. Unlike
      "custom_chain_filter()", this keeps selection fast when there
      are many chains.

   finalize_trial(answer, trial, experiment, participant)

      This function is run after the participant completes the trial.
      It can be optionally customised, for example to add some more
      postprocessing. If you override this, make sure you call
      "super().finalize_trial(...)" somewhere in your new method.

      Parameters:
         * **answer** -- The "answer" object provided by the trial.

         * **trial** -- The "Trial" object representing the trial.

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

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

   find_chains(participant, experiment)

      Find eligible chains for the participant's next trial.

      This method applies PsyNet's built-in eligibility checks (the
      participant's current block, capacity, async jobs, and
      "custom_chain_filter()"). Override "select_chain" to change
      which eligible chain is assigned. To wait, exit, or drop
      candidates after those built-in checks, override this method,
      call "super().find_chains", then filter or return ""wait"" /
      ""exit"". "select_chain" cannot return those outcomes.
      Overriding this method loads every eligible chain on each trial;
      "before_selection()" and "filter_chains_query()" keep selection
      in the database.

      Parameters:
         * **participant** -- The participant receiving the next
           trial.

         * **experiment** -- The current experiment.

      Returns:
         An empty list finishes the participant's current block;
         ""exit"" leaves the trial maker, skipping any remaining
         blocks.

      Return type:
         "exit", "wait", or list of chains

   grow_network(network, experiment, check_readiness=True)

      Extends the network if necessary by adding one or more nodes.
      Returns "True" if any nodes were added.

      Parameters:
         * **network** -- The network to be potentially extended.

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

   init_block_order(experiment, participant, blocks)

      Choose and store the participant's block order.

      "blocks" lists the trial maker's blocks in the order they first
      appear among its networks.

   init_participant(experiment, participant)

      Initializes the participant at the beginning of the sequence of
      trials. If you override this, make sure you call
      "super().init_particiant(...)" somewhere in your new method.

      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.

   property introduction

      The type of the None singleton.

   local_head_ready_condition(node_cls=None)

      SQL expression for the standard chain readiness condition.

      This is the live replacement for the old "ready_to_spawn" cache:
      the head must be structurally able to spawn, have enough
      finalized non-repeat trials, and have no alive unfinished
      trials.

   pre_deploy_routine(experiment)

      Defines a routine for setting up the experiment prior to
      deployment. This is a good place to prepare networks etc.

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

   ready_to_grow_network_query(network_ids=None)

      Return a query for networks that are ready to grow.

      The scheduler uses the corresponding ID select as the
      authoritative growth check for both within- and across-chain
      networks.

   select_chain(chains, participant, experiment)

      Select from a nonempty list of eligible chains.

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

   selection_pool_size = None

      Maximum number of eligible candidates passed to Python selection
      hooks such as "select_chain". "None" passes all of them. When
      set, PsyNet passes only the highest-ranked candidates, using the
      order described in Keeping selection fast.

   should_finish_block(participant, block)

      Return "True" to end the current block before it runs out of
      trials.

      The default ends the block once the participant has had
      "max_trials_per_block" trials in it. Override this for other
      rules; "participant.module_state.n_participant_trials_in_block"
      and
      "participant.module_state.n_participant_trials_in_trial_maker"
      give the participant's trial counts.

   state_class

      alias of "ChainTrialMakerState"

class psynet.trial.chain.ChainTrialMakerState(*args, **kwargs)

   Bases: "NetworkTrialMakerState"

   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.

   run_index

      Counts the participant's visits to the module, from 1, as when a
      loop repeats it.

   set_block_position(i)

      Move to block "i" and clear the previous block's chain and plan.

   time_of_death

      the time at which failing occurred

   type

   vars

class psynet.trial.chain.ChainVector(*args, **kwargs)

   Bases: "SQLMixinDallinger", "Vector"

   creation_time

      the time at which the Network was created.

   destination

      the Node at which the vector terminates.

   destination_id

      the id of the Node at which the vector terminates.

   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 vector is in.

   network_id

      the id of the network the vector is in.

   origin

      the Node at which the vector originates.

   origin_id

      the id of the Node at which the vector originates

   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

   type

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

      Note: The type column was added in 9/2022, 7+ years after the
      Vector ORM class was introduced. To support importing datasets
      which don't include this column we define a default value which
      will be used when deploying experiments from zip files.

   vars

psynet.trial.chain.count_completed_trials_for_network(network_id)

   Count completed, non-failed, non-repeat trials in a network.

   Return type:
      "int"

psynet.trial.chain.count_completed_trials_for_networks(network_ids)

   Return completed trial counts keyed by network id.

   Counts completed, non-failed, non-repeat trials.

   Return type:
      "dict"["int", "int"]

psynet.trial.chain.count_participant_trials_in_block(module_state_id, block_position)

   Count trials for a module state at a given block position.

   "block_position" is defined on "ChainTrial", not the base Trial.

   Return type:
      "int"

psynet.trial.chain.count_participant_trials_in_trial_maker(module_state_id)

   Count trials owned by a chain trial-maker module state.

   Return type:
      "int"

psynet.trial.chain.count_viable_trials_for_node(node_id)

   Return the number of viable trials for one node.

   Return type:
      "int"

psynet.trial.chain.count_viable_trials_for_nodes(node_ids)

   Return viable trial counts keyed by node id.

   A viable trial is non-failed and not a repeat trial.

   Return type:
      "dict"["int", "int"]
