Create and rate
***************

A create-and-rate experiment is a chain experiment in which each node
collects creations from some participants, such as text descriptions,
recordings or slider settings, and then ratings of those creations
from others. The best creation becomes the next node's definition: the
one with the highest mean rating, or the one chosen by the most
raters. The same structure can also validate stimuli during an
experiment.

The examples on this page come from
"demos/experiments/create_and_rate/basic", in which creators describe
a picture of an animal and raters judge the descriptions. To run it
from a PsyNet source checkout:

   cd demos/experiments/create_and_rate/basic
   psynet debug local


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

Each node first receives "n_creators" creator trials. Once those
trials are finalized, it receives "n_raters" rater trials. The trial
maker then summarizes the ratings to choose the next node's
definition. It sets "trials_per_node" to "n_creators + n_raters"
itself.

An experiment defines three classes, each combining a mixin from
"psynet.trial.create_and_rate" with a chain class. The mixin must come
first:

* a creator trial: "CreateTrialMixin" and a "ChainTrial" subclass;

* a rater trial: "RateTrialMixin" (for ratings) or "SelectTrialMixin"
  (for choosing one creation), and a "ChainTrial" subclass;

* a trial maker: "CreateAndRateTrialMakerMixin" and a
  "ChainTrialMaker" subclass.

"CreateAndRateNode" is the node class for most experiments.


Creator trials
==============

A creator trial works like any other chain trial. In the demo,
creators describe the image stored in the node's "context":

   class CreateTrial(CreateTrialMixin, ImitationChainTrial):
       time_estimate = 5

       def show_trial(self, experiment, participant):
           return ModularPage(
               "create_trial",
               animal_prompt(text="Describe the animal", img_url=self.context["img_url"]),
               TextControl(),
               time_estimate=self.time_estimate,
           )


Rater trials
============

A rater trial finds the creations to judge in "self.targets", and
reads each one's answer with "self.get_target_answer(target)". A
target is either a creator trial or, with
"include_previous_iteration=True", the current node.

With "RateTrialMixin" the answer is a number, or a list of numbers
when there are several targets:

   class SingleRateTrial(RateTrialMixin, ImitationChainTrial):
       time_estimate = 5

       def show_trial(self, experiment, participant):
           assert self.trial_maker.target_selection_method == "one"

           assert len(self.targets) == 1
           target = self.targets[0]
           creation = self.get_target_answer(target)
           return ModularPage(
               "rate_trial",
               animal_prompt(
                   text=Markup(
                       "How well does this description match the animal?<br><strong>{}</strong>"
                   ).format(creation),
                   img_url=self.context["img_url"],
               ),
               PushButtonControl(
                   choices=[1, 2, 3, 4, 5],
                   labels=["not at all", "a little", "somewhat", "very", "perfectly"],
                   arrange_vertically=False,
               ),
           )

With "SelectTrialMixin" the answer is the string form of the chosen
target, so the targets themselves serve as the choices:

   class SelectTrial(SelectTrialMixin, ImitationChainTrial):
       time_estimate = 5

       def show_trial(self, experiment, participant):
           target_strs = [f"{target}" for target in self.targets]
           answers = [self.get_target_answer(target) for target in self.targets]
           return ModularPage(
               "select_trial",
               animal_prompt(
                   text="Which of these descriptions is the best?",
                   img_url=self.context["img_url"],
               ),
               PushButtonControl(
                   choices=target_strs,
                   labels=answers,
               ),
           )


The trial maker
===============

The trial maker class only combines the mixin with a chain trial
maker:

   class CreateAndRateTrialMaker(CreateAndRateTrialMakerMixin, ImitationChainTrialMaker):
       pass

