Skip to content

Local objective and prediction

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

This notebook evaluates the KinOpt local prediction equation and objective for a simple feasible parameter vector.

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)
import jax
problem = build_toy_problem()
params = problem["params_initial"]
print("JAX float64 enabled:", jax.config.jax_enable_x64)
print("Configured loss:", problem["loss_type"])
print("Initial objective:", float(problem["obj_fun"](params)))
JAX float64 enabled: True
Configured loss: weighted
Initial objective: 3.905394838842179e-05
P_est = np.asarray(estimated_series(
    params,
    problem["t_max"],
    problem["P_init_dense"].shape[0],
    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"],
), dtype=float)
residuals = problem["P_init_dense"] - P_est
print(P_est.shape, residuals.shape, "minimum prediction", P_est.min())
(4, 14) (4, 14) minimum prediction 0.05
keys = list(problem["P_initial"].keys())
row = 0
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(time_points, problem["P_init_dense"][row], marker="o", label="observed")
ax.plot(time_points, P_est[row], marker="s", label="estimated")
ax.set_xscale("symlog", linthresh=1)
ax.set_xlabel("Time (minutes)")
ax.set_ylabel("Signal")
ax.set_title(f"Observed vs estimated: {keys[row][0]} {keys[row][1]}")
ax.legend()
plt.tight_layout()

png

base_value = objective_wrapper(
    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"],
    np.ones(problem["t_max"]),
    "base",
)
configured_value = problem["obj_fun"](params)
pd.DataFrame({"loss": ["base", problem["loss_type"]], "value": [float(base_value), float(configured_value)]})
loss value
0 base 0.011312
1 weighted 0.000039