Skip to content

Re-referencing

High-level entry point: ChemicalShifts.reref. The routines below operate on raw DataFrames.

Dispatch

compute_offsets

compute_offsets(df, method, n_std=_N_STD_OUTLIER, cona=True)

Fit per-atom re-referencing offsets for a long-format shift table.

Parameters:

Name Type Description Default
df DataFrame

Long-format shifts with at least Comp_ID, Seq_ID, Atom_ID, Val.

required
method (lacs, panav)
'lacs'
n_std int

LACS only — BMRB-statistics outlier threshold (default 4).

_N_STD_OUTLIER
cona bool

PANAV only — run the CONA fragment scan after offsets (default True). CONA does not change offsets; set False when only offsets are needed.

True

Returns:

Name Type Description
offsets dict {atom: float | None}

Correction per atom such that corrected = Val + offset (paper convention offset ≈ d_ave − d_obs); None where fitting failed. LACS atoms: CA, CB, C, N, H. PANAV atoms: N, CA, CB, C.

check dict {atom: bool}

Whether re-referencing succeeded for each atom.

meta dict | None

PANAV only — CONA fragment-scan summary (None for LACS, or when cona=False).

Returns ``(None, None, None)`` if no backbone shifts are present.
Source code in makeshift/reref/__init__.py
def compute_offsets(df, method, n_std=_N_STD_OUTLIER, cona=True):
    """
    Fit per-atom re-referencing offsets for a long-format shift table.

    Parameters
    ----------
    df : DataFrame
        Long-format shifts with at least Comp_ID, Seq_ID, Atom_ID, Val.
    method : {'lacs', 'panav'}
    n_std : int
        LACS only — BMRB-statistics outlier threshold (default 4).
    cona : bool
        PANAV only — run the CONA fragment scan after offsets (default True).
        CONA does not change offsets; set False when only offsets are needed.

    Returns
    -------
    offsets : dict {atom: float | None}
        Correction per atom such that ``corrected = Val + offset``
        (paper convention ``offset ≈ d_ave − d_obs``); None where
        fitting failed. LACS atoms: CA, CB, C, N, H. PANAV atoms: N, CA, CB, C.
    check : dict {atom: bool}
        Whether re-referencing succeeded for each atom.
    meta : dict | None
        PANAV only — CONA fragment-scan summary (``None`` for LACS, or when
        ``cona=False``).

    Returns ``(None, None, None)`` if no backbone shifts are present.
    """
    if method not in ("lacs", "panav"):
        raise ValueError(f"method must be 'lacs' or 'panav', got {method!r}")

    work = df.copy()
    work = work.loc[
        work.Atom_ID.isin(_BACKBONE) | work.Atom_ID.str.contains("^HA", na=False)
    ]

    # average GLY HA/HA2 into one HA per residue
    gly = (work["Comp_ID"] == "GLY") & work["Atom_ID"].str.contains("HA", na=False)
    for seq_id, group in work[gly].groupby("Seq_ID"):
        mask = (work["Seq_ID"] == seq_id) & gly
        work.loc[mask, "Val"] = group["Val"].mean()
        idx = work.loc[mask].index
        work.loc[idx[0], "Atom_ID"] = "HA"
        if len(idx) > 1:
            work.loc[idx[1:], "Atom_ID"] = "HA2"

    work = work.loc[work.Atom_ID.isin(_BACKBONE)].copy()
    if work.empty:
        return None, None, None

    if method == "lacs":
        offsets, check = reref_lacs(work, n_std=n_std)
        return offsets, check, None

    return reref_panav(work, cona=cona)

apply_offsets

apply_offsets(df, offsets)

Return a copy of df with Val + offset per atom (offset ≈ d_ave − d_obs). Atoms absent from offsets (or None) are left unchanged.

Source code in makeshift/reref/base.py
def apply_offsets(df, offsets):
    """
    Return a copy of ``df`` with ``Val + offset`` per atom
    (``offset ≈ d_ave − d_obs``). Atoms absent from ``offsets`` (or None)
    are left unchanged.
    """
    applied = {a: v for a, v in (offsets or {}).items() if v is not None}
    out = df.copy()
    if applied:
        out["Val"] = out["Val"] + out["Atom_ID"].map(applied).fillna(0.0)
    return out