The demo builds one trial maker for each of three configurations:

   def get_trial_maker(option):
       rater_class = SingleRateTrial
       n_creators = 2
       n_raters = 2
       rate_mode = "rate"
       include_previous_iteration = True
       target_selection_method = "one"

       if option == "include_previous_iteration":
           n_creators = 1
           pass
       elif option == "rate":
           include_previous_iteration = False
       elif option == "select":
           rater_class = SelectTrial
           n_raters = 3
           target_selection_method = "all"
           rate_mode = "select"
       else:
           raise ValueError(f"Unknown option: {option}")

       seed_definition = "initial creation" if include_previous_iteration else {}
       start_nodes = [
           CreateAndRateNode(context={"img_url": "static/dog.jpg"}, seed=seed_definition)
       ]

       return CreateAndRateTrialMaker(
           n_creators=n_creators,
           n_raters=n_raters,
           node_class=CreateAndRateNode,
           creator_class=CreateTrial,
           rater_class=rater_class,
           # mixin params
           include_previous_iteration=include_previous_iteration,
           rate_mode=rate_mode,
           target_selection_method=target_selection_method,
           verbose=True,  # for the demo
           # trial_maker params
           id_=option + "_trial_maker",
           chain_type="across",
           expected_trials_per_participant=len(start_nodes),
           max_trials_per_participant=len(start_nodes),
           start_nodes=start_nodes,
           chains_per_experiment=len(start_nodes),
           check_performance_at_end=True,
           check_performance_every_trial=False,
           propagate_failure=False,
           recruit_mode="n_trials",
           target_n_participants=None,
           wait_for_networks=False,
           max_nodes_per_chain=10,
       )

The create-and-rate arguments are:

* "n_creators" and "n_raters": positive integers.

* "node_class", "creator_class" and "rater_class".

* "rate_mode": ""rate"" (default) or ""select"". With ""select"", each
  node needs at least two targets and "rater_class" must use
  "SelectTrialMixin".

* "target_selection_method": ""one"" (default) gives each rater one
  target, chosen at random among those with the fewest ratings so far;
  ""all"" gives each rater every target. ""select"" requires ""all"".
  With ""rate"" and ""one"", "n_raters" must be a multiple of the
  number of targets.

* "include_previous_iteration" (default "False"): rate the current
  node's definition, the previous winner, alongside the new creations.
  Every start node then needs a "seed", as in the demo's
  "get_trial_maker".

* "randomize_target_order" (default "True"): shuffle the targets for
  each rater.

* "verbose" (default "False"): log how targets and winners are chosen.

The remaining arguments go to the chain trial maker; see Writing a
chain experiment.


Separate creators and raters
============================

By default, a participant creates or rates depending on which phase
the chosen node is in. To give participants a fixed role, override
"get_participant_role(self, participant, experiment)" to return
"self.CREATOR_ROLE" or "self.RATER_ROLE". Creators then only receive
nodes that still need creations. Raters receive nodes that are ready
for ratings, and wait or exit at nodes whose creations are not yet
finalized, depending on "wait_for_networks".

"demos/experiments/create_and_rate/gap" assigns roles in a "CodeBlock"
before the trial maker, stores them in "participant.var.is_rater", and
also limits how many trials each role completes:

   class CreateAndRateTrialMaker(CreateAndRateTrialMakerMixin, ImitationChainTrialMaker):
       def has_enough_trials(self, participant):
           if participant.var.is_rater:
               n_ratings = len(
                   self.rater_class.query.filter_by(participant=participant).all()
               )
               if n_ratings >= MAX_RATINGS_PER_PARTICIPANT:
                   return True
           else:
               n_creations = len(
                   self.creator_class.query.filter_by(participant=participant).all()
               )
               if n_creations >= MAX_CREATIONS_PER_PARTICIPANT:
                   return True
           return False

       def custom_chain_filter(self, chains, participant, experiment):
           if self.has_enough_trials(participant):
               return []
           return chains

       def get_participant_role(self, participant, experiment):
           if participant.var.is_rater:
               return self.RATER_ROLE
           return self.CREATOR_ROLE

Two more demos in the same folder use other creator trials: in
"picnic", creators propose a rule that raters check against examples;
in "robot_voice", creators adjust a synthesized voice with an
"AudioGibbsTrial".
