Example #1
0
class Group(BaseGroup):
    offered_coins = models.CurrencyField(choices=Constants.offered_choices)

    offer_accepted = models.BooleanField()

    punish_dictator = models.BooleanField()

    response_0 = models.BooleanField(widget=widgets.RadioSelectHorizontal())
    response_5 = models.BooleanField(widget=widgets.RadioSelectHorizontal())
    response_10 = models.BooleanField(widget=widgets.RadioSelectHorizontal())

    def set_payoffs(self):
        dictator = self.get_player_by_id(1)
        recipient = self.get_player_by_id(2)
        punisher = self.get_player_by_id(3)
        # if offer is accepted the punisher does not get involved/punish
        if self.offer_accepted:
            if self.amount_offered >= 5:
                dictator.payoff = Constants.endowment - self.amount_offered
                recipient.payoff = self.amount_offered
                punisher.payoff = 0
            else:
                dictator.payoff = Constants.endowment / 2
                recipient.payoff = dictator.payoff
                punisher.payoff = dictator.payoff

        # if the offer is rejected the punisher get invoved and deducts payoff
        # from the dictator or player one
        elif self.punish_dictator:
            # dictators pay is cut in half by the punisher
            dictator.payoff = Constants.endowment / 2
            # recipient gets a quater off the dictators payoff
            recipient.payoff = (dictator.payoff / 2) / 4
            # punisher gets a quater off the dictators payoff
            punisher.payoff = (dictator.payoff / 2) / 4
Example #2
0
class Player(BasePlayer):

    health = models.PositiveIntegerField(min=0, max=Constants.max_health)
    resources = models.PositiveIntegerField(min=0)

    use_toilet = models.BooleanField(widget=widgets.RadioSelectHorizontal())
    small_cleaning = models.BooleanField(widget=widgets.RadioSelectHorizontal())

    big_clean = models.BooleanField(widget=widgets.RadioSelectHorizontal())
Example #3
0
class Player(BasePlayer):
    health = models.FloatField(min=0, max=Constants.max_health_condition)
    resources = models.FloatField(min=0)
    resources_overflow = models.FloatField(min=0)

    use_toilet = models.BooleanField(widget=widgets.RadioSelectHorizontal())
    small_cleaning = models.BooleanField(
        widget=widgets.RadioSelectHorizontal())

    big_clean = models.BooleanField(widget=widgets.RadioSelectHorizontal())
Example #4
0
class Player(BasePlayer):
    def score_round(self):
        # update player payoffs
        if (self.solution == self.user_total):
            self.is_correct = True
            self.payoff_score = 1
        else:
            self.is_correct = False
            self.payoff_score = c(0)

    task_timer = models.PositiveIntegerField(
        doc="""The length of the real effort task timer.""")

    int1 = models.PositiveIntegerField(doc="this round's first int")

    int2 = models.PositiveIntegerField(doc="this round's second int")

    solution = models.PositiveIntegerField(
        doc="this round's correct summation")

    user_total = models.PositiveIntegerField(
        min=1,
        max=9999,
        doc="user's summation",
        widget=widgets.TextInput(attrs={'autocomplete': 'off'}))

    is_correct = models.BooleanField(doc="did the user get the task correct?")

    payoff_score = models.FloatField(doc='''score in this task''')
Example #5
0
class Player(BasePlayer):

    def score_round(self):
        # update player payoffs
        if (self.correct_text == self.user_text):
            self.is_correct = True
            self.payoff_score = 1
        else:
            self.is_correct = False
            self.payoff_score = 0


    task_timer = models.PositiveIntegerField(
        doc="""The length of the real effort task timer."""
    )

    correct_text = models.CharField(
        doc="user's transcribed text")

    user_text = models.CharField(
        doc="user's transcribed text",
        widget=widgets.TextInput(attrs={'autocomplete':'off'}))

    is_correct = models.BooleanField(
        doc="did the user get the task correct?")

    ret_final_score = models.IntegerField(
        doc="player's total score up to this round")

    payoff_score = models.FloatField(
            doc = '''score in this task'''
        )
Example #6
0
class Group(BaseGroup):
    # variables that change for each group
    treatment_endowment = models.IntegerField()
    treatment_treatment = models.TextField()
    a_takes = models.DecimalField(min=0, max=100, max_digits=5, decimal_places=2)
    total_taken = models.CurrencyField()
    b_predicts = models.PositiveIntegerField(min=0, max=100)
    b_willing = models.DecimalField(min=0, max_digits=6, decimal_places=3)
    b_message = models.TextField()
    b_message_price = models.DecimalField(max_digits=5, decimal_places=2)
    price_method = models.TextField()
    price_display = models.TextField()
    b_eligible = models.BooleanField()
    target_income = models.DecimalField(max_digits=5, decimal_places=2)
    reader_index = models.IntegerField()

    def final_pay(self):
        p1 = self.get_player_by_id(1)
        p2 = self.get_player_by_id(2)
        p1.final_reward = self.treatment_endowment+ p1.task_reward + self.total_taken

        if self.price_method != 'WTA':
            if self.b_eligible:
                p2.final_reward = self.treatment_endowment+ p2.task_reward - self.total_taken - self.b_message_price
            else:
                p2.final_reward = self.treatment_endowment + p2.task_reward - self.total_taken
        else:  # WTA
            if self.b_eligible:
                p2.final_reward = self.treatment_endowment + p2.task_reward - self.total_taken
            else:  # gave up right to send message
                p2.final_reward = self.treatment_endowment + p2.task_reward - self.total_taken + self.b_message_price

    def reader_pay(self):
        for p in self.get_players():
            p.final_reward = self.treatment_endowment + p.task_reward
