configfile: 'config/config.yaml'
localrules: all, aggregate_replicates


rule all:
    input:
        expand(
            'results/plots_{benchmark}/',
            benchmark=config['benchmarks'].keys())


rule run_benchmark:
    output:
        fname = 'results/replicates/bench_{benchmark}_{replicate}.csv'
    params:
        benchmark_script = srcdir('scripts/main.R')
    resources:
        mem_mb = 5_000
    run:
        import sh

        # select matching config information
        cur = config['benchmarks'][wildcards.benchmark]

        # select methods if needed
        methods_arg = []
        if cur['methods'] is not None:
            methods_arg = ['--methods', ','.join(str(v) for v in cur['methods'])]

        # execute benchmark script
        sh.Rscript(
            params.benchmark_script,
            '--variable', cur['parameter'],
            '--values', ','.join(str(v) for v in cur['values']),
            '--replicates', config['script_replicates'],
            '--output', output.fname,
            *methods_arg,
            _fg=True
        )


rule aggregate_replicates:
    input:
        fname_list = expand(
            'results/replicates/bench_{benchmark}_{replicate}.csv',
            replicate=list(range(config['rule_replicates'])),
            allow_missing=True)
    output:
        fname = 'results/bench_{benchmark}.csv'
    run:
        import pandas as pd

        df_list = [pd.read_csv(fname) for fname in input.fname_list]
        pd.concat(df_list).to_csv(output.fname, index=False)


rule plot_results:
    input:
        fname = 'results/bench_{benchmark}.csv'
    output:
        outdir = directory('results/plots_{benchmark}/')
    params:
        plotting_script = srcdir('scripts/plotting.R')
    run:
        import sh

        sh.Rscript(
            params.plotting_script,
            '--input', input.fname,
            '--output', output.outdir,
            _fg=True
        )