LACS

reref_lacs

reref_lacs(df, n_std=_N_STD_OUTLIER)

Compute per-atom LACS offsets for a backbone shift table.

Source code in makeshift/reref/lacs.py
def reref_lacs(df, n_std=_N_STD_OUTLIER):
    """Compute per-atom LACS offsets for a backbone shift table."""
    df = df.loc[:, ~df.columns.duplicated()].copy()
    df["reref_mask"] = True

    def _is_outlier(row):
        if pd.isna(row["Val"]):
            return False
        stats = _BMRB_STATS.get(str(row["Comp_ID"]).upper(), {}).get(
            str(row["Atom_ID"]).upper()
        )
        if stats is None:
            return True
        mean, std = stats
        return abs(row["Val"] - mean) > n_std * std

    df.loc[df.apply(_is_outlier, axis=1), "reref_mask"] = False

    seq_ids = sorted(df["Seq_ID"].dropna().unique())
    df["next_comp_id"] = df["Seq_ID"].map(
        {s: _comp_at(df, s + 1) for s in seq_ids}
    )
    df["prev_comp_id"] = df["Seq_ID"].map(
        {s: _comp_at(df, s - 1) for s in seq_ids}
    )

    def _secondary_shift(row):
        atom = row["Atom_ID"]
        aa = str(row["Comp_ID"]).upper()
        val = row["Val"]
        if atom in ("CA", "CB"):
            if row["next_comp_id"] == "PRO":
                rc = _RC_PRE_PRO.get(aa, {}).get(atom)
                if rc is not None and not np.isnan(val):
                    return val - rc
            try:
                rc = _RC[aa][atom]
            except KeyError:
                return np.nan
            return np.nan if (np.isnan(rc) or np.isnan(val)) else val - rc
        if atom == "C":
            if row["next_comp_id"] == "PRO":
                rc = _RC_PRE_PRO.get(aa, {}).get("C")
                if rc is not None and not np.isnan(val):
                    return val - rc
            rc = _RC_C_PRIME.get(aa, np.nan)
            return np.nan if (np.isnan(rc) or np.isnan(val)) else val - rc
        if atom == "N":
            try:
                rc = _RC[aa]["N"]
            except KeyError:
                return np.nan
            if np.isnan(rc) or np.isnan(val):
                return np.nan
            base = val - rc
            prev = row["prev_comp_id"]
            if prev is None:
                return base
            corr = _RC_N_PREV.get(prev)
            return base if corr is None else base - (corr - _RC_N_PREV_GLY)
        if atom == "H":
            try:
                rc = _RC[aa]["H"]
            except KeyError:
                return np.nan
            return np.nan if (np.isnan(rc) or np.isnan(val)) else val - rc
        return np.nan

    df["secondary_shift"] = df.apply(_secondary_shift, axis=1)

    csi_by_seq = {}
    for s in seq_ids:
        res = df.loc[df["Seq_ID"] == s]
        ca = res[res["Atom_ID"] == "CA"]
        cb = res[res["Atom_ID"] == "CB"]
        if ca.empty or cb.empty:
            csi_by_seq[s] = np.nan
            continue
        ca_sec = float(ca.iloc[0]["secondary_shift"])
        cb_sec = float(cb.iloc[0]["secondary_shift"])
        csi_by_seq[s] = (
            ca_sec - cb_sec
            if np.isfinite(ca_sec) and np.isfinite(cb_sec) else np.nan
        )
    df["csi"] = df["Seq_ID"].map(csi_by_seq)
    df["csi_prev"] = df["Seq_ID"].map(lambda s: csi_by_seq.get(s - 1, np.nan))

    raw = {}
    for atom in ("CA", "CB"):
        x, y = _prepare_fit_data(df[df["Atom_ID"] == atom], "csi")
        raw[atom] = _piecewise_offset(x, y)

    x, y = _prepare_fit_data(df[df["Atom_ID"] == "C"], "csi")
    mask = ~(np.isnan(x) | np.isnan(y))
    xc, yc = x[mask], y[mask]
    if len(xc) < 20:
        raw["C"] = np.nan
    else:
        _, intercept = _huber_fit(xc, yc)
        raw["C"] = (
            np.nan if intercept is None
            else (0.0 if abs(intercept) <= _THRESH_C else intercept)
        )

    for atom in ("N", "H"):
        expected_slope, slope_tight, threshold = _ATOM_PARAMS[atom]
        x, y = _prepare_fit_data(
            df[df["Atom_ID"] == atom], "csi_prev", exclude_col="prev_comp_id"
        )
        raw[atom] = _lacs_offset_linear(
            x, y, expected_slope, slope_tight, threshold, _SLOPE_TOL[atom]
        )

    # Fit intercept ≈ d_obs − d_ave; flip to offset = d_ave − d_obs.
    offsets, check = {}, {}
    for atom in _LACS_ATOMS:
        v = raw.get(atom)
        ok = v is not None and not (isinstance(v, float) and np.isnan(v))
        check[atom] = ok
        offsets[atom] = -v if ok else None
    return offsets, check