Example #7
0
class Player(BasePlayer):

    ret_timer = models.PositiveIntegerField(
        doc="""The length of the real effort task timer.""")
    user_text = models.CharField(doc="user's transcribed text")
    is_correct = models.BooleanField(doc="did the user get the task correct?")
    ret_final_score = models.IntegerField(
        doc="player's total score up to this round")
    round_payoff = models.FloatField(
        doc=
        "total number of correct real effort tasks, completed before timer expired"
    )

    def set_final_score(self):
        correct_cnt = 0
        for p in self.in_all_rounds():
            if p.round_payoff != None:
                correct_cnt = correct_cnt + p.round_payoff
            else:
                correct_cnt = correct_cnt + 0

        if correct_cnt == None:
            self.ret_final_score = 20
        elif (correct_cnt < 10):
            self.ret_final_score = 2 + (2 * correct_cnt)
        else:
            self.ret_final_score = 20
Example #8
0
class Player(BasePlayer):
    user_text = models.CharField(
    	doc="user's transcribed text")
    is_correct = models.BooleanField(
    	doc="did the user get the task correct?")
    final_score = models.IntegerField(
    	doc="player's total score up to this round")


    quiz_01 = models.PositiveIntegerField(
        verbose_name='Your earnings:',
        min = 0,
        max = 999,
        initial=None,
        doc='quiz answer')
      
    quiz_02 = models.PositiveIntegerField(
        verbose_name='Your earnings:',
        min = 0,
        max = 999,
        initial=None,
        doc='quiz answer')

    quiz_03 = models.PositiveIntegerField(
        verbose_name='Your earnings:',
        min = 0,
        max = 999,
        initial=None,
        doc='quiz answer')
      
    quiz_04 = models.FloatField(
        verbose_name='Your earnings:',
        min = 0,
        max = 999,
        initial=None,
        doc='quiz answer')
      
    quiz_05 = models.FloatField(
        verbose_name='Your earnings:',
        min = 0,
        max = 999,
        initial=None,
        doc='quiz answer')
      
    quiz_06= models.FloatField(
        verbose_name='Your earnings:',
        min = 0,
        max = 999,
        initial=None,
        doc='quiz answer')
      
    quiz_07 = models.FloatField(
        verbose_name='Your earnings:',
        min = 0,
        max = 999,
        initial=None,
        doc='quiz answer')
Example #9
0
class Group(BaseGroup):

    strategy = models.BooleanField(
    doc="""Whether this group uses strategy method"""
        )

    amount_offered = models.CurrencyField(choices=Constants.offer_choices)

    offer_accepted = models.BooleanField(
        doc="if offered amount is accepted (direct response method)"
    )

    def set_payoffs(self):
        p1, p2, p3 = self.get_players()

        if self.strategy:
            self.offer_accepted = getattr(self, 'response_{}'.format(int(self.amount_offered)))

        if self.offer_accepted:
            p1.payoff = Constants.endowment - self.amount_offered
            p2.payoff = self.amount_offered
Example #10
0
class Player(BasePlayer):
    penny_side = models.CharField(
    choices=['Heads','Tails'],
    widget=widgets.RadioSelect()
    )
    
    is_winner = models.BooleanField()
    
    def role(self):
        if self.id_in_group == 1:
            return 'Mismatcher'
        if self.id_in_group == 2:
            return 'Matcher'
Example #11
0
class Subsession(BaseSubsession):

    reader_message = models.TextField()
    debug_mode = models.BooleanField()
    vid_url = models.TextField()
    def before_session_starts(self):
        group_matrix = []
        empty_messages = []
        readers = max(self.session.config['readerSelection'])

        for reader in range(0, readers):
            empty_messages.append([])
            #  print(empty_messages)
            #  print(reader)
        self.reader_message = json.dumps(empty_messages)

        for grouping in self.session.config["group"]:
            print(grouping)
            # assigns groups based on array values in cofig
            group_matrix.append(grouping)

        self.set_group_matrix(group_matrix)
        self.debug_mode = self.session.config['debug']
        unparsed_video = self.session.config['video']
        vid_url = unparsed_video.split('v=')[1]

        i = 0
        for groupx in self.get_groups():
            groupx.treatment_endowment = self.session.config['endowment'][i]
            groupx.treatment_treatment = self.session.config['treatment'][i]
            groupx.target_income = self.session.config['targetIncome'][i]
            groupx.reader_index = self.session.config['readerSelection'][i]
            groupx.price_method = self.session.config['method'][i]
            for user in groupx.get_players():
                user.p_role = self.session.config['role'][i][user.id_in_group-1]
                # user.task_reward = user.participant.vars['task_income']
                # user.intermediate_reward = user.participant.vars['task_income'] + groupx.treatment_endowment

            if groupx.treatment_treatment == 'FM':
                groupx.b_eligible = True
                groupx.b_message_price = 0
            else:
                if self.session.config['price'][i] == -1: # -1 is encoding for random price
                    groupx.b_message_price = random.randrange(0, 300) / 100
                    # list vs cont only applies with WTP or WTA, not SOP
                    groupx.price_display = self.session.config['priceDisplay'][i]
                else:
                    groupx.b_message_price = self.session.config['price'][i]
            i += 1
        # message price is different (random) for every group
        print("finished set up before session starts")
