Skip to content

End-to-end reproducible toy pipeline

Download the notebook (executed for this page) ยท source

This compact notebook runs the full local KinOpt tutorial workflow: load, build mappings, optimize, predict, score, check feasibility, and save outputs.

from pathlib import Path
import sys
import os
from functools import partial

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


def find_repo_root(start=None):
    start = Path(start or Path.cwd()).resolve()
    for path in [start, *start.parents]:
        if (path / "config.toml").is_file():
            return path
    raise RuntimeError("Could not find repository root containing config.toml")

ROOT = find_repo_root()
os.chdir(ROOT)
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

DATA_DIR = ROOT / "notebooks" / "data"
OUTPUT_DIR = ROOT / "notebooks" / "outputs"
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

from config_loader import load
from kinopt.local.utils.iodata import apply_scaling
from kinopt.local.optcon import (
    build_P_initial,
    build_K_data,
    convert_to_sparse,
    precompute_mappings,
    init_parameters,
    compute_time_weights,
    build_constraints,
)
from kinopt.local.objfn import objective_wrapper, estimated_series
from kinopt.local.utils.params import compute_metrics, extract_parameters
from kinopt.local.opt import optrun

cfg = load("local", "kinopt")
time_points = np.asarray(cfg["time_points"], dtype=float)
time_cols = [f"x{i}" for i in range(1, len(time_points) + 1)]


def parse_kinase_list(value):
    return [item.strip() for item in str(value).strip().strip("{}").split(",") if item.strip()]


def load_toy_frames(apply_config_scaling=True):
    full_df = pd.read_csv(DATA_DIR / "toy_input1_hgnc.csv")
    interact_df = pd.read_csv(DATA_DIR / "toy_input2_interactions.csv")
    if apply_config_scaling:
        full_df = apply_scaling(
            full_df.copy(),
            time_cols,
            cfg.get("scaling_method", "none"),
            cfg.get("split_point", 9),
            cfg.get("segment_points"),
        )
    parsed = interact_df.copy()
    parsed["Kinase"] = parsed["Kinase"].apply(parse_kinase_list)
    return full_df, interact_df, parsed


def normalize_grouped_start(params, gene_alpha_starts, gene_kinase_counts, total_alpha, kinase_beta_counts):
    params = np.asarray(params, dtype=float).copy()
    for start, count in zip(gene_alpha_starts, gene_kinase_counts):
        params[start:start + count] = 1.0 / count
    beta_start = total_alpha
    for count in kinase_beta_counts:
        params[beta_start:beta_start + count] = 1.0 / count
        beta_start += count
    return params


