"""A single DAG around the original, unchanged numerical programs.

Run from work-science/program. Parsing only reads configuration files.
"""

import configparser
from pathlib import Path

shell.prefix(
    "export MPLBACKEND=Agg OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 "
    "MKL_NUM_THREADS=1 VECLIB_MAXIMUM_THREADS=1 NUMEXPR_NUM_THREADS=1; "
)

MOMENTA = ["000", "001", "011", "111"]
FIT_CONFIGS = {}
for path in sorted(Path("correlators/inis").glob("input_*.ini")):
    config = configparser.ConfigParser()
    config.read(path)
    fit = "tmin{}-tmax{}_model{}".format(
        config["input"]["fit_tmin"],
        config["input"]["fit_tmax"],
        config["input"]["fit_model"],
    )
    # Two supplied INIs describe the same output: schedule that fit once.
    FIT_CONFIGS.setdefault(fit, str(path))

ENERGIES = expand(
    "../data/energy_fits/d{momentum}_energy_{fit}.jack",
    momentum=MOMENTA, fit=sorted(FIT_CONFIGS),
)
COMBINED = expand("../data/dispersion_data/d{momentum}_energy.jack", momentum=MOMENTA)


rule all:
    input:
        ENERGIES,
        COMBINED,
        "energies/energies_chosen.pdf",
        "dispersion/dispersion_pion.pdf",


rule fit_correlator:
    input:
        data="../data/raw_data/pion_lambda.h5",
        config=lambda wildcards: FIT_CONFIGS[wildcards.fit],
        script="correlators/fit_correlator.py",
    output:
        expand("../data/energy_fits/d{momentum}_energy_{{fit}}.jack", momentum=MOMENTA),
    log:
        "logs/correlator_{fit}.log",
    threads: 1
    shell:
        "cd correlators && python fit_correlator.py -i ../{input.config:q} > ../{log:q} 2>&1"


rule combine_fits:
    input:
        energies=ENERGIES,
        script="energies/combine_fits.py",
    output:
        energies=COMBINED,
        plot="energies/energies_chosen.pdf",
    log:
        "logs/combine.log",
    threads: 1
    shell:
        "cd energies && python combine_fits.py ../../data/energy_fits "
        "../../data/dispersion_data > ../{log:q} 2>&1"


rule fit_dispersion:
    input:
        energies=COMBINED,
        filelist="dispersion/file.list",
        script="dispersion/fit_dispersion.py",
        functions="dispersion/dispersion.py",
        renderer="dispersion/run_dispersion_mathtext.py",
    output:
        "dispersion/dispersion_pion.pdf",
    log:
        "logs/dispersion.log",
    threads: 1
    shell:
        "cd dispersion && python run_dispersion_mathtext.py > ../{log:q} 2>&1"