Example #12
0
class Player(BasePlayer):

    q3_second_game_surprised = models.PositiveIntegerField(
        min=1, max=5, widget=widgets.SliderInput(show_value=False))
    q3_second_game_satisfied = models.PositiveIntegerField(
        min=1, max=5, widget=widgets.SliderInput(show_value=False))
    q3_second_game_upset = models.PositiveIntegerField(
        min=1, max=5, widget=widgets.SliderInput(show_value=False))

    q3_help_each_other_in_the_second_game = models.PositiveIntegerField(
        min=1, max=5, widget=widgets.SliderInput(show_value=False))
    q3_team_spirit = models.PositiveIntegerField(
        min=1, max=5, widget=widgets.SliderInput(show_value=False))
    q3_recommendations_of_actions_to_maximize_everyones_resources = models.PositiveIntegerField(
        min=1, max=5, widget=widgets.SliderInput(show_value=False))

    q3_i_follow_recommendations_of_action_followed = models.PositiveIntegerField(
        min=1, max=5, widget=widgets.SliderInput(show_value=False))
    q3_i_follow_recommendations_of_action_my_advantage = models.PositiveIntegerField(
        min=1, max=5, widget=widgets.SliderInput(show_value=False))

    q3_others_follow_recommendations_of_action_followed = models.PositiveIntegerField(
        min=1, max=5, widget=widgets.SliderInput(show_value=False))
    q3_others_follow_recommendations_of_action_their_advantage = models.PositiveIntegerField(
        min=1, max=5, widget=widgets.SliderInput(show_value=False))

    q3_yopinion_if_they_followed_would_everyone_max_his_resources = models.PositiveIntegerField(
        min=1, max=5, widget=widgets.SliderInput(show_value=False))

    q3_second_game_different_and_is_it_because_of_the_communication = models.TextField(
    )
    q3_the_best_strategy_to_optimize_everyones_resources = models.TextField()

    q3_gender = models.CharField(choices=["Male", "Female"],
                                 widget=widgets.RadioSelectHorizontal())
    q3_birthday = models.DateField(widget=widgets.Input())

    q3_main_subject_in_university = models.TextField()
    q3_already_take_part_in_a_problem_solving = models.BooleanField(
        widget=widgets.RadioSelectHorizontal())

    q3_experiment_itself_was_interessting = models.PositiveIntegerField(
        min=1, max=5, widget=widgets.SliderInput(show_value=False))
    q3_were_you_personally_engaged_achieving_good_results = models.PositiveIntegerField(
        min=1, max=5, widget=widgets.SliderInput(show_value=False))
    q3_dificult_understanding_and_solving_the_problem = models.PositiveIntegerField(
        min=1, max=5, widget=widgets.SliderInput(show_value=False))
    q3_was_it_obvious_what_to_do = models.PositiveIntegerField(
        min=1, max=5, widget=widgets.SliderInput(show_value=False))
    q3_short_feedback = models.TextField()
Example #13
0
class Player(BasePlayer):

    mpcr = models.FloatField(doc='''marginal per capital reutrn ''')

    is_correct = models.BooleanField(doc="did the user get the task correct?")
    final_score = models.IntegerField(
        doc="player's total score up to this round")
    quiz_text = models.CharField(doc="quiz question")
    quiz_sol = models.IntegerField(doc="solution")
    quiz_user_answer = models.FloatField(verbose_name='Your answer:',
                                         min=0,
                                         max=999,
                                         initial=None,
                                         doc='quiz answer')
    quiz_sol_text = models.CharField(doc="solution text")
Example #14
0
    def before_session_starts(self):

        if self.round_number == 1:
            for p in self.get_players():
                if 'treatment' in self.session.config:
                    # demo mode
                    p.participant.vars['TT'] = self.session.config['treatment']
                else:
                    p.participant.vars['TT'] = random.choice(
                        ['T1', 'T2', 'T3'])

        # end
        end = models.BooleanField(initial=False)
        pEnd = models.FloatField()

        numpy.random.uniform(low=0, high=1, size=1)
