The Experiment Class
Experiments are designed in Dallinger by creating a custom subclass of the base Experiment class. The code for the Experiment class is in experiments.py. Unlike the other classes, each experiment involves only a single Experiment object and it is not stored as an entry in a corresponding table, rather each Experiment is a set of instructions that tell the server what to do with the database when the server receives requests from outside.
- class dallinger.experiment.Experiment(session=None, no_configure=False)[source]
Define the structure of an experiment.
- verbose = True
Boolean, determines whether the experiment logs output when running. Default is True.
- task = 'Experiment title'
String, the name of the experiment. Default is “Experiment title”.
- session
Database session property.
This property is deprecated and will be removed in a future version. Use ‘dallinger.db.session’ instead. Alternatively, use ‘dallinger.db.session_scope()’ or ‘dallinger.db.scoped_session_decorator’ for explicit session management.
- Returns:
The database session (defaults to dallinger.db.session if not explicitly set)
- Type:
DEPRECATED
- experiment_repeats = 0
int, the number of non practice networks (see
rle). Default is 0.
- experiment_routes = <Blueprint 'experiment_routes'>
Flask Blueprint for experiment. Functions and methods on the class should be registered as Flask routes using the
experiment_route()decorator. Route functions can not be instance methods and should either be plain functions or classmethods. You can also register route functions at the module level using the standard route decorator on this Blueprint.
- initial_recruitment_size = 1
int, the number of participants requested when the experiment first starts. Default is 1.
- known_classes = {'Agent': <class 'dallinger.nodes.Agent'>, 'Compression': <class 'dallinger.transformations.Compression'>, 'Environment': <class 'dallinger.nodes.Environment'>, 'Gene': <class 'dallinger.information.Gene'>, 'Info': <class 'dallinger.models.Info'>, 'Meme': <class 'dallinger.information.Meme'>, 'Mutation': <class 'dallinger.transformations.Mutation'>, 'Node': <class 'dallinger.models.Node'>, 'Replication': <class 'dallinger.transformations.Replication'>, 'Response': <class 'dallinger.transformations.Response'>, 'Source': <class 'dallinger.nodes.Source'>, 'State': <class 'dallinger.information.State'>, 'Transformation': <class 'dallinger.models.Transformation'>}
dictionary, the classes Dallinger can make in response to front-end requests. Experiments can add new classes to this dictionary.
- participant_constructor = <class 'dallinger.models.Participant'>
Constructor for Participant objects. Callable returning an instance of
Participantor a sub-class. Used bycreate_participant().
- background_tasks
Optional list of functions that will be run at launch time in separate threads.
- channel = None
Optional Redis channel to subscribe to on launch. Note that if you set the channel, you will probably also want to override the
send()method, since this is where messages from Redis will be consumed. Setting a value here will also result in the experiment being subscribed to thedallinger_controlchannel for messages related to socket/subscription updates. This is also the defaultchannel_namefor messages sent using thepublish_to_subscribers()method.
- realtime_games = []
The real-time game types the experiment plays, as a list of
RealtimeGamesubclasses. Runners play sessions of these game types, andcreate_realtime_session()only starts sessions of them. Each needs a channel of its own, which can’t be the experiment’s ownchannel. When the list isn’t empty, each of the experiment’s worker processes starts a runner beside it.
- public_properties
dictionary, the properties of this experiment that are exposed to the public over an AJAX call
- __init__(session=None, no_configure=False)[source]
Create the experiment class. Sets the default value of attributes.
- Parameters:
session – DEPRECATED. Database session is now managed automatically. This parameter will be removed in Dallinger v13.x
- accept_websocket_connection(participant_id, scope)[source]
Decide whether a websocket connection that names a participant may open.
Every
/experiment-socketconnection names one. A/chatconnection that names none isn’t checked: it can subscribe and receive broadcasts, but it isn’t sent directed messages and can’t join a real-time session.Called once per connection, after the participant has been found and before the connection subscribes to anything or joins a real-time session. Return
Falseto refuse it: the connection is closed with code 1008, and Dallinger’s client helpers stop reconnecting. Any falsy return refuses, includingNone, so remember to returnTrue. The default accepts every connection.Neither route checks who is on the other end, so use this to check something only the participant’s page knows, such as a token the server signed when it rendered the page, passed as
scope. Using WebSockets in Dallinger Experiments has an example, and says where the scope is logged and saved.If this raises, the connection is closed with code 1013 and the browser tries again. Like
handle_websocket_message(), it runs on the one experiment instance that serves every connection on the process, so keep per-participant state offself. It blocks the web process while it waits on the database, and the session is removed after the call, so commit any writes yourself.- Parameters:
participant_id (str) – the id of an existing participant, as a decimal string, so
int(participant_id)is safescope (str or None) – opaque string from the connection’s query string
- Returns:
whether to accept the connection
- Return type:
bool
- add_node_to_network(node, network)[source]
Add a node to a network.
This passes node to
add_node().
- assignment_abandoned(participant)[source]
What to do if a participant abandons the hit.
This runs when a notification from AWS is received indicating that participant has run out of time. Calls
fail_participant().
- assignment_reassigned(participant)[source]
What to do if the assignment assigned to a participant is reassigned to another participant while the first participant is still working.
This runs when a participant is created with the same assignment_id as another participant if the earlier participant still has the status “working”. Calls
fail_participant().
- assignment_returned(participant)[source]
What to do if a participant returns the hit.
This runs when a notification from AWS is received indicating that participant has returned the experiment assignment. Calls
fail_participant().
- attention_check(participant)[source]
Check if participant performed adequately.
Return a boolean value indicating whether the participant’s data is acceptable. This is mean to check the participant’s data to determine that they paid attention. This check will run once the participant completes the experiment. By default performs no checks and returns True. See also
data_check().
- attention_check_failed(participant)[source]
What to do if a participant fails the attention check.
Runs when participant has failed the
attention_check(). By default callsfail_participant().
- bonus(participant)[source]
The bonus to be awarded to the given participant.
Return the value of the bonus to be paid to participant. By default returns 0.
- bonus_reason()[source]
The reason offered to the participant for giving the bonus.
Return a string that will be included in an email sent to the participant receiving a bonus. By default it is “Thank you for participating! Here is your bonus.”
- calculate_qualifications(participant)[source]
All the qualifications we want to assign to a worker.
This default implementation produces qualifications compatible with Dallinger’s standard recruiters, and the MTurkRecruiter in particular.
Workers will always be assigned one qualification specific to the experiment run. If a “group_name” config value is set, this will be parsed for additional qualifications to grant.
Return type is a list of dictionaries with “name”, “description”, and optionally “score” (an integer), or an empty list.
- check_recruiter_exit(participant)[source]
Return a response to send instead of the participant’s exit page.
/recruiter-exitcalls this after loading the participant named by itsparticipant_idparameter.dallinger.submitAssignment()also adds the participant’sunique_idto the link, which an experiment can require:def check_recruiter_exit(self, participant): if flask.request.args.get("unique_id") != participant.unique_id: return "Not your exit page", 403
- Parameters:
participant – the
Participantnamed byparticipant_id- Returns:
Noneto show the recruiter’s exit page, or anything a Flask view can return, sent instead. The default returnsNone.
- check_worker_status(participant)[source]
Return a response to send instead of recording the participant’s status.
/worker_complete,/worker_failed,/handle-errorand/prolific-submission-listenercall this after loading the participant named by theirparticipant_id(participantId) parameter, or, for/handle-error, by itsworker_idorassignment_id. When this refuses,/handle-errorstill records the error report and shows its usual confirmation page instead of the response, but doesn’t complete the participant.dallinger.submitAssignment(),dallinger.error(), the error page, the Prolific exit page and Dallinger’s bots also send the participant’sunique_id, which an experiment can require:def check_worker_status(self, participant): if flask.request.values.get("unique_id") != participant.unique_id: return "Not your assignment", 403
- Parameters:
participant – the
Participantthe request names- Returns:
Noneto record the status, or anything a Flask view can return, sent instead. The default returnsNone.
- collect(app_id, exp_config=None, bot=False, **kwargs)[source]
Collect data for the provided experiment id.
The
app_idparameter must be a valid UUID. If an existing data file is found for the UUID it will be returned, otherwise - if the UUID is not already registered - the experiment will be run and data collected.See
run()method for other parameters.
- create_participant(worker_id, hit_id, assignment_id, mode, recruiter_name=None, fingerprint_hash=None, entry_information=None)[source]
Creates and returns a new participant object. Uses
participant_constructoras the constructor.- Parameters:
worker_id (str) – the recruiter Worker Id
hit_id (str) – the recruiter HIT Id
assignment_id (str) – the recruiter Assignment Id
mode (str) – the application mode
recruiter_name (str) – the recruiter name
fingerprint_hash (str) – the user’s fingerprint
entry_information – a JSON serializable data structure containing additional participant entry information
- Returns:
A
Participantinstance
Note
This method is called inside a PostgreSQL transaction-level advisory lock (
pg_advisory_xact_lock). That lock is released automatically when the surrounding transaction commits. Overrides must therefore not callsession.commit(), since doing so releases the lock early and allows concurrent signup requests to enter the critical section before the current one has finished.
- dashboard_database_actions()[source]
Returns a sequence of custom actions for the database dashboard. Each action must have a
titleand anamecorresponding to a method on the experiment class.The named methods should take a single
dataargument which will be a list of dicts representing the datatables rendering of a Dallinger model object. The named methods should return adictcontaining a"message"which will be displayed in the dashboard.Returns a single action referencing the
dashboard_fail()method by default.
- dashboard_fail(data)[source]
Marks matching non-failed items as failed. Items are looked up by
idandobject_type(e.g."Participant").- Parameters:
data – A list of dicts representing model items to be marked as failed. Each must have an
idand anobject_type- Returns:
Returns a
dictwith a"message"string indicating how many items were successfully marked as failed.
- data_check(participant)[source]
Check that the data are acceptable.
Return a boolean value indicating whether the participant’s data is acceptable. This is meant to check for missing or invalid data. This check will be run once the participant completes the experiment. By default performs no checks and returns True. See also,
attention_check().
- data_check_failed(participant)[source]
What to do if a participant fails the data check.
Runs when participant has failed
data_check(). By default callsfail_participant().
- events_for_replay(session=None, target=None)[source]
Returns an ordered list of “events” for replaying. Experiments may override this method to provide custom replay logic. The “events” returned by this method will be passed to
replay_event(). The default implementation simply returns allInfoobjects in the order they were created.
- classmethod extra_parameters()[source]
Override this classmethod to register new config variables. It is called during config load. See Extra Configuration for an example.
- exit_info_for(participant)[source]
An experiment can return a dictionary of infomation that will be shown to the participant at the very last point in their lifecycle, if the HIT is not submitted to an external recruitment service for submission.
For complete control over the exit page, a customized version of the
exit_recruiter.htmltemplate can be included in the experient directory, and this will override the default provided by Dallinger.- Parameters:
participant – the
Participantinstance for which to calculate an exit value- Returns:
dictwhich may be rendered to the worker as an HTML table when they submit their assigment.
- get_network_for_participant(participant)[source]
Find a network for a participant.
If no networks are available, None will be returned. By default participants can participate only once in each network and participants first complete networks with role=”practice” before doing all other networks in a random order.
- handle_websocket_message(message, *, channel_name, participant_id=None, scope=None, receive_time=None)[source]
Handle one message from a
/experiment-socketconnection.Unlike
send(), this runs on the web process that owns the websocket, before the next message is read. Use it for messages the experiment must act on immediately. The default implementation passes the message tosend(), so an experiment that does not override this keeps the asynchronous handling it had.The session is removed once this returns, and one experiment instance serves every experiment socket on the process, so load what you need per call, commit your own writes, and keep per-participant state off
self.A handler blocks the whole web process while it waits on the database. The message does not reach
channel_nameeither. See Using WebSockets in Dallinger Experiments for the query budget and for broadcasting from a handler.- Parameters:
message (str) – the payload, with the channel prefix already stripped
channel_name (str) – the channel prefix the payload arrived with
participant_id (str) – the id of an existing participant, as named by the connection.
/experiment-socketis unauthenticated, so this says which participant the connection claims to be, not who is sendingscope (str or None) – opaque string from the connection’s query string, passed through without being interpreted. It is how an experiment tells apart two connections from the same participant, which are otherwise identical
receive_time (datetime.datetime) – when the message was read off the socket, naive and in local time, as
timenow()and every DallingerDateTimecolumn are. Read the arrival time from this argument. The default implementation does not forward it, andsend()stamps its own, which is when it ran rather than when the message arrived
- is_complete()[source]
Method for custom determination of experiment completion. Experiments should override this to provide custom experiment completion logic. Returns None to use the experiment server default logic, otherwise should return True or False.
- is_overrecruited(waiting_count)[source]
Returns True if the number of people waiting is in excess of the total number expected, indicating that this and subsequent users should skip the experiment. A quorum value of 0 means we don’t limit recruitment, and always return False.
- load_participant(assignment_id)[source]
Returns a participant object looked up by assignment_id.
Intended to allow a user to resume a session in a running experiment.
- Parameters:
assignment_id (str) – the recruiter Assignment Id
- Returns:
A
Participantinstance orNoneif there is not a single matching participant.
- classmethod make_uuid(app_id=None)[source]
Generates a new UUID. This is a class method and can be called as Experiment.make_uuid(). Takes an optional app_id which is converted to a string and, if it is a valid UUID, returned.
- normalize_entry_information(entry_information)[source]
Accepts a dictionary with information about a recruited user. Returns a dictionary containing data the needed to create or load a Dallinger Participant. The returned data should include valid
assignment_id,worker_id, andhit_idvalues. It may also include anentry_informationkey which should contain a transformedentry_informationdict which will be stored for newly created participants.By default, the extraction of these values is delegated to the recruiter’s normalize_entry_information method.
Returning a dictionary without valid
hit_id,assignment_id, orworker_idwill generally result in an exception./load-participantreturns the participant’sunique_idonly when theworker_idreturned here matches the participant’s, so takeworker_idfromentry_information.
- on_launch()[source]
This function is called upon experiment launch. Unlike the background tasks, this function is blocking: recruitment won’t start until the function has returned.
- participant_task_completed(participant)[source]
Called when an experiment task is first finished, and prior to recruiter submission, data and attendance checks.
Assigns the qualifications to the Participant, via their recruiter. These will include one Qualification for the experiment ID, and others for the configured group_name, if it’s been set.
Overrecruited participants don’t receive qualifications, since they haven’t actually completed the experiment. This allows them to remain eligible for future runs.
- Parameters:
participant – the
Participantinstance
- publish_to_participants(payload, participant_ids, scope=None)[source]
Send a payload to the WebSocket connections of specific participants.
Where
publish_to_subscribers()broadcasts to everyone subscribed to a channel, this method addresses participants. The recipients need no subscription and no channel of their own: any connection to/chator/experiment-socketwhich supplied aparticipant_idcan be addressed, and the payload will be delivered to every connection that participant holds, on whichever web process is holding it. The method may be called from anywhere, including a worker event or a WebSocket handler.The payload arrives on the client prefixed with the reserved
dallinger_directchannel name, in the same<channel>:<payload>format as every other message, so a client can distinguish a directed message from a channel broadcast. Experiments should neither publish to that channel nor subscribe to it.Naming a participant who has no open connection, or who is not connected to this deployment at all, delivers nothing and is not an error. Delivery is best effort, as it is for a broadcast: a payload published while a participant is reconnecting will not be replayed to their new connection.
A redis failure is the exception, and raises. The payload will have reached nobody when it does, so the whole call can be retried.
- Parameters:
payload (dict, list, str, or other JSON-serializable object) – the message to deliver, as anything
json.dumpsaccepts. It is serialized once, so every recipient of a single call is sent identical bytesparticipant_ids (list of int or str, or a single int or str) – the participants to deliver to. A single id may be given in place of a sequence, and an id which is not a whole number is logged and skipped
scope (str or None) – deliver only to those connections which supplied this same
scopevalue, the opaque string a connection may name in its query string. The default ofNonedelivers to all of a participant’s connections. It allows an experiment to reach the page a participant is on rather than a tab left open on an earlier one
- publish_to_subscribers(data, channel_name=None)[source]
Publish data to the given channel_name. Data will be sent to all channel subscribers, potentially including the experiment instance itself. If no
channel_nameis specified, then theExperimentchannelvalue will be used (and the data will automatically be consumed bysend()). Thedatamust be a string, it typically contains JSON.- Parameters:
data (str) – the message data to be send
channel_name (str) – the name of the channel to publish the data to
- Raises:
ValueError – if
channel_nameisdallinger_control,dallinger_direct,dallinger_realtime_sessionordallinger_time, which are reserved for Dallinger’s own use
- receive_message(message, channel_name=None, participant=None, node=None, receive_time=None)[source]
Stub implementation of a websocket message processor. The
send()method either queues incoming messages to be processed asynchronously using this method or directly calls this method for messages flagged for immediate processing.Experiment classes that wish to handle incoming WebSocket messages asynchronously should implement this method. An Experiment needs to implement either this method or customize
send()whenever theExperimentchannelattribute is set.messageis a string, e.g. containing JSON formatted data.Control messages about channel subscription and websocket connect/disconnect events are sent over the
"dallinger_control"channel.This method will be called synchronously in the experiment web server by
send()when the JSON message payload has an immediate property set. Otherwise, it will be called asynchronously by a Dallinger worker process.- Parameters:
message (str) – a websocket message string, usually JSON data
channel_name (str) – The name of the channel the message was received on.
participant (
Participantinstance) – the experiment participant object responsible for the messagenode (
Nodeinstance) – the experiment node the message corresponds toreceive_time (datetime.datetime) – The time the message was received by the experiment
- recruit()[source]
Recruit participants to the experiment as needed.
This method runs whenever a participant successfully completes the experiment (participants who fail to finish successfully are automatically replaced). By default it recruits 1 participant at a time until all networks are full.
- replay_event(event)[source]
Stub method to replay an event returned by
events_for_replay(). Experiments must override this method to provide replay support.
- replay_start()[source]
Stub method for starting an experiment replay. Experiments must override this method to provide replay support.
- replay_finish()[source]
Stub method for ending an experiment replay. Experiments must override this method to provide replay support.
- run(exp_config=None, app_id=None, bot=False, **kwargs)[source]
Deploy and run an experiment.
The exp_config object is either a dictionary or a
localconfig.LocalConfigobject with parameters specific to the experiment run grouped by section.
- save(*objects)[source]
Add all the objects to the session and commit them.
This only needs to be done for networks and participants.
- send(raw_message)[source]
Async implementation of websocket message processing. Attempts to extract a participant id or node id from the message, and send the message to be processed asynchronously by
receive_message()using the Dallinger worker_function. If the message pyaload is JSON and contains a property named immediate then the message will be processed synchronously byreceive_message().raw_messageis a string that includes a channel name prefix, for example a JSON message for ashoppingchannel might look like:'shopping:{"type":"buy","color":"blue","quantity":"2"}'Control messages about channel subscription and websocket connect/disconnect events use the
dallinger_controlchannel name.Experiments can override this method if they want to process all messages synchronously in a single application instance by default. For example if an experiment retains non-persisted state in an attribute of the experiment class that it uses for message responses then it’s best to override this method instead of
receive_message(), and explicitly hand off any state synchronization and database writes to async worker events.This method also backs the default
handle_websocket_message(), so a/experiment-socketconnection reaches it on the web process that owns the socket rather than on the one subscribed to the channel. Animmediatepayload is therefore processed on that web process, and blocks every other websocket and request it is serving untilreceive_message()returns.- Parameters:
raw_message (str) – a formatted message string
'$channel_name:$data'
- submission_successful(participant)[source]
Run when a participant’s experiment submission passes data and attendence checks.
- Parameters:
participant – the
Participantinstance
- transformation_get_request(node, transformations)[source]
Run when a request to get transformations is complete.
- transformation_post_request(node, transformation)[source]
Run when a request to transform an info is complete.
- dallinger.experiment.experiment_route(rule, **kwargs)[source]
Creates a decorator to register experiment functions or classmethods as routes on the
Experiment.experiment_routesblueprint. Accepts all standard flaskroutearguments. The registration is deferred until experiment server setup to allow routes to be overridden.- Returns:
A decorator to register methods from a class as experiment routes.