pubfigure 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pubfigure/__init__.py +38 -0
- pubfigure/cli.py +139 -0
- pubfigure/fitting.py +416 -0
- pubfigure/plotting.py +409 -0
- pubfigure/presets.py +119 -0
- pubfigure/stats.py +469 -0
- pubfigure-1.0.0.dist-info/LICENSE +21 -0
- pubfigure-1.0.0.dist-info/METADATA +121 -0
- pubfigure-1.0.0.dist-info/RECORD +12 -0
- pubfigure-1.0.0.dist-info/WHEEL +5 -0
- pubfigure-1.0.0.dist-info/entry_points.txt +2 -0
- pubfigure-1.0.0.dist-info/top_level.txt +1 -0
pubfigure/__init__.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""PubFigure Python SDK — Journal-compliant Matplotlib figures, nonlinear curve fitting & error propagation."""
|
|
2
|
+
|
|
3
|
+
from .fitting import FIT_PRESETS, FitResult, ParameterEstimate, eval_safe_formula, fit_curve
|
|
4
|
+
from .plotting import Figure, PanelBuilder
|
|
5
|
+
from .presets import COLOR_PALETTES, JOURNAL_PRESETS, JournalSpec, format_panel_badge, get_rcparams
|
|
6
|
+
from .stats import (
|
|
7
|
+
GroupedStatsResult,
|
|
8
|
+
PairwiseBracket,
|
|
9
|
+
UncertaintyPropagationResult,
|
|
10
|
+
aggregate_replicates,
|
|
11
|
+
grouped_hypothesis_test,
|
|
12
|
+
kruskal_wallis_test,
|
|
13
|
+
propagate_uncertainty,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
__version__ = "1.0.0"
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"COLOR_PALETTES",
|
|
20
|
+
"FIT_PRESETS",
|
|
21
|
+
"Figure",
|
|
22
|
+
"FitResult",
|
|
23
|
+
"GroupedStatsResult",
|
|
24
|
+
"JOURNAL_PRESETS",
|
|
25
|
+
"JournalSpec",
|
|
26
|
+
"PairwiseBracket",
|
|
27
|
+
"PanelBuilder",
|
|
28
|
+
"ParameterEstimate",
|
|
29
|
+
"UncertaintyPropagationResult",
|
|
30
|
+
"aggregate_replicates",
|
|
31
|
+
"eval_safe_formula",
|
|
32
|
+
"fit_curve",
|
|
33
|
+
"format_panel_badge",
|
|
34
|
+
"get_rcparams",
|
|
35
|
+
"grouped_hypothesis_test",
|
|
36
|
+
"kruskal_wallis_test",
|
|
37
|
+
"propagate_uncertainty",
|
|
38
|
+
]
|
pubfigure/cli.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Command-line interface (`pubfigure-py`) for Python scripts and automated pipelines."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
import argparse
|
|
5
|
+
import csv
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import sys
|
|
9
|
+
from typing import Dict, List
|
|
10
|
+
import matplotlib
|
|
11
|
+
|
|
12
|
+
matplotlib.use("Agg")
|
|
13
|
+
|
|
14
|
+
from .fitting import FIT_PRESETS, fit_curve
|
|
15
|
+
from .plotting import Figure
|
|
16
|
+
from .presets import JOURNAL_PRESETS
|
|
17
|
+
from .stats import grouped_hypothesis_test
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _read_csv_rows(path: Path) -> List[List[str]]:
|
|
21
|
+
with path.open("r", encoding="utf-8-sig", newline="") as f:
|
|
22
|
+
return [row for row in csv.reader(f) if any(cell.strip() for cell in row)]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def main(argv: List[str] | None = None) -> int:
|
|
26
|
+
parser = argparse.ArgumentParser(
|
|
27
|
+
prog="pubfigure-py",
|
|
28
|
+
description="PubFigure Python CLI — Journal-calibrated Matplotlib figures, nonlinear curve fitting & stats.",
|
|
29
|
+
)
|
|
30
|
+
sub = parser.add_subparsers(dest="cmd")
|
|
31
|
+
|
|
32
|
+
sub.add_parser("presets", help="List 14 journal presets and 10 nonlinear curve fit models")
|
|
33
|
+
|
|
34
|
+
p_fit = sub.add_parser("fit", help="Fit preset or custom analytical formula to XY CSV")
|
|
35
|
+
p_fit.add_argument("csv_file", type=Path)
|
|
36
|
+
p_fit.add_argument("--preset", default="exp_decay")
|
|
37
|
+
p_fit.add_argument("--formula", default=None)
|
|
38
|
+
p_fit.add_argument("--json", action="store_true")
|
|
39
|
+
|
|
40
|
+
p_stats = sub.add_parser("stats", help="Run grouped hypothesis suite + Holm brackets on CSV")
|
|
41
|
+
p_stats.add_argument("csv_file", type=Path)
|
|
42
|
+
p_stats.add_argument("--test", default="welch_t", choices=["welch_t", "student_t", "mann_whitney"])
|
|
43
|
+
p_stats.add_argument("--correction", default="holm", choices=["holm", "bonferroni", "none"])
|
|
44
|
+
p_stats.add_argument("--json", action="store_true")
|
|
45
|
+
|
|
46
|
+
p_render = sub.add_parser("render", help="Render CSV or workspace.json to PDF/SVG/PNG via Matplotlib")
|
|
47
|
+
p_render.add_argument("input_file", type=Path)
|
|
48
|
+
p_render.add_argument("-o", "--output", type=Path, required=True, help="Output .pdf, .svg, or .png path")
|
|
49
|
+
p_render.add_argument("--journal", default="nature-single")
|
|
50
|
+
p_render.add_argument("--fit", default=None)
|
|
51
|
+
p_render.add_argument("--formula", default=None)
|
|
52
|
+
p_render.add_argument("--title", default="")
|
|
53
|
+
p_render.add_argument("--xlabel", default="X")
|
|
54
|
+
p_render.add_argument("--ylabel", default="Y")
|
|
55
|
+
|
|
56
|
+
args = parser.parse_args(argv)
|
|
57
|
+
if not args.cmd:
|
|
58
|
+
parser.print_help()
|
|
59
|
+
return 0
|
|
60
|
+
|
|
61
|
+
if args.cmd == "presets":
|
|
62
|
+
for jid, j in JOURNAL_PRESETS.items():
|
|
63
|
+
print(f"{jid:16s} {j.single_col_mm:5.1f}mm / {j.double_col_mm:5.1f}mm {j.name}")
|
|
64
|
+
print("\nFit Presets:")
|
|
65
|
+
for fid, expr in FIT_PRESETS.items():
|
|
66
|
+
print(f" {fid:18s} y = {expr}")
|
|
67
|
+
return 0
|
|
68
|
+
|
|
69
|
+
if args.cmd == "fit":
|
|
70
|
+
rows = _read_csv_rows(args.csv_file)
|
|
71
|
+
headers = rows[0]
|
|
72
|
+
xs = [float(r[0]) for r in rows[1:]]
|
|
73
|
+
ys = [float(r[1]) for r in rows[1:]]
|
|
74
|
+
yerr = [float(r[2]) for r in rows[1:]] if len(headers) >= 3 and "err" in headers[2].lower() else None
|
|
75
|
+
res = fit_curve(xs, ys, yerr=yerr, preset=args.preset, formula=args.formula)
|
|
76
|
+
if args.json:
|
|
77
|
+
print(
|
|
78
|
+
json.dumps(
|
|
79
|
+
{
|
|
80
|
+
"formula": res.formula,
|
|
81
|
+
"r_squared": res.r_squared,
|
|
82
|
+
"rmse": res.rmse,
|
|
83
|
+
"parameters": [p.__dict__ for p in res.parameters],
|
|
84
|
+
"methods": res.methods_sentence,
|
|
85
|
+
},
|
|
86
|
+
indent=2,
|
|
87
|
+
)
|
|
88
|
+
)
|
|
89
|
+
else:
|
|
90
|
+
print(f"Model: y = {res.formula} | R² = {res.r_squared:.5f} | RMSE = {res.rmse:.4g}")
|
|
91
|
+
for p in res.parameters:
|
|
92
|
+
print(f" {p.name:10s} = {p.value:.5g} ± {p.std_error:.3g} (95% CI [{p.ci95_low:.4g}, {p.ci95_high:.4g}])")
|
|
93
|
+
print(res.methods_sentence)
|
|
94
|
+
return 0
|
|
95
|
+
|
|
96
|
+
if args.cmd == "stats":
|
|
97
|
+
rows = _read_csv_rows(args.csv_file)
|
|
98
|
+
headers = rows[0]
|
|
99
|
+
groups: Dict[str, List[float]] = {h: [] for h in headers}
|
|
100
|
+
for r in rows[1:]:
|
|
101
|
+
for idx, h in enumerate(headers):
|
|
102
|
+
if idx < len(r) and r[idx].strip():
|
|
103
|
+
groups[h].append(float(r[idx]))
|
|
104
|
+
rep = grouped_hypothesis_test(groups, test=args.test, correction=args.correction)
|
|
105
|
+
if args.json:
|
|
106
|
+
print(json.dumps({"methods": rep.methods_sentence, "comparisons": [c.__dict__ for c in rep.comparisons]}, indent=2))
|
|
107
|
+
else:
|
|
108
|
+
for c in rep.comparisons:
|
|
109
|
+
print(f"{c.group_a} vs {c.group_b}: adj. p = {c.adj_p:.4g} ({c.stars})")
|
|
110
|
+
print(rep.methods_sentence)
|
|
111
|
+
return 0
|
|
112
|
+
|
|
113
|
+
if args.cmd == "render":
|
|
114
|
+
inp: Path = args.input_file
|
|
115
|
+
if inp.suffix.lower() == ".json":
|
|
116
|
+
fig = Figure.from_workspace(inp)
|
|
117
|
+
else:
|
|
118
|
+
rows = _read_csv_rows(inp)
|
|
119
|
+
headers = rows[0]
|
|
120
|
+
fig = Figure(journal=args.journal)
|
|
121
|
+
ax = fig[0]
|
|
122
|
+
ax.set_labels(title=args.title, xlabel=args.xlabel, ylabel=args.ylabel)
|
|
123
|
+
xs = [float(r[0]) for r in rows[1:]]
|
|
124
|
+
ys = [float(r[1]) for r in rows[1:]]
|
|
125
|
+
yerr = [float(r[2]) for r in rows[1:]] if len(headers) >= 3 and "err" in headers[2].lower() else None
|
|
126
|
+
if args.fit or args.formula:
|
|
127
|
+
ax.fit(xs, ys, yerr=yerr, preset=args.fit or "custom", formula=args.formula, label=headers[1])
|
|
128
|
+
else:
|
|
129
|
+
ax.errorbar_series(xs, ys, yerr=yerr, label=headers[1])
|
|
130
|
+
fig.save(args.output)
|
|
131
|
+
fig.close()
|
|
132
|
+
print(f"Saved publication figure -> {args.output}")
|
|
133
|
+
return 0
|
|
134
|
+
|
|
135
|
+
return 0
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
if __name__ == "__main__":
|
|
139
|
+
sys.exit(main())
|
pubfigure/fitting.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
"""Safe AST formula evaluator and weighted Levenberg–Marquardt curve fitting engine (zero eval)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
import ast
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
import math
|
|
7
|
+
from typing import Dict, List, Mapping, Sequence, Tuple
|
|
8
|
+
import numpy as np
|
|
9
|
+
from .stats import student_t_critical, student_t_two_tailed_p
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
FIT_PRESETS: Dict[str, str] = {
|
|
13
|
+
"linear": "m * x + b",
|
|
14
|
+
"poly2": "a * x^2 + b * x + c",
|
|
15
|
+
"exp_decay": "A * exp(-x / tau) + y0",
|
|
16
|
+
"hill_4pl": "Bottom + (Top - Bottom) / (1 + (x / IC50)^Hill)",
|
|
17
|
+
"michaelis_menten": "(Vmax * x) / (Km + x)",
|
|
18
|
+
"power_law": "A * x^alpha + c",
|
|
19
|
+
"gaussian_peak": "y0 + A * exp(-0.5 * ((x - x0) / sigma)^2)",
|
|
20
|
+
"lorentzian_peak": "y0 + A * (gamma^2 / ((x - x0)^2 + gamma^2))",
|
|
21
|
+
"arrhenius": "A * exp(-Ea / x)",
|
|
22
|
+
"damped_osc": "y0 + A * exp(-x / T2) * cos(2 * pi * f * x + phi)",
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
_VectorizeErf = np.vectorize(math.erf, otypes=[float])
|
|
26
|
+
|
|
27
|
+
_ALLOWED_FUNCS = {
|
|
28
|
+
"exp": lambda z: np.exp(np.clip(z, -500.0, 500.0)),
|
|
29
|
+
"ln": np.log,
|
|
30
|
+
"log": np.log,
|
|
31
|
+
"log10": np.log10,
|
|
32
|
+
"log2": np.log2,
|
|
33
|
+
"sqrt": np.sqrt,
|
|
34
|
+
"abs": np.abs,
|
|
35
|
+
"sin": np.sin,
|
|
36
|
+
"cos": np.cos,
|
|
37
|
+
"tan": np.tan,
|
|
38
|
+
"tanh": np.tanh,
|
|
39
|
+
"sinh": lambda z: np.sinh(np.clip(z, -500.0, 500.0)),
|
|
40
|
+
"cosh": lambda z: np.cosh(np.clip(z, -500.0, 500.0)),
|
|
41
|
+
"erf": _VectorizeErf,
|
|
42
|
+
"pow": np.power,
|
|
43
|
+
"min": np.minimum,
|
|
44
|
+
"max": np.maximum,
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
_CONSTANTS = {
|
|
48
|
+
"pi": math.pi,
|
|
49
|
+
"e": math.e,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _normalize_expr(formula: str) -> str:
|
|
54
|
+
return formula.strip().replace("^", "**")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def extract_formula_parameters(formula: str, independent_var: str = "x") -> Tuple[ast.AST, List[str]]:
|
|
58
|
+
tree = ast.parse(_normalize_expr(formula), mode="eval")
|
|
59
|
+
seen: List[str] = []
|
|
60
|
+
for node in ast.walk(tree):
|
|
61
|
+
if isinstance(node, ast.Name):
|
|
62
|
+
ident = node.id
|
|
63
|
+
if ident == independent_var or ident in _CONSTANTS or ident in _ALLOWED_FUNCS:
|
|
64
|
+
continue
|
|
65
|
+
if ident not in seen:
|
|
66
|
+
seen.append(ident)
|
|
67
|
+
elif isinstance(node, ast.Call):
|
|
68
|
+
if not isinstance(node.func, ast.Name) or node.func.id not in _ALLOWED_FUNCS:
|
|
69
|
+
raise ValueError(f"Unsupported function in formula: {ast.dump(node.func)}")
|
|
70
|
+
elif not isinstance(
|
|
71
|
+
node,
|
|
72
|
+
(
|
|
73
|
+
ast.Expression,
|
|
74
|
+
ast.BinOp,
|
|
75
|
+
ast.UnaryOp,
|
|
76
|
+
ast.Constant,
|
|
77
|
+
ast.Load,
|
|
78
|
+
ast.Add,
|
|
79
|
+
ast.Sub,
|
|
80
|
+
ast.Mult,
|
|
81
|
+
ast.Div,
|
|
82
|
+
ast.Pow,
|
|
83
|
+
ast.USub,
|
|
84
|
+
ast.UAdd,
|
|
85
|
+
),
|
|
86
|
+
):
|
|
87
|
+
raise ValueError(f"Disallowed syntax in formula: {type(node).__name__}")
|
|
88
|
+
return tree.body, seen
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _eval_ast_node(node: ast.AST, env: Mapping[str, float | np.ndarray]) -> float | np.ndarray:
|
|
92
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
|
|
93
|
+
return float(node.value)
|
|
94
|
+
if isinstance(node, ast.Name):
|
|
95
|
+
if node.id in _CONSTANTS:
|
|
96
|
+
return _CONSTANTS[node.id]
|
|
97
|
+
if node.id in env:
|
|
98
|
+
return env[node.id]
|
|
99
|
+
raise ValueError(f"Unbound symbol '{node.id}' in formula.")
|
|
100
|
+
if isinstance(node, ast.UnaryOp):
|
|
101
|
+
val = _eval_ast_node(node.operand, env)
|
|
102
|
+
return -val if isinstance(node.op, ast.USub) else +val
|
|
103
|
+
if isinstance(node, ast.BinOp):
|
|
104
|
+
left = _eval_ast_node(node.left, env)
|
|
105
|
+
right = _eval_ast_node(node.right, env)
|
|
106
|
+
if isinstance(node.op, ast.Add):
|
|
107
|
+
return left + right
|
|
108
|
+
if isinstance(node.op, ast.Sub):
|
|
109
|
+
return left - right
|
|
110
|
+
if isinstance(node.op, ast.Mult):
|
|
111
|
+
return left * right
|
|
112
|
+
if isinstance(node.op, ast.Div):
|
|
113
|
+
return left / right
|
|
114
|
+
if isinstance(node.op, ast.Pow):
|
|
115
|
+
return np.power(left, right)
|
|
116
|
+
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
|
|
117
|
+
fn = _ALLOWED_FUNCS[node.func.id]
|
|
118
|
+
args = [_eval_ast_node(arg, env) for arg in node.args]
|
|
119
|
+
return fn(*args)
|
|
120
|
+
raise ValueError(f"Unsupported AST node: {type(node).__name__}")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def eval_safe_formula(formula: str, env: Mapping[str, float | np.ndarray]) -> float | np.ndarray:
|
|
124
|
+
body, _ = extract_formula_parameters(formula, independent_var="__none__")
|
|
125
|
+
return _eval_ast_node(body, env)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@dataclass
|
|
129
|
+
class ParameterEstimate:
|
|
130
|
+
name: str
|
|
131
|
+
value: float
|
|
132
|
+
std_error: float
|
|
133
|
+
ci95_low: float
|
|
134
|
+
ci95_high: float
|
|
135
|
+
t_stat: float
|
|
136
|
+
p_value: float
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@dataclass
|
|
140
|
+
class FitResult:
|
|
141
|
+
preset: str
|
|
142
|
+
formula: str
|
|
143
|
+
converged: bool
|
|
144
|
+
n: int
|
|
145
|
+
dof: int
|
|
146
|
+
weighted: bool
|
|
147
|
+
parameters: List[ParameterEstimate]
|
|
148
|
+
r_squared: float
|
|
149
|
+
adj_r_squared: float
|
|
150
|
+
rmse: float
|
|
151
|
+
reduced_chi_squared: float
|
|
152
|
+
aic: float
|
|
153
|
+
bic: float
|
|
154
|
+
curve_x: np.ndarray
|
|
155
|
+
curve_y: np.ndarray
|
|
156
|
+
ci_half_width: np.ndarray
|
|
157
|
+
compact_equation: str
|
|
158
|
+
methods_sentence: str
|
|
159
|
+
|
|
160
|
+
def param_dict(self) -> Dict[str, float]:
|
|
161
|
+
return {p.name: p.value for p in self.parameters}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _heuristic_initial_guesses(
|
|
165
|
+
preset: str,
|
|
166
|
+
param_names: Sequence[str],
|
|
167
|
+
x: np.ndarray,
|
|
168
|
+
y: np.ndarray,
|
|
169
|
+
) -> np.ndarray:
|
|
170
|
+
x_min, x_max = float(np.min(x)), float(np.max(x))
|
|
171
|
+
x_span = max(1e-9, x_max - x_min)
|
|
172
|
+
y_min, y_max = float(np.min(y)), float(np.max(y))
|
|
173
|
+
y_span = max(1e-9, y_max - y_min)
|
|
174
|
+
|
|
175
|
+
guesses: Dict[str, float] = {}
|
|
176
|
+
if preset == "linear":
|
|
177
|
+
slope, intercept = np.polyfit(x, y, 1)
|
|
178
|
+
guesses = {"m": float(slope), "b": float(intercept)}
|
|
179
|
+
elif preset == "poly2":
|
|
180
|
+
c2, c1, c0 = np.polyfit(x, y, 2)
|
|
181
|
+
guesses = {"a": float(c2), "b": float(c1), "c": float(c0)}
|
|
182
|
+
elif preset == "exp_decay":
|
|
183
|
+
y0 = float(y[-1])
|
|
184
|
+
amp = float(y[0] - y0) or y_span
|
|
185
|
+
guesses = {"A": amp, "tau": max(1e-6, x_span * 0.35), "y0": y0}
|
|
186
|
+
elif preset == "hill_4pl":
|
|
187
|
+
mid_y = 0.5 * (y_min + y_max)
|
|
188
|
+
mid_idx = int(np.argmin(np.abs(y - mid_y)))
|
|
189
|
+
ic50 = max(1e-9, float(x[mid_idx]))
|
|
190
|
+
hill = 1.0 if y[0] > y[-1] else -1.0
|
|
191
|
+
guesses = {"Bottom": y_min, "Top": y_max, "IC50": ic50, "Hill": hill}
|
|
192
|
+
elif preset == "michaelis_menten":
|
|
193
|
+
vmax = max(1e-6, y_max * 1.1)
|
|
194
|
+
half_idx = int(np.argmin(np.abs(y - 0.5 * vmax)))
|
|
195
|
+
guesses = {"Vmax": vmax, "Km": max(1e-6, float(x[half_idx]))}
|
|
196
|
+
elif preset == "power_law":
|
|
197
|
+
guesses = {"A": y_span, "alpha": -0.5 if y[-1] < y[0] else 0.5, "c": y_min}
|
|
198
|
+
elif preset in ("gaussian_peak", "lorentzian_peak"):
|
|
199
|
+
pk_idx = int(np.argmax(y))
|
|
200
|
+
guesses = {
|
|
201
|
+
"y0": y_min,
|
|
202
|
+
"A": y_max - y_min,
|
|
203
|
+
"x0": float(x[pk_idx]),
|
|
204
|
+
"sigma": x_span * 0.15,
|
|
205
|
+
"gamma": x_span * 0.15,
|
|
206
|
+
}
|
|
207
|
+
elif preset == "arrhenius":
|
|
208
|
+
guesses = {"A": max(1.0, y_max * 10.0), "Ea": max(1.0, float(np.mean(x)))}
|
|
209
|
+
elif preset == "damped_osc":
|
|
210
|
+
guesses = {
|
|
211
|
+
"y0": float(np.mean(y)),
|
|
212
|
+
"A": 0.5 * y_span,
|
|
213
|
+
"T2": x_span * 0.6,
|
|
214
|
+
"f": 2.0 / x_span,
|
|
215
|
+
"phi": 0.0,
|
|
216
|
+
}
|
|
217
|
+
else:
|
|
218
|
+
# Name-aware heuristic for arbitrary custom formulas (matching TypeScript curveFitting.ts)
|
|
219
|
+
for nm in param_names:
|
|
220
|
+
low = nm.lower()
|
|
221
|
+
if low in ("tau", "t1", "t2", "ic50", "ec50", "km", "kd"):
|
|
222
|
+
guesses[nm] = max(1e-6, x_span * 0.35)
|
|
223
|
+
elif low in ("x0", "mu", "center"):
|
|
224
|
+
guesses[nm] = float(x[int(np.argmax(y))])
|
|
225
|
+
elif low in ("sigma", "gamma", "width"):
|
|
226
|
+
guesses[nm] = max(1e-6, x_span * 0.18)
|
|
227
|
+
elif low in ("y0", "b", "c", "bottom", "offset", "baseline"):
|
|
228
|
+
guesses[nm] = float(y[-1]) if abs(y[-1]) < abs(y[0]) else y_min
|
|
229
|
+
elif low in ("a", "amp", "amplitude", "vmax", "top"):
|
|
230
|
+
guesses[nm] = y_span
|
|
231
|
+
elif low in ("k", "rate"):
|
|
232
|
+
guesses[nm] = 2.0 / x_span
|
|
233
|
+
else:
|
|
234
|
+
guesses[nm] = 1.0
|
|
235
|
+
return np.array([guesses.get(name, 1.0) for name in param_names], dtype=float)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def fit_curve(
|
|
239
|
+
x: Sequence[float],
|
|
240
|
+
y: Sequence[float],
|
|
241
|
+
yerr: Sequence[float] | None = None,
|
|
242
|
+
preset: str = "exp_decay",
|
|
243
|
+
formula: str | None = None,
|
|
244
|
+
p0: Mapping[str, float] | None = None,
|
|
245
|
+
log_x: bool = False,
|
|
246
|
+
sample_count: int = 120,
|
|
247
|
+
) -> FitResult:
|
|
248
|
+
"""Fit a preset or custom analytical model f(x) via weighted Levenberg–Marquardt (1/σ²)."""
|
|
249
|
+
x_arr = np.asarray(x, dtype=float)
|
|
250
|
+
y_arr = np.asarray(y, dtype=float)
|
|
251
|
+
order = np.argsort(x_arr)
|
|
252
|
+
x_arr = x_arr[order]
|
|
253
|
+
y_arr = y_arr[order]
|
|
254
|
+
|
|
255
|
+
expr = formula.strip() if formula else FIT_PRESETS.get(preset, "")
|
|
256
|
+
if not expr:
|
|
257
|
+
raise ValueError(f"Unknown preset '{preset}'. Provide formula='...' or a valid preset.")
|
|
258
|
+
|
|
259
|
+
ast_body, param_names = extract_formula_parameters(expr, independent_var="x")
|
|
260
|
+
p_count = len(param_names)
|
|
261
|
+
n = len(x_arr)
|
|
262
|
+
if p_count == 0:
|
|
263
|
+
raise ValueError("Formula must include at least one free parameter.")
|
|
264
|
+
if n <= p_count:
|
|
265
|
+
raise ValueError(f"Need more data points (n={n}) than free parameters (p={p_count}).")
|
|
266
|
+
|
|
267
|
+
weighted = False
|
|
268
|
+
weights = np.ones(n, dtype=float)
|
|
269
|
+
if yerr is not None:
|
|
270
|
+
s_arr = np.asarray(yerr, dtype=float)[order]
|
|
271
|
+
if s_arr.ndim == 2:
|
|
272
|
+
s_arr = 0.5 * (s_arr[0] + s_arr[1])
|
|
273
|
+
if np.all(np.isfinite(s_arr)) and np.all(s_arr > 0):
|
|
274
|
+
weights = 1.0 / s_arr
|
|
275
|
+
weighted = True
|
|
276
|
+
|
|
277
|
+
theta = _heuristic_initial_guesses(preset if not formula else "custom", param_names, x_arr, y_arr)
|
|
278
|
+
if p0:
|
|
279
|
+
for idx, name in enumerate(param_names):
|
|
280
|
+
if name in p0:
|
|
281
|
+
theta[idx] = float(p0[name])
|
|
282
|
+
|
|
283
|
+
def eval_vec(th: np.ndarray, xv: np.ndarray) -> np.ndarray:
|
|
284
|
+
env: Dict[str, float | np.ndarray] = {"x": xv}
|
|
285
|
+
for k, name in enumerate(param_names):
|
|
286
|
+
env[name] = float(th[k])
|
|
287
|
+
out = np.asarray(_eval_ast_node(ast_body, env), dtype=float)
|
|
288
|
+
return np.broadcast_to(out, xv.shape).copy()
|
|
289
|
+
|
|
290
|
+
def weighted_res(th: np.ndarray) -> np.ndarray:
|
|
291
|
+
return (y_arr - eval_vec(th, x_arr)) * weights
|
|
292
|
+
|
|
293
|
+
def jacobian(th: np.ndarray, xv: np.ndarray, wv: np.ndarray) -> np.ndarray:
|
|
294
|
+
jac = np.zeros((len(xv), p_count), dtype=float)
|
|
295
|
+
for j in range(p_count):
|
|
296
|
+
h = max(1e-7, abs(float(th[j])) * 1e-6)
|
|
297
|
+
tp = th.copy()
|
|
298
|
+
tm = th.copy()
|
|
299
|
+
tp[j] += h
|
|
300
|
+
tm[j] -= h
|
|
301
|
+
jac[:, j] = ((eval_vec(tp, xv) - eval_vec(tm, xv)) / (2.0 * h)) * wv
|
|
302
|
+
return jac
|
|
303
|
+
|
|
304
|
+
# Pure-NumPy damped Levenberg–Marquardt
|
|
305
|
+
r_vec = weighted_res(theta)
|
|
306
|
+
cost = float(np.dot(r_vec, r_vec))
|
|
307
|
+
lam = 1e-3
|
|
308
|
+
converged = False
|
|
309
|
+
for _ in range(180):
|
|
310
|
+
J = jacobian(theta, x_arr, weights)
|
|
311
|
+
jtj = J.T @ J
|
|
312
|
+
jtr = J.T @ r_vec
|
|
313
|
+
diag = np.maximum(np.diag(jtj), 1e-8)
|
|
314
|
+
try:
|
|
315
|
+
step = np.linalg.solve(jtj + lam * np.diag(diag), jtr)
|
|
316
|
+
except np.linalg.LinAlgError:
|
|
317
|
+
lam *= 10.0
|
|
318
|
+
continue
|
|
319
|
+
cand = theta + step
|
|
320
|
+
r_cand = weighted_res(cand)
|
|
321
|
+
if not np.all(np.isfinite(r_cand)):
|
|
322
|
+
lam *= 10.0
|
|
323
|
+
continue
|
|
324
|
+
cost_cand = float(np.dot(r_cand, r_cand))
|
|
325
|
+
if cost_cand < cost:
|
|
326
|
+
rel_imp = abs(cost - cost_cand) / max(1e-15, cost)
|
|
327
|
+
theta = cand
|
|
328
|
+
r_vec = r_cand
|
|
329
|
+
cost = cost_cand
|
|
330
|
+
lam = max(1e-11, lam * 0.35)
|
|
331
|
+
if rel_imp < 1e-10 or float(np.linalg.norm(step)) < 1e-10:
|
|
332
|
+
converged = True
|
|
333
|
+
break
|
|
334
|
+
else:
|
|
335
|
+
lam = min(1e10, lam * 5.0)
|
|
336
|
+
else:
|
|
337
|
+
converged = True
|
|
338
|
+
|
|
339
|
+
dof = max(1, n - p_count)
|
|
340
|
+
y_hat = eval_vec(theta, x_arr)
|
|
341
|
+
raw_res = y_arr - y_hat
|
|
342
|
+
sse = float(np.dot(raw_res, raw_res))
|
|
343
|
+
sst = float(np.sum((y_arr - np.mean(y_arr)) ** 2))
|
|
344
|
+
r2 = 1.0 - sse / sst if sst > 1e-15 else 1.0
|
|
345
|
+
adj_r2 = 1.0 - (1.0 - r2) * (n - 1) / dof
|
|
346
|
+
rmse = math.sqrt(sse / n)
|
|
347
|
+
chi2 = float(np.dot(r_vec, r_vec))
|
|
348
|
+
red_chi2 = chi2 / dof
|
|
349
|
+
|
|
350
|
+
J_final = jacobian(theta, x_arr, weights)
|
|
351
|
+
try:
|
|
352
|
+
jtj_inv = np.linalg.pinv(J_final.T @ J_final)
|
|
353
|
+
except np.linalg.LinAlgError:
|
|
354
|
+
jtj_inv = np.zeros((p_count, p_count), dtype=float)
|
|
355
|
+
cov = jtj_inv * red_chi2
|
|
356
|
+
t_crit = student_t_critical(dof, 0.05)
|
|
357
|
+
|
|
358
|
+
params_out: List[ParameterEstimate] = []
|
|
359
|
+
for j, name in enumerate(param_names):
|
|
360
|
+
se = math.sqrt(max(0.0, float(cov[j, j])))
|
|
361
|
+
val = float(theta[j])
|
|
362
|
+
t_val = val / se if se > 1e-15 else 0.0
|
|
363
|
+
p_val = student_t_two_tailed_p(abs(t_val), dof) if se > 1e-15 else 0.0
|
|
364
|
+
params_out.append(
|
|
365
|
+
ParameterEstimate(
|
|
366
|
+
name=name,
|
|
367
|
+
value=val,
|
|
368
|
+
std_error=se,
|
|
369
|
+
ci95_low=val - t_crit * se,
|
|
370
|
+
ci95_high=val + t_crit * se,
|
|
371
|
+
t_stat=t_val,
|
|
372
|
+
p_value=p_val,
|
|
373
|
+
)
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
if log_x and float(np.min(x_arr)) > 0:
|
|
377
|
+
cx = np.geomspace(float(np.min(x_arr)), float(np.max(x_arr)), sample_count)
|
|
378
|
+
else:
|
|
379
|
+
cx = np.linspace(float(np.min(x_arr)), float(np.max(x_arr)), sample_count)
|
|
380
|
+
cy = eval_vec(theta, cx)
|
|
381
|
+
J_grid = jacobian(theta, cx, np.ones_like(cx))
|
|
382
|
+
var_y = np.maximum(0.0, np.einsum("ij,jk,ik->i", J_grid, cov, J_grid))
|
|
383
|
+
ci_hw = t_crit * np.sqrt(var_y)
|
|
384
|
+
|
|
385
|
+
aic = n * math.log(max(1e-18, sse / n)) + 2.0 * p_count
|
|
386
|
+
bic = n * math.log(max(1e-18, sse / n)) + p_count * math.log(n)
|
|
387
|
+
|
|
388
|
+
param_summary = ", ".join(f"{p.name}={p.value:.3g}±{p.std_error:.2g}" for p in params_out[:3])
|
|
389
|
+
compact_eq = f"{param_summary} (R²={r2:.4f})"
|
|
390
|
+
w_str = "inverse-variance weighted (1/σ²) " if weighted else ""
|
|
391
|
+
methods = (
|
|
392
|
+
f"Nonlinear {w_str}Levenberg–Marquardt regression to y = {expr} (n={n}, df={dof}) "
|
|
393
|
+
f"yielded {', '.join(f'{p.name} = {p.value:.4g} ± {p.std_error:.2g}' for p in params_out)} "
|
|
394
|
+
f"(R² = {r2:.4f}, RMSE = {rmse:.4g})."
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
return FitResult(
|
|
398
|
+
preset=preset if not formula else "custom",
|
|
399
|
+
formula=expr,
|
|
400
|
+
converged=converged,
|
|
401
|
+
n=n,
|
|
402
|
+
dof=dof,
|
|
403
|
+
weighted=weighted,
|
|
404
|
+
parameters=params_out,
|
|
405
|
+
r_squared=r2,
|
|
406
|
+
adj_r_squared=adj_r2,
|
|
407
|
+
rmse=rmse,
|
|
408
|
+
reduced_chi_squared=red_chi2,
|
|
409
|
+
aic=aic,
|
|
410
|
+
bic=bic,
|
|
411
|
+
curve_x=cx,
|
|
412
|
+
curve_y=cy,
|
|
413
|
+
ci_half_width=ci_hw,
|
|
414
|
+
compact_equation=compact_eq,
|
|
415
|
+
methods_sentence=methods,
|
|
416
|
+
)
|