Example #15
0
class Group(BaseGroup):

    ##--------------------------------
    ## local variables
    total_catch   = models.FloatField()
    total_profit  = models.FloatField()
    #payoff_tab   = [None] * Constants.nb_catch_choice
    b_round       = models.FloatField()
    y             = models.FloatField()

    # Threshold and uncertainty range
    Blim_min      = models.FloatField()
    Blim_max      = models.FloatField()
    b_lim         = models.FloatField()

    # Biomass uncertainty
    bmin_round = models.FloatField()
    bmax_round = models.FloatField()

    # end
    end        = models.BooleanField(initial=False)

    ## projection variables and uncertainty range

    ##--------------------------------
    ## standard functions

    ## ending wqhen stock collapse
    def end(self):
        self.end = True
        #self.subsession.round_number = Constants.num_rounds

    ## compute nb of nested list
    def number_of_lists(x):
        f = lambda x: 0 if not isinstance(x, list) else (f(x[0]) + f(x[1:]) if len(x) else 1)
        return f(x) - 1

    ## compute current year
    def year(self):
        y = Constants.init_year + self.subsession.round_number - 1
        return y

    ## compute payoff (10^3 $), profit by player see protocol
    def compute_payoff(self , stock, harvest=0, harvestInd=0):

        if (harvest+harvestInd) == 0:
            prop=0
        else:
            prop=harvestInd/(harvest+harvestInd)

        if stock <= 0:
            prof = 0
        else:
            if self.session.config['treatment']=='T1':
                if self.subsession.round_number == 1:
                    prof = round((Constants.price_fish * harvestInd) -
                             (Constants.beta *(math.log(self.growth(b=Constants.init_biomass)) -
                                               math.log(self.growth(b=Constants.init_biomass) - (harvest+harvestInd)))*(prop)),1)
                else:
                    if harvestInd == 0:
                        prof = 0
                    elif stock - (harvest+harvestInd) <= 0:
                            prof = round((-Constants.beta * 2) * (prop),1)
                    else:
                            prof = round((Constants.price_fish * harvestInd) -
                                 (Constants.beta * (math.log(self.growth(b=stock)) -
                                                    math.log(self.growth(b=stock) - (harvest+harvestInd))) * (prop)), 1)
            else:
                if self.subsession.round_number == 1:
                    prof = round((Constants.price_fish * harvestInd) -
                             (Constants.beta * (math.log(self.growth(b=Constants.init_biomass)) -
                                                math.log(self.growth(b=Constants.init_biomass) - (harvest+harvestInd)))*(prop)), 1)
                else:
                    if stock <= Constants.Blim:
                        if harvestInd == 0:
                            prof = - Constants.tFixedCost
                        elif stock - (harvest + harvestInd) <= 0:
                            prof = round(((-Constants.beta * 2) * (prop))- Constants.tFixedCost,1)
                        else:
                            prof = round((Constants.price_fish * harvestInd) - Constants.tFixedCost -
                                         (Constants.beta * (math.log(self.growth(b=stock)) -
                                                            math.log(self.growth(b=stock) - (harvest + harvestInd))) * (
                                          prop)), 1)
                    elif stock > Constants.Blim:
                        if harvestInd == 0:
                            prof = 0
                        elif stock - (harvest + harvestInd) <= 0:
                            prof = round((-Constants.beta * 2) * (prop),1)
                        else:
                            prof = round((Constants.price_fish * harvestInd) -
                                         (Constants.beta * (math.log(self.growth(b=stock)) -
                                                            math.log(self.growth(b=stock) - (harvest + harvestInd))) * (
                                          prop)), 1)

        return prof

    def compute_payoff_test(self, stock, harvest=0, harvestInd=0):

        if (harvest + harvestInd) == 0:
            prop = 0
        else:
            prop = harvestInd / (harvest + harvestInd)

        if stock <= 0:
            prof = 0
        else:
            if self.session.config['treatment'] == 'T1':
                if stock - (harvest + harvestInd) <= 0:
                    prof =round((-Constants.beta * 2) * (prop),1)
                else:
                    prof = round((Constants.price_fish * harvestInd) -
                            (Constants.beta * (math.log(self.growth(b=stock)) -
                                                    math.log(self.growth(b=stock) - (harvest + harvestInd))) * (prop)),1)
            else:
                if stock <= Constants.Blim:
                        if harvestInd == 0:
                            prof =  - Constants.tFixedCost
                        elif stock - (harvest + harvestInd) <= 0:
                            prof = round(((-Constants.beta * 2) * (prop))- Constants.tFixedCost, 1)
                        else:
                            prof = round((Constants.price_fish * harvestInd) - Constants.tFixedCost -
                                     (Constants.beta * (math.log(self.growth(b=stock)) -
                                                        math.log(self.growth(b=stock) - (harvest + harvestInd))) * (
                                      prop)), 1)
                elif stock > Constants.Blim:
                        if harvestInd == 0:
                            prof = 0
                        elif stock - (harvest + harvestInd) <= 0:
                            prof = round((-Constants.beta * 2) * (prop), 1)
                        else:
                            prof = round((Constants.price_fish * harvestInd) -
                                     (Constants.beta * (math.log(self.growth(b=stock)) -
                                                        math.log(self.growth(b=stock) - (harvest + harvestInd))) * (
                                      prop)), 1)

        return prof

    ## biomass schaefer dynamic
    def schaefer(self, b, c=0):
        if b <= 0:
            biomass = 0
        else:
            biomass = round(b + (Constants.growth_rate * b) * (1 - (b / Constants.carrying_capacity)) - c, 0)

        return biomass  # []

    ## Growth function
    def growth(self, b):
        biomass = round(b + (Constants.growth_rate * b) * (1 - (b / Constants.carrying_capacity)) , 0)

        return biomass  # []

    ##--------------------------------
    ## upadating functions

    ## update payoff table
    def set_payoffTable(self):
        payoff_tab = [[] for _ in range(Constants.nb_catch_choice)]
        inc = -1
        for i in Constants.choice_catch:
            inc = inc + 1
            for j in Constants.other_choice_catch:
               # if i == 0 & j == 0:
                    payoff_tab[inc].append(self.compute_payoff(harvest=j, harvestInd=i, stock=self.b_round))
               # else:
                  #  if (self.b_round - (j + i)) <= 0:
                  #      payoff_tab[inc].append(Constants.max_negative_profit)
                   # else:
                   #     payoff_tab[inc].append(self.compute_payoff(harvest=j, harvestInd=i, stock=self.b_round))

        return (payoff_tab)

    def set_payoffTable_test(self,biomasse=Constants.b_test):
        payoff_tab = [[] for _ in range(Constants.nb_catch_choice)]
        inc = -1
        for i in Constants.choice_catch:
            inc = inc + 1
            for j in Constants.other_choice_catch:
                #if i == 0 & j == 0:
                    payoff_tab[inc].append(self.compute_payoff_test(harvest=j, harvestInd=i, stock=biomasse))
                #else:
                #   if (biomasse - (j + i)) <= 0:
                #        payoff_tab[inc].append(Constants.max_negative_profit)
                #    else:
                #        payoff_tab[inc].append(self.compute_payoff_test(harvest=j, harvestInd=i, stock=biomasse))

        return (payoff_tab)

    ## update payoff for the year by player
    def set_payoffs(self):

        if self.b_round > 0:

            self.total_catch = sum([p.catch_choice for p in self.get_players()])
            if self.subsession.round_number == 1:

                for p in self.get_players():
                    p.profit = round(self.compute_payoff(harvestInd=p.catch_choice,harvest=(self.total_catch-p.catch_choice),
                                                stock=Constants.init_biomass),1) + Constants.baseProfit
                    p.payoff = round( (self.compute_payoff(harvestInd=p.catch_choice,harvest=(self.total_catch-p.catch_choice),
                                                stock=Constants.init_biomass) + Constants.baseProfit )* Constants.convertionCurrency,1)
            else:

                for p in self.get_players():
                    p.profit = round(self.compute_payoff(harvestInd=p.catch_choice,harvest=(self.total_catch-p.catch_choice),
                                                   stock=self.b_round),1)
                    p.payoff = round(self.compute_payoff(harvestInd=p.catch_choice, harvest=(self.total_catch - p.catch_choice),
                                                   stock=self.b_round) * Constants.convertionCurrency,1)

            self.total_profit = round(sum([p.profit for p in self.get_players()]),1)
            self.b_lim        = Constants.Blim

    ## update payoff and only payoff for player who best predict others harvest
    def set_payoff_prediction(self):
        for p in self.get_players():
            if self.b_round > 0:
                if p.other_choice == self.total_catch - p.catch_choice:
                    p.payoff = p.payoff + Constants.anticipation
                    p.predProfit = p.predProfit + Constants.anticipation

    ## update biomass for the next year
    def set_biomass(self):
            bplus = models.FloatField()
            ctot  = models.FloatField()

            if self.subsession.round_number == 1:
                self.b_round = Constants.init_biomass

            elif self.subsession.round_number == 2:
                ctot = sum([p.in_round(self.subsession.round_number - 1).catch_choice for p in self.get_players()])
                for i in self.in_previous_rounds():
                    bplus = i.b_round
                self.b_round = bplus - ctot

            else:
                ctot  = sum([p.in_round(self.subsession.round_number -1).catch_choice for p in self.get_players()])

                for i in self.in_previous_rounds():
                    bplus = i.b_round

                self.b_round = self.schaefer(b=bplus, c=ctot)

    ##--------------------------------
    ## scientific advice

    ## function uncertainty around Blim for all rounds
    def set_Un_Blim(self):
        # uncertainty bounds around Blim
        self.Blim_max = Constants.Blim + (Constants.Blim * Constants.Blim_uncertainty)
        self.Blim_min = Constants.Blim - (Constants.Blim * Constants.Blim_uncertainty)

    ## function variation for each catch level
    def variation(self):
        var = [[] for _ in range(Constants.nb_catch_choice)]
        s   = models.FloatField()
        inc = -1

        if self.subsession.round_number == 1:
            for i in Constants.choice_catch:
                inc = inc + 1
                for j in Constants.other_choice_catch:
                    s = Constants.init_biomass - (i + j)
                    var[inc].append(round(((s - Constants.init_biomass) / Constants.init_biomass) * 100))
        else:
            for i in Constants.choice_catch:
                inc = inc + 1
                for j in Constants.other_choice_catch:
                    s = self.schaefer( b=self.b_round, c=(i + j))
                    var[inc].append(round(((s - self.b_round) / self.b_round)*100))

        return(var)

    ## function projection for 10 years
    def projection(self):
        proj = []
        bint = models.FloatField()
        proj.append(self.b_round)

        if self.subsession.round_number == 1:
            for i in Constants.sim_years:
                bint = proj[i] - self.total_catch
                if i == 1:
                    proj.append(bint)
                else:
                    proj.append(round(self.schaefer(bint, c=0), 0))
        else:
            for i in Constants.sim_years:
                bint = proj[i] - self.total_catch
                proj.append(round(self.schaefer(bint, c=0),0))

        return (proj)

    ## function uncertainty around projection for 10 years
    ##!!!!!!!!! attention pb correspondance avec l'incertitude sur le stock!!

    def projUncertainty(self):
        unrange = []
        b_range = []
        b_unrange = []
        un = []
        b_proj = self.projection()

        # uncertainty bounds around real projection
        for meanNorm in arange(Constants.uncertainty, Constants.max_uncertainty,
                               (Constants.max_uncertainty - Constants.uncertainty) / (len(Constants.sim_years))):
            un.append(numpy.random.normal(loc=round(meanNorm,3), scale=round(meanNorm,3) / 10))

        upperUn = numpy.round(numpy.asarray(b_proj[0:Constants.nb_sim_years]) * (1 + numpy.asarray(un)[0:Constants.nb_sim_years]),1)
       # upUN.append([int(x) for x in upperUn])

        lowerUn = numpy.round(numpy.asarray(b_proj[0:Constants.nb_sim_years]) * (1 - numpy.asarray(un)[0:Constants.nb_sim_years]),1)
        #lwUN.append([int(x) for x in lowerUn])
        range = numpy.vstack((upperUn, lowerUn)).T
        unrange.append(range.tolist())
        b_unrange.append(unrange)

        return (b_unrange)
