class Constants(otree.constants.BaseConstants): name_in_url = 'bargaining' players_per_group = 2 num_rounds = 1 amount_shared = c(100) bonus = c(10)
def play_round(self): # compete price self.submit(views.Introduction) self.submit(views.Question1, {'training_my_profit': c(1)}) self.submit(views.Feedback1) self.submit(views.Decide, {'price': c(30)}) self.submit(views.Results)
def test_currency_unary_operator(self): # https://github.com/oTree-org/otree-core/issues/391 msg = "Currency operator '{}' fail" for money in [c(-random.random()), c(random.random()), c(0)]: self.assertIsInstance(abs(money), c, msg.format("abs()")) self.assertIsInstance(-money, c, msg.format("-VALUE")) self.assertIsInstance(+money, c, msg.format("+VALUE"))
def play(self): # compete price self.submit(views.Introduction) self.submit(views.Question1, {'training_my_profit': c(1)}) self.submit(views.Feedback1) self.submit(views.Decide, {'price': c(30)}) self.submit(views.Results)
def variables_for_template(self): if self.player.private_value is None: self.player.private_value = self.player.generate_private_value() return {'private_value': self.player.private_value, 'min_bid': c(Constants.min_allowable_bid), 'max_bid': c(Constants.max_allowable_bid)}
def vars_for_template(self): if self.player.private_value is None: self.player.private_value = self.player.generate_private_value() return {'private_value': self.player.private_value, 'min_bid': c(Constants.min_allowable_bid), 'max_bid': c(Constants.max_allowable_bid)}
class Constants: name_in_url = 'bargaining' players_per_group = 2 number_of_rounds = 1 amount_shared = c(100) bonus = c(10)
def vars_for_template(self): fin_forzado = self.group.n_empresa_trabajador_finalizacion_forzada empresa = self.group.get_player_by_role(Constants.empresa) propuestas = empresa.all_propuestas() trabajador = self.group.get_player_by_role(Constants.trabajador) contrapropuestas = trabajador.all_contrapropuestas() lineas = [] print propuestas, contrapropuestas for idx, propuesta in enumerate(propuestas): linea = { "propuesta": c(propuesta), "contrapropuesta": c(contrapropuestas[idx]) if len(contrapropuestas) > idx else None, "final": False} lineas.append(linea) lineas[-1]["final"] = True acepto_empresa = not fin_forzado and len(propuestas) == len(contrapropuestas) acepto_trabajador = not fin_forzado and not acepto_empresa return { "fin_forzado": fin_forzado, "empresa": empresa, "trabajador": trabajador, "lineas": lineas, "acepto_empresa": acepto_empresa, "acepto_trabajador": acepto_trabajador}
class Constants(BaseConstants): name_in_url = 'three_ultimatum' players_per_group = 3 num_rounds = 1 endowment = c(10) if_offer_rejected = c(0) offer_increment = c(5) offered_choices = currency_range(0, endowment + 1, offer_increment)
class Constants(BaseConstants): name_in_url = 'dictator' players_per_group = 2 num_rounds = 1 bonus = c(10) # Initial amount allocated to the dictator allocated_amount = c(100)
class Constants(otree.constants.BaseConstants): name_in_url = 'WarGames_Test' num_rounds = 1 # Everyone in one group, but randomly split into teams below players_per_group = None # Starting War Chests, both at value 100 team_1_chest_start = c(100) team_2_chest_start = c(100)
class Constants(otree.constants.BaseConstants): players_per_group = 2 name_in_url = 'market' num_rounds = 1 bonus = c(0) maximum_price = c(400) alpha = 2 efficiency = 1.5
class Constants(BaseConstants): name_in_url = 'public_goods' players_per_group = 3 num_rounds = 1 """Amount allocated to each player""" endowment = c(75) efficiency_factor = 2 guess_correct = c(30)
class Constants: name_in_url = 'trust' players_per_group = 2 number_of_rounds = 1 #Initial amount allocated to each player amount_allocated = c(100) multiplication_factor = 3 bonus = c(10)
class Constants: name_in_url = 'common_value_auction' players_per_group = 1 number_of_rounds = 1 min_allowable_bid = c(0) max_allowable_bid = c(10) # Error margin for the value estimates shown to the players estimate_error_margin = 1
class Constants(otree.constants.BaseConstants): name_in_url = 'common_value_auction' players_per_group = None num_rounds = 1 min_allowable_bid = c(0) max_allowable_bid = c(10) # Error margin for the value estimates shown to the players estimate_error_margin = 1
class Constants(BaseConstants): name_in_url = 'mini_ultimatum' players_per_group = 3 num_rounds = 1 endowment = c(10) offer_increment = c(5) offer_choices = currency_range(0, endowment, offer_increment) offer_choices_count = len(offer_choices)
class Constants: name_in_url = 'public_goods' players_per_group = 3 number_of_rounds = 1 #"""Amount allocated to each player""" endowment = c(100) efficiency_factor = 1.8 base_points = c(10) question_correct = c(92)
class Constants(BaseConstants): name_in_url = 'vickrey_auction' players_per_group = 3 num_rounds = 1 fixed_payoff = c(100) min_allowable_bid = c(0) max_allowable_bid = c(100) training_question_1_my_payoff_limit = c(100) * players_per_group training_question_1_my_payoff_correct = c(105)
class Constants(BaseConstants): name_in_url = 'trustfield' players_per_group = 2 num_rounds = 5 endowment = c(10) mult_factor = 3 showupfee = 40 question_trustA_correct = c(14) question_trustB_correct = c(8)
def vars_for_template(self): for p in self.group.get_players(): # Function to compute total expenditure in punishing others p.punish_exp = p.punish_p1 + p.punish_p2 + p.punish_p3 + p.punish_p4 return { 'punish_cards': self.player.punish_exp, # Amount spent punishing others 'punish_exp': c(Constants.punish_cost * self.player.punish_exp), # Amount spent punishing others 'eff_punish_p1' : c(Constants.punish_tech * self.group.total_punish_p1), # Values of total punishment for each player 'eff_punish_p2' : c(Constants.punish_tech * self.group.total_punish_p2), 'eff_punish_p3' : c(Constants.punish_tech * self.group.total_punish_p3), 'eff_punish_p4' : c(Constants.punish_tech * self.group.total_punish_p4), }
class Constants(BaseConstants): name_in_url = 'common_value_auction' players_per_group = None num_rounds = 1 instructions_template = 'common_value_auction/Instructions.html' min_allowable_bid = c(0) max_allowable_bid = c(10) # Error margin for the value estimates shown to the players estimate_error_margin = 1
class Constants: name_in_url = 'stackelberg_competition' players_per_group = 2 number_of_rounds = 1 # Total production capacity of both players total_capacity = 60 max_units_per_player = int(total_capacity / 2) fixed_pay = c(50) training_1_correct = c(300)
class Constants: name_in_url = 'volunteer_dilemma' players_per_group = 3 number_of_rounds = 1 bonus = c(10) # """Payoff for each player if at least one volunteers""" general_benefit = c(100) # """Cost incurred by volunteering player""" volunteer_cost = c(40)
class Constants(otree.constants.BaseConstants): name_in_url = 'volunteer_dilemma' players_per_group = 3 num_rounds = 1 num_other_players = players_per_group - 1 bonus = c(10) # """Payoff for each player if at least one volunteers""" general_benefit = c(100) # """Cost incurred by volunteering player""" volunteer_cost = c(40)
class Constants(otree.constants.BaseConstants): name_in_url = 'matrix_symmetric' players_per_group = 2 num_rounds = 1 self_A_other_A = c(10) # How much I make if I choose A and the other player chooses B self_A_other_B = c(0) self_B_other_A = c(30) self_B_other_B = c(40)
class Constants(BaseConstants): name_in_url = 'trust' players_per_group = 2 num_rounds = 1 #Initial amount allocated to each player amount_allocated = c(100) multiplication_factor = 3 bonus = c(10) training_answer_x_correct = c(130) training_answer_y_correct = c(10)
class Constants: name_in_url = 'matrix_symmetric' players_per_group = 2 number_of_rounds = 1 self_A_other_A = c(0.10) # How much I make if I choose A and the other player chooses B self_A_other_B = c(0.00) self_B_other_A = c(0.30) self_B_other_B = c(0.40)
class Constants(BaseConstants): name_in_url = 'bribery_effort_info_RU' players_per_group = 3 endowment = c(10) prize = c(10) num_rounds = 10 # c() necessary? task_time = 300 max_task_amount = 10000000 training_answer_A_correct = c(17) training_answer_B_correct = c(6) training_answer_C_correct = c(17)
class Constants(otree.constants.BaseConstants): name_in_url = 'ultimatum' players_per_group = 2 num_rounds = 1 endowment = c(100) payoff_if_rejected = c(0) offer_increment = c(10) offer_choices = currency_range(0, endowment, offer_increment) offer_choices_count = len(offer_choices) keep_give_amounts = [(offer, endowment - offer) for offer in offer_choices]
class Constants(BaseConstants): name_in_url = 'stag_hunt' players_per_group = 2 num_rounds = 1 instructions_template = 'stag_hunt/Instructions.html' # e.g. stag_hare_payoff means: # "if I choose stag and the other player chooses hare, how much do I make? stag_stag_payoff = c(200) stag_hare_payoff = c(0) hare_stag_payoff = c(100) hare_hare_payoff = c(100)
class Constants(BaseConstants): players_per_group = 5 num_rounds = 1 name_in_url = 'beauty' winner_payoff = c(100) guess_max = 100 fixed_pay = c(10) training_question_1_win_pick_correct = 10 training_question_1_my_payoff_correct = c(50) training_1_maximun_pick = 100 training_1_maximun_offered_points = c(100)
def set_negociacion_empresa_trabajador_payoff(self): empresa = self.get_player_by_role(Constants.empresa) trabajador = self.get_player_by_role(Constants.trabajador) if self.n_empresa_trabajador_finalizacion_forzada: empresa.payoff = c(50) trabajador.payoff = 0 else: propuestas = empresa.all_propuestas() contrapropuestas = trabajador.all_contrapropuestas() X = c(contrapropuestas[-1] if len(propuestas) == len(contrapropuestas) else propuestas[-1]) trabajador.payoff = X empresa.payoff = 200 - X
def test_currency_inplace_operator(self): msg = "Currency operator '{}' fail" for money in [c(-random.random()), c(random.random()), c(0)]: money += 1 self.assertIsInstance(money, c, msg.format("+=")) money -= 1 self.assertIsInstance(money, c, msg.format("-=")) money /= 1 self.assertIsInstance(money, c, msg.format("/=")) money *= 1 self.assertIsInstance(money, c, msg.format("*=")) money **= 1 self.assertIsInstance(money, c, msg.format("**=")) money //= 1 self.assertIsInstance(money, c, msg.format("//="))
def test_currency_operator(self): msg = "Currency operator '{}' fail" for money in [c(-random.random()), c(random.random()), c(0)]: money = money + 1 self.assertIsInstance(money, c, msg.format("+")) money = money - 1 self.assertIsInstance(money, c, msg.format("-")) money = money / 1 self.assertIsInstance(money, c, msg.format("/")) money = money * 1 self.assertIsInstance(money, c, msg.format("*")) money = money ** 1 self.assertIsInstance(money, c, msg.format("**")) money = money // 1 self.assertIsInstance(money, c, msg.format("//"))
def player_two_decision(self): p1 = self.get_player_by_id(2) p2 = self.get_player_by_id(1) if p1.participant.vars["rank"] == "high": p2.payoff = p1.keep p1.payoff = c(150) - p2.keep p2.real_effort_dictator_endowment = 150 p2.participant.vars["dictator_payoff_p2"] = p1.keep p1.participant.vars["dictator_payoff_p1"] = c(50) - p2.keep elif p1.participant.vars["rank"] == "low": p2.payoff = p2.keep p1.payoff = c(50) - p2.keep p2.real_effort_dictator_endowment = 50 p2.participant.vars["dictator_payoff_p2"] = p1.keep p1.participant.vars["dictator_payoff_p1"] = c(50) - p2.keep
def set_negociacion_empresa_trabajador_payoff(self): empresa = self.get_player_by_role(Constants.empresa) trabajador = self.get_player_by_role(Constants.trabajador) if self.n_empresa_trabajador_finalizacion_forzada: empresa.payoff = c(50) trabajador.payoff = 0 else: propuestas = empresa.all_propuestas() contrapropuestas = trabajador.all_contrapropuestas() X = c( contrapropuestas[-1] if len(propuestas) == len(contrapropuestas) else propuestas[-1]) trabajador.payoff = X empresa.payoff = 200 - X
def test_is_numeric(self): numeric_types = (int, float, complex, decimal.Decimal) for value in [0, 1, random.random(), c(1), None, "something"]: actual = self.render( "{{value|is_numeric}}", context={'value': value}) expected = isinstance(value, c) or isinstance(value, numeric_types) self.assertEquals(actual, six.text_type(expected))
def get_context_data(self, **kwargs): session = self.session if session.mturk_HITId: with MTurkConnection( self.request, session.mturk_sandbox ) as mturk_connection: workers_with_submit = [ completed_assignment.WorkerId for completed_assignment in mturk_connection.get_assignments(session.mturk_HITId) ] participants = session.participant_set.filter( mturk_worker_id__in=workers_with_submit ) else: participants = session.get_participants() total_payments = 0.0 mean_payment = 0.0 if participants: total_payments = sum( part.money_to_pay() or c(0) for part in participants ) mean_payment = total_payments / len(participants) context = super(SessionPayments, self).get_context_data(**kwargs) context.update({ 'participants': participants, 'total_payments': total_payments, 'mean_payment': mean_payment, 'participation_fee': session.config['participation_fee'], }) return context
def vars_for_template(self): other = self.player.other_player().claim if self.player.claim < other: reward = Constants.reward penalty = c(0) elif self.player.claim > other: reward = c(0) penalty = Constants.penalty else: reward = c(0) penalty = c(0) return { "reward": reward, "penalty": penalty, "payoff_before_bonus": self.player.payoff - Constants.bonus, "amount_paid_to_both": self.player.payoff - Constants.bonus - reward, }
def vars_for_template(self): other = self.player.other_player().claim if self.player.claim < other: reward = Constants.reward penalty = c(0) elif self.player.claim > other: reward = c(0) penalty = Constants.penalty else: reward = c(0) penalty = c(0) return { 'reward': reward, 'penalty': penalty, 'payoff_before_bonus': self.player.payoff - Constants.bonus, 'amount_paid_to_both': self.player.payoff - Constants.bonus - reward, }
def payoff(self): app_sequence = self.session.config['app_sequence'] total_payoff = 0 for app in app_sequence: models_module = otree.common_internal.get_models_module(app) app_payoff = models_module.Player.objects.filter( participant=self).aggregate(Sum('payoff'))['payoff__sum'] total_payoff += (app_payoff or 0) return c(total_payoff)
def test_currency_non_ascii_character(self): # https://github.com/oTree-org/otree-core/issues/387 with self.settings(REAL_WORLD_CURRENCY_CODE='EUR', USE_POINTS=False): value = Currency(1) template = Template('''{{money}}''') ctx = Context({"money": c(1)}) rendered = template.render(ctx) self.assertIn('€', rendered) self.assertEquals(rendered, six.text_type(value))
def test_json(self): for python_input, expected_output in [ (None, 'null'), (c(1), '1.0'), ("hi", '"hi"'), ({"a": 1}, '{"a": 1}') ]: output = self.render("{{value|json}}", context={'value': python_input}) self.assertEquals(output, expected_output)
def test_strip(self): for value in [0, 1, random.random(), c(1), None, "something "]: if isinstance(value, six.string_types): actual = self.render( "{{value|strip}}", context={'value': value}) expected = value.strip() self.assertEquals(actual, expected) else: with self.assertRaises(AttributeError): self.render("{{value|strip}}", context={'value': value})
def play_round(self): self.submit(views.Introduction) if self.player.id_in_group == 1: self.submit(views.Offer, {'amount_offered': c(10)}) else: if self.group.strategy: self.submit(views.AcceptStrategy, {'response_{}'.format(int(offer)): True for offer in Constants.offer_choices}) else: self.submit(views.Accept, {'offer_accepted': True}) self.submit(views.Results)
def fine_bribe(self): if random.random() > 0.0000001 and (self.fine() > 0): if self.bribe > random.randrange(0, self.fine() * 6): return self.bribe else: self.get_player_by_id(2).participant.vars["uncooperative"] = True return self.fine() else: return c(0)
def vars_for_template(self): p = self.player return { 'answer': [p.training_my_payoff, c(60)], 'explanation': mark_safe(Question1.question + ''' <strong>Solution:</strong> Your payoff would be <strong>60 points</strong>. <strong>Explanation:</strong> As at least one (actually 2)\ participants volunteered, everyone received <strong>100</strong>\ points. You volunteered, so you had to pay <strong>40</strong>\ points. Together you had <strong>100-40=60</strong> points.''') }
def vars_for_template(self): p = self.player return { 'answer': [p.training_my_payoff, c(60)], 'explanation': mark_safe(Question1.question + ''' <strong>Solución:</strong> Su benefición sería de <strong>60 puntos</strong>. <strong>Explicación:</strong> Al menos un (de hecho 2)\ participante se han ofrecido voluntarios, por lo que todos reciben <strong>100</strong>\ puntos. Ha sido voluntario, por lo que paga <strong>40</strong>\ puntos. Junto a la recompensa, obtiene <strong>100-40=60</strong> puntos.''') }
def set_payoff(self): # randomly determine round to pay on player level if self.subsession.round_number == 1: self.session.vars['round_to_pay'] = random.randint(1,Constants.num_rounds) # determine round_result as (potential) payoff per round if self.bomb == 0: self.round_result = c(self.boxes_collected * Constants.box_value) else: self.round_result = c(0) # set payoffs if <random_payoff = True> to round_result of randomly chosen round if Constants.random_payoff == True: if self.subsession.round_number == self.session.vars['round_to_pay']: self.payoff = self.round_result else: self.payoff = c(0) # set payoffs to round_result if <random_payoff = False> else: self.payoff = self.round_result
def test_abs_value(self): for value in [0, 1, random.random(), c(1)]: actual = self.render("{{value|abs}}", context={'value': value}) expected = six.text_type(value) self.assertEquals(actual, expected) nvalue = -value expected = self.render("{{value|abs}}", context={'value': nvalue}) self.assertEquals(actual, expected) with self.assertRaises(TypeError): self.render("{{value|abs}}", context={'value': "foo"}) with self.assertRaises(TypeError): self.render("{{value|abs}}", context={'value': None})
def set_payoffs(self): matcher = self.get_player_by_role('Matcher') mismatcher = self.get_player_by_role('Mismatcher') if matcher.penny_side == mismatcher.penny_side: matcher.is_winner = True mismatcher.is_winner = False else: matcher.is_winner = False mismatcher.is_winner = True for player in [mismatcher, matcher]: if self.subsession.round_number == self.session.vars['paying_round'] and player.is_winner: player.payoff = Constants.stakes else: player.payoff = c(0)
def set_payoff(self): payoff_matrix = { 'Choose 4': { 'Choose 4': Constants.low_low_amount, 'Choose 6': Constants.low_high_amount, }, 'Choose 6': { 'Choose 4': Constants.high_low_amount, 'Choose 6': Constants.high_high_amount, } } # If the player plays this round, determine their payoff as a function of their decision & their partner's decisions if self.group.play_this_round is True: self.payoff = payoff_matrix[self.decision][self.other_player().decision] # If the player sits out this round, mark this with a payoff of -1 else: self.payoff = c(-1)
def set_payoffs(self): matcher = self.get_player_by_role('Matcher') #The argument to this method is a string that looks up the player by their role value. mismatcher = self.get_player_by_role('Mismatcher') #Decide the 'model.BooleanField()' if matcher.penny_side == mismatcher.penny_side: matcher.is_winner = True #matcher has its boolean field of 'is_winner' as 1(True) mismatcher.is_winner = False #matcher has its boolean field of 'is_winner' as 0(False) else: matcher.is_winner = False mismatcher.is_winner = True for player in [mismatcher, matcher]: if (self.subsession.round_number == self.session.vars['paying_round'] and player.is_winner): player.payoff = Constants.stakes else: player.payoff = c(0)
def set_payoffs(self): contrib = [ Constants.offer_value[p.contribution] for p in self.get_players()] self.provision_success = ( sum(contrib) >= Constants.cost + c(2) ) for p in self.get_players(): if self.provision_success: other_bids = [ x.contribution for x in self.get_players() if x!= p] num_L = other_bids.count('Low') num_M = other_bids.count('Median') p.share = Constants.payment[p.contribution][num_L,num_M] p.payoff = Constants.offer_value[p.contribution]-p.share else: p.share = 0 p.payoff = 0
def get_context_data(self, **kwargs): session = self.session if session.mturk_HITId: with MTurkConnection( self.request, session.mturk_sandbox ) as mturk_connection: workers_with_submit = [ completed_assignment.WorkerId for completed_assignment in mturk_connection.get_assignments(session.mturk_HITId) ] participants = session.participant_set.filter( mturk_worker_id__in=workers_with_submit ) else: participants = session.get_participants() total_payments = 0.0 mean_payment = 0.0 if participants: total_payments = sum( part.money_to_pay() or c(0) for part in participants ) mean_payment = total_payments / len(participants) # dictionary for json response # will be used only if json request is done self.context_json = { 'participants': getSerializableObjectWithAttributes(participants, True, props=['payoff_in_real_world_currency','money_to_pay','money_to_pay_display','payoff_in_real_world_currency']), 'total_payments': total_payments, 'mean_payment': mean_payment, 'participation_fee': session.participation_fee, } context = super(SessionPayments, self).get_context_data(**kwargs) context.update({ 'participants': participants, 'total_payments': total_payments, 'mean_payment': mean_payment, 'participation_fee': session.config['participation_fee'], }) return context
def get_context_data(self, **kwargs): session = self.session participants = session.get_participants() total_payments = 0.0 mean_payment = 0.0 if participants: total_payments = sum( part.money_to_pay() or c(0) for part in participants ) mean_payment = total_payments / len(participants) context = super(SessionPayments, self).get_context_data(**kwargs) context.update({ 'participants': participants, 'total_payments': total_payments, 'mean_payment': mean_payment, 'participation_fee': session.config['participation_fee'], }) return context
def sent_back_amount_choices(self): return currency_range(c(0), self.group.sent_amount * Constants.multiplication_factor, c(1))