import os
import subprocess
import itertools

# 配置参数
config_options = [
    "src/config/cifar10/der.yml",
    "src/config/cifar10/er.yml",
    "src/config/cifar100/der.yml",
    "src/config/cifar100/er.yml",
    "src/config/mini_imagenet/der.yml",
    "src/config/mini_imagenet/er.yml",
    "src/config/cifar10/rar.yml",
    "src/config/cifar100/rar.yml",
    "src/config/mini_imagenet/rar.yml",
]

dynamic_options = [False, True]
mean_evaluation_options = [False, True]
seed_options = [0, 1, 2]

# 生成所有实验配置组合
combinations = list(itertools.product(config_options, dynamic_options, mean_evaluation_options, seed_options))

# 过滤只考虑同时为 True 和 False 的组合
filtered_combinations = [
    (config, dynamic, mean_eval, seed)
    for config, dynamic, mean_eval, seed in combinations
    if (dynamic == mean_eval)
]

# 运行实验
running_processes = {}
gpu_count = 6

for config, dynamic, mean_eval, seed in filtered_combinations:
    command = f"python main_noboundaries.py --config {config} --dynamic {str(dynamic).lower()} --mean_evaluation {str(mean_eval).lower()} --wandblog true --seed {seed}"
    print(command)
    # 查找空闲的 GPU

    while True:
        for gpu in range(gpu_count):
            if gpu not in running_processes or running_processes[gpu].poll() is not None:
                # 如果找到空闲 GPU，则运行命令
                print(f"Starting: {command} on GPU {gpu}")
                process = subprocess.Popen(command, shell=True)
                running_processes[gpu] = process
                break
        else:
            # 如果没有空闲的 GPU，则等待
            for gpu in range(gpu_count):
                if gpu in running_processes and running_processes[gpu].poll() is not None:
                    del running_processes[gpu]
            continue
        break

# 等待所有进程结束
for process in running_processes.values():
    process.wait()