Example #16
0
class Player(BasePlayer):

    # create a column for each constant
    num_rounds = models.PositiveIntegerField()
    treatment = models.BooleanField()
    tax_rate = models.FloatField()

    # give each player a letter for identification (Important for Feedback)
    def role(self):
        return string.ascii_uppercase[self.id_in_group - 1]

    # Beliefs Variables

    investment_belief_0 = models.FloatField()
    investment_belief_1 = models.FloatField()

    production_belief_0 = models.PositiveIntegerField()
    production_belief_1 = models.PositiveIntegerField()

    # Contest Variables
    is_winner = models.BooleanField(
        initial=False,
        doc=
        """Indicates whether the player is the winner of the Tullock Contest"""
    )

    prob = models.FloatField(
        doc="Probabilities of getting the Prize in the next round. Tullock")

    prob_percent = models.FloatField(
        doc=
        "Probabilities in percent of getting the prize in next round. Tullock")
    investment_amount = models.FloatField(default=0,
                                          doc="Amount bidden by the player")

    # Real Effort Task variables
    # Number of Tasks Solved
    production_strings = models.FloatField(default=0)
    income_in_switch = models.FloatField(default=0)
    total_production = models.FloatField(
        default=0
    )  # the sum in tokens of earnings from string solving (gross) and switch

    # available income after solving RET
    income_strings_gross = models.FloatField(default=0)
    income_strings_after_tax = models.FloatField(default=0)
    income_after_redistribution = models.FloatField(default=0)
    net_income = models.FloatField(default=0)
    available_income = models.FloatField(
        default=0)  # what players are allowed to invest
    earnings = models.FloatField(
        default=0)  # what players keep after redistribution *and* investment
    taxation = models.FloatField(
        default=0)  # amount taxed for given participant

    # Variable is 1 when entering switch
    switch1 = models.PositiveIntegerField(
        default=0)  # word "switch" cannot be used as a variable in javascript

    switch_time = models.PositiveIntegerField(default=0)

    time_in_switch = models.PositiveIntegerField(default=0)

    additional_time = models.PositiveIntegerField(default=0)

    # correct to allow a variable number of tasks
    # for now, created with:
    # for i in range(10, 46):
    # print('t1{} = models.PositiveIntegerField(default=0)'.format(i))

    # def set_time_fields(self):
    #     for i in range(31):
    #         self.participant.vars['t1{}'.format(i)] = models.PositiveIntegerField(default=0)
    #     print(self.participant.vars)

    # Time Needed to Solve Task i in Round j with tjxi
    t101 = models.PositiveIntegerField(default=0)
    t102 = models.PositiveIntegerField(default=0)
    t103 = models.PositiveIntegerField(default=0)
    t104 = models.PositiveIntegerField(default=0)
    t105 = models.PositiveIntegerField(default=0)
    t106 = models.PositiveIntegerField(default=0)
    t107 = models.PositiveIntegerField(default=0)
    t108 = models.PositiveIntegerField(default=0)
    t109 = models.PositiveIntegerField(default=0)
    t110 = models.PositiveIntegerField(default=0)
    t111 = models.PositiveIntegerField(default=0)
    t112 = models.PositiveIntegerField(default=0)
    t113 = models.PositiveIntegerField(default=0)
    t114 = models.PositiveIntegerField(default=0)
    t115 = models.PositiveIntegerField(default=0)
    t116 = models.PositiveIntegerField(default=0)
    t117 = models.PositiveIntegerField(default=0)
    t118 = models.PositiveIntegerField(default=0)
    t119 = models.PositiveIntegerField(default=0)
    t120 = models.PositiveIntegerField(default=0)
    t121 = models.PositiveIntegerField(default=0)
    t122 = models.PositiveIntegerField(default=0)
    t123 = models.PositiveIntegerField(default=0)
    t124 = models.PositiveIntegerField(default=0)
    t125 = models.PositiveIntegerField(default=0)
    t126 = models.PositiveIntegerField(default=0)
    t127 = models.PositiveIntegerField(default=0)
    t128 = models.PositiveIntegerField(default=0)
    t129 = models.PositiveIntegerField(default=0)
    t130 = models.PositiveIntegerField(default=0)
    t131 = models.PositiveIntegerField(default=0)
    t132 = models.PositiveIntegerField(default=0)
    t133 = models.PositiveIntegerField(default=0)
    t134 = models.PositiveIntegerField(default=0)
    t135 = models.PositiveIntegerField(default=0)
    t136 = models.PositiveIntegerField(default=0)
    t137 = models.PositiveIntegerField(default=0)
    t138 = models.PositiveIntegerField(default=0)
    t139 = models.PositiveIntegerField(default=0)
    t140 = models.PositiveIntegerField(default=0)
    t141 = models.PositiveIntegerField(default=0)
    t142 = models.PositiveIntegerField(default=0)
    t143 = models.PositiveIntegerField(default=0)
    t144 = models.PositiveIntegerField(default=0)
    t145 = models.PositiveIntegerField(default=0)

    def set_switch(self):
        # Time at which switch was entered
        self.switch_time = self.switch1 * (
            self.additional_time + self.t101 + self.t102 + self.t103 +
            self.t104 + self.t105 + self.t106 + self.t107 + self.t108 +
            self.t109 + self.t110 + self.t111 + self.t112 + self.t113 +
            self.t114 + self.t115 + self.t116 + self.t117 + self.t118 +
            self.t119 + self.t120 + self.t121 + self.t122 + self.t123 +
            self.t124 + self.t125 + self.t126 + self.t127 + self.t128 +
            self.t129 + self.t130 + self.t131 + self.t132 + self.t133 +
            self.t134 + self.t135 + self.t136 + self.t137 + self.t138 +
            self.t139 + self.t140 + self.t141 + self.t142 + self.t143 +
            self.t144 + self.t145)

        # This variable determines the total time spent in switch
        self.time_in_switch = self.switch1 * (Constants.t - self.switch_time)

        # This variable determines the tokens per string received
        self.income_in_switch = self.time_in_switch / Constants.secondsper_token

        # This is the sum of strings + production in switch
        self.total_production = self.production_strings + self.income_in_switch