def build_toy_problem(seed=7):
    full_df, raw_interact_df, interact_df = load_toy_frames(apply_config_scaling=True)
    P_initial, P_array = build_P_initial(full_df, interact_df)
    K_index, K_array, beta_counts = build_K_data(
        full_df,
        interact_df,
        bool(cfg.get("estimate_missing_kinases", True)),
    )
    K_sparse, K_data, K_indices, K_indptr = convert_to_sparse(K_array)
    (
        unique_kinases,
        gene_kinase_counts,
        gene_alpha_starts,
        gene_kinase_idx,
        total_alpha,
        kinase_beta_counts,
        kinase_beta_starts,
    ) = precompute_mappings(P_initial, K_index)
    np.random.seed(seed)
    params_initial, bounds = init_parameters(
        total_alpha,
        float(cfg.get("lower_bound", -4.0)),
        float(cfg.get("upper_bound", 4.0)),
        kinase_beta_counts,
    )
    params_initial = normalize_grouped_start(
        params_initial,
        gene_alpha_starts,
        gene_kinase_counts,
        total_alpha,
        kinase_beta_counts,
    )
    loss_type = cfg.get("loss_type", "weighted")
    t_max, P_init_dense, time_weights = compute_time_weights(P_array, loss_type)
    opt_method = cfg.get("method", "projected-gradient")
    constraints = build_constraints(
        opt_method,
        gene_kinase_counts,
        unique_kinases,
        total_alpha,
        kinase_beta_counts,
        len(params_initial),
    )
    obj_fun = partial(
        objective_wrapper,
        P_init_dense=P_init_dense,
        t_max=t_max,
        gene_alpha_starts=gene_alpha_starts,
        gene_kinase_counts=gene_kinase_counts,
        gene_kinase_idx=gene_kinase_idx,
        total_alpha=total_alpha,
        kinase_beta_starts=kinase_beta_starts,
        kinase_beta_counts=kinase_beta_counts,
        K_data=K_data,
        K_indices=K_indices,
        K_indptr=K_indptr,
        time_weights=time_weights,
        loss_type=loss_type,
    )
    return {
        "full_df": full_df,
        "raw_interact_df": raw_interact_df,
        "interact_df": interact_df,
        "P_initial": P_initial,
        "P_array": P_array,
        "K_index": K_index,
        "K_array": K_array,
        "K_sparse": K_sparse,
        "K_data": K_data,
        "K_indices": K_indices,
        "K_indptr": K_indptr,
        "unique_kinases": unique_kinases,
        "gene_kinase_counts": gene_kinase_counts,
        "gene_alpha_starts": gene_alpha_starts,
        "gene_kinase_idx": gene_kinase_idx,
        "total_alpha": total_alpha,
        "kinase_beta_counts": kinase_beta_counts,
        "kinase_beta_starts": kinase_beta_starts,
        "params_initial": params_initial,
        "bounds": bounds,
        "constraints": constraints,
        "t_max": t_max,
        "P_init_dense": P_init_dense,
        "time_weights": time_weights,
        "obj_fun": obj_fun,
        "opt_method": opt_method,
        "loss_type": loss_type,
    }


def run_tutorial_optimization(maxiter=300):
    problem = build_toy_problem()
    previous_maxiter = optrun.MAXITER
    optrun.MAXITER = maxiter
    try:
        result, optimized_params = optrun.run_optimization(
            problem["obj_fun"],
            problem["params_initial"],
            problem["opt_method"],
            problem["bounds"],
            problem["constraints"],
        )
    finally:
        optrun.MAXITER = previous_maxiter
    np.savez_compressed(
        OUTPUT_DIR / "toy_optimized_params.npz",
        params=optimized_params,
        fun=float(result.fun),
        success=bool(result.success),
        constr_violation=float(result.constr_violation),
        nit=int(result.nit),
        opt_method=str(problem["opt_method"]),
        loss_type=str(problem["loss_type"]),
    )
    return problem, result, optimized_params


def load_or_run_tutorial_optimization(maxiter=300):
    artifact = OUTPUT_DIR / "toy_optimized_params.npz"
    problem = build_toy_problem()
    if artifact.exists():
        data = np.load(artifact, allow_pickle=True)
        return problem, data["params"], data
    problem, result, optimized_params = run_tutorial_optimization(maxiter=maxiter)
    return problem, optimized_params, np.load(artifact, allow_pickle=True)


def parameter_layout(problem):
    rows = []
    alpha_start = 0
    for group_id, ((gene, psite), item) in enumerate(problem["P_initial"].items()):
        for offset, kinase in enumerate(item["Kinases"]):
            idx = alpha_start + offset
            lo, hi = problem["bounds"][idx]
            rows.append({
                "index": idx,
                "type": "alpha",
                "gene": gene,
                "psite": psite,
                "kinase": kinase,
                "lower": lo,
                "upper": hi,
                "group_id": f"alpha:{gene}:{psite}",
            })
        alpha_start += len(item["Kinases"])
    beta_start = problem["total_alpha"]
    for kinase in problem["unique_kinases"]:
        for psite, _series in problem["K_index"][kinase]:
            lo, hi = problem["bounds"][beta_start]
            rows.append({
                "index": beta_start,
                "type": "beta",
                "gene": "",
                "psite": psite,
                "kinase": kinase,
                "lower": lo,
                "upper": hi,
                "group_id": f"beta:{kinase}",
            })
            beta_start += 1
    return pd.DataFrame(rows)


