Writing a static trial maker
****************************

Most examples on this page come from "demos/pipelines/simple_rating",
in which participants rate instrument sounds on two scales. To run it
from a PsyNet source checkout:

   cd demos/pipelines/simple_rating
   psynet debug local


How it works
============

Nodes are usually built in a "get_nodes" function. Here, one
"StaticNode" is created per audio file in "static/instrument_sounds",
and the file's URL is stored in the definition:

   def get_nodes():
       return [
           StaticNode(
               definition={
                   "stimulus_name": path.stem,
                   "audio_url": static_url_for(path),
               },
           )
           for path in sorted(STIMULUS_DIR.glob(STIMULUS_PATTERN))
       ]

The trial is a subclass of "StaticTrial". It needs a "time_estimate"
in seconds and a "show_trial" method that returns the page. The
trial's definition is available as "self.definition":

   class CustomTrial(StaticTrial):
       time_estimate = 10

       def show_trial(self, experiment, participant):
           return ModularPage(
               "ratings",
               AudioPrompt(
                   self.definition["audio_url"],
                   "Please rate the sound. You can replay it as many times as you like.",
                   controls="Play",
               ),
               MultiRatingControl(
                   RatingScale(
                       name="brightness",
                       values=5,
                       title="Brightness",
                       min_description="Dark",
                       max_description="Bright",
                   ),
                   RatingScale(
                       name="roughness",
                       values=5,
                       title="Roughness",
                       min_description="Smooth",
                       max_description="Rough",
                   ),
               ),
               events={
                   "submitEnable": Event(is_triggered_by="promptEnd"),
               },
           )

The "StaticTrialMaker" goes in the timeline:

   def get_timeline():
       return Timeline(
           InfoPage(
               """
               In this experiment you will hear some sounds.
               Your task will be to rate them from 1 to 5 on several scales.
               """,
               time_estimate=5,
           ),
           StaticTrialMaker(
               id_="ratings",
               trial_class=CustomTrial,
               nodes=get_nodes,
               expected_trials_per_participant="n_nodes",
           ),
           InfoPage(
               "Thank you for your participation!",
               time_estimate=5,
           ),
       )


What the trial adds
===================

Override "finalize_definition()". It receives a copy of the node's
definition and returns the trial's definition. In
"demos/experiments/static", each trial draws a random text color:

       def finalize_definition(self, definition, experiment, participant):
           definition["text_color"] = random.choice(["red", "green", "blue"])
           return definition

The method runs once, when the trial is created, so random draws
belong here. Variation that only changes how existing files are
presented, such as the order of response options, needs no new files.
To generate a new media file for each trial, see Managing assets.

For dense paradigms, where each trial samples a stimulus from a
continuous space, "psynet.trial.dense" provides trial classes that do
the sampling, such as "SingleStimulusTrial". The
"demos/features/dense_color" demo shows one in use.


Choosing the next node
======================

Allocation is set with arguments to "StaticTrialMaker":

* "expected_trials_per_participant" and "max_trials_per_participant":
  an integer, or ""n_nodes"" for one per node.

* "block_order" (default ""random"") and "node_order" (default
  ""balanced""); see Trial order.

* "allow_repeated_nodes" (default "False") and "n_repeat_trials"
  (default "0").

* "max_trials_per_block".

Blocks are set on the nodes. The "demos/experiments/static" demo puts
each animal in three blocks:

   nodes = [
       StaticNode(
           definition={"animal": animal},
           block=block,
       )
       for animal in ["cats", "dogs", "fish", "ponies"]
       for block in ["A", "B", "C"]
   ]



and limits each block to two trials, with three repeat trials at the
end:

   trial_maker = AnimalTrialMaker(
       id_="animals",
       trial_class=AnimalTrial,
       nodes=nodes,
       expected_trials_per_participant=6,
       max_trials_per_block=2,
       allow_repeated_nodes=True,
       check_performance_at_end=True,
       check_performance_every_trial=True,
       target_n_participants=1,
       target_trials_per_node=None,
       recruit_mode="n_participants",
       n_repeat_trials=3,
   )