Example #17
0
class Group(BaseGroup):

    # attacker
    a_choice = models.CharField(choices=[
        'Attack Defender',
        'Attack User',
        'No Attack'],
        verbose_name='Please select your action', doc = """Attacker choice""",
        widget=widgets.RadioSelect())
    # defender
    d_choice = models.CharField(choices=[
        'Standard Security',
        'Enhanced Security'],
        verbose_name='Please select your action', doc = """Defender choice""",
        widget=widgets.RadioSelect())

    # user
    u_choice = models.CharField(choices=[
        'Standard Security',
        'Enhanced Security'],
        verbose_name='Please select your action', doc = """User choice""",
        widget=widgets.RadioSelect())

    p_success = models.FloatField(default=0)

    atk_success = models.BooleanField(
        doc="""Whether an attack was successful"""
    )

    no_atk = models.BooleanField(
        doc="""Whether there is no attack"""
    )

    message = models.CharField(doc="""message displayed to all""")

    a_cost = models.CurrencyField()
    d_cost = models.CurrencyField()
    u_cost = models.CurrencyField()

    a_pay = models.CurrencyField()
    d_pay = models.CurrencyField()
    u_pay = models.CurrencyField()

    a_cum = models.CurrencyField()
    d_cum = models.CurrencyField()
    u_cum = models.CurrencyField()

    a_skipped = models.BooleanField()
    d_skipped = models.BooleanField()
    u_skipped = models.BooleanField()

    def set_payoffs(self):

        attacker = self.get_player_by_role('attacker')
        defender = self.get_player_by_role('defender')
        user = self.get_player_by_role('user')

        #rand=random.random()

        if self.a_choice == 'Attack Defender':
            self.a_cost = Constants.ACostD
        elif self.a_choice == 'Attack User':
            self.a_cost = Constants.ACostU
        elif self.a_choice == 'No Attack':
            self.a_cost = Constants.ACostNo

        if self.d_choice == 'Standard Security':
            self.d_cost = Constants.DCostLS
        elif self.d_choice == 'Enhanced Security':
            self.d_cost = Constants.DCostHS

        if self.u_choice == 'Standard Security':
            self.u_cost = Constants.UCostLS
        elif self.u_choice == 'Enhanced Security':
            self.u_cost = Constants.UCostHS

        if self.a_choice == 'Attack Defender':
            if self.d_choice == 'Standard Security':
                self.p_success = Constants.D_SProb_UHDH
        elif self.a_choice == 'Attack User':
            if self.u_choice == 'Standard Security':
                if self.d_choice == 'Standard Security':
                    self.p_success = Constants.U_SProb_ULDL
                elif self.d_choice == 'Enhanced Security':
                    self.p_success = Constants.U_SProb_ULDH
            elif self.u_choice == 'Enhanced Security':
                if self.d_choice == 'Standard Security':
                    self.p_success = Constants.U_SProb_UHDL
                elif self.d_choice == 'Enhanced Security':
                    self.p_success = Constants.U_SProb_UHDH
        elif self.a_choice == 'No Attack':
            self.no_atk = True
            self.p_success = 0

        rand=random.random()
        if self.a_choice == 'No Attack':
            self.message = Constants.no_atk_msg
            attacker.payoff = Constants.APayoff_No
            defender.payoff = Constants.DPayoff_No
            user.payoff = Constants.UPayoff_No
        else:
            if rand < self.p_success:
                self.atk_success = True
                self.message = Constants.success_msg
            elif rand > self.p_success:
                self.atk_success = False
                self.message = Constants.fail_msg

        if self.atk_success is True:
            if self.a_choice == 'Attack Defender':
                attacker.payoff = Constants.APayoff_DefS
                defender.payoff = Constants.DPayoff_DefS
                user.payoff = Constants.UPayoff_DefS
            elif self.a_choice == 'Attack User':
                attacker.payoff = Constants.APayoff_UseS
                defender.payoff = Constants.DPayoff_UseS
                user.payoff = Constants.UPayoff_UseS
        elif self.atk_success is False:
            if self.a_choice == 'Attack Defender':
                attacker.payoff = Constants.APayoff_DefF
                defender.payoff = Constants.DPayoff_DefF
                user.payoff = Constants.UPayoff_DefF
            elif self.a_choice == 'Attack User':
                attacker.payoff = Constants.APayoff_UseF
                defender.payoff = Constants.DPayoff_UseF
                user.payoff = Constants.UPayoff_UseF

        self.a_pay = attacker.payoff
        self.d_pay = defender.payoff
        self.u_pay = user.payoff

        if self.subsession.round_number in self.session.vars['paying_rounds']:
            if self.a_skipped:
                self.a_cum = 0
            else:
                self.a_cum = attacker.payoff
            if self.d_skipped:
                self.d_cum = 0
            else:
                self.d_cum = defender.payoff
            if self.u_skipped:
                self.u_cum = 0
            else:
                self.u_cum = user.payoff
        else:
            self.a_cum = 0
            self.d_cum = 0
            self.u_cum = 0
