from __future__ import annotations import numpy as np def forward_committor(msm, A_active, B_active): """Forward committor q+ via deeptime (absorbing boundaries on A, B).""" return np.asarray(msm.model.committor_forward(list(A_active), list(B_active))) def forward_committor_linsolve(P, A, B): """Reference forward committor by direct linear solve. Solves (I - P_TT) q_T = P_TB 1 on the transient set T = all \\ (A u B), with q|A = 0, q|B = 1. Independent of deeptime; used only to cross-check. """ P = np.asarray(P, dtype=np.float64) m = P.shape[0] A = np.asarray(list(A), dtype=int) B = np.asarray(list(B), dtype=int) mask = np.ones(m, dtype=bool) mask[A] = False mask[B] = False T = np.where(mask)[0] q = np.zeros(m) q[B] = 1.0 if len(T) == 0: return q P_TT = P[np.ix_(T, T)] rhs = P[np.ix_(T, B)].sum(axis=1) q[T] = np.linalg.solve(np.eye(len(T)) - P_TT, rhs) return np.clip(q, 0.0, 1.0) def committor_agreement(msm, A_active, B_active): """Max |q_deeptime - q_linsolve| over active states (should be ~1e-10).""" q_dt = forward_committor(msm, A_active, B_active) q_ls = forward_committor_linsolve(msm.P, A_active, B_active) return float(np.max(np.abs(q_dt - q_ls))), q_dt, q_ls def committor_half_states(q, tol=0.1): """Active indices with |q - 1/2| <= tol (the committor-1/2 ensemble).""" return np.where(np.abs(np.asarray(q) - 0.5) <= tol)[0] def committor_half_mass(msm, q, tol=0.1): """Stationary probability carried by the committor-1/2 ensemble.""" idx = committor_half_states(q, tol=tol) return float(msm.stationary[idx].sum()), idx def reactive_flux(msm, A_active, B_active): """deeptime ReactiveFlux object for the A -> B reaction.""" return msm.model.reactive_flux(list(A_active), list(B_active)) def pathway_fractions(rf, fraction=0.9): """Decompose the reactive flux into pathways and their flux fractions.""" paths, caps = rf.pathways(fraction=fraction) caps = np.asarray(caps, dtype=float) total = float(rf.total_flux) return { "paths": [list(map(int, p)) for p in paths], "capacities": caps, "frac_of_total": caps / max(total, 1e-300), "total_flux": total, "n_paths": len(paths), } def path_passes_through(path, target_active, exclude_endpoints=True): """True if a pathway visits any microstate in ``target_active``.""" nodes = path[1:-1] if (exclude_endpoints and len(path) > 2) else path return bool(set(nodes) & set(int(t) for t in target_active))