如何在oTree中为每个Session动态设置轮次数量?
在oTree中为不同Session自定义轮次数量
核心方案:将轮次参数配置到Session Config中,动态控制运行轮次
你完全可以通过在Session Config里定义自定义参数,实现无需修改实验代码即可为不同Session设置不同轮次的需求,具体操作如下:
1. 在settings.py中添加带自定义轮次参数的Session Config
在项目的settings.py文件里,给不同的Session配置项添加num_rounds(或分序列的num_seq、num_rounds_per_seq)参数:
SESSION_CONFIGS = [ { 'name': 'formal_experiment', 'display_name': '正式实验(100轮)', 'app_sequence': ['your_experiment_app'], 'num_rounds': 100, # 正式实验轮次 }, { 'name': 'manager_demo', 'display_name': '主管演示(2轮)', 'app_sequence': ['your_experiment_app'], 'num_rounds': 2, # 演示用轮次 # 若需分序列设置,可替换为: # 'num_seq': 1, # 'num_rounds_per_seq': 2, }, ]
2. 修改实验App的代码,动态读取Session Config参数
首先在App的__init__.py里,把固定的num_rounds设为一个足够大的上限值(覆盖所有可能的实验需求):
from otree.api import * class Constants(BaseConstants): name_in_url = 'your_experiment_app' players_per_group = None # 根据你的实验设置调整 num_rounds = 1000 # 设一个足够大的通用上限
然后在每个实验页面的is_displayed方法中,判断当前轮次是否超过Session Config中设定的目标轮次,只显示符合条件的轮次:
class ExperimentPage(Page): def is_displayed(self): # 读取Session Config中的轮次,默认值设为100 target_rounds = self.session.config.get('num_rounds', 100) return self.round_number <= target_rounds # 若使用分序列配置,可改为: # class ExperimentPage(Page): # def is_displayed(self): # num_seq = self.session.config.get('num_seq', 1) # rounds_per_seq = self.session.config.get('num_rounds_per_seq', 100) # total_rounds = num_seq * rounds_per_seq # return self.round_number <= total_rounds
3. (可选)在结果/统计页面使用实际轮次参数
如果需要在结果页面展示实际运行的轮次数量,同样可以读取Session Config的参数:
class ResultsPage(Page): @staticmethod def vars_for_template(player: Player): target_rounds = player.session.config.get('num_rounds', 100) return { 'actual_played_rounds': target_rounds }
方案优势
- 无需修改实验核心逻辑,仅通过配置即可切换不同轮次模式
- 实验者在oTree后台创建Session时,直接选择对应的配置项即可,操作便捷
- 支持单轮次数量配置,也支持分序列的轮次组合配置
内容的提问来源于stack exchange,提问作者NBekelman
相关产品推荐
相关产品推荐