Participant groups are also set on the nodes:

   StaticNode(definition={"instrument": "trumpet"}, participant_group="brass_players")

To assign participant groups, pass "choose_participant_group", a
function from the participant to a group name. It is required whenever
nodes have participant groups:

   StaticTrialMaker(
       ...,
       choose_participant_group=lambda participant: participant.var.instrument_family,
   )

To let the trial maker decide when recruitment stops, pass
"recruit_mode="n_participants"" with "target_n_participants", or
"recruit_mode="n_trials"" with "target_trials_per_node". A target
without its matching "recruit_mode" raises an error.

With ""n_participants"", "n_participants_completion" decides who fills
the quota. ""experiment"" (the default) counts participants who finish
the whole experiment. ""trial_maker"" counts participants who finish
this trial maker, even if they leave before the end page. In both
cases, people still working in the experiment hold a slot so PsyNet
does not recruit a replacement straight away. Passing ""trial_maker""
with "recruit_mode=None" or ""n_trials"" raises an error.

To choose the node yourself, for example in an adaptive design,
override two hooks. "custom_node_filter()" removes nodes the
participant must not receive, and "select_node()" picks one of the
rest; blocks, repeat rules, performance checks and trial-based
recruitment keep working. The nodes arrive in selection order (see
Keeping selection fast), and the default "select_node" takes the
first. "select_node" must return one of the objects it was given, not
a re-queried copy, either directly or wrapped in a "Selection" with a
"context". Returning "None" raises "TypeError". PsyNet passes the
context to "on_trial_created()" as "selection_context":

   class AdaptiveTrialMaker(StaticTrialMaker):
       def select_node(self, nodes, participant, experiment):
           scores = [score_item(node.definition) for node in nodes]
           best = max(range(len(nodes)), key=scores.__getitem__)
           return Selection(value=nodes[best], context={"score": scores[best]})

       def on_trial_created(self, trial, experiment, participant, selection_context=None):
           record = SelectionRecord(participant_id=participant.id, details=selection_context)
           record.trial = trial
           db.session.add(record)

"on_trial_created" runs in the same database transaction as trial
creation, once per selection, for primary trials only: not for repeat
trials or for the copies given to other members of a synchronized
group. Chain trial makers have the equivalent hooks for chains; see
Writing a chain experiment.


Trial order
-----------

