How to use the psiturk.models.Participant.query function in PsiTurk

To help you get started, we’ve selected a few PsiTurk examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Dallinger / Dallinger / examples / rogers / tests.py View on Github external
for agent in agents:
                    is_asocial = agent.infos(type=LearningGene)[0].contents == "asocial"
                    assert agent.fitness == ((baseline + agent.score*b - is_asocial*c) ** e)

            print("Testing fitness...                   done!")
            sys.stdout.flush()

            """
            TEST BONUS
            """

            print("Testing bonus payments...", end="\r")
            sys.stdout.flush()

            assert exp.bonus(participant=Participant.query.filter_by(uniqueid=p_ids[0]).all()[0]) == exp.bonus_payment

            print("Testing bonus payments...            done!")
            sys.stdout.flush()

            print("All tests passed: good job!")

            print("Timings:")
            overall_time = overall_stop_time - overall_start_time
            print("Overall time to simulate experiment: {}".format(overall_time))
            setup_time = exp_setup_stop - exp_setup_start
            print("Experiment setup(): {}".format(setup_time))
            print("Experiment load: {}".format(exp_setup_stop2 - exp_setup_start2))
            print("Participant assignment: {}".format(assign_time))
            print("Participant processing: {}".format(process_time))
            for i in range(len(p_times)):
                if i == 0:
github NYUCCL / psiTurk / psiturk / example / custom.py View on Github external
@custom_code.route('/compute_bonus', methods=['GET'])
def compute_bonus():
    # check that request includes a uniqueId
    if not request.args.has_key('uniqueId'):
        raise ExperimentError('improper_inputs')  # i don't like returning HTML to JSON requests...  maybe should change this
    uniqueId = request.args['uniqueId']

    try:
        # lookup user in database
        user = Participant.query.\
               filter(Participant.uniqueid == uniqueId).\
               one()
        user_data = loads(user.datastring) # load datastring from JSON
        bonus = 0

        for record in user_data['data']: # for line in data file
            trial = record['trialdata'] # get part of line holding trial info
            if trial['phase']=='TEST': #check that trial is in test phase, not instructions
                if trial['hit']==True: # increment bonus if subject got correct
                    bonus += 0.02
        user.bonus = bonus #set bonus field to new value
        db_session.add(user)
        db_session.commit() #commit to database
        resp = {"bonusComputed": "success"}
        return jsonify(**resp)
    except:
github NYUCCL / psiTurk / psiturk / amt_services_wrapper.py View on Github external
def unreject_assignment(self, assignment_id, all_studies=False):
        ''' Unreject assignment '''
        response = self.amt_services.unreject_assignment(assignment_id)
        result = {}
        if not response.success:
            raise response.exception
        else:
            message='unrejected {}'.format(assignment_id)
            try:
                participant = Participant.query\
                    .filter(Participant.assignmentid == assignment_id)\
                    .order_by(Participant.beginhit.desc()).first()
                participant.status = CREDITED
                db_session.add(participant)
                db_session.commit()
            except:
                message = '{} but failed to update local db'.format(
                    message)
        return message
github NYUCCL / psiTurk / psiturk / experiment.py View on Github external
def update(uid=None):
    """
    Save experiment data, which should be a JSON object and will be stored
    after converting to string.
    """
    app.logger.info("PUT /sync route with id: %s" % uid)

    try:
        user = Participant.query.\
            filter(Participant.uniqueid == uid).\
            one()
    except exc.SQLAlchemyError:
        app.logger.error("DB error: Unique user not found.")

    if hasattr(request, 'json'):
        user.datastring = request.data.decode('utf-8').encode(
            'ascii', 'xmlcharrefreplace'
        )
        db_session.add(user)
        db_session.commit()

    try:
        data = json.loads(user.datastring)
    except:
        data = {}
github NYUCCL / psiTurk / psiturk / amt_services_wrapper.py View on Github external
def add_bonus_info(assignment_dict):
        " Adds DB-logged worker bonus to worker list data "
        try:
            unique_id = '{}:{}'.format(
                assignment_dict['workerId'], assignment_dict['assignmentId'])
            worker = Participant.query.filter(
                Participant.uniqueid == unique_id).one()
            assignment_dict['bonus'] = worker.bonus
        except sa.exc.InvalidRequestError:
            # assignment is found on mturk but not in local database.
            assignment_dict['bonus'] = 'not-found-in-study-database'
        return assignment_dict
github NYUCCL / psiTurk / psiturk / amt_services_wrapper.py View on Github external
def get_assignments(self, hit_ids=None, assignment_status=None, all_studies=False):
        '''
        assignment_status, if set, can be one of `Submitted`, `Approved`, or `Rejected`
        '''
        if not all_studies and assignment_status != 'Rejected':
            p_query = Participant.query
            p_query = p_query.filter(~Participant.uniqueid.contains('debug'))
            if assignment_status:
                mturk_status_to_local_status = {
                    'Submitted': SUBMITTED,
                    'Approved': CREDITED,
                }
                local_status = mturk_status_to_local_status[assignment_status]
                p_query = p_query.filter(Participant.status == local_status)
            if hit_ids:
                p_query = p_query.filter(Participant.hitid.in_(hit_ids))
            assignments = p_query.all()
        else:
            assignments = self.amt_services.get_assignments(
                assignment_status=assignment_status, hit_ids=hit_ids).data
            if assignments:
                assignments = [self.add_bonus_info(
github NYUCCL / psiTurk / psiturk / amt_services_wrapper.py View on Github external
def count_workers(self, codeversion='latest', mode='live', status='completed'):
        '''
        Counts the number of participants in the database who have made it through
        the experiment.
        '''
        if codeversion == 'latest':
            codeversion = [self.config.get(
                'Task Parameters', 'experiment_code_version')]

        if status == 'completed':
            status = [3,4,5,7]
        query = Participant.query
        if mode:
            query = query.filter(Participant.mode == mode)
        if codeversion:
            if not isinstance(codeversion, list):
                codeversion = [codeversion]
            query = query.filter(Participant.codeversion.in_(codeversion))
        if status:
            if not isinstance(status, list):
                status = [status]
            query = query.filter(Participant.status.in_(status))
        worker_count = Participant.count_workers(query=query, group_bys=[])
        return worker_count
github NYUCCL / psiTurk / psiturk / experiment.py View on Github external
Returns a tuple: (cond, condition)
    """
    cutofftime = datetime.timedelta(minutes=-CONFIG.getint('Server Parameters',
                                                           'cutoff_time'))
    starttime = datetime.datetime.now() + cutofftime

    try:
        conditions = json.load(
            open(os.path.join(app.root_path, 'conditions.json')))
        numconds = len(list(conditions.keys()))
        numcounts = 1
    except IOError as e:
        numconds = CONFIG.getint('Task Parameters', 'num_conds')
        numcounts = CONFIG.getint('Task Parameters', 'num_counters')

    participants = Participant.query.\
        filter(Participant.codeversion ==
               CONFIG.get('Task Parameters', 'experiment_code_version')).\
        filter(Participant.mode == mode).\
        filter(or_(Participant.status == COMPLETED,
                   Participant.status == CREDITED,
                   Participant.status == SUBMITTED,
                   Participant.status == BONUSED,
                   Participant.beginhit > starttime)).all()
    counts = Counter()
    for cond in range(numconds):
        for counter in range(numcounts):
            counts[(cond, counter)] = 0
    for participant in participants:
        condcount = (participant.cond, participant.counterbalance)
        if condcount in counts:
            counts[condcount] += 1