Ejemplo n.º 1
0
class Player(BasePlayer):

    ##-------------------------------
    # treatment assigment variable
    TT = models.PositiveIntegerField()  # treatment player variable

    # test Form variables
    growthTest = models.PositiveIntegerField(min=0, max=3)
    profitTest = models.PositiveIntegerField(min=0, max=150)
    profitIndTest = models.FloatField()
    biomassTest = models.FloatField()

    ##-------------------------------
    ## players variables
    profit = models.FloatField(initial=0)
    predProfit = models.FloatField(initial=0)

    ## player etimation other harvesting level
    other_choice = models.PositiveIntegerField(
        choices=Constants.other_choice_catch, initial=0)

    ## player harvest choice
    catch_choice = models.PositiveIntegerField(choices=Constants.choice_catch,
                                               initial=0)

    ## player proposal harvest choice
    catch_pledge = models.PositiveIntegerField(choices=Constants.choice_catch,
                                               initial=0)
Ejemplo n.º 2
0
    def variation(self):
        var = [[] for _ in range(Constants.nb_catch_choice)]
        s1 = models.FloatField()
        s2 = 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:
                    s1 = self.bmin_round - (i + j)
                    var[inc].append(
                        round(
                            ((s1 - self.bmin_round) / self.bmin_round) * 100))
                    s2 = self.bmax_round - (i + j)
                    var[inc].append(
                        round(
                            ((s2 - self.bmax_round) / self.bmax_round) * 100))
        else:
            for i in Constants.choice_catch:
                inc = inc + 1
                for j in Constants.other_choice_catch:
                    s1 = self.schaefer(b=self.bmin_round, c=(i + j))
                    var[inc].append(
                        round(
                            ((s1 - self.bmin_round) / self.bmin_round) * 100))
                    s2 = self.schaefer(b=self.bmax_round, c=(i + j))
                    var[inc].append(
                        round(
                            ((s2 - self.bmax_round) / self.bmax_round) * 100))

        return (var)
Ejemplo n.º 3
0
    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)
Ejemplo n.º 4
0
class Player(BasePlayer):

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

    period_number = models.PositiveIntegerField(doc='''period number''')

    subperiod_number = models.PositiveIntegerField(doc='''subperiod number''')

    rp = models.FloatField(doc='''customer reserve price''')

    mc = models.FloatField(doc='''firm mill cost''')

    transport_cost = models.FloatField(doc="""transport, or shopping cost""")

    loc = models.FloatField(doc="player's location")

    price = models.FloatField(doc="player's price in previous round/subperiod")

    next_subperiod_price = models.FloatField(
        doc="player's price in current round/subperiod")

    boundary_lo = models.FloatField(doc="player's low end of boundary")

    boundary_hi = models.FloatField(doc="player's high end of boundary")

    prev_round_payoff = models.FloatField(
        doc="player's payoffs this previous round/subperiod")

    prev_round_cumulative_payoff = models.FloatField(
        doc="player's payoffs cumulative the previous round/subperiod.")

    paid_period = models.IntegerField(
        doc='''1 if this is a paid period, 0 otherwise''')
Ejemplo n.º 5
0
class Player(BasePlayer):

   ##-------------------------------
   # treatment assigment variable
   TT = models.CharField() # treatment player variable

   ##-------------------------------
   # 1st Form variables
   name       = models.CharField()
   profession = models.CharField()
   age        = models.PositiveIntegerField()
   playAs     =  models.CharField(
       choices=["Pêcheur", "Gestionnaire dans le domaine de l'halieutique", "Scientifique dans le domaine de l'halieutique",
                "Scientifique (autre)","Etudiant dans le domaine de l'halieutique", "Etudiant (autre)","Autre"])

   # test Form variables
   growthTest     = models.PositiveIntegerField(min=0, max= 3)
   profitTest     = models.PositiveIntegerField(min=0, max=150)
   profitIndTest  = models.FloatField()
   biomassTest    = models.FloatField()

   # 2nd Form variables
   dynamicKnowledge = models.CharField(
       choices=["Complètement d'accord", "D'accord", "Ni d'accord,n ni pas d'accord",
                "pas d'accord", "Complètement pas d'accord"])
   groupCooperation = models.CharField(
       choices=["Complètement d'accord", "D'accord", "Ni d'accord,n ni pas d'accord",
                "pas d'accord", "Complètement pas d'accord"])
   leverageCooperation = models.CharField(
       choices=["Analyse du tableau des profits", "Analyse des propositions", "Analyse du niveau de biomasse",
                "Analyse du niveau de capture et de profit des autres participants"])
   suffConditionCooperation = models.CharField(
       choices=["Complètement d'accord", "D'accord", "Ni d'accord,n ni pas d'accord",
                "pas d'accord", "Complètement pas d'accord"])
   biomassUncertainty = models.CharField(
       choices=["Complètement d'accord", "D'accord", "Ni d'accord,n ni pas d'accord",
                "pas d'accord", "Complètement pas d'accord"])

   blimUncertainty = models.CharField(
       choices=["Complètement d'accord", "D'accord", "Ni d'accord,n ni pas d'accord",
                "pas d'accord", "Complètement pas d'accord", "Pas dans mon traitement"])

   ##-------------------------------
   ## players variables
   profit     = models.FloatField(initial=0)
   predProfit = models.FloatField(initial=0)

   ## player etimation other harvesting level
   other_choice = models.PositiveIntegerField(
       choices=Constants.other_choice_catch,initial=0)

   ## player harvest choice
   catch_choice = models.PositiveIntegerField(
            choices=Constants.choice_catch,initial=0)

   ## player proposal harvest choice
   catch_pledge = models.PositiveIntegerField(
       choices=Constants.choice_catch,initial=0)