PANAV

reref_panav

reref_panav(df, cona=True)

Return (offsets, check, cona_meta).

CONA runs after offsets are fit and does not change them. Pass cona=False to skip the fragment scan (faster when only offsets matter).

Source code in makeshift/reref/panav.py
def reref_panav(df, cona=True):
    """Return ``(offsets, check, cona_meta)``.

    CONA runs after offsets are fit and does not change them. Pass
    ``cona=False`` to skip the fragment scan (faster when only offsets matter).
    """
    df = df.copy()
    df["Atom_ID"] = df["Atom_ID"].replace({"HA2": "HA", "HA3": "HA"})
    df["Comp_ID"] = df["Comp_ID"].str.upper()

    orig = {}
    for _, r in df.iterrows():
        atom = r["Atom_ID"]
        if atom not in _ALL_ATOMS or pd.isna(r["Val"]):
            continue
        sid = int(r["Seq_ID"])
        rec = orig.setdefault(sid, {"aa": r["Comp_ID"], "shifts": {}})
        rec["aa"] = r["Comp_ID"]
        v = float(r["Val"])
        prev = rec["shifts"].get(atom)
        rec["shifts"][atom] = v if prev is None else 0.5 * (prev + v)

    seq_ids = sorted(orig)
    none = {a: None for a in _OFFSET_ATOMS}
    if not seq_ids:
        return none, {a: False for a in _OFFSET_ATOMS}, None

    # crude offsets → deviant (6σ from every SS)
    crude = {}
    for atom in _ALL_ATOMS:
        vals = [
            orig[s]["shifts"][atom]
            for s in seq_ids
            if atom in orig[s]["shifts"]
            and not (atom == "CA" and orig[s]["aa"] == "GLY")
            and not (atom == "CB" and orig[s]["aa"] in ("ALA", "SER", "THR"))
        ]
        crude[atom] = (float(np.mean(vals)) - _STD[atom]) if vals else 0.0

    deviant = {s: set() for s in seq_ids}
    for s in seq_ids:
        aa = orig[s]["aa"]
        for atom, val in orig[s]["shifts"].items():
            if not _ok(aa, atom):
                continue
            if all(
                abs(val + crude[atom] - _REF[aa][ss][atom][0])
                > 6 * _REF[aa][ss][atom][1]
                for ss in _SS
            ):
                deviant[s].add(atom)

    ss = {}

    def assign_ss(cn_off):
        atoms = ("HA", "N", "CA", "CB", "C") if cn_off is not None else ("HA",)
        probs = {}
        for s in seq_ids:
            sh = dict(orig[s]["shifts"])
            if cn_off is not None:
                for atom in _OFFSET_ATOMS:
                    if cn_off.get(atom) is not None and atom in sh:
                        sh[atom] = sh[atom] + cn_off[atom]
            label, p = _ss_prob(orig[s]["aa"], sh, atoms)
            ss[s], probs[s] = label, (p or {})
        _smooth(seq_ids, ss, probs)

    def compute_offsets():
        out, ok = {}, {}
        for atom in _OFFSET_ATOMS:
            deltas = []
            for s in seq_ids:
                aa, sh = orig[s]["aa"], orig[s]["shifts"]
                if atom in deviant[s] or atom not in sh or ss.get(s) is None:
                    continue
                if not _ok(aa, atom):
                    continue
                mu, _ = _REF[aa][ss[s]][atom]
                deltas.append(mu - sh[atom])
            off = _mean_3sigma(deltas)
            out[atom], ok[atom] = (off, True) if off is not None else (None, False)
        return out, ok

    # HA→SS → offsets; then two rounds with trial-adjusted C/N
    assign_ss(None)
    offsets, check = compute_offsets()
    for _ in range(2):
        assign_ss(offsets)
        offsets, check = compute_offsets()

    cal = {
        s: {
            "aa": orig[s]["aa"],
            "shifts": {
                a: (v + offsets[a] if a in _OFFSET_ATOMS and offsets.get(a) is not None else v)
                for a, v in orig[s]["shifts"].items()
            },
            "ss": ss[s],
        }
        for s in seq_ids
    }

    # CONA: score each 3–6-mer under every same-length window in the protein.
    # Runs after offsets are final — skipping it does not change offsets.
    if not cona:
        return offsets, check, None

    cona_meta, suggestions = {}, []
    tot_sel = tot_conf = 0
    for k in (3, 4, 5, 6):
        windows = []
        for i in range(len(seq_ids) - k + 1):
            ids = seq_ids[i:i + k]
            if ids[-1] - ids[0] != k - 1:
                continue
            n_cacb = sum(
                ("CA" in cal[s]["shifts"]) + ("CB" in cal[s]["shifts"]) for s in ids
            )
            if n_cacb < k:
                continue
            aas = [cal[s]["aa"] for s in ids]
            shs = [cal[s]["shifts"] for s in ids]
            seq1 = "".join(_AA_3TO1.get(a, "X") for a in aas)
            windows.append((ids[0], ids[-1], aas, seq1, shs))

        selected = confirmed = 0
        for oi, (start, end, _, seq_o, shs_o) in enumerate(windows):
            selected += 1
            scores = np.array([
                float(np.prod([_residue_prob(a, sh) for a, sh in zip(w[2], shs_o)]))
                for w in windows
            ])
            p_max = float(scores.max()) if len(scores) else 0.0
            j_best = int(np.argmax(scores)) if len(scores) else oi
            norm = scores / p_max if p_max > 0 else scores
            if float(norm[oi]) >= 1.0 - _CONA_TOL:
                confirmed += 1
            elif j_best != oi:
                suggestions.append({
                    "start": int(start),
                    "end": int(end),
                    "original": seq_o,
                    "original_pct": round(100.0 * float(norm[oi]), 2),
                    "suggested": windows[j_best][3],
                    "suggested_pct": 100.0,
                    "suggested_start": int(windows[j_best][0]),
                    "suggested_end": int(windows[j_best][1]),
                })

        cona_meta[f"{k}-residue"] = {
            "selected": selected,
            "confirmed": confirmed,
            "score": (100.0 * confirmed / selected) if selected else None,
        }
        tot_sel += selected
        tot_conf += confirmed

    suspicious = []
    for s in seq_ids:
        aa, sh, ssi = cal[s]["aa"], cal[s]["shifts"], cal[s]["ss"]
        if ssi is None:
            continue
        for atom, val in sh.items():
            if not _ok(aa, atom):
                continue
            mu, sig = _REF[aa][ssi][atom]
            if abs(val - mu) > 4 * sig:
                suspicious.append(
                    {"seq_id": int(s), "aa": aa, "atom": atom, "val": val}
                )

    cona_meta["overall"] = {
        "selected": tot_sel,
        "confirmed": tot_conf,
        "score": (100.0 * tot_conf / tot_sel) if tot_sel else None,
    }
    if suggestions:
        cona_meta["suggestions"] = suggestions
    if suspicious:
        cona_meta["suspicious"] = suspicious
    deviant_list = [
        {"seq_id": int(s), "aa": orig[s]["aa"], "atom": a}
        for s, atoms in deviant.items() for a in atoms
    ]
    if deviant_list:
        cona_meta["deviant"] = deviant_list

    return offsets, check, cona_meta