Fit metrics and diagnostics
Download the notebook (executed for this page) ยท source
This notebook computes predictions, residuals, and standard fit metrics from the optimized toy parameters.
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, optimized_params, artifact = load_or_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"],
)
metrics = pd.DataFrame([{"MSE": mse, "RMSE": rmse, "MAE": mae, "MAPE": mape, "R2": r_squared}])
metrics.to_csv(OUTPUT_DIR / "toy_fit_metrics.csv", index=False)
metrics
| MSE | RMSE | MAE | MAPE | R2 | |
|---|---|---|---|---|---|
| 0 | 0.00006 | 0.007776 | 0.005314 | 1.522542 | 0.999234 |
R2 can be negative when a model predicts worse than simply using the global mean of the observed data. The optimizer objective can also differ from raw SSE when the configured loss is weighted or robust.
obs = problem["P_init_dense"].ravel()
fit = P_est.ravel()
fig, ax = plt.subplots(figsize=(4, 4))
ax.scatter(obs, fit, alpha=0.8)
lims = [min(obs.min(), fit.min()), max(obs.max(), fit.max())]
ax.plot(lims, lims, color="black", linewidth=1)
ax.set_xlabel("Observed")
ax.set_ylabel("Estimated")
ax.set_title("Observed vs estimated")
plt.tight_layout()

keys = list(problem["P_initial"].keys())
fig, ax = plt.subplots(figsize=(8, 4))
for i, (gene, psite) in enumerate(keys):
ax.plot(time_points, residuals[i], marker="o", linewidth=1, label=f"{gene} {psite}")
ax.axhline(0, color="black", linewidth=0.8)
ax.set_xscale("symlog", linthresh=1)
ax.set_xlabel("Time (minutes)")
ax.set_ylabel("Residual")
ax.legend(ncol=2, fontsize=8)
plt.tight_layout()

fig, axes = plt.subplots(1, 2, figsize=(9, 3.5))
axes[0].hist(residuals.ravel(), bins=12, color="#4c78a8")
axes[0].set_title("Residual histogram")
axes[0].set_xlabel("Residual")
axes[1].plot(np.cumsum(residuals.ravel()), color="#f58518")
axes[1].axhline(0, color="black", linewidth=0.8)
axes[1].set_title("Cumulative residuals")
plt.tight_layout()

alpha_values, beta_values = extract_parameters(
problem["P_initial"],
problem["gene_kinase_counts"],
problem["total_alpha"],
problem["unique_kinases"],
problem["K_index"],
optimized_params,
)
alpha_df = pd.DataFrame([
{"Gene": gene, "Psite": psite, "Kinase": kinase, "Alpha": value}
for (gene, psite), kinases in alpha_values.items()
for kinase, value in kinases.items()
])
beta_df = pd.DataFrame([
{"Kinase": kinase, "Psite": psite, "Beta": value}
for (kinase, psite), value in beta_values.items()
])
alpha_df.to_csv(OUTPUT_DIR / "toy_alpha_values.csv", index=False)
beta_df.to_csv(OUTPUT_DIR / "toy_beta_values.csv", index=False)
display(alpha_df)
display(beta_df)
| Gene | Psite | Kinase | Alpha | |
|---|---|---|---|---|
| 0 | RAF1 | S338 | MAPK1 | 0.748910 |
| 1 | RAF1 | S338 | MAPK3 | 0.251090 |
| 2 | ELK1 | S383 | MAPK1 | 0.468035 |
| 3 | ELK1 | S383 | RPS6KA1 | 0.531965 |
| 4 | JUN | S63 | MAPK3 | 0.555769 |
| 5 | JUN | S63 | RPS6KA1 | 0.444231 |
| 6 | JUN | S73 | MAPK1 | 0.386297 |
| 7 | JUN | S73 | MAPK3 | 0.282453 |
| 8 | JUN | S73 | RPS6KA1 | 0.331251 |
| Kinase | Psite | Beta | |
|---|---|---|---|
| 0 | MAPK1 | T185 | 0.619674 |
| 1 | MAPK1 | Y187 | 0.380326 |
| 2 | MAPK3 | T202 | 0.680871 |
| 3 | MAPK3 | Y204 | 0.319129 |
| 4 | RPS6KA1 | S380 | 1.000000 |