Example #18
0
class Player(BasePlayer):
    test = models.CharField(choices=["test1", "test2", "test3"])
    intensity_group = models.CharField(choices=Constants.c_groups)
    balls_before_draw = models.CharField()
    balls_after_draw = models.CharField()
    ball_position_drawn = models.IntegerField()
    game_played = models.CharField(choices=Constants.c_games)
    offer_0 = models.FloatField()
    price_0 = models.FloatField()
    won_offer_price = models.BooleanField()
    give_shock = models.IntegerField(choices=[0, 1])

    def set_ballsbeforedraw(self, x):
        self.balls_before_draw = json.dumps(x)

    def get_ballsbeforedraw(self):
        return json.loads(self.balls_before_draw)

    def set_ballsafterdraw(self, x):
        self.balls_after_draw = json.dumps(x)

    def get_ballsafterdraw(self):
        return json.loads(self.balls_after_draw)

    def determine_and_apply_drawing_result(self):
        if self.price_0 > self.offer_0:
            self.won_offer_price = False
        else:
            self.won_offer_price = True
        if self.won_offer_price:
            if self.game_played == '1ball':
                # '1ball': Exchange 1 red ball
                temp = self.get_ballsafterdraw()
                temp[temp.index(
                    Constants.c_ball_colors[1])] = Constants.c_ball_colors[0]
                self.set_ballsafterdraw(temp)
            elif self.game_played == '2balls':
                # '2balls': Exchange 2 red balls
                temp = self.get_ballsafterdraw()
                temp[temp.index(
                    Constants.c_ball_colors[1])] = Constants.c_ball_colors[0]
                temp[temp.index(
                    Constants.c_ball_colors[1])] = Constants.c_ball_colors[0]
                self.set_ballsafterdraw(temp)

    def draw_ball(self):
        self.ball_position_drawn = random.randint(1,
                                                  Constants.c_number_of_balls)
        temp = self.get_ballsafterdraw()
        print("temp:", temp)
        print("temp[self.ball_position_drawn - 1]:", temp[2])
        print("self.ball_position_drawn:", self.ball_position_drawn)
        print("Constants.c_ball_colors[1]", Constants.c_ball_colors[1])
        if temp[self.ball_position_drawn] == Constants.c_ball_colors[1]:
            self.give_shock = 1
        else:
            self.give_shock = 0
        print("self.give_shock:", self.give_shock)

    def role(self):
        if self.id_in_group == 1:
            return 'Experimenter'
        else:
            return 'Player'