Ejemplo n.º 6
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')
Ejemplo n.º 7
0
class Subsession(BaseSubsession):
    all_contributions = models.FloatField()
    average_contribution = models.FloatField()

    def creating_session(self):
        if self.round_number == 1:
            paying_rounds = random.sample(range(1, Constants.num_rounds), 1)
            self.session.vars['paying_rounds'] = paying_rounds

        self.group_randomly(fixed_id_in_group=True)
Ejemplo n.º 8
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())
Ejemplo n.º 9
0
class Player(BasePlayer):
    # <built-in>
    subsession = models.ForeignKey(Subsession)
    group = models.ForeignKey(Group, null=True)
    # </built-in>
    x_place = models.FloatField()
    y_place = models.FloatField()
    price = models.CurrencyField(doc="""The mill price""", )

    def other_player(self):
        """Returns other player in group. Only valid for 2-player groups."""
        return self.get_others_in_group()[0]
Ejemplo n.º 10
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")
Ejemplo n.º 11
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''')
Ejemplo n.º 12
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
Ejemplo n.º 13
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'''
        )
Ejemplo n.º 14
0
    def projection(self):
        proj = []
        bint = models.FloatField()

        proj.append(self.b_round)
        for i in Constants.sim_years:
            bint = proj[i] - self.total_catch
            proj.append(round(self.schaefer(bint, c=0), 0))
        return (proj)
Ejemplo n.º 15
0
class Player(BasePlayer):

   ##-------------------------------
   # treatment assigment variable
   TT = models.CharField() # treatment player variable

   ##-------------------------------
   # Form variables
   name = models.CharField()
   profession = models.CharField()
   age = models.PositiveIntegerField()
   playAs = models.CharField(
       choices=["General audience", "Fisherman", "Manager", "Scientist in the field of fisheries",
                "Scientist (other)", "Student in the field of fisheries", "Student (other)"])

   dynamicKnowledge =  models.CharField(
       choices=["Fully agree", "Agree", "Neither agree nor disagree ",
                "Disagree","Fully disagree"])
   groupCooperation = models.CharField(
       choices=["Fully agree", "Agree", "Neither agree nor disagree ",
                "Disagree","Fully disagree"])
   leverageCooperation = models.CharField(
       choices=["Profit table analysis", "Pledge analysis", "Biomass analysis",
                "Catch & others profit analysis"])
   suffConditionCooperation = models.CharField(
       choices=["Fully agree", "Agree", "Neither agree nor disagree ",
                "Disagree","Fully disagree"])
   biomassUncertainty = models.CharField(
       choices=["Fully agree", "Agree", "Neither agree nor disagree ",
                "Disagree", "Fully disagree"])

   blimUncertainty = models.CharField(
            choices=["Fully agree", "Agree", "Neither agree nor disagree ",
                "Disagree", "Fully disagree","Not in my treatment"])


   ##-------------------------------
   ## players variables
   profit = models.FloatField()

   ## player etimation other harvesting level
   other_choice = models.PositiveIntegerField(
       choices=Constants.other_choice_catch,initial=0)

   ## player harvest choice
   catch_choice = models.PositiveIntegerField(
            choices=Constants.choice_catch,initial=0)

   ## player proposal harvest choice
   catch_pledge = models.PositiveIntegerField(
       choices=Constants.choice_catch,initial=0)
Ejemplo n.º 16
0
class Player(BasePlayer):

    ##-------------------------------
    # treatment assigment variable
    TT = models.CharField()  # treatment player variable

    ##-------------------------------
    # 1st Form variables
    name = models.CharField()
    profession = models.CharField()
    age = models.PositiveIntegerField()
    playAs = models.CharField(choices=[
        "General audience", "Fisherman", "Manager",
        "Scientist in the field of fisheries", "Scientist (other)",
        "Student in the field of fisheries", "Student (other)"
    ])

    # test Form variables
    growthTest = models.PositiveIntegerField(min=0, max=3)
    profitTest = models.PositiveIntegerField(min=0, max=150)
    profitIndTest = models.FloatField()
    #biomassTest    = models.PositiveIntegerField(min=0, max=70)

    ##-------------------------------
    ## players variables
    profit = models.FloatField()

    ## player etimation other harvesting level
    other_choice = models.PositiveIntegerField(
        choices=Constants.other_choice_catch, initial=0)

    ## player harvest choice
    catch_choice = models.PositiveIntegerField(choices=Constants.choice_catch,
                                               initial=0)

    ## player proposal harvest choice
    catch_pledge = models.PositiveIntegerField(choices=Constants.choice_catch,
                                               initial=0)
Ejemplo n.º 17
0
class Player(BasePlayer):
    pain_1 = models.PositiveIntegerField()
    pain_2 = models.PositiveIntegerField()
    pain_3 = models.PositiveIntegerField()
    pain_4 = models.PositiveIntegerField()
    pain_5 = models.PositiveIntegerField()
    pain_6 = models.PositiveIntegerField()
    pain_7 = models.PositiveIntegerField()
    pain_8 = models.PositiveIntegerField()
    int_sens = models.FloatField()
    int_pain = models.FloatField()

    def compute_pain_levels(self):
        self.int_sens = 2
        self.int_pain = 7
        with open('pain_file_phase1_out.csv', 'a') as f:
            f.write("{},{},{},{},{},{},{}".format(
                self.participant.vars['firstname'],
                self.participant.vars['surname'], self.participant.vars['sex'],
                self.participant.vars['school'], self.int_sens, self.int_pain))

    def role(self):
        return {1: 'Experimenter', 2: 'Player'}[self.id_in_group]
