import subprocess
from itertools import product
import subprocess

def run_and_log(cmd, logfile_path="target_output_lsoda.log"):
    with open(logfile_path, "a") as log_file:
        process = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            bufsize=1  # Line-buffered
        )

        for line in process.stdout:
            print(line, end="")         # Print to console
            log_file.write(line)        # Write to file
            log_file.flush()            # Optional: flush frequently

        process.wait()


# Parameters
n_sample = [20000]
n_col = [480, 1200, 1600, 2400]  
ratios = [2]
reg_consts = [1e-8, 1e-10] #, 1e-14
time_blocks = [9]
tols = [1e-5]#, 1e-11, 1e-12

# Fixed values (can be added if needed)
grad_percent = 0.03  # Not used in arg_sets but you can add it too
# Generate all combinations
arg_sets = []
for n_s, n_c, t_b, r_c, r, tol in product(n_sample, n_col, time_blocks, reg_consts, ratios, tols):
    arg_set = {
        "--n_s": str(n_s),
        "--n_c": str(n_c),
        "--r": str(r),
        "--r_c": str(r_c),
        "--t_b": str(t_b),
        "--tol": str(tol)
    }
    arg_sets.append(arg_set)

# Preview first 2 to confirm
for i, args in enumerate(arg_sets):
    print(f"arg_set {i+1}:", args)

print(f"\nTotal combinations: {len(arg_sets)}")

# Loop through arguments and call the target script
for args in arg_sets:
    cmd = ["python", "hyp_param.py"]
    for k, v in args.items():
        cmd.extend([k, v])
    
    print(f"Running: {' '.join(cmd)}")
    result = subprocess.run(cmd, capture_output=True, text=True) #
    result = run_and_log(cmd)


