oTree Forum >

Questions about 'creating_session'.

#1 by Xinghao_Yao

Hi,

I want to generate random 'signals' and 'first_signals' for each round. But my code generate the same value of them for all round. Should I just 'creating_session' or not? Here is my code:

class C(BaseConstants):
    NAME_IN_URL = 'Selected'
    PLAYERS_PER_GROUP = None
    NUM_ROUNDS = 8
    signal_list = [50, 70, 90, 110, 130, 150]
    
def creating_session(subsession: Subsession):
    session = subsession.session
    signals = random.choices(population=C.signal_list, k=6)
    session.vars['signals'] = signals
    first_signal = random.choice(session.vars['signals'])
    session.vars['first_signal'] = first_signal
    
    
Thanks a lot!

#2 by Daniel_Frey

Hi there, Happy New Year!

I think I see your problem: creating_session is executed for each round, but you overwrite session.vars['signals'] and session.vars['first_signal'] each round, so only the values that were chosen in the last round will be stored in session.vars['signals'] / session.vars['first_signal'].
You need a dictionary, where you can store the list & the first signal for each round.

By the way, constants in 'class C(BaseConstants)' should be all upper-case.

Try this code (I haven't tested it, but it should work):

class C(BaseConstants):
    NAME_IN_URL = 'Selected'
    PLAYERS_PER_GROUP = None
    NUM_ROUNDS = 8
    SIGNAL_LIST= [50, 70, 90, 110, 130, 150]

def creating_session(subsession: Subsession):
    session = subsession.session
    round_nr = subsession.round_nr
    
    # The dicts must be created so that they can get filled with values each round, but only in round 1, otherwise they          
    # would get overwritten
    if round_nr == 1:
        session.vars['signals_per_round'] = dict()
        session.vars['first_signal_per_round'] = dict()

    signals = random.choices(population=C.SIGNAL_LIST, k=6)
    session.vars['signals_per_round'][round_nr] = signals
    first_signal = random.choice(signals)
    session.vars['first_signal'][round_nr] = first_signal
    
    # Check if the lists are saved correctly
    print('signals_list:', session.vars['signals_list'], 'first_signal:', session.vars['first_signal_per_round']
    
I hope that helps!

Best,
Daniel

#3 by Xinghao_Yao

Hi Daniel,

Thanks for your reply. It works!

As a beginner of oTree, your comments are super helpful.

Best,
Xinghao

Write a reply

Set forum username