Core Code

Source code for the models described on the Mathematical Modeling page.

RGG Phase Separation Model

RGG Phase Separation Model.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
from __future__ import annotations

import json
import os
import sys

import numpy as np

FULL_CONSTRUCT_SEQ = (
    "MPRESNQSNNGGSGNAALNRGGRYVPPHLRGGDGGAAAAASAGGDDRRGGAGGGGYRRGGGNSGGGGGGGY"
    "DRGYNDNRDDRDNRGGSGGYGRDRNYEDRGYNGGGGGGGNRGYNNNRGGGGGGYNRQDRGDGGSSNFSRGG"
    "YNNRDEGSDNRGSGRSYNNDRRDNGGDGTSLEMVSKGEELFTGVVPILVELDGDVNGHKFSVRGEGEGDA"
    "TNGKLTLKFICTTGKLPVPWPTLVTTLTYGVQCFSRYPDHMKRHDFFKSAMPEGYVQERTISFKDDGTYK"
    "TRAEVKFEGDTLVNRIELKGIDFKEDGNILGHKLEYNFNSHNVYITADKQKNGIKANFKIRHNVEDGSVQ"
    "LADHYQQNTPIGDGPVLLPDNHYLSTQSVLSKDPNEKRDHMVLLEFVTAAGITHGMDELYKHHHHHH"
)
RGG_DOMAIN_SEQ = (
    "MPRESNQSNNGGSGNAALNRGGRYVPPHLRGGDGGAAAAASAGGDDRRGGAGGGGYRRGGGNSGGGGGGGY"
    "DRGYNDNRDDRDNRGGSGGYGRDRNYEDRGYNGGGGGGGNRGYNNNRGGGGGGYNRQDRGDGGSSNFSRGG"
    "YNNRDEGSDNRGSGRSYNNDRRDNGGDG"
)

LAF1_RGG_SEQ = (
    "MESNQSNNGGSGNAALNRGGRYVPPHLRGGDGGAAAAASAGGDDRRGGAGGGGYRRGGGNSGGGGGGG"
    "YDRGYNDNRDDRDNRGGSGGYGRDRNYEDRGYNGGGGGGGNRGYNNNRGGGGGGYNRQDRGDGGSSNFS"
    "RGGYNNRDEGSDNRGSGRSYNNDRRDNGGDG"
)
DDX4N1_SEQ = (
    "MGDEDWEAEINPHMSSYVPIFEKDRYSGENGDNFNRTPASSSEMDDGPSRRDHFMKSGFASGRNFGNRDA"
    "GECNKRDNTSTMGGFGVGKSFGNRGFSNSRFEDGDSSGFWRESSNDCEDNPTRNRGFSKRGGYRDGNNSE"
    "ASGPYRRGGRGSFRGCRGGFGLGSPNNDLDPDECMQRTGGLFGSRRPVLSGTGNGDTSQSRSGSGSERGG"
    "YKGLNEEVITGSGKNSWKSEAEGGES"
)

def _resolve_epic_repo(start=None):

    env = os.environ.get("EPIC_REPO")
    if env and os.path.isdir(env):
        return env
    d = start or _PKG
    for _ in range(5):
        cand = os.path.join(d, "_epic_idp_repo")
        if os.path.isdir(cand):
            return cand
        nd = os.path.dirname(d)
        if nd == d:
            break
        d = nd
    return os.path.join(_OUT, "_epic_idp_repo")

def extract_rgg_domain(full_seq, sf_gfp_marker="MVSKGEELF", linker="TSLE"):

    idx = full_seq.find(sf_gfp_marker)
    if idx < 0:
        raise ValueError("sfGFP marker not found")
    rgg = full_seq[:idx]
    return rgg[: -len(linker)] if rgg.endswith(linker) else rgg

STICKER_RESIDUES = set("WRYFK")
BACKGROUND_RESIDUE = "A"
WINDOW = 10

DOC_RHO_S, DOC_KAPPA_S = 0.126046, 0.681839
DOC_X_RGG = 0.211989
DOC_CHI0, DOC_ALPHA = 3.4313, -12.3370
DOC_ANCHOR_X = {"LAF-1 RGG": 0.211811, "Ddx4N1": 0.221681}

try:
    import torch
    from transformers import EsmTokenizer, EsmForMaskedLM
    _HAS_ESM = True
except ImportError:
    torch = None
    _HAS_ESM = False

def load_model(model_name="facebook/esm2_t12_35M_UR50D"):

    tokenizer = EsmTokenizer.from_pretrained(model_name)
    model = EsmForMaskedLM.from_pretrained(model_name)
    model.eval()
    return model, tokenizer

def masked_log_probs(seq, model, tokenizer):

    out = np.zeros((len(seq), len(tokenizer.get_vocab())))
    with torch.no_grad():
        for i in range(len(seq)):
            inputs = tokenizer(seq[:i] + "<mask>" + seq[i + 1:], return_tensors="pt")
            logits = model(**inputs).logits
            pos = (inputs.input_ids == tokenizer.mask_token_id).nonzero(as_tuple=True)[1][0].item()
            out[i] = torch.log_softmax(logits[0, pos], dim=-1).detach().cpu().numpy()
    return out

def compute_residue_weights(seq, model, tokenizer):

    lp = masked_log_probs(seq, model, tokenizer)

    idx = {a: tokenizer.convert_tokens_to_ids(a) for a in "ACDEFGHIKLMNPQRSTVWY"}
    return {i: float(lp[i, idx[aa]] - lp[i, idx[BACKGROUND_RESIDUE]])
            for i, aa in enumerate(seq) if aa in STICKER_RESIDUES}

def normalize_weights(weights):

    if not weights:
        return {}
    vals = np.array(list(weights.values()))
    lo, hi = vals.min(), vals.max()
    if hi - lo < 1e-12:
        return {i: 1.0 for i in weights}
    return {i: (w - lo) / (hi - lo) for i, w in weights.items()}

def rho_s_from_plm(seq, norm_weights):
    return sum(norm_weights.values()) / len(seq)

def kappa_s_from_plm(seq, norm_weights, window=WINDOW):
    field = np.zeros(len(seq))
    for i, w in norm_weights.items():
        field[i] = w
    if len(seq) < window:
        return float("nan")
    dens = np.array([field[i:i + window].sum() / window for i in range(len(seq) - window + 1)])
    return float(dens.std() / (dens.mean() + 1e-9))

def analyze_sequence(seq, model=None, tokenizer=None):

    if model is None or tokenizer is None:
        if _HAS_ESM:
            model, tokenizer = load_model()
        elif seq == RGG_DOMAIN_SEQ:
            return {"rho_s": DOC_RHO_S, "kappa_s": DOC_KAPPA_S}
    norm = normalize_weights(compute_residue_weights(seq, model, tokenizer))
    return {"rho_s": rho_s_from_plm(seq, norm), "kappa_s": kappa_s_from_plm(seq, norm)}

RESIDUE_MASS = {
    'G': 57.0519, 'A': 71.0788, 'S': 87.0782, 'P': 97.1167, 'V': 99.1326,
    'T': 101.1051, 'C': 103.1388, 'L': 113.1594, 'I': 113.1594, 'N': 114.1038,
    'D': 115.0886, 'Q': 128.1307, 'K': 128.1741, 'E': 129.1155, 'M': 131.1926,
    'H': 137.1411, 'F': 147.1766, 'R': 156.1875, 'Y': 163.1760, 'W': 186.2132,
}
WATER_MASS = 18.01524
V_BAR = 0.73
RESIDUES_PER_BEAD = 3

def protein_mw(seq):
    return sum(RESIDUE_MASS[a] for a in seq.upper()) + WATER_MASS

def phi_to_concentration(phi, mw, v_bar=V_BAR):

    c_gml = phi / v_bar
    return c_gml * 1000.0, c_gml * 1000.0 / mw * 1e6

def critical_point(N):

    phi_c = 1.0 / (1.0 + np.sqrt(N))
    return phi_c, (1.0 + np.sqrt(N)) ** 2 / (2.0 * N)

def chem_potentials(phi, N, chi):

    phi = np.clip(phi, 1e-12, 1.0 - 1e-12)
    mu1 = np.log(1.0 - phi) + (1.0 - 1.0 / N) * phi + chi * phi ** 2
    mu2 = np.log(phi) + (1.0 - N) * (1.0 - phi) + N * chi * (1.0 - phi) ** 2
    return mu1, mu2

def solve_binodal(chi, N, phi_c=None, chi_c=None, guess=None,
                  min_sep=1e-4, rtol=1e-8):

    from scipy.optimize import root

    if phi_c is None or chi_c is None:
        phi_c, chi_c = critical_point(N)
    if chi <= chi_c:
        return None

    def eqs(x):
        a, b = x
        m1a, m2a = chem_potentials(a, N, chi)
        m1b, m2b = chem_potentials(b, N, chi)
        return [m1a - m1b, m2a - m2b]

    spread = min(0.49, 2.0 * np.sqrt(max(chi - chi_c, 1e-12) / chi_c))
    cands = ([list(guess)] if guess is not None else []) + [
        [max(1e-6, phi_c * (1 - spread)), min(0.999, phi_c + spread * (1 - phi_c) * 3)],
        [1e-3, 0.9], [1e-4, 0.6], [1e-2, 0.8], [5e-4, 0.5], [1e-5, 0.99],
        [1e-6, 0.7], [1e-8, 0.7], [1e-8, 0.95],
    ]
    best = None
    for g in cands:
        sol = root(eqs, g)
        if not sol.success:
            continue
        a, b = sorted(sol.x)
        if not (1e-12 < a < b - min_sep < 1 - 1e-9):
            continue
        r = max(abs(v) for v in eqs([a, b]))
        if r < rtol and (best is None or (b - a) > (best[1] - best[0])):
            best = (float(a), float(b))
    return best

def binodal_branches(chi_start, chi_end, N, n=300):

    phi_c, chi_c = critical_point(N)
    keep, pd_, pe_, guess = [], [], [], None
    for c in np.linspace(chi_start, chi_end, n):
        out = solve_binodal(c, N, phi_c, chi_c, guess=guess, min_sep=1e-6, rtol=1e-9)
        if out is None:
            guess = None
            continue
        guess = out
        keep.append(c); pd_.append(out[0]); pe_.append(out[1])
    return np.array(keep), np.array(pd_), np.array(pe_)

def invert_chi_from_phi_dilute(target_phi, N, chi_hi=3.0, n_scan=400):

    from scipy.optimize import brentq

    phi_c, chi_c = critical_point(N)
    grid = np.linspace(chi_c * 1.001, chi_hi, n_scan)
    vals = [solve_binodal(c, N, phi_c, chi_c) for c in grid]
    vals = [v[0] if v else None for v in vals]
    for i in range(len(grid) - 1):
        if (vals[i] is not None and vals[i + 1] is not None
                and (vals[i] - target_phi) * (vals[i + 1] - target_phi) < 0):
            def f(c):
                out = solve_binodal(c, N, phi_c, chi_c)
                return (out[0] if out else target_phi + 1.0) - target_phi
            return brentq(f, grid[i], grid[i + 1])
    return None

ANCHOR_CHI_CODE = {"LAF-1 RGG": 0.81817436, "Ddx4N1": 0.69640600}
ANCHOR_SPECS = (("LAF-1 RGG", LAF1_RGG_SEQ, None, 50.0),
                ("Ddx4N1", DDX4N1_SEQ, 0.005, None))

def _anchor_phi_target(seq, phi_dilute, csat_uM):

    if phi_dilute is not None:
        return float(phi_dilute)
    return (csat_uM * 1e-6 * protein_mw(seq) / 1000.0) * V_BAR