def feasibility_table(problem, params, tol=1e-6):
    rows = []
    layout = parameter_layout(problem)
    for group_id, group in layout.groupby("group_id", sort=False):
        total = float(params[group["index"].to_numpy()].sum())
        rows.append({"constraint": group_id, "sum": total, "violation": total - 1.0, "feasible": abs(total - 1.0) <= tol})
    lb = np.array([b[0] for b in problem["bounds"]], dtype=float)
    ub = np.array([b[1] for b in problem["bounds"]], dtype=float)
    lower_violation = np.maximum(lb - params, 0.0)
    upper_violation = np.maximum(params - ub, 0.0)
    rows.append({
        "constraint": "bounds",
        "sum": np.nan,
        "violation": float(max(lower_violation.max(), upper_violation.max())),
        "feasible": bool(max(lower_violation.max(), upper_violation.max()) <= tol),
    })
    return pd.DataFrame(rows)
problem = build_toy_problem(seed=7)
problem["P_array"].shape, problem["K_array"].shape, len(problem["params_initial"])
((4, 14), (5, 14), 14)
problem, result, optimized_params = run_tutorial_optimization(maxiter=300)
P_est, residuals, mse, rmse, mae, mape, r_squared = compute_metrics(
    optimized_params,
    problem["P_init_dense"],
    problem["t_max"],
    problem["gene_alpha_starts"],
    problem["gene_kinase_counts"],
    problem["gene_kinase_idx"],
    problem["total_alpha"],
    problem["kinase_beta_starts"],
    problem["kinase_beta_counts"],
    problem["K_data"],
    problem["K_indices"],
    problem["K_indptr"],
)
checks = feasibility_table(problem, optimized_params, tol=1e-5)
summary = pd.DataFrame([{
    "objective": float(result.fun),
    "success": bool(result.success),
    "constraint_violation": float(result.constr_violation),
    "MSE": mse,
    "RMSE": rmse,
    "MAE": mae,
    "MAPE": mape,
    "R2": r_squared,
    "all_constraints_feasible": bool(checks["feasible"].all()),
}])
summary
objective success constraint_violation MSE RMSE MAE MAPE R2 all_constraints_feasible
0 0.000002 True 0.0 0.00006 0.007776 0.005314 1.522542 0.999234 True
keys = pd.DataFrame(list(problem["P_initial"].keys()), columns=["GeneID", "Psite"])
observed = pd.concat([keys, pd.DataFrame(problem["P_init_dense"], columns=time_cols)], axis=1)
estimated = pd.concat([keys, pd.DataFrame(P_est, columns=time_cols)], axis=1)
residual_df = pd.concat([keys, pd.DataFrame(residuals, columns=time_cols)], axis=1)
observed.to_csv(OUTPUT_DIR / "toy_observed.csv", index=False)
estimated.to_csv(OUTPUT_DIR / "toy_estimated.csv", index=False)
residual_df.to_csv(OUTPUT_DIR / "toy_residuals.csv", index=False)
summary.to_csv(OUTPUT_DIR / "toy_end_to_end_summary.csv", index=False)
checks.to_csv(OUTPUT_DIR / "toy_end_to_end_feasibility.csv", index=False)
OUTPUT_DIR
PosixPath('<repository>/notebooks/outputs')
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5))
axes[0].scatter(problem["P_init_dense"].ravel(), P_est.ravel(), alpha=0.8)
lims = [min(problem["P_init_dense"].min(), P_est.min()), max(problem["P_init_dense"].max(), P_est.max())]
axes[0].plot(lims, lims, color="black", linewidth=1)
axes[0].set_xlabel("Observed")
axes[0].set_ylabel("Estimated")
axes[0].set_title("Fit")
violations = checks["violation"].abs()
axes[1].bar(checks["constraint"], violations, color="#4c78a8")
axes[1].set_yscale("symlog", linthresh=1e-16)  # symlog: a violation of exactly 0 cannot be shown on a log scale
axes[1].tick_params(axis="x", rotation=45)
axes[1].set_title("Constraint violations" + (" (all exactly 0)" if (violations == 0).all() else ""))
plt.tight_layout()

png