Ejemplo n.º 18
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)
Ejemplo n.º 19
0
 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)
Ejemplo n.º 20
0
    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)
Ejemplo n.º 21
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
Ejemplo n.º 22
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)
Ejemplo n.º 23
0
class Player(BasePlayer):

    player_role = models.CharField(doc="player role, A or F")

    quiz_01_a = models.FloatField(
        verbose_name="In A1, Role F's Group Exchange Contribution",
        min=0,
        max=999,
        initial=None,
        doc='''quiz_01_a answer In A1, Role F's Group Exchange Contribution''')
    quiz_01_b = models.FloatField(
        verbose_name="In A1, Role A's Group Exchange Contribution",
        min=0,
        max=999,
        initial=None,
        doc='''quiz_01_b answer In A1, Role A's Group Exchange Contribution''')
    quiz_01_c = models.FloatField(
        verbose_name="In A1, Role A's Score",
        min=0,
        max=999,
        initial=None,
        doc='''quiz_01_c answer In A1, Role A's Score''')
    quiz_01_d = models.FloatField(
        verbose_name="In A1, Role F's Score",
        min=0,
        max=999,
        initial=None,
        doc='''quiz_01_d answer In A1, Role F's Score''')
    quiz_01_e = models.FloatField(
        verbose_name="In F1, Role A's Score",
        min=0,
        max=999,
        initial=None,
        doc='''quiz_01_c answer In F1, Role A's Score''')
    quiz_01_f = models.FloatField(
        verbose_name="In F1, Role F's Score",
        min=0,
        max=999,
        initial=None,
        doc='''quiz_01_d answer In F1, Role F's Score''')

    quiz_02_a = models.FloatField(
        verbose_name="In N1, Role A's Score",
        min=0,
        max=999,
        initial=None,
        doc='''quiz_02_a answer In N1, Role A's Score''')
    quiz_02_b = models.FloatField(
        verbose_name="In N1, Role F's Score",
        min=0,
        max=999,
        initial=None,
        doc='''quiz_02_b answer In N1, Role F's Score''')
    quiz_02_c = models.FloatField(
        verbose_name="In N2, Role A's Score",
        min=0,
        max=999,
        initial=None,
        doc='''quiz_02_c answer In N2, Role A's Score''')
    quiz_02_d = models.FloatField(
        verbose_name="In N2, Role F's Score",
        min=0,
        max=999,
        initial=None,
        doc='''quiz_02_d answer In N2, Role F's Score''')
    quiz_02_e = models.FloatField(
        verbose_name="The Probability of N1 Occurring",
        min=0,
        max=999,
        initial=None,
        doc='''quiz_02_e answer The Probability of N1 Occurring''')

    ret_score = models.IntegerField(
        doc=
        "player's real effort task score - correct number of RETs mapped to a number."
    )

    vcm_score = models.FloatField(doc="score player received in vcm round.")

    vcm_ge_percent = models.FloatField(
        doc="player's average group exchange contribution in vcm rounds")

    passive_Player_Earnings = models.FloatField(
        doc=''' The score of this round's passive player.  ''')

    def set_round_payoff(self):
        """calc player payoffs"""
        ''' called inside group functions, eg A1A2_update '''

        for p in self.group.get_players():

            # group exchange
            F_GE = (p.GE_Low_F)
            if ((p.terminal_choice == 'F1') | (p.terminal_choice == 'N1')):
                F_GE = (p.GE_Low_F * p.F1_F_mult)
            GE = p.GE_Low_A + F_GE + 40

            #scores
            A_score = (GE * p.mpcr) + (20 - p.GE_Low_A)
            F_score = (GE * p.mpcr) + (20 - F_GE)

            if ((p.terminal_choice == 'N2') | (p.terminal_choice == 'N1')):
                A_score = (GE * p.mpcr) + (20 - p.GE_Low_A) - p.boycott_cost

            if (p.participant.vars['Role'] == 'A'):
                p.postStage_self_individual_exchange = 20 - p.GE_Low_A
                p.postStage_self_ge = p.GE_Low_A
                p.postStage_op_individual_exchange = str(20 - F_GE)
                p.postStage_op_group_exchange = str(F_GE)
                p.round_payoff = A_score
                p.postStage_round_points = A_score

            elif (p.participant.vars['Role'] == 'F'):
                p.postStage_self_individual_exchange = F_GE
                p.postStage_self_ge = p.GE_Low_F
                p.postStage_op_individual_exchange = str(20 - p.GE_Low_A)
                p.postStage_op_group_exchange = str(p.GE_Low_A)
                p.postStage_round_points = F_score
                p.round_payoff = F_score

    def set_payoff(self, round):
        # in views, determine round to pay
        # similar to VCM
        pass

    def passivePlayerEarnings(self):
        for p in self.group.get_players():

            # group exchange
            F_GE = (p.GE_Low_F)
            if ((p.terminal_choice == 'F1') | (p.terminal_choice == 'N1')):
                F_GE = (p.GE_Low_F * p.F1_F_mult)
            GE = p.GE_Low_A + F_GE + 40

            self.passive_Player_Earnings = (GE * p.mpcr)

            #scores
            return (GE * p.mpcr)

    stage_round_count = models.PositiveIntegerField(
        doc='The stage round number.')

    paid_round = models.PositiveIntegerField(doc=''' Paid stage round ''')

    paid_active_round_score = models.FloatField(
        doc=''' Score from paid actie player round''')

    round_payoff = models.FloatField(doc="this player's earnings this round")

    GE_Low_A = models.FloatField(
        doc="player A's group exchange contribution at 1X")
    GE_Low_F = models.FloatField(
        doc="player F's group exchange contribution at 1X")

    mpcr = models.FloatField(
        doc="marginal per-capita rate of return to vcm game")

    boycott_cost = models.FloatField(doc="cost of boycoff to player A")
    passive_ge_contrib = models.FloatField(
        doc="passive players' total contribution to group exchange")

    A1_A_mult = models.FloatField(doc="multiplier on GE of A at node A1")
    A1_F_mult = models.FloatField(doc="multiplier on GE of F at node A1")

    F1_A_mult = models.FloatField(doc="multiplier on GE of A at node F1")
    F1_F_mult = models.FloatField(doc="multiplier on GE of F at node F1")

    A3_A_mult = models.FloatField(doc="multiplier on GE of A at node A3")
    A3_F_mult = models.FloatField(doc="multiplier on GE of F at node A3")

    N1_prob = models.FloatField(
        doc="Probability of N1, where prob of N2 is (1 - N1_prob)")

    A_stage1 = models.CharField(
        initial=None,
        choices=['A1', 'A2'],
        verbose_name='Make your decision',
        doc='Player A decision between A1 and A2, Stage 1',
        widget=widgets.RadioSelect())

    F_stage2 = models.CharField(
        initial=None,
        choices=['F1', 'F2'],
        verbose_name='Make your decision',
        doc='Player F decision between F1 and F2, Stage 2',
        widget=widgets.RadioSelect())

    A_stage3 = models.CharField(
        initial=None,
        choices=['A3', 'A4'],
        verbose_name='Make your decision',
        doc='Player A decision between A3 and A4, Stage 3',
        widget=widgets.RadioSelect())

    Nature = models.CharField(
        doc="""'Should nature move, this is nature's move""",
        widget=widgets.RadioSelect())

    terminal_choice = models.CharField(
        doc="""'the terminal node reached by A and F""",
        widget=widgets.RadioSelect())

    def set_terminal_node(self):
        """explicitly define terminal node reached by A and F in this group"""
        A_tn = None
        F_tn = None
        N_tn = None  #nature
        for p in self.group.get_players():
            p.player_role = p.participant.vars['Role']
            if p.participant.vars['Role'] == 'A':
                if p.A_stage1 == "A1": A_tn = "A1"
                elif p.A_stage3 == "A3": A_tn = "A3"
                elif p.A_stage3 == "A4": A_tn = "A4"
            elif p.participant.vars['Role'] == 'F':
                if p.F_stage2 == 'F1': F_tn = 'F1'
                elif p.F_stage2 == 'F2': F_tn = 'F2'

            if p.Nature == 'N1': N_tn = 'N1'
            elif p.Nature == 'N2': N_tn = 'N2'

        TN = None
        if A_tn == "A1": TN = A_tn
        elif F_tn == 'F1': TN = F_tn
        elif A_tn == "A3": TN = A_tn
        else: TN = N_tn

        for p in self.group.get_players():
            p.terminal_choice = TN

    postStage_self_individual_exchange = models.FloatField(
        doc='''"player's individual exchange contribution after stage game"''')

    postStage_self_ge = models.FloatField(
        doc='''"player's group exchange contribution after stage game"''')

    postStage_op_individual_exchange = models.CharField(
        doc=
        '''"player's three other countryparty player's individual after stage game"'''
    )

    postStage_op_group_exchange = models.CharField(
        doc=
        '''"player's three other countryparty player's group exchange after stage game"'''
    )

    postStage_round_points = models.FloatField(
        doc='''"player's final score from stage game"''')

    followup_1 = models.CharField()

    # Survey questions

    q_birthMonth = models.PositiveIntegerField(
        verbose_name="What is the month of your birth?",
        choices=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
        doc=''' birth month ''',
    )
    q_birthYear = models.PositiveIntegerField(
        verbose_name="What is the year of your birth?",
        min=1900,
        max=2016,
        doc=''' birth year ''',
    )
    q_sex = models.CharField(
        verbose_name="Are you male or female?",
        choices=["male", "female"],
        doc=''' male or female ''',
    )

    q_languages = models.CharField(
        verbose_name="What language do you speak most often at home?",
        doc='''languages''',
    )

    q_YearsInUAE = models.PositiveIntegerField(
        verbose_name="How long have you lived in the UAE (in years)?",
        doc=''' How long have you lived in the UAE (in years)? ''',
    )

    q_nationality = models.CharField(
        verbose_name="What is your nationality?",
        doc=''' What is your nationality? ''',
    )

    q_major = models.CharField(
        verbose_name="What is your major?",
        doc=''' What is your major? ''',
    )

    q_part2strat = models.CharField(
        verbose_name=
        "In Part 2, how did you decide how much to contribute to the group exchange?",
        doc=
        ''' In Part 2, how did you decide how much to contribute to the group exchange? ''',
        widget=widgets.Textarea)

    q_part3_A1strat = models.CharField(
        blank=None,
        verbose_name=
        "In Part 3, if you were a Role A player, how did you decide between A1 and A2?",
        doc=
        ''' In Part 3, if you were a Role A player, how did you decide between A1 and A2? ''',
        widget=widgets.Textarea)

    q_part3_F1strat = models.CharField(
        blank=None,
        verbose_name=
        "In Part 3, if you were a Role F player, how did you decide between F1 and F2?",
        doc=
        ''' In Part 3, if you were a Role F player, how did you decide between F1 and F2? ''',
        widget=widgets.Textarea)

    q_part3_A3strat = models.CharField(
        blank=None,
        verbose_name=
        "In Part 3, if you were a Role A player, how did you decide between A3 and A4?",
        doc=
        ''' In Part 3, if you were a Role A player, how did you decide between A3 and A4? ''',
        widget=widgets.Textarea)

    q_part3_dynamic = models.CharField(
        blank=None,
        verbose_name=
        "In Part 3, how did your strategy change over the many rounds you played?",
        doc=''' In Part 3, how did your strategy change over rounds? ''',
        widget=widgets.Textarea)