def verify_anchor_consistency(model=None, tokenizer=None, tol=1e-3):

    out = {}
    for name, seq, phi_dilute, csat_uM in ANCHOR_SPECS:
        N = max(10, len(seq) // RESIDUES_PER_BEAD)
        phi_t = _anchor_phi_target(seq, phi_dilute, csat_uM)
        chi_code = invert_chi_from_phi_dilute(phi_t, N)
        d_chi = abs(chi_code - ANCHOR_CHI_CODE[name])
        rec = {"N": N, "chi_code": chi_code, "d_chi": d_chi, "ok_chi": d_chi <= tol}
        if model is not None or tokenizer is not None:
            feat = analyze_sequence(seq, model, tokenizer)
            x = feat["rho_s"] * (1.0 + feat["kappa_s"])
            rec.update(x=x, d_x=abs(x - DOC_ANCHOR_X[name]))
        out[name] = rec
        print(line)
    return out

def calibrate_for_granularity(r, x_rgg=None, verbose=False):

    x_rgg = DOC_X_RGG if x_rgg is None else x_rgg
    x1, x2 = DOC_ANCHOR_X["LAF-1 RGG"], DOC_ANCHOR_X["Ddx4N1"]
    out = {"r": r}
    chi_a = []
    for name, seq, phi_dilute, csat_uM in ANCHOR_SPECS:
        N_a = max(10, len(seq) // r)
        phi_t = _anchor_phi_target(seq, phi_dilute, csat_uM)
        chi_a.append(invert_chi_from_phi_dilute(phi_t, N_a))
        out["N_" + ''.join(ch for ch in name.split()[0] if ch.isalnum())] = N_a
    out["chi_anchor"] = tuple(chi_a)
    alpha = (chi_a[0] - chi_a[1]) / (x1 - x2)
    chi0 = chi_a[0] - alpha * x1
    out.update(chi0=chi0, alpha=alpha)
    N = max(10, len(RGG_DOMAIN_SEQ) // r)
    chi_eff = chi0 + alpha * x_rgg
    phi_c, chi_c = critical_point(N)
    out.update(N=N, chi_eff=chi_eff, chi_c=chi_c, phi_c=phi_c)
    if chi_eff > chi_c:
        pd_, pe_ = solve_binodal(chi_eff, N, phi_c, chi_c)
        mg, uM = phi_to_concentration(pd_, protein_mw(FULL_CONSTRUCT_SEQ))
        out.update(phi_dilute=pd_, phi_dense=pe_, csat_mgml=mg, csat_uM=uM,
                   csat_orders=float(np.log10(mg)))
    return out

def equivalent_chi(phi_target, N, chi_hi=1.6, n=300):

    phi_c, chi_c = critical_point(N)
    grid = np.linspace(chi_c + 0.005, chi_hi, n)
    vals = []
    for c in grid:
        o = solve_binodal(c, N, phi_c, chi_c)
        vals.append(o[0] if o else np.nan)
    vals = np.array(vals, dtype=float)
    ok = ~np.isnan(vals)
    idx = np.where(ok)[0]
    for k in range(len(idx) - 1):
        a, b = idx[k], idx[k + 1]
        if (vals[a] - phi_target) * (vals[b] - phi_target) <= 0:
            return float(grid[a] + (phi_target - vals[a]) * (grid[b] - grid[a]) / (vals[b] - vals[a]))
    return None

def check_pairing(N, chi, phi_target=None, tol_orders=1.0, verbose=True):

    ref = phi_target if phi_target is not None else calibrate_for_granularity(RESIDUES_PER_BEAD)["phi_dilute"]
    phi_c, chi_c = critical_point(N)
    test = np.log10(ref)
    msg = {}
        o = solve_binodal(chi, N, phi_c, chi_c)
        gap = float(np.log10(o[0]) - test) if o else -np.inf
        msg["gap_orders"] = gap
 
    if verbose:
        for k in ("fix_recalibrate", "fix_equivalent_chi"):
            if msg.get(k):
                print("      -", msg[k])
    return msg

def granularity_consistency_report(r_ref=None, n_show=3):

    r_ref = RESIDUES_PER_BEAD if r_ref is None else r_ref
    base = calibrate_for_granularity(r_ref)
    ref_lit = calibrate_for_granularity(1)
    phi_c, chi_c = critical_point(ref_lit["N"])
    o = solve_binodal(base["chi_eff"], ref_lit["N"], phi_c, chi_c)
    if o:
        mg, _ = phi_to_concentration(o[0], protein_mw(FULL_CONSTRUCT_SEQ))
    return base, ref_lit

def calibrate_chi0_alpha(model=None, tokenizer=None, tol=1e-3):

        return DOC_CHI0, DOC_ALPHA

    xs = []
    for name, seq, phi_dilute, csat_uM in ANCHOR_SPECS:
        feat = analyze_sequence(seq, model, tokenizer)
        x = feat["rho_s"] * (1.0 + feat["kappa_s"])
        if abs(x - DOC_ANCHOR_X[name]) > tol:

        xs.append(x)
        print(f"  {name}: rho_s={feat['rho_s']:.4f}, kappa_s={feat['kappa_s']:.4f}, x={x:.4f}")

    chis = [invert_chi_from_phi_dilute(_anchor_phi_target(s[1], s[2], s[3]),
                                       max(10, len(s[1]) // RESIDUES_PER_BEAD)) for s in ANCHOR_SPECS]
    if abs(xs[0] - xs[1]) < 1e-9:
        return DOC_CHI0, DOC_ALPHA
    alpha = (chis[0] - chis[1]) / (xs[0] - xs[1])
    chi0 = chis[0] - alpha * xs[0]
    return chi0, alpha

def estimate_chi_eff(rho_s, kappa_s, chi0, alpha, x_override=None):

    x = x_override if x_override is not None else rho_s * (1.0 + kappa_s)
    return chi0 + alpha * x

B_T = 465.0
T_REF = 298.15

LIT_TSAT = ((0.3, 288.15, "LAF-1 RGG 15 °C @ 0.3 mg/mL"),
            (1.0, 299.15, "LAF-1 RGG 26 °C @ 1.0 mg/mL"))

def _tsat_for_B(c_mgml, B, N=56, chi_eff=0.8159783349, steps=60):

    phi = c_mgml * V_BAR / 1000.0
    phi_c, chi_c = critical_point(N)
    if phi >= phi_c:
        return None
    lo, hi = 272.0, 520.0
    for _ in range(steps):
        mid = 0.5 * (lo + hi)
        chi = chi_eff + B * (1.0 / mid - 1.0 / T_REF)
        if chi <= chi_c:
            hi = mid; continue
        out = solve_binodal(chi, N, phi_c, chi_c)
        if out is None:
            hi = mid; continue
        if out[0] < phi:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)

def calibrate_B_from_literature(chi_eff=0.8159783349, verbose=True):

    grid = [b for b in np.arange(400.0, 560.0, 1.0)]
    best = None
    for B in grid:
        rss = 0.0
        for c, T_lit, _ in LIT_TSAT:
            T = _tsat_for_B(c, B, chi_eff=chi_eff)
            if T is None:
                rss += 1e6; continue
            rss += (T - T_lit) ** 2
        if best is None or rss < best[0]:
            best = (rss, float(B))
    rss, B = best
    den = critical_point(56)[1] - (chi_eff - B / T_REF)
    ucst = B / den
    return dict(B=B, rss=rss, rmse=float(np.sqrt(rss / len(LIT_TSAT))), ucst=ucst)

def temperature_phase_boundary(chi_eff, N=56, T_min=282.0, n=400, B=None):

    B = B_T if B is None else B
    phi_c, chi_c = critical_point(N)
    A = chi_eff - B / T_REF
    T_ucst = B / (chi_c - A)
    chs, pd_, pe_ = binodal_branches(A + B / T_min, A + B / (T_ucst - 0.05), N, n=n)
    return B / (chs - A), pd_, pe_, T_ucst, A

EPIC_PARAMS = dict(rho0=1.0, lB=1.7, kappa=0.75, a=0.1, Vh0=3.0)   # EPIC-IDP
EPIC_MATRICES = ["Mpipi", "CALVADOS2", "URRY"]
ESM_CHI = {"LAF-1 RGG (anchor, 168aa)": 0.81817436,
           "Ddx4N1 (anchor, 236aa)": 0.69640600,
           "Team RGG (170aa)": 0.8159783349}

def _patch_numpy_loadtxt_encoding():

    if getattr(np.loadtxt, "_epic_utf8_patched", False):
        return
    orig = np.loadtxt

    def loadtxt(fname, *args, **kwargs):
        if isinstance(fname, (str, bytes, os.PathLike)):
            kwargs.setdefault("encoding", "utf-8")
        try:
            return orig(fname, *args, **kwargs)
        except UnicodeDecodeError:
            kwargs["encoding"] = "latin-1"
            return orig(fname, *args, **kwargs)

    loadtxt._epic_utf8_patched = True
    np.loadtxt = loadtxt

def epic_self_chi(seqs, matrix, repo_path=None):

    repo = repo_path or _resolve_epic_repo()
    if repo not in sys.path:
        sys.path.insert(0, repo)
    _patch_numpy_loadtxt_encoding()
    from epic_idp import chi_effective_calculator

    cec = chi_effective_calculator(interaction_matrix=matrix, **EPIC_PARAMS)
    for name, seq in seqs.items():
        cec.add_IDP(name, seq)
    mat = cec.calc_all_chi_eff()
    return {name: float(mat[i, i]) for i, name in enumerate(seqs)}

def robustness_check(out_json=None):

    a1, a2, team = ("LAF-1 RGG (anchor, 168aa)", "Ddx4N1 (anchor, 236aa)", "Team RGG (170aa)")
    seqs = {a1: LAF1_RGG_SEQ, a2: DDX4N1_SEQ, team: RGG_DOMAIN_SEQ}
    res = {"epic_params": EPIC_PARAMS, "routes": {}}
    for m in EPIC_MATRICES:
        res["routes"][m] = epic_self_chi(seqs, m)
        print(f"  [{m}] " + "  ".join(f"{k.split(' ')[0]}={v:.4f}" for k, v in res["routes"][m].items()))

    mp = res["routes"]["Mpipi"]
    b, a = np.polyfit([mp[a1], mp[a2]], [ESM_CHI[a1], ESM_CHI[a2]], 1)
    pred = b * mp[team] + a
    res["cross_validation"] = {
        "mapping": f"FH_chi = {b:.4f} * chi_B + {a:.4f}",
        "pred_TeamRGG_from_routeB": float(pred),
        "ESM_route_TeamRGG": ESM_CHI[team],
        "abs_diff": float(abs(pred - ESM_CHI[team])),
    }
    order_esm = "LAF-1 > Ddx4N1" if ESM_CHI[a1] > ESM_CHI[a2] else "Ddx4N1 > LAF-1"
    order_B = "LAF-1 > Ddx4N1" if mp[a1] > mp[a2] else "Ddx4N1 > LAF-1"
    res["ordering"] = {"route_A": order_esm, "route_B": order_B, "consistent": order_esm == order_B}
    if out_json:
        with open(out_json, "w", encoding="utf-8") as f:
            json.dump(res, f, ensure_ascii=False, indent=2)
    return res

ELP Spatial Distribution Model

Code 1: Polar localization_Colescence.m (local functions)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
function [kp, kc] = evaluate_rates(T_K, p, c)
kp = (c.kB * T_K / c.h) * exp(p.DeltaS / c.R) * exp(-p.DeltaH / (c.R * T_K));
eta = p.eta0 * exp(p.B / (T_K - p.T0));
gamma = p.gamma0 + p.alpha * (T_K - c.Tr);
kc = p.kc0 * gamma / eta;
end
function dPdt = polar_ode(~, P, kp, kc)
dPdt = kp * (1 - P) - kc * P;
end
function lhs = custom_lhs(N, D)
lhs = zeros(N, D);
for j = 1:D
    lhs(:, j) = (randperm(N)' - rand(N, 1)) / N;
end
end
function r = custom_rank(x)
[~, idx] = sort(x);
r = zeros(size(x));
r(idx) = 1:numel(x);
end
function prcc = calculate_prcc(X, Y)
N = size(X, 1);
D = size(X, 2);
Rx = zeros(N, D);
for j = 1:D
    Rx(:, j) = custom_rank(X(:, j));
end
Ry = custom_rank(Y);
W = [Rx, Ry];
C = corrcoef(W);
V = inv(C + eye(size(C)) * 1e-12);
prcc = zeros(D, 1);
for j = 1:D
    prcc(j) = -V(j, D+1) / sqrt(V(j, j) * V(D+1, D+1));
end
end
function display_ranking_tables(names, prcc20, prcc37, prccDP)
fprintf('====================================================================\n');
fprintf('             GLOBAL SENSITIVITY ANALYSIS (PRCC RANKING)             \n');
fprintf('====================================================================\n');
[~, idx20] = sort(abs(prcc20), 'descend');
fprintf('\n[Rank for Polar Steady State P*(20 degC)]:\n');
fprintf('%-4s | %-12s | %-10s\n', 'Rank', 'Parameter', 'PRCC Value');
fprintf('--------------------------------------\n');
for r = 1:length(idx20)
    idx = idx20(r);
    fprintf('%-4d | %-12s | %+.4f\n', r, names{idx}, prcc20(idx));
end
[~, idx37] = sort(abs(prcc37), 'descend');
fprintf('\n[Rank for Dispersed Steady State P*(37 degC)]:\n');
fprintf('%-4s | %-12s | %-10s\n', 'Rank', 'Parameter', 'PRCC Value');
fprintf('--------------------------------------\n');
for r = 1:length(idx37)
    idx = idx37(r);
    fprintf('%-4d | %-12s | %+.4f\n', r, names{idx}, prcc37(idx));
end
[~, idxDP] = sort(abs(prccDP), 'descend');
fprintf('\n[Rank for Transition Drop (Delta P = P20 - P37)]:\n');
fprintf('%-4s | %-12s | %-10s\n', 'Rank', 'Parameter', 'PRCC Value');
fprintf('--------------------------------------\n');
for r = 1:length(idxDP)
    idx = idxDP(r);
    fprintf('%-4d | %-12s | %+.4f\n', r, names{idx}, prccDP(idx));
end
fprintf('====================================================================\n\n');
end
Code 2: Polar localization_Colescence.m (main program)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
const.kB = 1.380649e-23;
const.h  = 6.62607015e-34;
const.R  = 8.314;
const.Tr = 293.15;
param.T0     = 241;
param.B      = 670;
param.eta0   = 1.3e-5;
param.gamma0 = 5.0e-3;
param.alpha  = 1.0e-4;
param.kc0    = 1 / (15 * 3e-7);
param.DeltaH = 48800;
param.DeltaS = -20;
T_20K = 20 + 273.15;
T_37K = 37 + 273.15;
[kp_20, kc_20] = evaluate_rates(T_20K, param, const);
Pstar_20_steady = kp_20 / (kp_20 + kc_20);
tau_20 = 1 / (kp_20 + kc_20);
[t_20, P_20] = ode15s(@(t, P) polar_ode(t, P, kp_20, kc_20), [0, 5*tau_20], 0.1);
[kp_37, kc_37] = evaluate_rates(T_37K, param, const);
Pstar_37_steady = kp_37 / (kp_37 + kc_37);
tau_37 = 1 / (kp_37 + kc_37);
[t_37, P_37] = ode15s(@(t, P) polar_ode(t, P, kp_37, kc_37), [0, 5*tau_37], 0.1);
fprintf('--- Task 1: Physically Tuned Parameters Initialized Successfully ---\n\n');
T_celsius = 18:0.1:40;
T_kelvin = T_celsius + 273.15;
N_pts = length(T_celsius);
kp_sweep    = zeros(1, N_pts);
kc_sweep    = zeros(1, N_pts);
Pi_sweep    = zeros(1, N_pts);
Pstar_sweep = zeros(1, N_pts);
for i = 1:N_pts
    [kp_sweep(i), kc_sweep(i)] = evaluate_rates(T_kelvin(i), param, const);
    Pi_sweep(i) = kp_sweep(i) / kc_sweep(i);
    Pstar_sweep(i) = kp_sweep(i) / (kp_sweep(i) + kc_sweep(i));
end
T_transition = interp1(Pi_sweep, T_celsius, 1);
fprintf('--- Task 2: Temperature Sweep Completed ---\n');
if isnan(T_transition)
    fprintf('Calculated Transition Point (Pi = 1): Out of range\n\n');
else
    fprintf('Calculated Transition Point (Pi = 1): %.2f degC\n\n', T_transition);
end
P0 = 0.1;
T_nodes_C = linspace(20, 40, 6);
for i = 1:length(T_nodes_C)
    T_C = T_nodes_C(i);
    T_K = T_C + 273.15;
    [kp_i, kc_i] = evaluate_rates(T_K, param, const);
    tau_i = 1 / (kp_i + kc_i);
    t_span_i = [0, 5 * tau_i];
    [t_i, P_i] = ode15s(@(t, P) polar_ode(t, P, kp_i, kc_i), t_span_i, P0);
    Pstar_steady = kp_i / (kp_i + kc_i);
end
N_samples = 10000;
param_names = {'eta0', 'B', 'T0', 'gamma0', 'alpha', 'kc0', 'DeltaH', 'DeltaS'};
D = length(param_names);
bounds.eta0   = [1.17e-5, 1.43e-5];
bounds.B      = [636.5, 703.5];
bounds.T0     = [236.18, 245,82];
bounds.gamma0 = [4.5e-3, 5.5e-3];
bounds.alpha  = [0.9e-4, 1.1e-4];
bounds.kc0    = [2.0e5, 2.44e5];
bounds.DeltaH = [43920, 53680];
bounds.DeltaS = [-22, -18];
rng(42);
lhs_normalized = custom_lhs(N_samples, D);
X_samples = zeros(N_samples, D);
for j = 1:D
    limits = bounds.(param_names{j});
    X_samples(:, j) = limits(1) + lhs_normalized(:, j) * (limits(2) - limits(1));
end
P20_sim = zeros(N_samples, 1);
P37_sim = zeros(N_samples, 1);
DeltaP_sim = zeros(N_samples, 1);
for i = 1:N_samples
    temp_param.eta0   = X_samples(i, 1);
    temp_param.B      = X_samples(i, 2);
    temp_param.T0     = X_samples(i, 3);
    temp_param.gamma0 = X_samples(i, 4);
    temp_param.alpha  = X_samples(i, 5);
    temp_param.kc0    = X_samples(i, 6);
    temp_param.DeltaH = X_samples(i, 7);
    temp_param.DeltaS = X_samples(i, 8);
    [kp_20_tmp, kc_20_tmp] = evaluate_rates(T_20K, temp_param, const);
    P20_sim(i) = kp_20_tmp / (kp_20_tmp + kc_20_tmp);
    [kp_37_tmp, kc_37_tmp] = evaluate_rates(T_37K, temp_param, const);
    P37_sim(i) = kp_37_tmp / (kp_37_tmp + kc_37_tmp);
    DeltaP_sim(i) = P20_sim(i) - P37_sim(i);
end
mu_P20 = mean(P20_sim);
mu_P37 = mean(P37_sim);
mu_DeltaP = mean(DeltaP_sim);
prcc_P20 = calculate_prcc(X_samples, P20_sim);
prcc_P37 = calculate_prcc(X_samples, P37_sim);
prcc_DeltaP = calculate_prcc(X_samples, DeltaP_sim);
display_ranking_tables(param_names, prcc_P20, prcc_P37, prcc_DeltaP);
t_steady_sweep = zeros(1, N_pts);
for i = 1:N_pts
    [kp_tmp, kc_tmp] = evaluate_rates(T_kelvin(i), param, const);
    t_steady_sweep(i) = -log(0.01) / (kp_tmp + kc_tmp);
end
t_steady_20_ms = (-log(0.01) / (kp_20 + kc_20)) * 1e3;
t_steady_37_ms = (-log(0.01) / (kp_37 + kc_37)) * 1e3;
save('simulation_results.mat', 'param', 'const', 'T_celsius', 'Pi_sweep', ...
'Pstar_sweep', 't_20', 'P_20', 't_37', 'P_37', 'X_samples', ...
'P20_sim', 'P37_sim', 'DeltaP_sim', 'prcc_P20', 'prcc_P37', 'prcc_DeltaP');
fprintf('--- Simulation Completed! Data saved to "simulation_results.mat". ---\n');
Code 3: PDE.m (local functions)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
function s = celsius_symbol()
    s = [char(176) 'C'];
end
function [A, maskLinIdx, idOfLin] = build_laplacian_operator(mask, h)
    [ny, nx] = size(mask);
    maskLinIdx = find(mask);
    Np = numel(maskLinIdx);
    idOfLin = zeros(ny, nx);
    idOfLin(maskLinIdx) = 1:Np;
    [rows, cols] = ind2sub([ny, nx], maskLinIdx);
    currentId = (1:Np)';
    dirs = [1 0; -1 0; 0 1; 0 -1];
    I = zeros(0, 1); J = zeros(0, 1); V = zeros(0, 1);
    for d = 1:4
        di = dirs(d, 1); dj = dirs(d, 2);
        ni = rows + di; nj = cols + dj;
        valid = ni >= 1 & ni <= ny & nj >= 1 & nj <= nx;
        idx = find(valid);
        ni2 = ni(idx); nj2 = nj(idx);
        nbLin = sub2ind([ny, nx], ni2, nj2);
        keep = mask(nbLin);
        idx2 = idx(keep);
        nbLin2 = sub2ind([ny, nx], rows(idx2) + di, cols(idx2) + dj);
        nbId = idOfLin(nbLin2);
        I = [I; currentId(idx2); currentId(idx2)];
        J = [J; nbId; currentId(idx2)];
        w = ones(numel(idx2), 1) / h^2;
        V = [V; w; -w];
    end
    A = sparse(I, J, V, Np, Np);
end
function Lmob = build_weighted_laplacian(mask, idOfLin, Mfield, h)
    [ny, nx] = size(mask);
    maskLinIdx = find(mask);
    Np = numel(maskLinIdx);
    [rows, cols] = ind2sub([ny, nx], maskLinIdx);
    currentId = (1:Np)';
    dirs = [1 0; -1 0; 0 1; 0 -1];
    I = zeros(0, 1); J = zeros(0, 1); V = zeros(0, 1);
    for d = 1:4
        di = dirs(d, 1); dj = dirs(d, 2);
        ni = rows + di; nj = cols + dj;
        valid = ni >= 1 & ni <= ny & nj >= 1 & nj <= nx;
        idx = find(valid);
        ni2 = ni(idx); nj2 = nj(idx);
        nbLin = sub2ind([ny, nx], ni2, nj2);
        keep = mask(nbLin);
        idx2 = idx(keep);
        nbLin2 = sub2ind([ny, nx], rows(idx2) + di, cols(idx2) + dj);
        nbId = idOfLin(nbLin2);
        faceM = 0.5 * (Mfield(idx2) + Mfield(nbId));
        I = [I; currentId(idx2); currentId(idx2)];
        J = [J; nbId; currentId(idx2)];
        V = [V; faceM / h^2; -faceM / h^2];
    end
    Lmob = sparse(I, J, V, Np, Np);
end
function chiVal = chi_from_temperature(T_K, model, pH)
    if nargin < 3 || isempty(pH)
        chiVal = model.chiA + model.chiB ./ T_K;
    else
        dpH = pH - model.pHRef;
        chiVal = model.chiA + model.chiB ./ T_K ...
            + model.chiPH1 .* dpH + model.chiPH2 .* dpH.^2 ...
            + model.chiPHOffset;
    end
    chiVal = min(max(chiVal, model.chiMin), model.chiMax);
end
function M_T = mobility_temperature(T_K, model)
    M_T = model.Mref .* exp(-model.EaR .* ...
        (1 ./ T_K - 1 / model.Tref_K));
end
function Mfield = mobility_field(phi, T_K, model)
    M_T = mobility_temperature(T_K, model);
    phiClip = min(max(phi, 0), 1);
    Mfield = M_T .* phiClip .* (1 - phiClip);
end
function mu = local_chemical_potential(phi, chi, N, kBT)
    phiClip = min(max(phi, 1e-8), 1 - 1e-8);
    mu = kBT .* ((1 / N) .* (log(phiClip) + 1) ...
        - (log(1 - phiClip) + 1) + chi .* (1 - 2 .* phiClip));
end
function [phiFinal, heteroIndex, avgFluor, massHistory] = ...
        run_case(P, phiInit, chi, T_K, model)
    Np = numel(phiInit);
    phi = phiInit;
    dt = P.dt_init;
    accepted = 0;
    stepCount = 0;
    massHistory = zeros(P.max_steps, 1);
    phiLo = 1e-7;
    phiHi = 1 - 1e-7;
    targetSum = sum(phiInit);
    while stepCount < P.max_steps
        muBulk = local_chemical_potential(phi, chi, P.N, P.kBT);
        Mfield = mobility_field(phi, T_K, model);
        Lmob = build_weighted_laplacian(P.mask, P.idOfLin, Mfield, P.h);
        RHS = phi + dt .* (Lmob * muBulk);
        LHS = speye(Np) + dt .* P.kappa .* (Lmob * P.A);
        phiTry = LHS \ RHS;
        isValid = all(isfinite(phiTry)) ...
            && max(phiTry) <= 1.02 && min(phiTry) >= -0.02;
        if ~isValid
            dt = max(dt * P.shrinkFactor, P.dt_min);
            accepted = 0;
            if dt <= P.dt_min
                phiTry = phi;
            else
                continue;
            end
        end
        stepCount = stepCount + 1;
        phi = conservative_project(phiTry, targetSum, phiLo, phiHi);
        massHistory(stepCount) = sum(phi) * P.h^2;
        accepted = accepted + 1;
        if accepted >= P.growAfter
            dt = min(dt * P.growFactor, P.dt_max);
            accepted = 0;
        end
    end
    massHistory = massHistory(1:stepCount);
    phiFinal = phi;
    field2d = nan(P.ny, P.nx);
    field2d(P.maskLinIdx) = phiFinal;
    if ~any(isfinite(field2d(:)))
        error('ELP:InvalidFinalField', ...
            'Final field contains no finite values.');
    end
    heteroIndex = field_heterogeneity(field2d, P.mask);
    avgFluor = mean_fluorescence_proxy(phiFinal, model, P.h);
end
function phiC = conservative_project(phiTry, targetSum, lo, hi)
    Np  = numel(phiTry);
    tol = 1e-13 * max(abs(targetSum), 1);
    phiC = min(max(phiTry, lo), hi);
    if targetSum <= Np * lo || targetSum >= Np * hi
        return;
    end
    for it = 1:10
        dm = targetSum - sum(phiC);
        if abs(dm) <= tol
            return;
        end
        w  = (phiC - lo) .* (hi - phiC);
        sw = sum(w);
        if sw <= eps
            break;
        end
        phiC = min(max(phiC + dm * (w / sw), lo), hi);
    end
    if abs(targetSum - sum(phiC)) <= tol
        return;
    end
    sLo = -1;  sHi = 1;
    for k = 1:80
        sMid = 0.5 * (sLo + sHi);
        if sum(min(max(phiTry + sMid, lo), hi)) < targetSum
            sLo = sMid;
        else
            sHi = sMid;
        end
        if sHi - sLo < 1e-15
            break;
        end
    end
    phiC = min(max(phiTry + 0.5 * (sLo + sHi), lo), hi);
end
function avgFluor = mean_fluorescence_proxy(phi, model, h)
    signal = model.fluorescenceBackground + ...
        model.fluorescenceGain .* phi;
    signalCorrected = max(signal - model.fluorescenceBackground, 0);
    avgFluor = sum(signalCorrected) * h^2 / (numel(phi) * h^2);
end
function heteroIndex = field_heterogeneity(field2d, mask)
    values = field2d(mask);
    meanValue = mean(values);
    if ~isfinite(meanValue) || meanValue <= 0
        heteroIndex = NaN;
        return;
    end
    heteroIndex = std(values) / meanValue;
end
function [bestParams, report] = fit_chi_to_metrics(P, phiInit, options, model)
    TrefFit_K = mean(options.T_C + 273.15);
    bScale = 1000;
    bInitial = options.initialAB(2);
    chiRefInitial = options.initialAB(1) + bInitial / TrefFit_K;
    u0 = [chiRefInitial, bInitial / bScale];
    Pcoarse = P;
    Pcoarse.max_steps = min(P.max_steps, options.coarseSteps);
    if isfield(P, 'max_steps_slowQuench') && P.max_steps > 0
        stepRatio = P.max_steps_slowQuench / P.max_steps;
        Pcoarse.max_steps_slowQuench = max(Pcoarse.max_steps, ...
            round(Pcoarse.max_steps * stepRatio));
    end
    opts = optimset('Display', 'on', ...
        'MaxIter', options.maxIter, ...
        'MaxFunEvals', floor(1.5 * options.maxIter), ...
        'TolX', 5e-4, 'TolFun', 1e-5);
    coarseObjective = @(u) chi_fit_objective(u, Pcoarse, ...
        phiInit, options, model);
    [uCoarse, ~, ~, coarseOutput] = fminsearch(coarseObjective, u0, opts);
    fullObjective = @(u) chi_fit_objective(u, P, phiInit, options, model);
    [uBest, fval, exitflag, output] = fminsearch(fullObjective, uCoarse, opts);
    bBest = uBest(2) * bScale;
    aBest = uBest(1) - bBest / TrefFit_K;
    bestParams.a = aBest;
    bestParams.b = bBest;
    report.enabled = true;
    report.objective = fval;
    report.exitflag = exitflag;
    report.output = output;
    report.coarseOutput = coarseOutput;
    report.T_C = options.T_C;
    report.targetMetrics = experimental_fit_metrics(options.expMetrics);
    report.fittedMetrics = simulate_fit_metrics( ...
        aBest, bBest, P, phiInit, options, model);
end
function value = chi_fit_objective(u, P, phiInit, options, model)
    T_K = options.T_C + 273.15;
    bScale = 1000;
    TrefFit_K = mean(T_K);
    b = u(2) * bScale;
    a = u(1) - b / TrefFit_K;
    chiVals = a + b ./ T_K;
    penalty = 0;
    chi12 = a + b / (options.TcLower_C + 273.15);
    chi20 = a + b / (options.TcUpper_C + 273.15);
    if chi12 > options.chiCrit
        penalty = penalty + 100 * (chi12 - options.chiCrit)^2;
    end
    if chi20 <= options.chiCrit
        penalty = penalty + 100 * (options.chiCrit - chi20 + 1e-3)^2;
    end
    chiAt20fit = a + b / options.T20_K;
    if chiAt20fit < options.chiMin20
       penalty = penalty + 1e3 * (options.chiMin20 - chiAt20fit + 1e-4)^2;
    end
    if any(chiVals < options.chiMin | chiVals > options.chiMax)
        penalty = penalty + 100 * sum( ...
            max(options.chiMin - chiVals, 0).^2 ...
            + max(chiVals - options.chiMax, 0).^2);
    end
    if a < options.aBounds(1) || a > options.aBounds(2)
        penalty = penalty + 100 * max(options.aBounds(1) - a, 0)^2 ...
            + 100 * max(a - options.aBounds(2), 0)^2;
    end
    if b < options.bBounds(1) || b > options.bBounds(2)
        penalty = penalty + 100 * max(options.bBounds(1) - b, 0)^2 ...
            + 100 * max(b - options.bBounds(2), 0)^2;
    end
    if penalty > 0
        value = penalty + 1;
        return;
    end
    fitted = simulate_fit_metrics(a, b, P, phiInit, options, model);
    target = experimental_fit_metrics(options.expMetrics);
    scaleFloor = 1e-3;
    scales = max(abs(target) .* options.fluorescenceRelativeSigma(:), scaleFloor);
    residual = (fitted - target) ./ scales;
    delta = options.huberDelta;
    absResidual = abs(residual);
    rho = 0.5 .* min(absResidual, delta).^2 ...
        + delta .* max(absResidual - delta, 0);
    value = mean(rho(:));
end
function metrics = experimental_fit_metrics(expMetrics)
    metrics = expMetrics.condensateFluorescenceIntensity(:) ...
        ./ expMetrics.cellFluorescenceIntensity(:);
end
function fitted = simulate_fit_metrics(a, b, P, phiInit, options, model)
    T_K = options.T_C + 273.15;
    fitted = zeros(numel(T_K), 1);
    slowSteps = P.max_steps;
    if isfield(P, 'max_steps_slowQuench')
        slowSteps = P.max_steps_slowQuench;
    end
    for i = 1:numel(T_K)
        Pi = P;
        Pi.max_steps = adaptive_max_steps(options.T_C(i), P.max_steps, slowSteps);
        [phi, ~] = run_case(Pi, phiInit, a + b / T_K(i), T_K(i), model);
        field2d = nan(P.ny, P.nx);
        field2d(P.maskLinIdx) = phi;
        fitted(i) = simulated_fluorescence_fraction(field2d, P.mask, options);
    end
end
function nSteps = adaptive_max_steps(T_C, baseSteps, slowSteps)
    T_lo = 20.0;
    T_hi = 35.0;
    p    = 1.4;
    frac = (T_hi - T_C) / (T_hi - T_lo);
    frac = min(max(frac, 0), 1);
    frac = frac .^ p;
    nSteps = round(baseSteps + frac * (slowSteps - baseSteps));
end
function fluorFraction = simulated_fluorescence_fraction(field2d, mask, options)
    normalized = field2d;
    normalized(~mask) = 0;
    normalized(~isfinite(normalized)) = 0;
    normalized = mat2gray(normalized);
    adaptiveMask = imbinarize(normalized, 'adaptive', ...
        'Sensitivity', options.condensateAdaptiveSensitivity);
    adaptiveMask = adaptiveMask & mask;
    radius = options.condensateMorphologyRadiusPx;
    if radius > 0
        se = strel('disk', max(1, round(radius)), 0);
        adaptiveMask = imopen(adaptiveMask, se);
        adaptiveMask = imclose(adaptiveMask, se);
    end
    condensate = bwareaopen(adaptiveMask, options.condensateMinAreaPx, 8);
    fluorFraction = sum(field2d(condensate), 'omitnan') ...
        / max(sum(field2d(mask), 'omitnan'), eps);
end
function f = chi_to_fraction(P, phiInit, chi, T_K, nSteps, model, seg)
    P.max_steps = nSteps;
    phi = run_case(P, phiInit, chi, T_K, model);
    field2d = nan(P.ny, P.nx);
    field2d(P.maskLinIdx) = phi;
    f = simulated_fluorescence_fraction(field2d, P.mask, seg);
end
function n = ph_steps_for(P, T_C)
    if isfield(P, 'phSteps') && ~isempty(P.phSteps)
        n = P.phSteps;
    else
        n = adaptive_max_steps(T_C, P.max_steps, P.max_steps_slowQuench);
    end
end
function [fractions, fields] = simulate_ph_fraction(P, phiInit, T_C, pH, model, seg)
    n = numel(T_C);
    fractions = nan(n, 1);
    fields = cell(n, 1);
    for i = 1:n
        T_K = T_C(i) + 273.15;
        chi = chi_from_temperature(T_K, model, pH(i));
        Pi = P;
        Pi.max_steps = ph_steps_for(P, T_C(i));
        phi = run_case(Pi, phiInit, chi, T_K, model);
        field2d = nan(P.ny, P.nx);
        field2d(P.maskLinIdx) = phi;
        fields{i} = field2d;
        fractions(i) = simulated_fluorescence_fraction(field2d, P.mask, seg);
    end
end
function [v, vData] = ph_objective(theta, model, expPH, tempList, tIdx, chiGrid, fracGrid, sigmaAbs, bnd, reg)
    c1 = min(max(theta(1), bnd.c1(1)), bnd.c1(2));
    d0 = min(max(theta(2), bnd.d0(1)), bnd.d0(2));
    pen = 1e3 * ((theta(1) - c1)^2 + (theta(2) - d0)^2);
    m = model;
    m.chiPH1 = c1;
    m.chiPH2 = 0;
    m.chiPHOffset = d0;
    r = zeros(numel(expPH.pH), 1);
    for it = 1:numel(tempList)
        sel = (tIdx == it);
        chi = chi_from_temperature(tempList(it) + 273.15, m, expPH.pH(sel));
        chi = min(max(chi, chiGrid(1)), chiGrid(end));
        fm = interp1(chiGrid, fracGrid(:, it), chi, 'linear');
        r(sel) = (fm(:) - expPH.fraction(sel)) ./ sigmaAbs(sel);
    end
    vData = sum(r.^2);
    v = vData + reg * (d0 / 0.1)^2 + pen;
end
function fracGrid = scan_fraction_curves(P, phiInit, chiGrid, tempList, model, seg, useParallel)
    nT = numel(tempList);
    nG = numel(chiGrid);
    nJ = nG * nT;
    jobChi = repmat(chiGrid(:)', 1, nT);
    jobT_C = repelem(tempList(:)', nG);
    jobSteps = arrayfun(@(t) ph_steps_for(P, t), jobT_C);
    fracVec = nan(1, nJ);
    if useParallel
        parfor j = 1:nJ
            fracVec(j) = chi_to_fraction(P, phiInit, jobChi(j), ...
                jobT_C(j) + 273.15, jobSteps(j), model, seg);
        end
    else
        for j = 1:nJ
            fracVec(j) = chi_to_fraction(P, phiInit, jobChi(j), ...
                jobT_C(j) + 273.15, jobSteps(j), model, seg);
            fprintf('  %g%s, chi = %.4f -> fraction = %.4f\n', ...
                jobT_C(j), celsius_symbol(), jobChi(j), fracVec(j));
        end
    end
    fracGrid = reshape(fracVec, nG, nT);
end
function br = ph_target_bracket(chiGrid, fracGrid, expPH, tIdx, margin)
    chiGrid = chiGrid(:);
    lo = inf;  hi = -inf;
    for it = 1:size(fracGrid, 2)
        f = fracGrid(:, it);
        tg = expPH.fraction(tIdx == it);
        [fPk, ipk] = max(f);
        fLo = max(min(tg) - margin, 0);
        fHi = min(max(tg) + margin, fPk);
        iL = find(f(1:ipk) <= fLo, 1, 'last');
        if isempty(iL), iL = 1; end
        iH = find(f(1:ipk) >= fHi, 1, 'first');
        if isempty(iH), iH = ipk; end
        if iH <= iL, iH = min(iL + 1, numel(chiGrid)); end
        lo = min(lo, chiGrid(iL));
        hi = max(hi, chiGrid(iH));
    end
    if hi - lo < 1e-3
        lo = lo - 0.01;  hi = hi + 0.01;
    end
    br = [lo, hi];
end
function [thBest, vBest, vDataBest] = fit_ph_on_curves(model, expPH, tempList, tIdx, ...
        chiGrid, fracGrid, sigmaAbs, cfg)
    bnd.c1 = [0, cfg.phC1Max];
    if cfg.phFitOffset
        bnd.d0 = cfg.phD0Bounds(:)';
    else
        bnd.d0 = [0, 0];
    end
    chiCol = chiGrid(:);
    obj = @(th) ph_objective(th, model, expPH, tempList, tIdx, chiCol, ...
        fracGrid, sigmaAbs, bnd, cfg.phD0Reg);
    c1v = linspace(bnd.c1(1), bnd.c1(2), cfg.phC1ScanN);
    if cfg.phFitOffset
        d0v = linspace(bnd.d0(1), bnd.d0(2), cfg.phD0ScanN);
    else
        d0v = 0;
    end
    O = zeros(numel(d0v), numel(c1v));
    for i = 1:numel(d0v)
        for j = 1:numel(c1v)
            O(i, j) = obj([c1v(j), d0v(i)]);
        end
    end
    [~, ord] = sort(O(:));
    nStart = min(5, numel(ord));
    opts = optimset('TolX', 1e-8, 'TolFun', 1e-10, 'Display', 'off', ...
        'MaxIter', 400, 'MaxFunEvals', 800);
    thBest = [];  vBest = inf;
    for s = 1:nStart
        [i, j] = ind2sub(size(O), ord(s));
        th0 = [c1v(j), d0v(i)];
        if cfg.phFitOffset
            [th, v] = fminsearch(obj, th0, opts);
        else
            th = th0;  v = O(i, j);
        end
        th(1) = min(max(th(1), bnd.c1(1)), bnd.c1(2));
        th(2) = min(max(th(2), bnd.d0(1)), bnd.d0(2));
        if v < vBest
            vBest = v;  thBest = th;
        end
    end
    [~, vDataBest] = ph_objective(thBest, model, expPH, tempList, tIdx, chiCol, ...
        fracGrid, sigmaAbs, bnd, cfg.phD0Reg);
end
function [bestParams, report] = fit_ph_to_fraction(P, phiInit, expPH, model, seg, cfg)
    tempList = unique(expPH.T_C(:));
    nT = numel(tempList);
    tIdx = arrayfun(@(t) find(abs(tempList - t) < 1e-9, 1), expPH.T_C(:));
    sigmaAbs = max(expPH.fraction(:) .* cfg.phFractionRelativeSigma(:), 1e-3);
    useParallel = cfg.phUseParallel ...
        && license('test', 'Distrib_Computing_Toolbox');
    chi0 = arrayfun(@(t) chi_from_temperature(t + 273.15, model), tempList);
    lo1 = max(model.chiMin, min(chi0) + cfg.phScanOffsets(1));
    hi1 = min(model.chiMax, max(chi0) + cfg.phScanOffsets(2));
    chiGrid = linspace(lo1, hi1, cfg.phGridN)';
    fprintf('\npH fit, stage 1: %d chi values in [%.4f, %.4f] at %d temperature(s) (%d simulations)%s ...\n', ...
        numel(chiGrid), lo1, hi1, nT, numel(chiGrid) * nT, ...
        ternary(useParallel, ' [parfor]', ''));
    fracGrid = scan_fraction_curves(P, phiInit, chiGrid, tempList, model, seg, useParallel);
    for rd = 1:cfg.phRefineRounds
        br = ph_target_bracket(chiGrid, fracGrid, expPH, tIdx, cfg.phBracketMargin);
        cand = linspace(br(1), br(2), cfg.phRefineN)';
        keep = true(size(cand));
        for k = 1:numel(cand)
            keep(k) = all(abs(cand(k) - chiGrid) > 1e-9);
        end
        newChi = cand(keep);
        if isempty(newChi)
            break;
        end
        fprintf('pH fit, refine %d: %d extra chi values in [%.4f, %.4f] (%d simulations)%s ...\n', ...
            rd, numel(newChi), br(1), br(2), numel(newChi) * nT, ...
            ternary(useParallel, ' [parfor]', ''));
        newFrac = scan_fraction_curves(P, phiInit, newChi, tempList, model, seg, useParallel);
        chiAll = [chiGrid; newChi];
        fracAll = [fracGrid; newFrac];
        [chiAll, ord] = sort(chiAll);
        chiGrid = chiAll;
        fracGrid = fracAll(ord, :);
    end
    [thBest, objBest, objData] = fit_ph_on_curves(model, expPH, tempList, tIdx, ...
        chiGrid, fracGrid, sigmaAbs, cfg);
    fprintf('  c1 = %.6f, d0 = %+.6f (weighted SSE = %.4f, incl. regularisation %.4f)\n', ...
        thBest(1), thBest(2), objData, objBest);
    if thBest(1) >= cfg.phC1Max - 1e-9
        warning('ELP:PHC1AtBound', ...
            'c1 hit the upper bound cfg.phC1Max = %g; consider raising it.', cfg.phC1Max);
    end
    if cfg.phFitOffset && (thBest(2) <= cfg.phD0Bounds(1) + 1e-9 ...
            || thBest(2) >= cfg.phD0Bounds(2) - 1e-9)
        warning('ELP:PHD0AtBound', ...
            'd0 hit a bound of cfg.phD0Bounds = [%g, %g]; consider widening it.', ...
            cfg.phD0Bounds(1), cfg.phD0Bounds(2));
    end
    bestParams = struct('c1', thBest(1), 'd0', thBest(2), 'c2', 0);
    report = struct();
    report.enabled = true;
    report.tempList = tempList;
    report.chiGrid = chiGrid(:);
    report.fracGrid = fracGrid;
    report.objective = objData;
    report.targetFraction = expPH.fraction(:);
end
function out = ternary(cond, a, b)
    if cond, out = a; else, out = b; end
end
function sensitivity = analyze_mobility_sensitivity(P, phiInit, ...
        fitT_C, model, relativeStep)
    names = {'Mref'; 'EaR'; 'Tref_K'};
    fieldNames = {'Mref', 'EaR', 'Tref_K'};
    T_K = fitT_C + 273.15;
    baseHetero = simulate_mobility_heterogeneity(P, phiInit, T_K, model);
    nRows = 3 * numel(T_K);
    parameterColumn = cell(nRows, 1);
    temperatureColumn = zeros(nRows, 1);
    lowValues = zeros(nRows, 1);
    baseValues = zeros(nRows, 1);
    highValues = zeros(nRows, 1);
    elasticity = zeros(nRows, 1);
    row = 0;
    for ip = 1:numel(fieldNames)
        key = fieldNames{ip};
        baseValue = model.(key);
        lowModel = model;
        highModel = model;
        lowModel.(key) = baseValue * (1 - relativeStep);
        highModel.(key) = baseValue * (1 + relativeStep);
        lowerHetero = simulate_mobility_heterogeneity(P, phiInit, T_K, lowModel);
        upperHetero = simulate_mobility_heterogeneity(P, phiInit, T_K, highModel);
        for it = 1:numel(T_K)
            row = row + 1;
            parameterColumn{row} = names{ip};
            temperatureColumn(row) = T_K(it) - 273.15;
            lowValues(row) = lowerHetero(it);
            baseValues(row) = baseHetero(it);
            highValues(row) = upperHetero(it);
            denominator = max(abs(baseHetero(it)) * 2 * relativeStep, eps);
            elasticity(row) = (upperHetero(it) - lowerHetero(it)) / denominator;
        end
    end
    sensitivity = table(parameterColumn, temperatureColumn, ...
        repmat(relativeStep * 100, nRows, 1), ...
        lowValues, baseValues, highValues, elasticity, ...
        'VariableNames', {'Parameter', 'Temperature_C', ...
        'PerturbationPercent', 'Heterogeneity_Low', 'Heterogeneity_Base', ...
        'Heterogeneity_High', 'NormalizedSensitivity'});
end
function heteroValues = simulate_mobility_heterogeneity(P, phiInit, T_K, model)
    heteroValues = zeros(size(T_K));
    for it = 1:numel(T_K)
        chi = chi_from_temperature(T_K(it), model);
        [~, heteroValues(it)] = run_case(P, phiInit, chi, T_K(it), model);
    end
end
Code 2: quantifyELPSpatialFeatures.m
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
function results = quantifyELPSpatialFeatures(fluorescenceFile, varargin)
opts = parseOptions(varargin{:});
if ~(ischar(fluorescenceFile) || isstring(fluorescenceFile))
    error('quantifyELPSpatialFeatures:InvalidInput', ...
        'fluorescenceFile must be a character vector or string scalar.');
end
fluorescenceFile = char(fluorescenceFile);
if ~isfile(fluorescenceFile)
    error('quantifyELPSpatialFeatures:FileNotFound', ...
        'Fluorescence file not found: %s', fluorescenceFile);
end
[fluorescence, inputInfo] = readFluorescenceImage( ...
    fluorescenceFile, opts.FluorescenceChannel);
imageSize = size(fluorescence);
if ~isempty(opts.BrightfieldFile)
    if ~isfile(opts.BrightfieldFile)
        error('quantifyELPSpatialFeatures:FileNotFound', ...
            'Brightfield file not found: %s', opts.BrightfieldFile);
    end
    brightfield = readGrayImage(opts.BrightfieldFile);
    if ~isequal(size(brightfield), imageSize)
        error('quantifyELPSpatialFeatures:SizeMismatch', ...
            'Brightfield and fluorescence images must have identical dimensions.');
    end
else
    brightfield = [];
end
if isempty(opts.CellMask)
    if isempty(brightfield)
        cellMask = true(imageSize);
        cellMaskSource = 'full image';
    else
        cellMask = segmentCellFromBrightfield(brightfield, fluorescence, opts);
        cellMaskSource = 'brightfield';
        if ~any(cellMask(:))
            if opts.UseFullImageIfNoCell
                warning('quantifyELPSpatialFeatures:CellSegmentationFailed', ...
                    'Automatic cell segmentation failed; using the full image.');
                cellMask = true(imageSize);
                cellMaskSource = 'full image fallback';
            else
                error('quantifyELPSpatialFeatures:CellSegmentationFailed', ...
                    'Automatic cell segmentation failed.');
            end
        end
    end
else
    if ~islogical(opts.CellMask) || ~isequal(size(opts.CellMask), imageSize)
        error('quantifyELPSpatialFeatures:InvalidCellMask', ...
            'CellMask must be a logical array with the same size as the fluorescence image.');
    end
    cellMask = opts.CellMask;
    cellMaskSource = 'user supplied';
end
if ~any(cellMask(:))
    error('quantifyELPSpatialFeatures:EmptyCellMask', 'The cell mask is empty.');
end
processed = backgroundCorrect(fluorescence, opts);
processed(~isfinite(processed)) = 0;
processed = max(processed, 0);
condensateMask = segmentCondensates(processed, cellMask, opts);
condensateMask = condensateMask & cellMask;
condensates = measureCondensates(condensateMask, processed, opts.PixelSizeUm);
acf = calculateRadialACF(processed, cellMask, opts.PixelSizeUm, ...
    opts.MaxACFRadiusUm);
metrics = calculateScalarMetrics(processed, cellMask, condensateMask, ...
    condensates, acf, opts.PixelSizeUm);
polarROI = makePolarROI(opts.PolarROI, imageSize);
polarization = calculatePolarization(processed, cellMask, polarROI);
results = struct();
results.input = inputInfo;
results.input.fluorescenceFile = fluorescenceFile;
results.input.brightfieldFile = opts.BrightfieldFile;
results.input.cellMaskSource = cellMaskSource;
results.input.pixelSizeUm = opts.PixelSizeUm;
results.input.options = opts;
results.images = struct( ...
    'fluorescence', fluorescence, ...
    'backgroundCorrected', processed, ...
    'brightfield', brightfield);
results.masks = struct( ...
    'cell', cellMask, ...
    'condensates', condensateMask, ...
    'polarROI', polarROI);
results.condensates = condensates;
results.metrics = metrics;
results.acf = acf;
results.polarization = polarization;
end
function opts = parseOptions(varargin)
parser = inputParser;
parser.FunctionName = 'quantifyELPSpatialFeatures';
addParameter(parser, 'BrightfieldFile', '', @(x) ischar(x) || isstring(x));
addParameter(parser, 'PixelSizeUm', 1, @(x) validateattributes(x, ...
    {'numeric'}, {'scalar', 'real', 'finite', 'positive'}));
addParameter(parser, 'FluorescenceChannel', 1, @(x) validateattributes(x, ...
    {'numeric'}, {'scalar', 'integer', '>=', 1, '<=', 3}));
addParameter(parser, 'CellMask', [], @(x) isempty(x) || islogical(x));
addParameter(parser, 'PolarROI', [], @(x) isempty(x) || islogical(x) || ...
    (isnumeric(x) && isvector(x) && numel(x) == 4));
addParameter(parser, 'BackgroundMethod', 'gaussian', @(x) ...
    ischar(x) || isstring(x));
addParameter(parser, 'BackgroundSigmaSmall', 0, @(x) validateattributes(x, ...
    {'numeric'}, {'scalar', 'real', 'finite', 'nonnegative'}));
addParameter(parser, 'BackgroundSigmaLarge', 20, @(x) validateattributes(x, ...
    {'numeric'}, {'scalar', 'real', 'finite', 'positive'}));
addParameter(parser, 'RollingBallRadius', 20, @(x) validateattributes(x, ...
    {'numeric'}, {'scalar', 'real', 'finite', 'positive'}));
addParameter(parser, 'AdaptiveSensitivity', 0.95, @(x) validateattributes(x, ...
    {'numeric'}, {'scalar', 'real', 'finite', '>', 0, '<', 1}));
addParameter(parser, 'MinCondensateAreaPx', 0.2, @(x) validateattributes(x, ...
    {'numeric'}, {'scalar', 'integer', 'positive'}));
addParameter(parser, 'MorphologyRadiusPx', 0, @(x) validateattributes(x, ...
    {'numeric'}, {'scalar', 'integer', 'nonnegative'}));
addParameter(parser, 'MaxACFRadiusUm', [], @(x) isempty(x) || ...
    (isnumeric(x) && isscalar(x) && isfinite(x) && x > 0));
addParameter(parser, 'UseFullImageIfNoCell', true, @(x) islogical(x) && isscalar(x));
parse(parser, varargin{:});
opts = parser.Results;
opts.BrightfieldFile = char(opts.BrightfieldFile);
opts.BackgroundMethod = lower(char(opts.BackgroundMethod));
if ~ismember(opts.BackgroundMethod, {'gaussian', 'rollingball'})
    error('quantifyELPSpatialFeatures:InvalidBackgroundMethod', ...
        'BackgroundMethod must be ''gaussian'' or ''rollingball''.');
end
end
function [image, info] = readFluorescenceImage(fileName, channel)
raw = imread(fileName);
info = struct();
info.class = class(raw);
info.originalSize = size(raw);
info.bitDepth = inferBitDepth(raw);
if ismatrix(raw)
    image = im2double(raw);
    info.channelUsed = 1;
    info.wasRGB = false;
else
    if size(raw, 3) < channel
        error('quantifyELPSpatialFeatures:InvalidChannel', ...
            'Requested channel %d is not available in the image.', channel);
    end
    image = im2double(raw(:, :, channel));
    info.channelUsed = channel;
    info.wasRGB = true;
end
end
function image = readGrayImage(fileName)
raw = imread(fileName);
if ismatrix(raw)
    image = im2double(raw);
else
    image = im2double(rgb2gray(raw(:, :, 1:3)));
end
end
function bitDepth = inferBitDepth(image)
if isa(image, 'uint8')
    bitDepth = 8;
elseif isa(image, 'uint16')
    bitDepth = 16;
else
    bitDepth = NaN;
end
end
function corrected = backgroundCorrect(image, opts)
switch opts.BackgroundMethod
    case 'gaussian'
        small = imgaussfilt(image, opts.BackgroundSigmaSmall);
        large = imgaussfilt(image, opts.BackgroundSigmaLarge);
        corrected = small - large;
    case 'rollingball'
        radius = max(1, round(opts.RollingBallRadius));
        se = diskSE(radius);
        background = imopen(image, se);
        corrected = image - background;
end
corrected = corrected - median(corrected(:));
end
function cellMask = segmentCellFromBrightfield(brightfield, fluorescence, opts)
smooth = imgaussfilt(brightfield, 1);
background = imgaussfilt(smooth, max(5, min(size(smooth)) / 8));
darkResponse = mat2gray(background - smooth);
brightResponse = mat2gray(smooth - background);
darkMask = imbinarize(darkResponse, 'adaptive', ...
    'Sensitivity', min(0.95, max(0.05, opts.AdaptiveSensitivity)));
brightMask = imbinarize(brightResponse, 'adaptive', ...
    'Sensitivity', min(0.95, max(0.05, opts.AdaptiveSensitivity)));
darkMask = cleanCellMask(darkMask, fluorescence);
brightMask = cleanCellMask(brightMask, fluorescence);
darkScore = cellMaskScore(darkMask, fluorescence);
brightScore = cellMaskScore(brightMask, fluorescence);
if darkScore >= brightScore
    cellMask = darkMask;
else
    cellMask = brightMask;
end
if any(cellMask(:))
    cellMask = selectSignalContainingComponent(cellMask, fluorescence);
end
end
function mask = cleanCellMask(mask, fluorescence)
minArea = max(10, round(numel(mask) * 0.0005));
mask = bwareaopen(mask, minArea);
mask = imclose(mask, diskSE(max(1, round(min(size(mask)) / 100))));
mask = imfill(mask, 'holes');
mask = selectSignalContainingComponent(mask, fluorescence);
end
function score = cellMaskScore(mask, fluorescence)
if ~any(mask(:))
    score = -Inf;
    return;
end
signal = fluorescence;
signal = signal - min(signal(:));
signal = signal / max(eps, max(signal(:)));
score = sum(signal(mask)) / nnz(mask) + 0.05 * log1p(nnz(mask));
end
function mask = selectSignalContainingComponent(mask, fluorescence)
labels = bwlabel(mask, 8);
numberOfLabels = max(labels(:));
if numberOfLabels == 0
    return;
end
signal = fluorescence - min(fluorescence(:));
signal = signal / max(eps, max(signal(:)));
scores = zeros(numberOfLabels, 1);
areas = zeros(numberOfLabels, 1);
for k = 1:numberOfLabels
    component = labels == k;
    areas(k) = nnz(component);
    scores(k) = sum(signal(component)) / max(1, areas(k));
end
scores = scores .* (1 ./ sqrt(max(1, areas)));
[~, best] = max(scores);
mask = labels == best;
end
function condensates = measureCondensates(mask, intensity, pixelSizeUm)
properties = regionprops(mask, intensity, ...
    'Area', 'Centroid', 'EquivDiameter', 'Perimeter', ...
    'MeanIntensity', 'BoundingBox', 'PixelIdxList');
numberOfObjects = numel(properties);
if numberOfObjects == 0
    condensates = struct( ...
        'count', 0, ...
        'areaPx', zeros(0, 1), ...
        'areaUm2', zeros(0, 1), ...
        'equivalentDiameterPx', zeros(0, 1), ...
        'equivalentDiameterUm', zeros(0, 1), ...
        'centroidPx', zeros(0, 2), ...
        'meanIntensity', zeros(0, 1), ...
        'integratedIntensity', zeros(0, 1), ...
        'perimeterPx', zeros(0, 1), ...
        'boundingBoxPx', zeros(0, 4));
    return;
end
areaPx = vertcat(properties.Area);
equivDiameterPx = vertcat(properties.EquivDiameter);
centroidPx = vertcat(properties.Centroid);
meanIntensity = vertcat(properties.MeanIntensity);
perimeterPx = vertcat(properties.Perimeter);
boundingBoxPx = vertcat(properties.BoundingBox);
integratedIntensity = zeros(numberOfObjects, 1);
for k = 1:numberOfObjects
    integratedIntensity(k) = sum(intensity(properties(k).PixelIdxList));
end
condensates = struct();
condensates.count = numberOfObjects;
condensates.areaPx = areaPx;
condensates.areaUm2 = areaPx * pixelSizeUm^2;
condensates.equivalentDiameterPx = equivDiameterPx;
condensates.equivalentDiameterUm = equivDiameterPx * pixelSizeUm;
condensates.centroidPx = centroidPx;
condensates.meanIntensity = meanIntensity;
condensates.integratedIntensity = integratedIntensity;
condensates.perimeterPx = perimeterPx;
condensates.boundingBoxPx = boundingBoxPx;
end
function acf = calculateRadialACF(image, cellMask, pixelSizeUm, maxRadiusUm)
image = double(image);
cellMask = double(cellMask);
meanInsideCell = sum(image(:) .* cellMask(:)) / max(1, sum(cellMask(:)));
fluctuation = (image - meanInsideCell) .* cellMask;
[rows, columns] = size(image);
fftRows = 2 * rows - 1;
fftColumns = 2 * columns - 1;
signalFFT = fft2(fluctuation, fftRows, fftColumns);
maskFFT = fft2(cellMask, fftRows, fftColumns);
numerator = fftshift(real(ifft2(abs(signalFFT).^2)));
denominator = fftshift(real(ifft2(abs(maskFFT).^2)));
acf2D = numerator ./ max(denominator, eps);
centerRow = rows;
centerColumn = columns;
c0 = acf2D(centerRow, centerColumn);
if ~isfinite(c0) || c0 <= 0
    acf = emptyACF(pixelSizeUm);
    return;
end
acf2D = acf2D / c0;
[xGrid, yGrid] = meshgrid((1:fftColumns) - centerColumn, ...
    (1:fftRows) - centerRow);
radiusPx = hypot(xGrid, yGrid);
radiusUm = radiusPx * pixelSizeUm;
if isempty(maxRadiusUm)
    maxRadiusUm = floor(min(rows, columns) / 2) * pixelSizeUm;
end
valid = isfinite(acf2D) & denominator > 0 & radiusUm <= maxRadiusUm;
binPx = floor(radiusPx(valid)) + 1;
binCount = max(binPx);
radialSum = accumarray(binPx(:), acf2D(valid), [binCount, 1], @sum, 0);
radialCount = accumarray(binPx(:), 1, [binCount, 1], @sum, 0);
radialACF = radialSum ./ max(radialCount, 1);
radialRadiusPx = ((1:binCount)' - 0.5);
radialRadiusUm = radialRadiusPx * pixelSizeUm;
if ~isempty(radialACF)
    radialACF(1) = 1;
end
correlationLengthUm = firstCrossing(radialRadiusUm, radialACF, exp(-1));
cellAreaUm2 = nnz(cellMask) * pixelSizeUm^2;
positiveACF = max(radialACF, 0);
integralPositive = 2 * pi * trapz(radialRadiusUm, ...
    positiveACF .* radialRadiusUm);
integralIndex = integralPositive / max(cellAreaUm2, eps);
acf = struct();
acf.radiusPx = radialRadiusPx;
acf.radiusUm = radialRadiusUm;
acf.radial = radialACF;
acf.correlationLengthUm = correlationLengthUm;
acf.integralPositiveUm2 = integralPositive;
acf.integralIndex = integralIndex;
acf.normalization = 'C(0)=1; mask-overlap corrected';
acf.formula = ['2*pi*integral(max(C(r),0)*r dr) / cellArea; ' ...
    'cellArea = nnz(cellMask)*pixelSizeUm^2'];
acf.twoDimensional = acf2D;
acf.radiusGridUm = radiusUm;
end
function acf = emptyACF(pixelSizeUm)
acf = struct( ...
    'radiusPx', zeros(0, 1), ...
    'radiusUm', zeros(0, 1), ...
    'radial', zeros(0, 1), ...
    'correlationLengthUm', NaN, ...
    'integralPositiveUm2', NaN, ...
    'integralIndex', NaN, ...
    'normalization', 'undefined because variance inside cell is zero', ...
    'formula', 'Not available', ...
    'twoDimensional', [], ...
    'radiusGridUm', []);
acf.pixelSizeUm = pixelSizeUm;
end
function metrics = calculateScalarMetrics(image, cellMask, condensateMask, ...
    condensates, acf, pixelSizeUm)
cellAreaPx = nnz(cellMask);
cellAreaUm2 = cellAreaPx * pixelSizeUm^2;
condensateAreaPx = nnz(condensateMask);
condensateAreaUm2 = condensateAreaPx * pixelSizeUm^2;
cellIntensity = sum(max(image(cellMask), 0));
if condensates.count == 0
    meanDiameterUm = NaN;
    meanAreaUm2 = NaN;
else
    meanDiameterUm = mean(condensates.equivalentDiameterUm);
    meanAreaUm2 = mean(condensates.areaUm2);
end
metrics = struct();
metrics.cellAreaPx = cellAreaPx;
metrics.cellAreaUm2 = cellAreaUm2;
metrics.condensateAreaPx = condensateAreaPx;
metrics.condensateAreaUm2 = condensateAreaUm2;
metrics.condensateAreaFraction = condensateAreaPx / max(cellAreaPx, 1);
metrics.condensateAreaPercent = 100 * metrics.condensateAreaFraction;
metrics.condensateCount = condensates.count;
metrics.condensateNumberDensityPerUm2 = condensates.count / max(cellAreaUm2, eps);
metrics.meanCondensateDiameterUm = meanDiameterUm;
metrics.meanCondensateAreaUm2 = meanAreaUm2;
metrics.acfCorrelationLengthUm = acf.correlationLengthUm;
metrics.acfIntegralIndex = acf.integralIndex;
metrics.totalCellFluorescence = cellIntensity;
metrics.condensateFluorescence = sum(max(image(condensateMask), 0));
end
function polarROI = makePolarROI(roiInput, imageSize)
if isempty(roiInput)
    polarROI = false(imageSize);
    return;
end
if islogical(roiInput)
    if ~isequal(size(roiInput), imageSize)
        error('quantifyELPSpatialFeatures:InvalidPolarROI', ...
            'A logical PolarROI must have the same size as the image.');
    end
    polarROI = roiInput;
    return;
end
roi = double(roiInput(:)');
x1 = max(1, floor(roi(1)));
y1 = max(1, floor(roi(2)));
x2 = min(imageSize(2), ceil(roi(1) + roi(3) - 1));
y2 = min(imageSize(1), ceil(roi(2) + roi(4) - 1));
polarROI = false(imageSize);
if x2 >= x1 && y2 >= y1
    polarROI(y1:y2, x1:x2) = true;
end
end
function polarization = calculatePolarization(image, cellMask, polarROI)
if ~any(polarROI(:))
    polarization = struct( ...
        'defined', false, ...
        'polarROIWithinCell', polarROI & cellMask, ...
        'polarIntensity', NaN, ...
        'wholeCellIntensity', sum(max(image(cellMask), 0)), ...
        'polarizationIndex', NaN);
    return;
end
signal = max(image, 0);
polarWithinCell = polarROI & cellMask;
polarIntensity = sum(signal(polarWithinCell));
wholeCellIntensity = sum(signal(cellMask));
polarization = struct();
polarization.defined = true;
polarization.polarROIWithinCell = polarWithinCell;
polarization.polarIntensity = polarIntensity;
polarization.wholeCellIntensity = wholeCellIntensity;
polarization.polarizationIndex = polarIntensity / max(wholeCellIntensity, eps);
end
function mask = segmentCondensates(image, cellMask, opts)
    values = image(cellMask);
    if isempty(values) || max(values) <= 0
        mask = false(size(image));
        return;
    end
    img = double(image);
    img(~cellMask) = 0;
    if isfield(opts, 'CondensateTopHatRadiusPx') && ...
            opts.CondensateTopHatRadiusPx > 0
        seRadius = opts.CondensateTopHatRadiusPx;
    else
        seRadius = 3;
    end
    se = strel('disk', max(1, round(seRadius)), 0);
    tophat = imtophat(img, se);
    tophatValues = tophat(cellMask);
    noiseFloor = prctile(tophatValues, 25);
    signalRange = max(tophatValues) - noiseFloor;
    if signalRange <= 0
        mask = false(size(image));
        return;
    end
    tophatNorm = max(tophat - noiseFloor, 0) / signalRange;
    otsuLevel = graythresh(tophatNorm(cellMask));
    maskOtsu = tophatNorm > otsuLevel;
    maskAdaptive = imbinarize(tophatNorm, 'adaptive', ...
        'Sensitivity', opts.AdaptiveSensitivity);
    adaptiveMask = (maskOtsu | maskAdaptive) & cellMask;
    radius = opts.MorphologyRadiusPx;
    if radius > 0
        se2 = diskSE(radius);
        adaptiveMask = imopen(adaptiveMask, se2);
        adaptiveMask = imclose(adaptiveMask, se2);
    end
    minArea = max(1, round(opts.MinCondensateAreaPx));
    mask = bwareaopen(adaptiveMask, minArea, 4);
end
function se = diskSE(radius)
se = strel('disk', max(1, round(radius)), 0);
end
function crossing = firstCrossing(x, y, target)
crossing = NaN;
if numel(x) < 2
    return;
end
for k = 2:numel(y)
    if isfinite(y(k - 1)) && isfinite(y(k)) && ...
            y(k - 1) >= target && y(k) <= target
        if y(k) == y(k - 1)
            crossing = x(k);
        else
            fraction = (target - y(k - 1)) / (y(k) - y(k - 1));
            crossing = x(k - 1) + fraction * (x(k) - x(k - 1));
        end
        return;
    end
end
end
Code 3: PDE.m (main program)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
clear; clc;
rng(1);
totalTimer = tic;
tempUnit = celsius_symbol();
cfg = struct();
cfg.enableChiFit = false;
cfg.chiManual = struct('a', 8.3773, 'b', -2233.93);
cfg.saveResults = true;
cfg.outputPrefix = 'ELP_ACF';
cfg.enablePHFit = true;
cfg.pHManual = struct('c1', 0, 'd0', 0, 'c2', 0);
cfg.runPHDiagnostics = true;
cfg.phFixedSteps = 700;
cfg.phFitOffset = true;
cfg.phGridN = 9;
cfg.phScanOffsets = [-0.10, 0.45];
cfg.phRefineN = 9;
cfg.phRefineRounds = 2;
cfg.phBracketMargin = 0.06;
cfg.phC1Max = 0.2;
cfg.phD0Bounds = [-0.10, 0.35];
cfg.phC1ScanN = 101;
cfg.phD0ScanN = 101;
cfg.phD0Reg = 0.05;
cfg.phUseParallel = false;
cfg.phFractionRelativeSigma = 0.15 * ones(3, 1);
model = struct();
model.kBT = 1.0;
model.N = 50;
model.kappaCenter = 0.4;
model.kappaList = linspace(0.5, 1.5, 5) * model.kappaCenter;
model.kappaMain = model.kappaCenter;
model.fluorescenceGain = 1.0;
model.fluorescenceBackground = 0.0;
model.fluorescenceMeanTarget = 0.25;
model.Tc_C = 16.0;
model.Tc_K = model.Tc_C + 273.15;
model.TcLower_C = 12.0;
model.TcUpper_C = 16;
model.chiABounds = [-100, 100];
model.chiBBounds = [-5.0e4, 5.0e4];
model.chiMin = 0.20;
model.chiMax = 1.85;
model.spinodalFactor = 1.05;
model.pHRef = 7.0;
model.chiPH1 = 0;
model.chiPH2 = 0;
model.chiPHOffset = 0;
model.Mref = 1;
model.EaR = 1200.0;
model.Tref_K = 293.15;
nx = 70;
ny = 26;
h = 1;
xvec = ((1:nx) - (nx+1)/2) * h;
yvec = ((1:ny) - (ny+1)/2) * h;
[X, Y] = meshgrid(xvec, yvec);
R = (ny/2) * h;
halfStraight = (nx*h - 2*R) / 2;
inRect = (abs(X) <= halfStraight) & (abs(Y) <= R);
xcap = sign(X) .* halfStraight;
distCap = sqrt((X - xcap).^2 + Y.^2);
inCap = (abs(X) > halfStraight) & (distCap <= R);
mask = inRect | inCap;
[A, maskLinIdx, idOfLin] = build_laplacian_operator(mask, h);
Np = numel(maskLinIdx);
fprintf('Cell grid: %d x %d, internal points: %d\n', nx, ny, Np);
phi_avg = model.fluorescenceMeanTarget / model.fluorescenceGain;
noise_amp = 0.05;
phi0_2d = phi_avg + noise_amp * (rand(ny, nx) - 0.5);
phi0_2d(~mask) = 0;
phi_init_vec = phi0_2d(maskLinIdx);
chi_crit = 0.5 * (1 + 1/sqrt(model.N))^2;
phi_c_crit = 1 / (1 + sqrt(model.N));
chi_spin   = 0.5 * (1/(model.N*phi_avg) + 1/(1 - phi_avg));
chi_min20  = model.spinodalFactor * chi_spin;
T20_K      = 20 + 273.15;
fprintf('chi_s = %.6f, required chi(20%s) >= %.6f\n', chi_spin, tempUnit, chi_min20);
caseT_C = [20, 24, 28, 32, 37, 40];
caseT_K = caseT_C + 273.15;
fitT_C = [20, 37, 40];
fitT_K = fitT_C + 273.15;
acfDiagnosticTarget = [0.435, 0.748, 0.596];
expMetrics.cellFluorescenceIntensity      = [252.97, 259.37, 266.66];
expMetrics.condensateFluorescenceIntensity = [61.472, 190.32, 214.26];
expPH.T_C      = [25; 25; 25];
expPH.pH       = [ 6;  7;  9];
expPH.fraction = [0.316654358105616; 0.387887450269553; 0.413922251179682];
cfg.condensateAdaptiveSensitivity = 0.52;
cfg.condensateMorphologyRadiusPx = 1;
cfg.condensateMinAreaPx = 2;
cfg.fluorescenceRelativeSigma = [0.15, 0.15, 0.15];
cfg.huberDelta = 1.5;
fprintf('N = %d, chi_crit = %.6f, phi_c = %.6f\n', ...
    model.N, chi_crit, phi_c_crit);
fprintf('Transition window: %.1f < Tc < %.1f%s; fixed Tc = %.1f%s\n', ...
    model.TcLower_C, model.TcUpper_C, tempUnit, model.Tc_C, tempUnit);
P = struct();
P.A = A;
P.idOfLin = idOfLin;
P.mask = mask;
P.maskLinIdx = maskLinIdx;
P.ny = ny;
P.nx = nx;
P.h = h;
P.xvec = xvec;
P.yvec = yvec;
P.N = model.N;
P.kBT = model.kBT;
P.kappa = model.kappaMain;
P.Mref = model.Mref;
P.EaR = model.EaR;
P.Tref_K = model.Tref_K;
P.dt_init = 0.02;
P.dt_min = 1e-5;
P.dt_max = 0.4;
P.growAfter = 8;
P.growFactor = 1.1;
P.shrinkFactor = 0.5;
P.max_steps = 300;
P.max_steps_slowQuench = 700;
assert(numel(model.kappaList) == 5 && all(model.kappaList > 0) ...
    && abs(model.kappaList(1) - 0.5 * model.kappaCenter) < eps ...
    && abs(model.kappaList(end) - 1.5 * model.kappaCenter) < eps, ...
    sprintf('kappaList must span %.4g +/- 50%% with five positive values.', ...
    model.kappaCenter));
assert(numel(caseT_C) == 6, 'caseT_C must have six display temperatures.');
assert(numel(fitT_C) == 3 && numel(acfDiagnosticTarget) == 3, ...
    'Fit temperatures and diagnostic ACF values must have length 3.');
assert(numel(expPH.T_C) == numel(expPH.pH) ...
    && numel(expPH.pH) == numel(expPH.fraction) ...
    && numel(cfg.phFractionRelativeSigma) == numel(expPH.fraction), ...
    'pH experimental data and relative sigma must have the same length.');
assert(all(isfinite(phi_init_vec)) && all(phi_init_vec > 0) ...
    && all(phi_init_vec < 1), 'Initial field must be finite and in (0,1).');
hasMetricTargets = ...
    all(isfinite(expMetrics.cellFluorescenceIntensity)) ...
    && all(isfinite(expMetrics.condensateFluorescenceIntensity)) ...
    && isfinite(cfg.condensateAdaptiveSensitivity) ...
    && isfinite(cfg.condensateMorphologyRadiusPx) ...
    && isfinite(cfg.condensateMinAreaPx) ...
    && all(expMetrics.cellFluorescenceIntensity > 0) ...
    && all(expMetrics.condensateFluorescenceIntensity >= 0) ...
    && all(expMetrics.condensateFluorescenceIntensity ...
        <= expMetrics.cellFluorescenceIntensity) ...
    && numel(cfg.fluorescenceRelativeSigma) == numel(fitT_C) ...
    && all(cfg.fluorescenceRelativeSigma > 0) ...
    && cfg.condensateAdaptiveSensitivity > 0 ...
    && cfg.condensateAdaptiveSensitivity < 1 ...
    && cfg.condensateMorphologyRadiusPx >= 0 ...
    && cfg.condensateMinAreaPx > 0;
dInv     = 1/model.Tc_K - 1/T20_K;
bInitial = -(1.02*chi_min20 - chi_crit) / dInv;
aInitial = chi_crit - bInitial / model.Tc_K;
if cfg.enableChiFit && hasMetricTargets
    fitP = P;
    fitP.max_steps = 300;
    fitOptions = struct();
    fitOptions.T_C = fitT_C;
    fitOptions.expMetrics = expMetrics;
    fitOptions.condensateAdaptiveSensitivity = cfg.condensateAdaptiveSensitivity;
    fitOptions.condensateMorphologyRadiusPx = cfg.condensateMorphologyRadiusPx;
    fitOptions.condensateMinAreaPx = cfg.condensateMinAreaPx;
    fitOptions.fluorescenceRelativeSigma = cfg.fluorescenceRelativeSigma;
    fitOptions.huberDelta = cfg.huberDelta;
    fitOptions.chiCrit = chi_crit;
    fitOptions.Tc_K = model.Tc_K;
    fitOptions.TcLower_C = model.TcLower_C;
    fitOptions.TcUpper_C = model.TcUpper_C;
    fitOptions.aBounds = model.chiABounds;
    fitOptions.bBounds = model.chiBBounds;
    fitOptions.chiMin = model.chiMin;
    fitOptions.chiMax = model.chiMax;
    fitOptions.chiMin20 = chi_min20;
    fitOptions.T20_K    = T20_K;
    fitOptions.initialAB = [aInitial, bInitial];
    fitOptions.maxIter = 100;
    fitOptions.coarseSteps = 150;
    [chiParams, fitReport] = fit_chi_to_metrics( ...
        fitP, phi_init_vec, fitOptions, model);
else
    chiParams.a = cfg.chiManual.a;
    chiParams.b = cfg.chiManual.b;
    fitReport = struct('enabled', false, 'manual', true);
    if hasMetricTargets
        manOptions = struct();
        manOptions.T_C = fitT_C;
        manOptions.condensateAdaptiveSensitivity = cfg.condensateAdaptiveSensitivity;
        manOptions.condensateMorphologyRadiusPx = cfg.condensateMorphologyRadiusPx;
        manOptions.condensateMinAreaPx = cfg.condensateMinAreaPx;
        fitReport.targetMetrics = experimental_fit_metrics(expMetrics);
        fitReport.fittedMetrics = simulate_fit_metrics(chiParams.a, ...
            chiParams.b, P, phi_init_vec, manOptions, model);
    end
end
model.chiA = chiParams.a;
model.chiB = chiParams.b;
chiAt20fit = chi_from_temperature(T20_K, model);
assert(chiAt20fit >= chi_min20 - 1e-9, ...
    'chi(20%s) = %.4f violates >= %.4f', tempUnit, chiAt20fit, chi_min20);
fprintf('  chi(20%s) = %.6f (= %.3f chi_s)\n', ...
    tempUnit, chiAt20fit, chiAt20fit/chi_spin);
mobilitySensitivity = analyze_mobility_sensitivity( ...
    P, phi_init_vec, fitT_C, model, 0.05);
fprintf('\nFitted chi parameters:\n');
fprintf('  a = %.8f\n', model.chiA);
fprintf('  b = %.8f K\n', model.chiB);
if ~fitReport.enabled
    fprintf('  Status: a, b taken from cfg.chiManual (chi(T) fit skipped).\n');
end
fprintf('  chi(Tc) = %.6f\n', chi_from_temperature(model.Tc_K, model));
chiAt12 = chi_from_temperature(model.TcLower_C + 273.15, model);
chiAt20 = chi_from_temperature(model.TcUpper_C + 273.15, model);
fprintf('  chi(%g%s) = %.6f, chi(%g%s) = %.6f\n', ...
    model.TcLower_C, tempUnit, chiAt12, model.TcUpper_C, tempUnit, chiAt20);
fprintf('\nLocal mobility sensitivity of fitted-temperature heterogeneity (central +/-5%%):\n');
disp(mobilitySensitivity);
fittedTc_C = NaN;
if abs(model.chiB) > eps
    fittedTc_K = model.chiB / (chi_crit - model.chiA);
    if isfinite(fittedTc_K) && fittedTc_K > 0 ...
            && fittedTc_K > 200 && fittedTc_K < 400
        chiAtCrossing = model.chiA + model.chiB / fittedTc_K;
        if abs(chiAtCrossing - chi_crit) < 1e-6 ...
                && chiAtCrossing >= model.chiMin ...
                && chiAtCrossing <= model.chiMax
            fittedTc_C = fittedTc_K - 273.15;
        end
    end
end
if isfinite(fittedTc_C)
    fprintf('  Fitted transition from chi = chi_crit: Tc = %.3f%s\n', ...
        fittedTc_C, tempUnit);
    if fittedTc_C >= 16
        warning('ELP:TcAboveTarget', ...
            ['Fitted Tc = %.2f%s is not below the 16%s target. ' ...
             'Consider tightening model.TcUpper_C further below its ' ...
             'current value of %.1f%s.'], fittedTc_C, tempUnit, ...
             tempUnit, model.TcUpper_C, tempUnit);
    end
else
    fprintf('  Fitted chi(T) has no finite physical chi_crit crossing.\n');
end
if isfield(fitReport, 'fittedMetrics')
    fprintf('\nCondensate fluorescence fraction (fit vs. experiment):\n');
    for i = 1:numel(fitT_C)
        fprintf('  %g%s: model = %.4f, experiment = %.4f\n', ...
            fitT_C(i), tempUnit, fitReport.fittedMetrics(i), ...
            fitReport.targetMetrics(i));
    end
end
phSeg = struct();
phSeg.condensateAdaptiveSensitivity = cfg.condensateAdaptiveSensitivity;
phSeg.condensateMorphologyRadiusPx = cfg.condensateMorphologyRadiusPx;
phSeg.condensateMinAreaPx = cfg.condensateMinAreaPx;
phFitP = P;
phFitP.phSteps = cfg.phFixedSteps;
if cfg.runPHDiagnostics
    fprintf('\nDiagnostics: model fluorescence fraction at pH %g (chi = a + b/T)\n', model.pHRef);
    diagT_C = [20, 25, 30];
    for i = 1:numel(diagT_C)
        T_K = diagT_C(i) + 273.15;
        chiD = chi_from_temperature(T_K, model);
        nAd = adaptive_max_steps(diagT_C(i), P.max_steps, P.max_steps_slowQuench);
        fAd = chi_to_fraction(phFitP, phi_init_vec, chiD, T_K, nAd, model, phSeg);
        fFx = chi_to_fraction(phFitP, phi_init_vec, chiD, T_K, ...
            P.max_steps_slowQuench, model, phSeg);
        fprintf('  %g%s: chi = %.4f | adaptive (%d steps): f = %.4f | %d steps: f = %.4f\n', ...
            diagT_C(i), tempUnit, chiD, nAd, fAd, P.max_steps_slowQuench, fFx);
    end
    fprintf('  experiment at pH 7: 20%s = 0.2426, 25%s = 0.3879\n', tempUnit, tempUnit);
end
if cfg.enablePHFit
    phTimer = tic;
    [phParams, phReport] = fit_ph_to_fraction( ...
        phFitP, phi_init_vec, expPH, model, phSeg, cfg);
    phReport.elapsed_s = toc(phTimer);
else
    phParams = cfg.pHManual;
    phReport = struct('enabled', false, 'tempList', unique(expPH.T_C(:)), ...
        'chiGrid', [], 'fracGrid', [], 'elapsed_s', 0);
end
model.chiPH1 = phParams.c1;
model.chiPH2 = 0;
model.chiPHOffset = phParams.d0;
if model.chiPH1 > 1e-9
    phpH0 = model.pHRef - model.chiPHOffset / model.chiPH1;
else
    phpH0 = NaN;
end
[phFittedFraction, phFields] = simulate_ph_fraction( ...
    phFitP, phi_init_vec, expPH.T_C, expPH.pH, model, phSeg);
phFittedFraction = phFittedFraction(:);
phChiAtPoints = zeros(numel(expPH.pH), 1);
for i = 1:numel(expPH.pH)
    phChiAtPoints(i) = chi_from_temperature( ...
        expPH.T_C(i) + 273.15, model, expPH.pH(i));
end
phSigmaAbs = max(expPH.fraction(:) .* cfg.phFractionRelativeSigma(:), 1e-3);
phSseSim = sum(((phFittedFraction - expPH.fraction(:)) ./ phSigmaAbs).^2);
fprintf('\nFitted pH parameters (pH_ref = %g, data at %s):\n', ...
    model.pHRef, strjoin(arrayfun(@(t) sprintf('%g%s', t, tempUnit), ...
    unique(expPH.T_C(:))', 'UniformOutput', false), ' and '));
fprintf('  c1 = %.6f per pH unit (chi increases with pH)\n', model.chiPH1);
fprintf('  d0 = %+.6f (chi offset at pH %g), equivalent pH0 = %s\n', ...
    model.chiPHOffset, model.pHRef, ternary(isfinite(phpH0), sprintf('%.3f', phpH0), 'n/a'));
if abs(model.chiPHOffset) > 1e-9
    fprintf('  Note: d0 ~= 0 shifts chi at pH %g away from a + b/T for the pH-dependent runs only.\n', model.pHRef);
end
if ~phReport.enabled
    fprintf('  Status: pH fit skipped; using cfg.pHManual.\n');
else
    fprintf('  pH fit time: %.1f s, weighted SSE on interpolated curve = %.4f\n', ...
        phReport.elapsed_s, phReport.objective);
end
fprintf('  weighted SSE of the final simulations = %.4f\n', phSseSim);
fprintf('\nCondensate fluorescence fraction vs. pH (fit vs. experiment):\n');
for i = 1:numel(expPH.pH)
    fprintf('  %g%s, pH %g: chi = %.4f, model = %.4f, experiment = %.4f\n', ...
        expPH.T_C(i), tempUnit, expPH.pH(i), phChiAtPoints(i), ...
        phFittedFraction(i), expPH.fraction(i));
end
nCases = numel(caseT_C);
chiVals = zeros(1, nCases);
MbulkVals = zeros(1, nCases);
heteroVals = zeros(1, nCases);
avgFluorescenceVals = zeros(1, nCases);
massDrift = zeros(1, nCases);
phiFinal2D = cell(1, nCases);
massHistories = cell(1, nCases);
for icase = 1:nCases
    T_K = caseT_K(icase);
    chiVal = chi_from_temperature(T_K, model);
    Mbulk = mobility_temperature(T_K, model);
    chiVals(icase) = chiVal;
    MbulkVals(icase) = Mbulk;
    fprintf('\nCase %d: T = %g%s\n', icase, caseT_C(icase), tempUnit);
    fprintf('  chi = %.6f, chi/chi_crit = %.4f, M_T = %.6e\n', ...
        chiVal, chiVal/chi_crit, Mbulk);
    Pcase = P;
    Pcase.kappa = model.kappaMain;
    Pcase.max_steps = adaptive_max_steps(caseT_C(icase), P.max_steps, ...
        P.max_steps_slowQuench);
    [phiFinal, heteroIndex, avgFluor, massHistory] = ...
        run_case(Pcase, phi_init_vec, chiVal, T_K, model);
    heteroVals(icase) = heteroIndex;
    avgFluorescenceVals(icase) = avgFluor;
    massHistories{icase} = massHistory;
    initialMass = sum(phi_init_vec) * h^2;
    massDrift(icase) = (massHistory(end) - initialMass) / initialMass;
    field2d = nan(ny, nx);
    field2d(maskLinIdx) = phiFinal;
    phiFinal2D{icase} = field2d;
    fprintf('  Heterogeneity index = %.6f\n', heteroIndex);
    fprintf('  mean fluorescence proxy = %.6f\n', avgFluor);
    fprintf('  relative mass drift = %.3e\n', massDrift(icase));
end
idx20C = find(abs(caseT_C - 20) < 1e-9, 1);
if ~isempty(idx20C) && heteroVals(idx20C) < 0.15
    warning('ELP:WeakSeparationAt20C', ...
        ['Heterogeneity index at 20%s is %.3f, which may be too low ' ...
         'to call "significant" phase separation. Consider lowering ' ...
         'model.TcUpper_C further, relaxing model.chiMax slightly more, ' ...
         'or raising P.max_steps_slowQuench.'], tempUnit, heteroVals(idx20C));
end
kappaScanHeterogeneity = zeros(size(model.kappaList));
kappaScanFluor = zeros(size(model.kappaList));
kappaFields = cell(size(model.kappaList));
scanT_C = 37.0;
scanT_K = scanT_C + 273.15;
scanChi = chi_from_temperature(scanT_K, model);
fprintf('\nKappa sensitivity scan at %g%s, chi = %.6f\n', ...
    scanT_C, tempUnit, scanChi);
for ik = 1:numel(model.kappaList)
    Pscan = P;
    Pscan.kappa = model.kappaList(ik);
    Pscan.max_steps = 350;
    [phiFinal, heteroIndex, avgFluor] = run_case( ...
        Pscan, phi_init_vec, scanChi, scanT_K, model);
    kappaScanHeterogeneity(ik) = heteroIndex;
    kappaScanFluor(ik) = avgFluor;
    field2d = nan(ny, nx);
    field2d(maskLinIdx) = phiFinal;
    assert(all(isfinite(phiFinal)) && all(phiFinal >= 0) ...
        && all(phiFinal <= 1), ...
        'Kappa scan returned an invalid final field.');
    kappaFields{ik} = field2d;
    fprintf('  kappa = %.3f -> Heterogeneity = %.6f, mean fluorescence = %.6f\n', ...
        model.kappaList(ik), heteroIndex, avgFluor);
end
results = struct();
results.model = model;
results.chi_crit = chi_crit;
results.phi_c_crit = phi_c_crit;
results.caseT_C = caseT_C;
results.fitT_C = fitT_C;
results.acfDiagnosticReference = acfDiagnosticTarget;
results.experimentalFluorescenceMetrics = expMetrics;
results.chiVals = chiVals;
results.MbulkVals = MbulkVals;
results.heterogeneityVals = heteroVals;
results.avgFluorescenceVals = avgFluorescenceVals;
results.massDrift = massDrift;
results.kappaList = model.kappaList;
results.kappaScanHeterogeneity = kappaScanHeterogeneity;
results.kappaScanFluor = kappaScanFluor;
results.fitReport = fitReport;
results.mobilitySensitivity = mobilitySensitivity;
results.fittedTc_C = fittedTc_C;
results.massHistories = massHistories;
results.expPH = expPH;
results.phParams = phParams;
results.phReport = phReport;
results.phSseSimulation = phSseSim;
resultTable = table(caseT_C(:), heteroVals(:), avgFluorescenceVals(:), ...
    chiVals(:), MbulkVals(:), massDrift(:), ...
    'VariableNames', {'Temperature_C', 'HeterogeneityIndex', ...
    'MeanFluorescence', 'Chi', 'MobilityTemperatureFactor', ...
    'RelativeMassDrift'});
experimentalMetricsTable = table(fitT_C(:), ...
    expMetrics.cellFluorescenceIntensity(:), ...
    expMetrics.condensateFluorescenceIntensity(:), ...
    'VariableNames', {'Temperature_C', ...
    'CellIntegratedFluorescence', 'CondensateIntegratedFluorescence'});
experimentalMetricsTable.CondensateFluorescenceFraction = ...
    expMetrics.condensateFluorescenceIntensity(:) ...
    ./ expMetrics.cellFluorescenceIntensity(:);
if isfield(fitReport, 'fittedMetrics')
    fittedMetricsTable = table(fitT_C(:), fitReport.fittedMetrics(:), ...
        'VariableNames', {'Temperature_C', ...
        'CondensateFluorescenceFraction'});
else
    fittedMetricsTable = table();
end
kappaTable = table(model.kappaList(:), kappaScanHeterogeneity(:), ...
    kappaScanFluor(:), ...
    'VariableNames', {'Kappa', 'HeterogeneityIndex', 'MeanFluorescence'});
phTable = table(expPH.T_C(:), expPH.pH(:), expPH.fraction(:), ...
    phFittedFraction(:), phChiAtPoints(:), ...
    'VariableNames', {'Temperature_C', 'pH', 'ExperimentFraction', ...
    'ModelFraction', 'Chi'});
if ~isempty(phReport.chiGrid)
    nGsave = numel(phReport.chiGrid);
    nTsave = numel(phReport.tempList);
    phCurveTable = table(repelem(phReport.tempList(:), nGsave), ...
        repmat(phReport.chiGrid(:), nTsave, 1), phReport.fracGrid(:), ...
        'VariableNames', {'Temperature_C', 'Chi', 'ModelFraction'});
else
    phCurveTable = table();
end
if cfg.saveResults
    save([cfg.outputPrefix '_results.mat'], 'results', 'resultTable', ...
        'kappaTable', 'experimentalMetricsTable', 'fittedMetricsTable', ...
        'phiFinal2D', 'kappaFields', 'phTable', 'phCurveTable', 'phFields');
    writetable(resultTable, [cfg.outputPrefix '_temperature_results.csv']);
    writetable(kappaTable, [cfg.outputPrefix '_kappa_scan.csv']);
    writetable(experimentalMetricsTable, ...
        [cfg.outputPrefix '_experimental_metrics.csv']);
    if ~isempty(fittedMetricsTable)
        writetable(fittedMetricsTable, ...
            [cfg.outputPrefix '_fitted_metrics.csv']);
    end
    writetable(mobilitySensitivity, ...
        [cfg.outputPrefix '_mobility_sensitivity.csv']);
    writetable(phTable, [cfg.outputPrefix '_ph_fit.csv']);
    if ~isempty(phCurveTable)
        writetable(phCurveTable, [cfg.outputPrefix '_ph_fraction_vs_chi.csv']);
    end
    fprintf('\nResults saved to %s_results.mat and CSV tables.\n', ...
        cfg.outputPrefix);
end
fprintf('\nAll calculations completed in %.1f s.\n', toc(totalTimer));

Protein Transportation Model

Protein Transportation Model.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
"""Core formula implementation

Dependencies: numpy scipy; plotting: matplotlib
Run: python core_model.py --out results [--plot] [--full]
Units: time in min; states are counts per cell; x=aTc/100, q=cumate/3.
"""
from __future__ import annotations

import argparse
import json
from dataclasses import asdict, dataclass, replace
from pathlib import Path

import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import brentq

STATE_NAMES = ("P1", "P2", "T", "C", "S0", "S1", "S2", "F1", "F2")
NA = 6.02214076e23


# I01-I06: independent exponential waiting model; results are normalized to the plateau of each end.
def progress(t, k):
    if k <= 0 or np.any(np.asarray(t) < 0):
        raise ValueError("k must be positive and t must be non-negative")
    return -np.expm1(-k * np.asarray(t))


def both_progress(t, k_a, k_b):
    return progress(t, k_a) * progress(t, k_b)


def completion_time(k_a, k_b, target=0.90):
    if min(k_a, k_b) <= 0 or not 0 < target < 1:
        raise ValueError("rates must be positive and target must be in (0,1)")
    # When each end reaches sqrt(target), the product of the two ends is at least target.
    upper = 2 * -np.log1p(-np.sqrt(target)) / min(k_a, k_b)
    return brentq(lambda t: both_progress(t, k_a, k_b) - target, 0, upper)


def intein_metrics(k_a, k_b):
    return dict(k_a=k_a, k_b=k_b, half_a_min=np.log(2)/k_a,
                half_b_min=np.log(2)/k_b, t90_min=completion_time(k_a, k_b),
                mean_both_min=1/k_a+1/k_b-1/(k_a+k_b),
                rate_ratio=max(k_a, k_b)/min(k_a, k_b))


def coordination(beta, kappa):
    if beta <= 0 or kappa < 0:
        raise ValueError("requires beta>0 and kappa>=0")
    return dict(probability=beta/(beta+kappa),
                derivative_kappa=-beta/(beta+kappa)**2)


def reference_rates(m=2.0):
    if m < 1:
        raise ValueError("matching factor m must be >=1")
    cat, cfa = np.log(2)/(59/60), np.log(2)/(20/60)
    return dict(cat=cat, original_cfa=cfa, ratio=cfa/cat,
                mut_rate_interval=[cat/m, cat*m],
                mut_half_time_seconds=[59/m, 59*m],
                original=coordination(cat, cfa), matched=coordination(cat, cat))


@dataclass(frozen=True)
class Parameters:
    # Default: dynamic baseline from Table 4; Figure 3 uses demo_parameters() separately.
    mu: float = 0.025
    eta1: float = 0.90
    eta2: float = 0.78
    kcat1: float = 0.023
    kcat2: float = 2.08
    Km1: float = 9.2
    Km2: float = 50.0
    ma: float = 3.126
    mc: float = 2.0
    n1: float = 2.0
    n2: float = 2.0
    K1: float = 8.0
    K2: float = 140.0
    Ka: float = 100.0
    Kc: float = 3.0
    alpha1: float = 7800.0
    alpha2: float = 7800.0
    alphaS: float = 1560.0
    kdegP1: float = 0.0
    kdegP2: float = 0.0
    kdegF1: float = 0.0
    kdegF2: float = 0.0
    kLVA: float = 0.0
    Vcell: float = 1e-15
    theta1: float = 1.0
    theta2: float = 1.0

    def __post_init__(self):
        positive = ("mu", "eta1", "eta2", "kcat1", "kcat2", "Km1", "Km2",
                    "ma", "mc", "n1", "n2", "K1", "K2", "Ka", "Kc",
                    "alpha1", "alpha2", "alphaS", "Vcell", "theta1", "theta2")
        for name, value in asdict(self).items():
            if not np.isfinite(value) or (value <= 0 if name in positive else value < 0):
                raise ValueError(f"Invalid value for parameter {name}: {value}")

    @property
    def M(self):
        return NA * self.Vcell * 1e-9

    @property
    def a1(self):
        return self.theta1 * self.kcat1 * self.eta1

    @property
    def a2(self):
        return self.theta2 * self.kcat2 * self.eta2


def demo_parameters():
    return replace(Parameters(), kcat1=0.04, kcat2=0.03)


def initial_state(p, demo=False):
    y = np.zeros(9)
    y[4] = p.alphaS / p.mu
    if demo:
        y[:2] = 1.0
    return y


def production_and_loss(y, p, x, q):
    """M01-M07; x and q are normalized concentrations; return G and L separately to check M11."""
    P1, P2, T, C, S0, S1, S2, F1, F2 = y
    teff = T / p.M / (1 + x**p.ma)
    ceff = C / p.M / (1 + q**p.mc)
    r1 = p.alpha1 / (1 + (teff / p.K1)**p.n1)
    r2 = p.alpha2 / (1 + (ceff / p.K2)**p.n2)
    v1 = p.a1*S0*P1/(p.M*p.Km1+P1)
    v2 = p.a2*S1*P2/(p.M*p.Km2+P2)
    G = np.array([r1, r2, v2, v1, p.alphaS, v1, v2, v1, v2])
    L = np.array([v1+(p.mu+p.kdegP1)*P1, v2+(p.mu+p.kdegP2)*P2,
                  (p.mu+p.kLVA)*T, p.mu*C, v1+p.mu*S0,
                  v2+p.mu*S1, p.mu*S2, (p.mu+p.kdegF1)*F1,
                  (p.mu+p.kdegF2)*F2])
    return G, L


def rhs(t, y, p, x, q):
    G, L = production_and_loss(y, p, x, q)
    return G-L


def fractions(y):
    """M09; supports shape=(9,) or (9,n)."""
    scaffold = np.asarray(y)[4:7]
    return scaffold/scaffold.sum(axis=0)


def observe(z_mature, A, background, noise=0.0):
    """M10: """
    return np.asarray(A) @ np.asarray(z_mature) + background + noise


def integrate(y0, duration, p, x, q, method="BDF", rtol=2e-8, atol=1e-10,
              threshold=None):
    if duration <= 0 or min(x, q) < 0 or not np.all(np.isfinite(y0)):
        raise ValueError("duration must be positive, inputs non-negative, and initial state finite")
    if np.min(y0) < -1e-6:
        raise ValueError("initial state contains negative amounts")
    event = None
    if threshold is not None:
        def event(t, y):
            return fractions(y)[1] - threshold
    sol = solve_ivp(rhs, (0, duration), y0, args=(p, x, q),
                    method=method, rtol=rtol, atol=atol, max_step=10,
                    dense_output=True,
                    events=None if event is None else lambda t, y, *args: event(t, y))
    if not sol.success:
        raise RuntimeError(sol.message)
    if np.min(sol.y) < -1e-6:
        raise RuntimeError("integration produced significantly negative amounts; check parameters and tolerances")
    expected = p.alphaS/p.mu + (sum(y0[4:7])-p.alphaS/p.mu)*np.exp(-p.mu*sol.t)
    if not np.allclose(sol.y[4:7].sum(axis=0), expected, rtol=5e-7, atol=1e-5):
        raise RuntimeError("M08 scaffold balance check failed")
    return sol


def figure3(method="BDF", step=0.1):
    p = demo_parameters()
    y = initial_state(p, demo=True)
    times, states, offset = [], [], 0.0
    for duration, x, q in [(30, 0, 0), (60, 2, 0), (160, 2, 10/3)]:
        sol = integrate(y, duration, p, x, q, method=method)
        local = np.linspace(0, duration, int(np.ceil(duration/step))+1)
        # Restart the solver at input switches while keeping the state continuous.
        if times:
            local = local[1:]
        times.extend(local+offset)
        states.append(sol.sol(local))
        y = sol.y[:, -1]
        offset += duration
    return np.asarray(times), np.concatenate(states, axis=1)


def jacobian(y, p, x, q):
    """Complex-step differentiation to avoid subtractive cancellation in finite differences."""
    J = np.empty((9, 9))
    for j in range(9):
        probe = np.asarray(y, dtype=complex)
        probe[j] += 1e-20j
        J[:, j] = rhs(0, probe, p, x, q).imag/1e-20
    return J


def residual(y, p, x, q):
    G, L = production_and_loss(y, p, x, q)
    return float(np.max(np.abs(G-L)/(1e-9+1e-8*np.maximum(abs(G), abs(L)))))


def reduced_state(z, p, q):
    """H in M13 is not expanded in the original text. Here it is constructed by eliminating variables from M06, with no additional physical assumptions.

    v1 = vmax*sigmoid(z); S0=(alphaS-v1)/mu;
    P1=M*Km1*v1/(a1*S0-v1).
    Use P2=(r2-v2)/deltaP2 and S1=(v1-v2)/mu to solve the quadratic and take the physical solution.
    Finally only dP1/dt=0 remains unsatisfied, which serves as the scalar H.
    """
    vmax = p.alphaS*p.a1/(p.mu+p.a1)
    v1 = vmax/(1+np.exp(-z))
    S0 = (p.alphaS-v1)/p.mu
    # Algebraically simplify the logistic to avoid precision loss from subtracting denominators when z is large.
    P1 = p.M*p.Km1*p.mu/(p.mu+p.a1)*np.exp(z)
    C = v1/p.mu
    ceff = C/p.M/(1+q**p.mc)
    r2 = p.alpha2/(1+(ceff/p.K2)**p.n2)
    d2 = p.mu+p.kdegP2
    aa = p.mu+p.a2
    bb = p.mu*(d2*p.M*p.Km2+r2)+p.a2*(v1+r2)
    cc = p.a2*v1*r2
    # Use an equivalent form for the small root to avoid numerical cancellation in bb - sqrt(...).
    v2 = 2*cc/(bb+np.sqrt(bb*bb-4*aa*cc))
    P2 = (r2-v2)/d2
    T = v2/(p.mu+p.kLVA)
    return np.array([P1, P2, T, C, S0, (v1-v2)/p.mu, v2/p.mu,
                     v1/(p.mu+p.kdegF1), v2/(p.mu+p.kdegF2)])


def H(z, p, x, q):
    return rhs(0, reduced_state(z, p, q), p, x, q)[0]/p.alpha1


def Hz(z, p, x, q):
    return float(np.imag(H(z+1e-20j, p, x, q))/1e-20)


def equilibrium_record(z, p, x, q):
    y = reduced_state(z, p, q)
    R = residual(y, p, x, q)
    if R > 1 or np.min(y) < 0:
        raise RuntimeError(f"Steady-state residual or non-negativity check failed: Rmax={R}")
    lam = float(np.linalg.eigvals(jacobian(y, p, x, q)).real.max())
    return dict(z=float(z), state=y.tolist(), red=float(fractions(y)[1]),
                Rmax=R, lambda_max=lam, stable=lam < -1e-8)


def steady_states(p, x, q, grid_size=2049):
    """M11-M12. Add stationary-point splitting of H to improve detection of double roots near folds."""
    if min(x, q) < 0:
        raise ValueError("x and q must be non-negative")
    grid = np.linspace(-36, 36, grid_size)
    slopes = [Hz(z, p, x, q) for z in grid]
    stationary = [brentq(lambda z: Hz(z, p, x, q), a, b, xtol=1e-12)
                  for a, b, da, db in zip(grid[:-1], grid[1:], slopes[:-1], slopes[1:])
                  if da*db < 0]
    nodes = sorted(set([*grid, *stationary]))
    roots = []
    vals = [H(z, p, x, q) for z in nodes]
    for z in stationary:
        if abs(H(z, p, x, q)) < 1e-13:
            roots.append(z)
    for a, b, fa, fb in zip(nodes[:-1], nodes[1:], vals[:-1], vals[1:]):
        if fa == 0:
            roots.append(a)
        elif fa*fb < 0:
            roots.append(brentq(lambda z: H(z, p, x, q), a, b, xtol=1e-13))
    unique = []
    for z in sorted(roots):
        if not unique or abs(z-unique[-1]) > 1e-7:
            unique.append(z)
    return [equilibrium_record(z, p, x, q) for z in unique]


def input_on_steady_branch(z, p, q):
    """Invert the first production law to obtain x(z) on H=0."""
    y = reduced_state(z, p, q)
    v1 = p.a1*y[4]*y[0]/(p.M*p.Km1+y[0])
    required = v1+(p.mu+p.kdegP1)*y[0]
    if not 0 < required < p.alpha1:
        return np.nan
    base = y[2]/(p.M*p.K1)*(required/(p.alpha1-required))**(1/p.n1)-1
    return float(base**(1/p.ma)) if base > 0 else np.nan


def fold_points(p, q, grid_size=2049):
    """M13-M14: scan the physical H=0 branch, refine Hz=0, then verify.

    Search domain: z in [-36,36], positive x. Mesh refinement is recommended
    after changing parameters substantially; absence of roots is not a proof.
    """
    def slope(z):
        x = input_on_steady_branch(z, p, q)
        return Hz(z, p, x, q) if np.isfinite(x) else np.nan
    grid = np.linspace(-36, 36, grid_size)
    values = [slope(z) for z in grid]
    found = []
    for a, b, fa, fb in zip(grid[:-1], grid[1:], values[:-1], values[1:]):
        if not (np.isfinite(fa) and np.isfinite(fb)) or fa*fb >= 0:
            continue
        z = brentq(slope, a, b, xtol=1e-13)
        x = input_on_steady_branch(z, p, q)
        hzz = (Hz(z+1e-4, p, x, q)-Hz(z-1e-4, p, x, q))/2e-4
        hx = np.imag(H(z, p, x+1e-20j, q))/1e-20
        if abs(H(z, p, x, q)) > 1e-9 or abs(hzz) < 1e-8 or abs(hx) < 1e-8:
            continue
        rec = equilibrium_record(z, p, x, q)
        eig = np.linalg.eigvals(jacobian(np.array(rec["state"]), p, x, q))
        if np.min(abs(eig)) > 1e-6:
            continue
        found.append(dict(x=float(x), u_ng_ml=float(x*p.Ka), Hzz=float(hzz),
                          Hu=float(hx/p.Ka), **rec))
    found.sort(key=lambda r: r["x"])
    width = None
    if len(found) == 2:
        mid = np.sqrt(found[0]["x"]*found[1]["x"])
        interior = steady_states(p, mid, q)
        if sum(r["stable"] for r in interior) == 2:
            width = float(np.log10(found[1]["x"]/found[0]["x"]))
    return dict(q=q, folds=found, Wlog=width)


def prepare(p, history="low", minutes=240):
    if history not in ("low", "high") or minutes < 0:
        raise ValueError("history must be low/high and minutes must be non-negative")
    y = initial_state(p)
    if minutes == 0:
        return y
    x, q = (0, 10) if history == "low" else (10, 0)
    return integrate(y, minutes, p, x, q).y[:, -1]


def history_difference(p, x, q=1.5, prep_minutes=240, read_minutes=240):
    """M16, M18: compare two independent histories under the same input at the same time."""
    red = {}
    for history in ("high", "low"):
        y0 = prepare(p, history, prep_minutes)
        y = integrate(y0, read_minutes, p, x, q).y[:, -1]
        red[history] = float(fractions(y)[1])
    return dict(**red, delta_red=red["high"]-red["low"],
                delta_percentage_points=100*(red["high"]-red["low"]))


def serial_scan(p, levels, q=1.5, hold=120, prep_minutes=240, threshold=0.225):
    """M15, M17, M19; the highest concentration is held only once, and all nine states are propagated continuously."""
    levels = np.asarray(levels, dtype=float)
    if len(levels) < 2 or np.any(np.diff(levels) <= 0) or min(levels) < 0:
        raise ValueError("levels must be at least two strictly increasing non-negative concentrations")
    y = prepare(p, "low", prep_minutes)
    schedule = np.r_[levels, levels[-2::-1]]
    rows, crossings = [], []
    for k, x in enumerate(schedule):
        sol = integrate(y, hold, p, float(x), q, threshold=threshold)
        y = sol.y[:, -1]
        red = float(fractions(y)[1])
        late = abs(red-float(fractions(sol.sol(0.8*hold))[1]))
        rows.append(dict(stage=k+1, time_min=prep_minutes+(k+1)*hold,
                         x=float(x), q=q, red=red, blue=float(fractions(y)[2]),
                         late_drift=late, state=y.tolist()))
        for t in sol.t_events[0]:
            at = sol.sol(t)
            dy = rhs(t, at, p, float(x), q)
            s = sum(at[4:7])
            dr = (dy[5]*s-at[5]*sum(dy[4:7]))/s**2
            absolute_t = prep_minutes+k*hold+float(t)
            if crossings and abs(absolute_t-crossings[-1]["time_min"]) < 1e-7:
                continue
            crossings.append(dict(time_min=absolute_t, x=float(x),
                                  direction="up" if dr > 0 else "down"))
    red = np.array([r["red"] for r in rows])
    n = len(levels)
    up, down = red[:n], np.r_[red[n:][::-1], red[n-1]]
    gaps = abs(up-down)
    area = float(np.sum((gaps[:-1]+gaps[1:])*np.diff(levels)/2))
    returned = float(abs(red[-1]-red[0]))
    up_n = sum(c["direction"] == "up" for c in crossings)
    down_n = sum(c["direction"] == "down" for c in crossings)
    return dict(levels=levels.tolist(), stages=len(rows), rows=rows, crossings=crossings,
                total_hours=(prep_minutes+(2*n-1)*hold)/60,
                final_red=float(red[-1]), return_difference=returned,
                round_trip=bool(up_n >= 1 and down_n >= 1 and red[0] < threshold
                                and returned <= 0.02),
                gap_area=area, max_late_drift=max(r["late_drift"] for r in rows))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--out", type=Path, default=Path("results"))
    parser.add_argument("--plot", action="store_true", help="additionally generate a Figure 3 style curve")
    parser.add_argument("--full", action="store_true", help="additionally compute folds, scans, and history differences")
    args = parser.parse_args()
    args.out.mkdir(parents=True, exist_ok=True)
    cases = {"native_25C": (4.2, 1.122), "non_native_25C": (0.0078, 0.00174),
             "non_native_37C": (0.0192, 0.00372)}
    summary = {"intein": {k: intein_metrics(*v) for k, v in cases.items()},
               "reference_rates": reference_rates(),
               "demo_parameters": asdict(demo_parameters()),
               "dynamic_parameters": asdict(Parameters())}
    t, y = figure3()
    summary["figure3_peaks"] = {}
    for name, j in [("red", 5), ("blue", 6)]:
        i = int(np.argmax(y[j]))
        summary["figure3_peaks"][name] = dict(time_min=float(t[i]),
                                              sites=float(y[j, i]),
                                              fraction=float(fractions(y[:, i])[j-4]))
    # Plain-text numerical trajectory; column order matches STATE_NAMES.
    np.savetxt(args.out/"figure3_trajectory.csv", np.column_stack([t, y.T, fractions(y).T]),
               delimiter=",", header=",".join(("time_min", *STATE_NAMES, "g", "r", "b")),
               comments="")
    if args.full:
        p = Parameters()
        summary["folds"] = [fold_points(p, q) for q in [1.2, 1.5, 3.0]]
        ladders = {"coarse_7": np.arange(7), "uniform_fine_13": np.arange(0, 6.01, .5),
                   "fold_focused_7": [0, .75, 1.25, 2.25, 3.25, 4, 6]}
        summary["scans"] = {name: serial_scan(p, levels) for name, levels in ladders.items()}
        summary["history_at_x4_5"] = {str(t): history_difference(p, 4.5, read_minutes=t)
                                       for t in [240, 1200]}
    (args.out/"summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False),
                                       encoding="utf-8")
    if args.plot:
        import matplotlib
        matplotlib.use("Agg")
        import matplotlib.pyplot as plt
        fig, axes = plt.subplots(2, 1, figsize=(10, 7), sharex=True, layout="constrained")
        axes[0].plot(t, y[4], color="forestgreen", label="S0 green")
        axes[1].plot(t, y[5], color="firebrick", label="S1 red")
        axes[1].plot(t, y[6], color="steelblue", label="S2 blue")
        for ax in axes:
            for switch in [30, 90]:
                ax.axvline(switch, color="grey", linestyle=":")
            ax.set_ylabel("Scaffold sites / cell")
            ax.grid(alpha=.2)
            ax.legend()
        axes[1].set_xlabel("Time (min)")
        fig.savefig(args.out/"figure3.png", dpi=180)
        plt.close(fig)
    for name, result in summary["intein"].items():
        print(f"{name}: t90 = {result['t90_min']:.6f} min")
    print(json.dumps(summary["figure3_peaks"], indent=2))
    if args.full:
        for row in summary["folds"]:
            print("folds:", row["q"], [r["x"] for r in row["folds"]], row["Wlog"])
        for name, row in summary["scans"].items():
            print(name, "hours=", row["total_hours"], "final_red=", row["final_red"],
                  "round_trip=", row["round_trip"])
    print("Results:", args.out.resolve())


if __name__ == "__main__":
    main()