A participant works through their blocks one at a time, and PsyNet
only considers nodes in the current block. The block ends when the
participant reaches "max_trials_per_block", when
"should_finish_block()" returns "True" (it receives "participant" and
the block's name), or when the block has nothing more to give them.
PsyNet then moves to the next block, or leaves the trial maker after
the last one.

"block_order" sets the order of the blocks:

* ""random"" (default): a new random order for each participant.

* ""listed"": the order in which the blocks first appear in "nodes".

* A list of block names, used for every participant. It may name only
  some of the blocks.

* A function that takes any of "participant", "experiment" and
  "blocks" and returns a list of block names. It may leave blocks out
  to give a participant only some of them, but must keep at least one.

"node_order" sets the order of the nodes within a block. Dynamic
orders are recomputed in the database for each trial:

* ""balanced"" (default): nodes with the fewest trials first, counting
  trials in progress, with ties broken at random. Participants
  requesting a trial at the same moment are given different nodes
  where possible, unless node selection runs in Python (see Keeping
  selection fast).

* ""random"": a fresh random draw for each trial. Without
  "allow_repeated_nodes" this gives each participant the block's nodes
  in a random order; with it, a node can come up again before others
  have been seen. For a shuffle without such repeats, use a function
  such as "lambda nodes: random.sample(nodes, len(nodes))".

A custom "node_priority()" sorts first; a dynamic order only breaks
ties among the nodes it ranks equally.

Planned orders are fixed when the participant enters the block:

* ""listed"": the order of "nodes".

* A function that takes any of "participant", "experiment", "block"
  (the block's name) and "nodes" (the block's nodes in listed order),
  by name, and returns the nodes in the order to present them.
  Returning fewer nodes gives the participant only those; set
  "expected_trials_per_participant" to match, as PsyNet uses it for
  progress and payment estimates. With "allow_repeated_nodes=True"
  (which also needs "max_trials_per_participant" or
  "max_trials_per_block") it may list a node more than once.

To use a different order in each block, pass a dict from block name to
order; it must name every block. For example, to counterbalance the
block order across participants and shuffle the conditions within each
block with at most two trials of the same condition in a row:

   from psynet.utils import shuffle_with_max_run

   StaticTrialMaker(
       ...,
       block_order=lambda participant: ["A", "B"] if participant.id % 2 else ["B", "A"],
       node_order=lambda nodes: shuffle_with_max_run(
           nodes, key=lambda node: node.definition["condition"], max_run=2
       ),
   )

A planned order gives the participant exactly the nodes it lists,
however many trials those nodes already have. If a planned node is
waiting for asynchronous processing, the participant waits for it; if
it has failed, PsyNet skips it and logs a warning. A planned order
already decides which node comes next, so it cannot be combined with
"select_node", "node_priority" or "find_nodes"; filter with
"filter_nodes_query" or "custom_node_filter" instead. Repeat trials
come after the last block and are not part of the plan.

Chain trial makers take "block_order" too, and "chain_order" in place
of "node_order"; see Writing a chain experiment.


Keeping selection fast
----------------------

PsyNet finds each trial's node in the database, without loading the
other candidates. It orders the eligible nodes by any custom priority,
then by balancing (with "node_order="balanced""), then randomly, and
loads only the first. With ""balanced"", no Python selection hooks and
no "node_priority", PsyNet locks that node until the trial is saved
and skips nodes that simultaneous requests have locked, so
participants arriving together are spread across the best 20 nodes;
beyond that, they share. A "node_priority" always wins, so
simultaneous participants may share its top node. Nodes are not
eligible if they are waiting for asynchronous processing, or if they
are outside the participant's group or current block.
"target_trials_per_node" only decides when "recruit_mode="n_trials""
stops recruiting; it never makes a node ineligible. Planned orders
(see Trial order) load the block's nodes once, when the participant
enters the block.

Balancing counts each eligible node's trials for every selection. An
index keeps this cheap, but the cost still grows slowly with the
trials collected: in local tests with 300 nodes it took about 15 ms at
200,000 trials and 50 ms at a million. If one trial maker will collect
far more trials than that, "node_order="random"", which counts
nothing, stays fast.

"custom_node_filter", "select_node" and "find_nodes" run in Python, so
overriding them makes PsyNet load every eligible node for every trial.
With a few hundred nodes that is fine. With thousands it slows each
response, and PsyNet logs a warning. There are three ways to keep it
fast:

* Filter and rank in the database. "filter_nodes_query()" receives the
  query and returns it with extra conditions. "node_priority()"
  returns SQL expressions to sort by. Both can use columns of
  "self.network_class" and of your node class, including columns you
  add to it. Refer to those columns through your own class
  ("ColorNode.difficulty" in the example), because a static trial
  maker's "self.node_class" is always "StaticNode".

* Decide whether the participant should get a trial at all in
  "before_selection()". It runs before PsyNet looks for nodes and
  returns ""wait"", ""exit"" or "None" (go ahead).

* Set "selection_pool_size" to pass only the best-ranked eligible
  nodes to the Python hooks. Nodes outside the pool are ignored for
  that trial, unless "custom_node_filter" rejects every available node
  in the pool; PsyNet then loads them all and filters again, so the
  filter may see the same node twice in one selection. Keep filters
  free of side effects.

   from sqlalchemy import Column, Integer

   class ColorNode(StaticNode):
       difficulty = Column(Integer)

   class ColorTrialMaker(StaticTrialMaker):
       selection_pool_size = 50

       def filter_nodes_query(self, query, participant, experiment):
           return query.filter(ColorNode.difficulty <= participant.var.level)

       def node_priority(self, participant, experiment):
           return [ColorNode.difficulty.desc()]

       def select_node(self, nodes, participant, experiment):
           return max(nodes, key=lambda node: score_item(node.definition))

"filter_nodes_query" and "node_priority" work in SQL, so they cannot
read "node.definition", which PsyNet stores in encoded form. Store
anything you filter or rank on in its own column. Chain trial makers
have the same hooks under the names "filter_chains_query" and
"chain_priority".


After the response
==================

"score_answer()" returns the trial's score, which is stored as
"self.score". From "demos/experiments/static":

       def score_answer(self, answer, definition):
           if answer == "Not at all":
               return 0.0
           return 1.0

"show_feedback()" returns a page shown after the response:

   def show_feedback(self, experiment, participant):
       return InfoPage("Correct!" if self.score else "Incorrect.", time_estimate=3)

For recordings, return a page with an "AudioRecordControl" or
"VideoRecordControl". To analyze the recording on the server, inherit
from "AudioRecordTrial" (or "CameraRecordTrial") *before* the trial
class, and define "analyze_recording". With the classes the other way
round, the analysis never runs. The returned dictionary must include
""failed""; "True" fails the trial. The "demos/pipelines/tapping" demo
analyzes each tapping recording:

       def analyze_recording(self, audio_file: str, output_plot: str):
           info = self.get_info()
           stim_name = info["stim_name"]
           title_in_graph = "Participant {}".format(self.participant_id)
           analysis = REPPAnalysis(config=sms_tapping)
           output, analysis, is_failed = analysis.do_analysis(
               info, audio_file, title_in_graph, output_plot
           )
           output = json.dumps(output, cls=NumpySerializer)
           analysis = json.dumps(analysis, cls=NumpySerializer)
           return {
               "failed": is_failed["failed"],
               "reason": is_failed["reason"],
               "output": output,
               "analysis": analysis,
               "stim_name": stim_name,
           }

The analysis runs in a background process. By default, feedback waits
until the trial is finalized (the analysis has finished and
"on_finalized" has set "score") or has failed, for example because the
analysis rejected the recording. In "show_feedback", check
"self.failed" to tell the two apart. Results such as "self.analysis"
exist only if the analysis ran; for recording trials, "failed_reason
== "analysis"" means it ran and rejected the recording. Set
"wait_for_feedback = False" on the trial class to skip waiting;
feedback may then see a trial whose analysis is still running.

For a performance check, set "check_performance_at_end=True" or
"check_performance_every_trial=True" and choose a built-in check with
"performance_check_type" (""score"", ""performance"", or
""consistency"") and "performance_threshold". With "score_answer"
defined, this passes participants whose total score is at least 5:

   class CustomTrialMaker(StaticTrialMaker):
       performance_check_type = "score"
       performance_threshold = 5

   CustomTrialMaker(..., check_performance_at_end=True)

PsyNet raises an error if checks are enabled without a
"performance_check_type" or a custom check. For other rules, override
"performance_check()" and return a dictionary with "score" and
"passed". To show a page to participants who pass, set
"give_end_feedback_passed = True" and override
"get_end_feedback_passed_page()". The "demos/experiments/static" demo
does both:

   class AnimalTrialMaker(StaticTrialMaker):
       def performance_check(self, experiment, participant, participant_trials):
           """Should return a dict: {"score": float, "passed": bool}"""
           score = 0
           failed = False
           for trial in participant_trials:
               if trial.answer == "Not at all":
                   failed = True
               else:
                   score += 1
           return {"score": score, "passed": not failed}

       def compute_performance_reward(self, score, passed):
           # At the end of the trial maker, we give the participant 1 dollar for each point.
           # This is combined with their trial-level performance reward to give their overall performance reward.
           return 1.0 * score

       give_end_feedback_passed = True

       def get_end_feedback_passed_page(self, score):
           return InfoPage(
               Markup("You finished the animal questions! Your score was {}.").format(
                   score
               ),
               time_estimate=5,
           )

To change what failing participants see, override
"check_fail_logic()".

"fail_trials_on_participant_performance_check" (default "True")
controls whether a failed check also fails the participant's trials in
this trial maker. See Handling failed participants and trials.


Trials without a trial maker
============================

"cue()" puts a single trial into the timeline, with no trial maker.
You then choose the trials yourself with timeline constructs such as
"for_loop()". The argument is the trial's definition as a "dict", a
function returning one, or a "ChainNode". In
"demos/experiments/trial", each participant rates three randomly
sampled words:

   word_ratings = Module(
       "word_ratings",
       for_loop(
           label="Randomly sample three words from the word list",
           iterate_over=lambda: random.sample(WORDS, 3),
           logic=lambda word: RateTrial.cue(
               {
                   "word": word,
               }
           ),
           time_estimate_per_iteration=3,
       ),
   )



With a node, the trial takes the node's definition and can use its
assets through "self.node.assets". Pass the nodes to the enclosing
"Module"; functions inside the module can then take a "nodes"
argument. From "demos/experiments/trial_2":

   NODES = [
       Node(
           definition={
               "frequency_gradient": frequency_gradient,
               "start_frequency": start_frequency,
               "frequencies": [start_frequency + i * frequency_gradient for i in range(5)],
           },
           assets={
               "stimulus": asset(
                   synth_stimulus,
                   extension=".wav",
               )
           },
       )
       for frequency_gradient in [-100, -50, 0, 50, 100]
       for start_frequency in [-100, 0, 100]
   ]


   class RateTrial(Trial):
       time_estimate = 5

       def show_trial(self, experiment, participant):
           return ModularPage(
               "audio_rating",
               AudioPrompt(
                   self.node.assets["stimulus"],
                   text="How happy is the following word?",
               ),
               PushButtonControl(
                   ["Not at all", "A little", "Very much"],
               ),
           )


   audio_ratings = Module(
       "audio_ratings",
       for_loop(
           label="Deliver 5 random samples from the stimulus set",
           iterate_over=lambda nodes: random.sample(nodes, 5),
           logic=lambda node: RateTrial.cue(node),
           time_estimate_per_iteration=RateTrial.time_estimate,
           expected_repetitions=5,
       ),
       nodes=NODES,
   )



Without nodes, pass trial-specific assets to "cue" with "assets". This
suits externally hosted and on-demand assets, as in
"demos/experiments/trial_3":

   audio_ratings = Module(
       "audio_ratings",
       for_loop(
           label="Deliver 5 trials with randomly sampled parameters",
           iterate_over=lambda: [
               {
                   "frequency_gradient": random.uniform(-100, 100),
                   "start_frequency": random.uniform(-100, 100),
               }
               for _ in range(5)
           ],
           logic=lambda definition: RateTrial.cue(
               definition,
               assets={
                   "audio": asset(synth_stimulus, extension=".wav", on_demand=True),
               },
           ),
           time_estimate_per_iteration=RateTrial.time_estimate,
       ),
   )



To create related database records in the same transaction as the
trial, pass an "on_trial_created" callback, and pass request-local
values for it through "creation_context". Assign relationships in the
callback rather than IDs, because the trial's database ID may not
exist until the transaction flushes. If the callback raises an
exception, the trial and the related records are both rolled back.
Passing "creation_context" without "on_trial_created" raises an error.
"demos/features/trial_cue_adaptive" uses this for a participant-level
staircase inside a "while_loop()"; the Make an experiment adaptive
skill describes the recommended approach to adaptive designs.

In group games, cued trials can be the rounds. Set "sync_group_type"
on the trial class and cue it inside a "Module": "cue" numbers each
group's rounds by itself, and the trials that the members of a group
cue in one round share one "SyncGroupRound", whose "var" holds the
group's results. Each trial records the group, the player's role and
the round. "definition" can then be a function of "group" and "round",
called once per group and round. "round=" overrides the automatic
round in the rare cases that need it. See Rounds of cued trials.

A trial maker is the better choice when trials should be balanced
across nodes or participants, when chains develop across participants,
or when you need performance checks or trial-based recruitment.


Where the data goes
===================

Nodes and trials are database rows, so you can inspect them in the
dashboard's database view while the experiment runs, and query them in
code:

   StaticNode.query.filter_by(trial_maker_id="ratings").all()
   trial.node
   node.all_trials
   participant.all_trials

"psynet.experiment.get_trial_maker()" returns a trial maker by its
"id_".

See also: Static and Main in the API reference.