Ejemplo n.º 24
0
class Player(BasePlayer):

    vcm_round = models.PositiveIntegerField(doc='The vcm round number.')

    individual_exchange = models.FloatField(
        initial=None,
        verbose_name='Individual exchange:',
        doc="Individual exchange contribution in this round")

    group_exchange = models.FloatField(
        initial=None,
        verbose_name='Group exchange:',
        doc="Group exchange contribution in this round")

    group_exchange_percent = models.FloatField(
        min=5,
        max=95,
        blank=True,  #not required
        doc=
        "in this round, this subject's percent contribution to group exchange relative to total amount availale to user",
        widget=widgets.SliderInput(attrs={
            'step': '1',
            'value': '5'
        }))

    total_op_individual_exchange = models.FloatField(
        doc='total individual_exchange contributions of opposing players')

    total_op_group_exchange = models.FloatField(
        doc='total group_exchange contributions of opposing players')
    round_points = models.FloatField(
        doc='Points earned this round from the VCM')

    player_role = models.CharField(doc="player type, A or F")

    player_role_list = models.CharField(
        doc=
        "list of all player roles after assignment. index 0 -> P1, index 1 -> P2"
    )

    paid_round = models.PositiveIntegerField(doc='vmc period that is paid on')

    final_score = models.FloatField(
        doc="this palyer's final score in this round")

    final_ge = models.PositiveIntegerField(
        doc=
        "this player's final group exchange contribution in the randomly chosen round"
    )

    def set_payoffs(self):
        """calc player payoffs"""
        self.total_op_individual_exchange = sum(
            [p.individual_exchange for p in self.get_others_in_group()])
        self.total_op_group_exchange = sum(
            [p.group_exchange for p in self.get_others_in_group()])

        self.round_points = self.individual_exchange - (
            1 / 2) * self.total_op_individual_exchange + (
                1 / 2) * self.group_exchange + Constants.automatic_earnings

    def set_roles(self, overall_ge_percent_list):
        """set player roles"""

        own_id_index = self.id_in_group - 1

        # rank 1 and 2 are smallest ge%
        # rank 3 and 4 are biggest ge contributers (check out scipy.stats `rankdata` for details)
        if (np.where(
                rankdata(np.array(overall_ge_percent_list), method='ordinal')
                == 4)[0] == own_id_index):
            self.player_role = self.participant.vars['Role'] = "A"
        elif (np.where(
                rankdata(np.array(overall_ge_percent_list), method='ordinal')
                == 3)[0] == own_id_index):
            self.player_role = self.participant.vars['Role'] = "A"
        else:
            self.player_role = self.participant.vars['Role'] = "F"

        # set player_role_list, a log of each player's role
        player_role_list = []
        for id_ in range(0, len(overall_ge_percent_list)):
            if (np.where(
                    rankdata(np.array(overall_ge_percent_list),
                             method='ordinal') == 4)[0] == id_):
                player_role_list.append("A")
            elif (np.where(
                    rankdata(np.array(overall_ge_percent_list),
                             method='ordinal') == 3)[0] == id_):
                player_role_list.append("A")
            else:
                player_role_list.append("F")

        self.player_role_list = self.participant.vars[
            'player_role_list'] = player_role_list  #just for debugging, might delete  self.participant.vars['player_role_list'] later.

        #this is the key var passed to stage game.
        self.participant.vars[
            'player_role_list'] = player_role_list  #used to get roles in stage game.
        self.participant.vars[
            'overall_ge_percent_list'] = overall_ge_percent_list
        self.participant.vars['overall_ge_percent'] = overall_ge_percent_list[
            own_id_index]