Example #19
0
class Subsession(BaseSubsession):
    grouping_done = models.BooleanField(initial=False)

    def before_session_starts(self):
        pass

    def vars_for_admin_report(self):
        payoffs = sorted([p.payoff for p in self.get_players()])
        return {'payoffs': payoffs}

    def make_grouping(self):
        # Grouping
        allplayers = self.get_players()
        print(allplayers)  # ???
        experimenters = [
            p for p in allplayers
            if p.participant.label == self.session.config['experimenter_pc']
        ]
        players = [
            p for p in allplayers
            if p.participant.label != self.session.config['experimenter_pc']
        ]
        print("Experimenters: ", experimenters)  # ???
        print("Players: ", players)  # ???
        group_matrix = []
        if not experimenters:
            print("Inside not experimenters")  # ???
            # Demo: Choose arbitrarely the first player to be the experimenter
            experimenter = players.pop()
            # Create the "playing" group
            playing_group = [experimenter, players.pop(self.round_number)]
            # Put all the other players in a "waiting group"
            waiting_group = [players.pop()]
            for p in players:
                waiting_group.append(p)
            group_matrix.append(playing_group)
            group_matrix.append(waiting_group)
        else:
            print("Inside Experimenters")  # ???
            # Real XP
            # Save the experimenter
            experimenter = experimenters.pop()
            # Create the "playing" group
            playing_group = [
                experimenter,
                players.pop(int(self.round_number / len(Constants.c_games)))
            ]
            # Put all the other players in a "waiting group"
            waiting_group = [players.pop()]
            for p in players:
                waiting_group.append(p)
            group_matrix.append(playing_group)
            group_matrix.append(waiting_group)
        print(group_matrix)  # ???
        self.set_group_matrix(group_matrix)
        self.grouping_done = True
        # Assign the group variables
        done = False
        for g in self.get_groups():
            if not done:
                g.role = 'Playing'
                done = True
            else:
                g.role = 'Waiting'
        # Initialize the player variables
        self.initialize_variables_forallgames()

    def initialize_variables_forallgames(self):
        # Inside the playing group, initialize the variables
        for g in self.get_groups():
            if g.role == 'Playing':
                # Set the player variables (the experimenter has no variable to be set)
                theplayer = g.get_player_by_role('Player')
                # Set the participants variables that will be constants for all 4 games
                theplayer.participant.vars['game_counter'] = 0
                theplayer.participant.vars['games_order'] = Constants.c_games
                shuffle(theplayer.participant.vars['games_order'])
                theplayer.participant.vars['intensity_group'] = random.choice(
                    Constants.c_groups)  # ??? Get from file
                theplayer.intensity_group = theplayer.participant.vars[
                    'intensity_group']
                if theplayer.participant.vars['intensity_group'] == 'H':
                    theplayer.participant.vars['balls_before_draw'] = [
                        'rouge', 'rouge', 'rouge', 'rouge', 'rouge', 'rouge',
                        'rouge', 'blanche', 'blanche', 'blanche'
                    ]
                elif theplayer.participant.vars['intensity_group'] == 'M':
                    theplayer.participant.vars['balls_before_draw'] = [
                        'rouge', 'rouge', 'rouge', 'rouge', 'rouge', 'blanche',
                        'blanche', 'blanche', 'blanche', 'blanche'
                    ]
                elif theplayer.participant.vars['intensity_group'] == 'L':
                    theplayer.participant.vars['balls_before_draw'] = [
                        'rouge', 'rouge', 'rouge', 'blanche', 'blanche',
                        'blanche', 'blanche', 'blanche', 'blanche', 'blanche'
                    ]
                else:
                    raise Exception('Unknown intensity_group')

    def initialize_variables_foreachgame(self, theplayer, gamenumber):
        # Set the participants variables that are specific to each game
        theplayer.game_played = theplayer.participant.vars['games_order'][
            gamenumber]
        temp = theplayer.participant.vars['balls_before_draw']
        shuffle(temp)
        theplayer.set_ballsbeforedraw(temp)
        theplayer.set_ballsafterdraw(temp)
        theplayer.offer_0 = c(0)
        theplayer.won_offer_price = False
Example #20
0
class Player(BasePlayer):
    timed_out = models.BooleanField()
    contribution = models.CurrencyField(
        min=0,
        max=Constants.endowment,
        doc="""The amount contributed by the player""")