Ejemplo n.º 25
0
class Player(BasePlayer):

    # save Constants as an extra column for each observation

    time_per_round = models.PositiveIntegerField(
    )  # Total Time in seconds available for both solving and staying in switch

    tokensper_string = models.PositiveIntegerField()
    tokensper_string_high = models.PositiveIntegerField()
    eurosper_token = models.FloatField()
    secondsper_token = models.PositiveIntegerField()

    increase_per_string = models.PositiveIntegerField()

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

    # Control Instructions Variables
    solution_1 = models.PositiveIntegerField(default=0)
    solution_2 = models.PositiveIntegerField(default=0)

    solution_3 = models.PositiveIntegerField()
    solution_4 = models.PositiveIntegerField()
    solution_5 = models.PositiveIntegerField()

    # Control Instructions High
    solution_6 = models.PositiveIntegerField(default=0)
    solution_7 = models.PositiveIntegerField(default=0)

    solution_8 = models.PositiveIntegerField()
    solution_9 = models.PositiveIntegerField()
    solution_10 = models.PositiveIntegerField()

    # Number of Tasks Solved
    output_trial = models.FloatField(default=0)
    production_strings = models.FloatField(default=0)

    # available income after solving RET
    income_strings_gross = models.FloatField(default=0)
    net_income = models.FloatField(default=0)
    earnings = models.FloatField(default=0)

    # Variable is 1 when entering switch
    switch1 = models.PositiveIntegerField(default=0)

    switch_time = models.PositiveIntegerField(default=0)

    time_in_switch = models.PositiveIntegerField(default=0)

    additional_time = models.PositiveIntegerField(default=0)

    income_in_switch = models.FloatField(default=0)

    total_production = models.FloatField(default=0)

    # Time Needed to Solve Task i in Round j with tjxi

    t001 = models.PositiveIntegerField(default=0)
    t002 = models.PositiveIntegerField(default=0)
    t003 = models.PositiveIntegerField(default=0)
    t004 = models.PositiveIntegerField(default=0)
    t005 = 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)

    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_switch1(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
Ejemplo n.º 26
0
class Player(BasePlayer):

    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')

    ret_score = models.IntegerField(
        doc=
        "player's real effort task score - correct number of RETs mapped to a number."
    )

    vcm_score = models.IntegerField(doc="score player received in vcm round.")

    vcm_ge_percent = models.IntegerField(
        doc="player's average group exchange contribution in vcm rounds")

    role = models.CharField(doc="player role, A or F")

    def set_payoff(self, A_GE, A_Endow, F_GE, F_Endow):
        """calc player payoffs"""

        for p in self.group.get_players():
            if p.participant.vars['Role'] == 'F':
                total_op_individual_exchange = A_Endow - A_GE
                total_op_group_exchange = A_GE

                p.round_payoff = (F_Endow - F_GE) - (
                    1 / 2 * total_op_individual_exchange) + (
                        1 / 2 * F_GE) + Constants.automatic_earnings

            elif p.participant.vars['Role'] == 'A':
                total_op_individual_exchange = F_Endow - F_GE
                total_op_group_exchange = F_GE

                p.round_payoff = (A_Endow - A_GE) - (
                    1 / 2 * total_op_individual_exchange) + (
                        1 / 2 * A_GE) + Constants.automatic_earnings

    round_payoff = models.FloatField(doc="this player's earnings this round")

    A_stage1 = models.CharField(
        initial=None,
        choices=['A1', 'A2'],
        verbose_name='Make your decision',
        doc='Player A decision between A1 and A2, Stage 1',
        widget=widgets.RadioSelect())

    F_stage2 = models.CharField(
        initial=None,
        choices=['F1', 'F2'],
        verbose_name='Make your decision',
        doc='Player F decision between F1 and F2, Stage 2',
        widget=widgets.RadioSelect())

    A_stage3 = models.CharField(
        initial=None,
        choices=['A3', 'A4'],
        verbose_name='Make your decision',
        doc='Player A decision between A3 and A4, Stage 3',
        widget=widgets.RadioSelect())

    Nature = models.CharField(
        doc="""'Should nature move, this is nature's move""",
        widget=widgets.RadioSelect())

    terminal_choice = models.CharField(
        doc="""'the terminal node reached by A and F""",
        widget=widgets.RadioSelect())

    def set_terminal_node(self):
        """explicitly define terminal node reached by A and F in this group"""
        A_tn = None
        F_tn = None
        N_tn = None  #nature
        for p in self.group.get_players():
            if p.participant.vars['Role'] == 'A':
                if p.A_stage1 == "A1": A_tn = "A1"
                elif p.A_stage3 == "A3": A_tn = "A3"
                elif p.A_stage3 == "A4": A_tn = "A4"
            elif p.participant.vars['Role'] == 'F':
                if p.F_stage2 == 'F1': F_tn = 'F1'
                elif p.F_stage2 == 'F2': F_tn = 'F2'

            if p.Nature == 'N1': N_tn = 'N1'
            elif p.Nature == 'N2': N_tn = 'N2'

        TN = None
        if A_tn == "A1": TN = A_tn
        elif F_tn == 'F1': TN = F_tn
        elif A_tn == "A3": TN = A_tn
        else: TN = N_tn

        for p in self.group.get_players():
            p.terminal_choice = TN
Ejemplo n.º 27
0
class Group(BaseGroup):
    toilet = models.FloatField(min=0,
                               max=Constants.max_toilet_condition,
                               default=Constants.start_value_toilet)

    def resources_reduction(self, player):

        return Constants.max_resources_reduction * (
            Constants.max_health_condition - player.health
        ) / (Constants.max_health_condition - Constants.min_health_condition)

    def init_group(self):
        if self.round_number == 1:
            self.toilet = Constants.start_value_toilet
        else:
            prev_round = self.in_round(self.round_number - 1)
            self.toilet = prev_round.toilet

        for player in self.get_players():
            if self.round_number == 1:
                player.health = Constants.start_value_health
                player.resources = Constants.start_value_resources
            else:
                player_prev_round = player.in_round(self.round_number - 1)

                player.resources = (
                    player_prev_round.resources +
                    Constants.resources_incrementation -
                    self.resources_reduction(player_prev_round))

                player.health = player_prev_round.health + 1

                if player.health > Constants.max_health_condition:
                    player.health = Constants.max_health_condition

    def current_toilet_usage_health_lose(self):

        return Constants.max_health_effect * (
            Constants.max_toilet_condition - self.toilet
        ) / (Constants.max_toilet_condition - Constants.min_toilet_condition)

    def missing_resources(self, player, contribution):
        if player.resources < contribution:
            missing_resources = contribution - player.resources

            return missing_resources

        else:
            return 0

    def overflow_resources(self, player, contribution):
        if player.resources > contribution:
            overflow_resources = player.resources - contribution
            player.resources_overflow = overflow_resources

            return overflow_resources

        else:
            return 0

    def contribution_to_big_clean(self, player, contribution,
                                  total_resources_missing,
                                  total_resources_overflow):
        if player.resources <= contribution:
            contribution_to_big_clean = player.resources
            player.resources = 0

            return contribution_to_big_clean

        else:
            contribution_to_big_clean = contribution
            if total_resources_missing > 0:
                contribution_to_big_clean += total_resources_missing * player.resources_overflow / total_resources_overflow

            if contribution_to_big_clean < Constants.big_clean_min_contribution:
                contribution_to_big_clean = Constants.big_clean_min_contribution

            player.resources -= contribution_to_big_clean

            return contribution_to_big_clean

    def set_payoff(self):
        players = self.get_players()
        toilet_dirt, part_of_big_clean = 0., []
        dont_use_the_toilet = sum(1 for player in players
                                  if not player.use_toilet)
        toilet_usage_health_lose = self.current_toilet_usage_health_lose()

        for player in players:
            if not player.health:
                continue  # if player is dead don't play

            player.health -= dont_use_the_toilet

            if player.use_toilet:
                player.health -= toilet_usage_health_lose
                if player.small_cleaning and player.resources:
                    toilet_dirt += 0.5
                    player.resources -= 1
                else:
                    toilet_dirt += 1

            if player.health < 0:
                player.health = 0
            if player.health > Constants.max_health_condition:
                player.health = Constants.max_health_condition

            if player.big_clean:
                part_of_big_clean.append(player)

        # set the new status of toilet
        self.toilet -= toilet_dirt
        if self.toilet < 0:
            self.toilet = 0

        # big clean
        if part_of_big_clean:
            contribution, resources = int(Constants.big_clean_cost /
                                          len(part_of_big_clean)), 0.
            total_resources_missing = 0.
            total_resources_overflow = 0.

            for player in part_of_big_clean:
                total_resources_missing += self.missing_resources(
                    player, contribution)
                total_resources_overflow += self.overflow_resources(
                    player, contribution)
                toilet_dirt -= 0.5

            for player in part_of_big_clean:
                resources += self.contribution_to_big_clean(
                    player, contribution, total_resources_missing,
                    total_resources_overflow)

            if resources >= Constants.big_clean_cost:
                self.toilet = Constants.max_toilet_condition

        # in the last round set the resources as payoff
        if self.round_number == Constants.num_rounds:
            for player in players:
                player.payoff = player.resources
Ejemplo n.º 28
0
class Player(BasePlayer):

    player_role = models.CharField(doc="player role, A or F")

    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')

    ret_score = models.IntegerField(
        doc=
        "player's real effort task score - correct number of RETs mapped to a number."
    )

    vcm_score = models.FloatField(doc="score player received in vcm round.")

    vcm_ge_percent = models.FloatField(
        doc="player's average group exchange contribution in vcm rounds")

    op_ret_scores = models.CharField(
        doc='this subjects opposing player ret scores from task 1.')

    op_ge_overallavg = models.CharField(
        doc=
        'this subjects opposing player overall average group contribution from vcm.'
    )

    round_base_points = models.FloatField(
        doc=
        ''' player's base score. if no adjustments are made to own or counterpart GE contributions, player will earn this '''
    )

    def set_payoff(self, A_GE, A_Endow, F_GE, F_Endow):
        """calc player payoffs"""
        ''' called inside group functions, eg A1A2_update '''

        op_GE = self.participant.vars['group_exchange_other2p']
        op_IE = self.participant.vars['individual_exchange_other2p']

        for p in self.group.get_players():
            if p.participant.vars['Role'] == 'F':

                total_op_individual_exchange = (A_Endow - A_GE) + sum(op_IE)
                total_op_group_exchange = A_GE + sum(op_GE)

                p.round_payoff = (F_Endow - F_GE) - (
                    1 / 2 * total_op_individual_exchange) + (
                        1 / 2 * F_GE) + Constants.automatic_earnings

                #for debugging and results screen
                p.postStage_self_individual_exchange = F_Endow - F_GE
                p.postStage_self_ge = F_GE
                p.postStage_op_individual_exchange = str([(A_Endow - A_GE)] +
                                                         op_IE)
                p.postStage_op_group_exchange = str([A_GE] + op_GE)
                p.postStage_round_points = p.round_payoff

            elif p.participant.vars['Role'] == 'A':
                total_op_individual_exchange = (F_Endow - F_GE) + sum(op_IE)
                total_op_group_exchange = F_GE + sum(op_GE)

                p.round_payoff = (A_Endow - A_GE) - (
                    1 / 2 * total_op_individual_exchange) + (
                        1 / 2 * A_GE) + Constants.automatic_earnings

                #for debugging and results screen
                p.postStage_self_individual_exchange = A_Endow - A_GE
                p.postStage_self_ge = A_GE
                p.postStage_op_individual_exchange = str([(F_Endow - F_GE)] +
                                                         op_IE)
                p.postStage_op_group_exchange = str([F_GE] + op_GE)
                p.postStage_round_points = p.round_payoff

    round_payoff = models.FloatField(doc="this player's earnings this round")

    A_stage1 = models.CharField(
        initial=None,
        choices=['A1', 'A2'],
        verbose_name='Make your decision',
        doc='Player A decision between A1 and A2, Stage 1',
        widget=widgets.RadioSelect())

    F_stage2 = models.CharField(
        initial=None,
        choices=['F1', 'F2'],
        verbose_name='Make your decision',
        doc='Player F decision between F1 and F2, Stage 2',
        widget=widgets.RadioSelect())

    A_stage3 = models.CharField(
        initial=None,
        choices=['A3', 'A4'],
        verbose_name='Make your decision',
        doc='Player A decision between A3 and A4, Stage 3',
        widget=widgets.RadioSelect())

    Nature = models.CharField(
        doc="""'Should nature move, this is nature's move""",
        widget=widgets.RadioSelect())

    terminal_choice = models.CharField(
        doc="""'the terminal node reached by A and F""",
        widget=widgets.RadioSelect())

    def set_terminal_node(self):
        """explicitly define terminal node reached by A and F in this group"""
        A_tn = None
        F_tn = None
        N_tn = None  #nature
        for p in self.group.get_players():
            p.player_role = p.participant.vars['Role']
            if p.participant.vars['Role'] == 'A':
                if p.A_stage1 == "A1": A_tn = "A1"
                elif p.A_stage3 == "A3": A_tn = "A3"
                elif p.A_stage3 == "A4": A_tn = "A4"
            elif p.participant.vars['Role'] == 'F':
                if p.F_stage2 == 'F1': F_tn = 'F1'
                elif p.F_stage2 == 'F2': F_tn = 'F2'

            if p.Nature == 'N1': N_tn = 'N1'
            elif p.Nature == 'N2': N_tn = 'N2'

        TN = None
        if A_tn == "A1": TN = A_tn
        elif F_tn == 'F1': TN = F_tn
        elif A_tn == "A3": TN = A_tn
        else: TN = N_tn

        for p in self.group.get_players():
            p.terminal_choice = TN

    postStage_self_individual_exchange = models.FloatField(
        doc='''"player's individual exchange contribution after stage game"''')

    postStage_self_ge = models.FloatField(
        doc='''"player's group exchange contribution after stage game"''')

    postStage_op_individual_exchange = models.CharField(
        doc=
        '''"player's three other countryparty player's individual after stage game"'''
    )

    postStage_op_group_exchange = models.CharField(
        doc=
        '''"player's three other countryparty player's group exchange after stage game"'''
    )

    postStage_round_points = models.FloatField(
        doc='''"player's final score from stage game"''')
Ejemplo n.º 29
0
class Group(BaseGroup):

    total_investments = models.FloatField(
        initial=0)  # define group variable to calculate probabilities

    # determine total investments

    def set_total_investments(self):
        total_investments = sum(p.investment_amount
                                for p in self.get_players())
        # retrieves a list of all individual incomes
        # and sums them up
        self.total_investments = total_investments

    #  calculate probabilities
    def set_probabilities(self):
        self.set_total_investments()
        # probabilities do not add to 1 if all investments are equal (because of floats)
        # this means if all investments or offers are equal
        if len(set(p.investment_amount for p in self.get_players())) == 1:
            for p in self.get_players():
                p.prob = 1 / Constants.players_per_group
        else:
            for p in self.get_players():
                p.prob = p.investment_amount / self.total_investments
        for p in self.get_players():
            p.prob_percent = p.prob * 100

    # determine winner
    def set_winner(self):
        prob = [
            p.prob for p in self.get_players()  # creates list of probabilities
        ]
        prob2 = []  # creates empty list to be normalized in next step
        for i in prob:
            prob2.append(
                i / sum(prob)
            )  # this normalizes the variable and makes sure that probabilities sum up to 1
        winner = np.random.choice(self.get_players(), p=prob2)
        winner.is_winner = True
        for p in self.get_players():
            p.participant.vars['is_winner'] = p.is_winner

    # determine income:
    def set_incomes(
        self
    ):  # income is defined in Tokens. What a player obtains at the end in currency are payoffs
        if Constants.treatment:  # if taxation and redistribution are implemented. Only work income is taxed.
            for p in self.get_players():
                if self.round_number > 1:
                    if p.in_round(self.round_number - 1).is_winner:
                        p.income_strings_gross = p.production_strings * Constants.tokensper_string_high
                        p.income_strings_after_tax = p.income_strings_gross * (
                            1 - Constants.tax_rate)
                    else:
                        p.income_strings_gross = p.production_strings * Constants.tokensper_string
                        p.income_strings_after_tax = p.income_strings_gross * (
                            1 - Constants.tax_rate)

                else:  # in the first round all start equally
                    p.income_strings_gross = p.production_strings * Constants.tokensper_string
                    p.income_strings_after_tax = p.income_strings_gross * (
                        1 - Constants.tax_rate)

        else:  # if taxation and redistribution are NOT implemented
            for p in self.get_players():
                if self.round_number > 1:
                    if p.in_round(self.round_number - 1).is_winner:
                        p.income_strings_gross = p.production_strings * Constants.tokensper_string_high
                        p.income_strings_after_tax = p.income_strings_gross
                    else:
                        p.income_strings_gross = p.production_strings * Constants.tokensper_string
                        p.income_strings_after_tax = p.income_strings_gross
                else:  # in the first round all start equally
                    p.income_strings_gross = p.production_strings * Constants.tokensper_string
                    p.income_strings_after_tax = p.income_strings_gross

    # determine redistribution

    total_fiscal = models.FloatField(initial=0)
    transfer = models.FloatField(
        initial=0)  # the amount per round that each participant receives

    def set_fiscal(self):
        if Constants.treatment:  # if taxation and redistribution are implemented
            # define sum to be redistributed:
            for p in self.get_players():
                p.taxation = p.income_strings_gross * Constants.tax_rate
            total_fiscal = sum(p.taxation for p in self.get_players())

            self.total_fiscal = total_fiscal

            # Redistribute total Budget equally among participants
            for p in self.get_players():
                self.transfer = self.total_fiscal / Constants.players_per_group
                p.available_income = self.transfer + p.income_strings_after_tax
                p.net_income = p.income_strings_after_tax + p.income_in_switch + self.transfer

        else:  # if taxation and redistribution are NOT implemented
            for p in self.get_players():
                p.available_income = p.income_strings_gross
                p.net_income = p.income_strings_gross + p.income_in_switch

    # determine payoffs:
    def set_payoffs(self):
        for p in self.get_players():
            p.earnings = p.net_income - p.investment_amount
            p.payoff = p.earnings * Constants.eurosper_token
Ejemplo n.º 30
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