theoryforge 0.1.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.
@@ -0,0 +1,66 @@
1
+ """theoryforge: systematic theory development.
2
+
3
+ A rigorous, reproducible workflow for building, developing and testing scientific
4
+ theories. This is the feature-parity twin of the R package of the same name
5
+ (https://pablobernabeu.github.io/theoryforge/r/). Every public function has an
6
+ identically behaving counterpart there, pinned by the shared public specification
7
+ (https://github.com/pablobernabeu/theoryforge/blob/main/API_SPEC.md), so the two
8
+ implementations produce identical verdicts and byte-identical diagram intermediate
9
+ representations. The only exceptions are the assistive helpers that depend on a
10
+ network service or a user-supplied embedder (``fetch_corpus``, ``osf_push`` and
11
+ ``embedding_redundancy``), which are documented as such.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ from importlib.metadata import PackageNotFoundError, version
16
+
17
+ from .core import Theory, new_theory, read, write
18
+ from .develop import appraise_amendment
19
+ from .diagram import diagram
20
+ from .dossier import dossier
21
+ from .embedding import embedding_redundancy
22
+ from .lit import fetch_corpus, landscape, lit_diagram, litmap, new_evidence_dois, read_corpus
23
+ from .osf import osf_push
24
+ from .prereg import preregister
25
+ from .redundancy import jaccard, redundancy_check, tokens
26
+ from .report_render import render_report
27
+ from .rigor import check, report
28
+ from .scoring import severity
29
+ from .sem import compile_sem
30
+ from .simulate import simulate
31
+
32
+ # The installed distribution's version (declared once, in pyproject.toml).
33
+ # The fallback covers running from an uninstalled source tree.
34
+ try:
35
+ __version__ = version("theoryforge")
36
+ except PackageNotFoundError: # pragma: no cover - uninstalled source tree
37
+ __version__ = "0+unknown"
38
+
39
+ __all__ = [
40
+ "Theory",
41
+ "read",
42
+ "write",
43
+ "new_theory",
44
+ "check",
45
+ "report",
46
+ "diagram",
47
+ "redundancy_check",
48
+ "tokens",
49
+ "jaccard",
50
+ "severity",
51
+ "appraise_amendment",
52
+ "preregister",
53
+ "read_corpus",
54
+ "litmap",
55
+ "landscape",
56
+ "lit_diagram",
57
+ "fetch_corpus",
58
+ "new_evidence_dois",
59
+ "compile_sem",
60
+ "dossier",
61
+ "simulate",
62
+ "embedding_redundancy",
63
+ "render_report",
64
+ "osf_push",
65
+ "__version__",
66
+ ]
theoryforge/_num.py ADDED
@@ -0,0 +1,19 @@
1
+ """Deterministic, cross-platform rounding (API_SPEC.md section 3).
2
+
3
+ Python's built-in ``round`` uses round-half-to-even on the exact double, whose result can
4
+ differ across platforms for values that sit on an exact decimal half-boundary (e.g. 0.6125).
5
+ ``rnd`` rounds half away from zero using pure floor arithmetic with a tiny bias (1e-6) that is
6
+ far larger than any cross-platform unit-in-the-last-place jitter (~1e-13 at these magnitudes)
7
+ yet far smaller than the rounding grid, so the result is identical on every platform and matches
8
+ the R implementation byte-for-byte.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import math
13
+
14
+
15
+ def rnd(x: float, n: int) -> float:
16
+ s = 10 ** n
17
+ if x >= 0:
18
+ return math.floor(x * s + 0.5 + 1e-6) / s
19
+ return -math.floor(-x * s + 0.5 + 1e-6) / s
@@ -0,0 +1,14 @@
1
+ """Access to the vendored rigour checklist."""
2
+ from __future__ import annotations
3
+
4
+ from functools import lru_cache
5
+ from importlib.resources import files
6
+
7
+ import yaml
8
+
9
+
10
+ @lru_cache(maxsize=1)
11
+ def checklist() -> dict:
12
+ """The rigour checklist specification (items, weights, thresholds, citations)."""
13
+ text = (files("theoryforge") / "schema" / "rigor_checklist.yaml").read_text(encoding="utf-8")
14
+ return yaml.safe_load(text)
theoryforge/core.py ADDED
@@ -0,0 +1,321 @@
1
+ """The Theory object, with read, validate, write, and the public methods."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from pathlib import Path
6
+
7
+ import yaml
8
+
9
+ from .develop import appraise_amendment as _appraise_amendment
10
+ from .diagram import diagram as _diagram
11
+ from .dossier import dossier as _dossier
12
+ from .embedding import embedding_redundancy as _embedding_redundancy
13
+ from .lit import landscape as _landscape
14
+ from .lit import new_evidence_dois as _new_evidence_dois
15
+ from .osf import osf_push as _osf_push
16
+ from .prereg import preregister as _preregister
17
+ from .redundancy import redundancy_check as _redundancy_check
18
+ from .report_render import render_report as _render_report
19
+ from .rigor import _as_list
20
+ from .rigor import check as _check
21
+ from .rigor import report as _report
22
+ from .scoring import severity as _severity
23
+ from .sem import compile_sem as _compile_sem
24
+ from .simulate import simulate as _simulate
25
+
26
+ _MATURITY = {"draft", "building", "developing", "testing"}
27
+ _FORM = {"variance", "network", "typology", "process"}
28
+ _RELATION = {"increases", "decreases", "moderates", "mediates", "causes", "associates"}
29
+ _PRED_TYPE = {"point", "interval", "directional", "existence"}
30
+
31
+
32
+ def _nonempty_str(v) -> bool:
33
+ return isinstance(v, str) and v.strip() != ""
34
+
35
+
36
+ class Theory:
37
+ """A theory as a versioned, machine-checkable object.
38
+
39
+ Wraps the parsed mapping (``self.data``); all accessors tolerate missing
40
+ optional collections by treating them as empty.
41
+ """
42
+
43
+ def __init__(self, data: dict):
44
+ if not isinstance(data, dict):
45
+ raise TypeError("Theory data must be a mapping")
46
+ self.data = data
47
+
48
+ # -- convenience accessors -------------------------------------------------
49
+ @property
50
+ def id(self) -> str:
51
+ return self.data.get("id", "")
52
+
53
+ @property
54
+ def maturity(self) -> str:
55
+ return self.data.get("maturity", "")
56
+
57
+ def _list(self, key: str) -> list:
58
+ v = self.data.get(key)
59
+ return v if isinstance(v, list) else []
60
+
61
+ # -- validation ------------------------------------------------------------
62
+ def validate(self, *, full: bool = False) -> bool:
63
+ """Structural validation against the schema's required fields and enums.
64
+
65
+ Returns True on success, raises ValueError listing every problem found.
66
+ With ``full=True`` additionally checks referential integrity: that every
67
+ id is unique within its collection and that every cross-reference
68
+ (proposition endpoints, prediction derivations and diagnostics,
69
+ assumption/evidence/test-outcome targets) points to a declared id. The
70
+ ``full`` checks are deterministic.
71
+ """
72
+ errors: list[str] = []
73
+ d = self.data
74
+ for req in ("schema_version", "id", "title", "maturity"):
75
+ if not _nonempty_str(d.get(req)):
76
+ errors.append(f"missing/empty required field: {req}")
77
+ if d.get("maturity") not in _MATURITY:
78
+ errors.append(f"maturity must be one of {', '.join(sorted(_MATURITY))}")
79
+ if "theory_form" in d and d["theory_form"] not in _FORM:
80
+ errors.append(f"theory_form must be one of {', '.join(sorted(_FORM))}")
81
+ for i, c in enumerate(self._list("constructs")):
82
+ for req in ("id", "label", "definition"):
83
+ if not _nonempty_str(c.get(req)):
84
+ errors.append(f"construct[{i}] missing/empty {req}")
85
+ for i, p in enumerate(self._list("propositions")):
86
+ for req in ("id", "from", "to", "relation"):
87
+ if not _nonempty_str(p.get(req)):
88
+ errors.append(f"proposition[{i}] missing/empty {req}")
89
+ if p.get("relation") not in _RELATION and _nonempty_str(p.get("relation")):
90
+ errors.append(f"proposition[{i}] relation '{p.get('relation')}' not allowed")
91
+ for i, p in enumerate(self._list("predictions")):
92
+ for req in ("id", "statement", "type"):
93
+ if not _nonempty_str(p.get(req)):
94
+ errors.append(f"prediction[{i}] missing/empty {req}")
95
+ if p.get("type") not in _PRED_TYPE and _nonempty_str(p.get("type")):
96
+ errors.append(f"prediction[{i}] type '{p.get('type')}' not allowed")
97
+
98
+ if full:
99
+ self._referential_errors(errors)
100
+
101
+ if errors:
102
+ raise ValueError("invalid theory object: " + "; ".join(errors))
103
+ return True
104
+
105
+ def _referential_errors(self, errors: list[str]) -> None:
106
+ """Append referential-integrity problems (used by ``validate(full=True)``).
107
+
108
+ Deterministic and mirrored byte-for-byte by the R implementation: the
109
+ same checks in the same order with the same message text.
110
+ """
111
+ cons = self._list("constructs")
112
+ props = self._list("propositions")
113
+ preds = self._list("predictions")
114
+ alts = self._list("alternatives")
115
+ auxs = self._list("auxiliary_assumptions")
116
+ construct_ids = {c.get("id") for c in cons if _nonempty_str(c.get("id"))}
117
+ proposition_ids = {p.get("id") for p in props if _nonempty_str(p.get("id"))}
118
+ prediction_ids = {p.get("id") for p in preds if _nonempty_str(p.get("id"))}
119
+ alternative_ids = {a.get("id") for a in alts if _nonempty_str(a.get("id"))}
120
+
121
+ def dups(items: list, kind: str) -> None:
122
+ seen: set = set()
123
+ for it in items:
124
+ i = it.get("id")
125
+ if _nonempty_str(i):
126
+ if i in seen:
127
+ errors.append(f"duplicate {kind} id: {i}")
128
+ seen.add(i)
129
+
130
+ dups(cons, "construct")
131
+ dups(props, "proposition")
132
+ dups(preds, "prediction")
133
+ dups(alts, "alternative")
134
+ dups(auxs, "assumption")
135
+ for i, p in enumerate(props):
136
+ frm, to = p.get("from"), p.get("to")
137
+ if _nonempty_str(frm) and frm not in construct_ids:
138
+ errors.append(f"proposition[{i}] from '{frm}' is not a known construct")
139
+ if _nonempty_str(to) and to not in construct_ids:
140
+ errors.append(f"proposition[{i}] to '{to}' is not a known construct")
141
+ for i, p in enumerate(preds):
142
+ for dref in _as_list(p.get("derives_from")):
143
+ if _nonempty_str(dref) and dref not in proposition_ids:
144
+ errors.append(f"prediction[{i}] derives_from '{dref}' is not a known proposition")
145
+ for dv in _as_list(p.get("diagnostic_vs")):
146
+ if _nonempty_str(dv) and dv not in alternative_ids:
147
+ errors.append(f"prediction[{i}] diagnostic_vs '{dv}' is not a known alternative")
148
+ for i, a in enumerate(auxs):
149
+ for pr in _as_list(a.get("protects")):
150
+ if _nonempty_str(pr) and pr not in prediction_ids:
151
+ errors.append(f"assumption[{i}] protects '{pr}' is not a known prediction")
152
+ for i, t in enumerate(self._list("test_outcomes")):
153
+ pid = t.get("prediction_id")
154
+ if _nonempty_str(pid) and pid not in prediction_ids:
155
+ errors.append(f"test_outcome[{i}] prediction_id '{pid}' is not a known prediction")
156
+ for i, e in enumerate(self._list("evidence")):
157
+ s = e.get("supports")
158
+ if _nonempty_str(s) and s not in prediction_ids:
159
+ errors.append(f"evidence[{i}] supports '{s}' is not a known prediction")
160
+
161
+ # -- serialisation ---------------------------------------------------------
162
+ def write(self, path) -> None:
163
+ path = Path(path)
164
+ if path.suffix.lower() == ".json":
165
+ path.write_text(json.dumps(self.data, indent=2, ensure_ascii=False), encoding="utf-8")
166
+ else:
167
+ path.write_text(
168
+ yaml.safe_dump(self.data, sort_keys=False, allow_unicode=True),
169
+ encoding="utf-8",
170
+ )
171
+
172
+ # -- builder (BUILDING mode) ----------------------------------------------
173
+ def _provenance(self, action: str, detail: str) -> None:
174
+ prov = self.data.setdefault("provenance", [])
175
+ prov.append({"step": str(len(prov) + 1), "action": action, "detail": detail})
176
+
177
+ def _coll(self, key: str) -> list:
178
+ return self.data.setdefault(key, [])
179
+
180
+ def add_construct(self, id, label, definition, measurement=None, boundary_conditions=None):
181
+ c = {"id": id, "label": label, "definition": definition}
182
+ if measurement is not None:
183
+ c["measurement"] = list(measurement)
184
+ if boundary_conditions is not None:
185
+ c["boundary_conditions"] = list(boundary_conditions)
186
+ self._coll("constructs").append(c)
187
+ self._provenance("tf_add_construct", id)
188
+ return self
189
+
190
+ def add_proposition(self, id, frm, to, relation, mechanism=None):
191
+ p = {"id": id, "from": frm, "to": to, "relation": relation}
192
+ if mechanism is not None:
193
+ p["mechanism"] = mechanism
194
+ self._coll("propositions").append(p)
195
+ self._provenance("tf_add_proposition", id)
196
+ return self
197
+
198
+ def add_prediction(self, id, statement, type, derives_from=None, diagnostic_vs=None):
199
+ p = {"id": id, "statement": statement, "type": type}
200
+ if derives_from is not None:
201
+ p["derives_from"] = list(derives_from)
202
+ if diagnostic_vs is not None:
203
+ p["diagnostic_vs"] = list(diagnostic_vs)
204
+ self._coll("predictions").append(p)
205
+ self._provenance("tf_add_prediction", id)
206
+ return self
207
+
208
+ def add_alternative(self, id, label, key_constructs=None):
209
+ a = {"id": id, "label": label}
210
+ if key_constructs is not None:
211
+ a["key_constructs"] = list(key_constructs)
212
+ self._coll("alternatives").append(a)
213
+ self._provenance("tf_add_alternative", id)
214
+ return self
215
+
216
+ def add_assumption(self, id, statement, added_for=None, protects=None):
217
+ a = {"id": id, "statement": statement, "added_for": added_for}
218
+ if protects is not None:
219
+ a["protects"] = list(protects)
220
+ self._coll("auxiliary_assumptions").append(a)
221
+ self._provenance("tf_add_assumption", id)
222
+ return self
223
+
224
+ def set_formal_model(self, type, spec_ref=None):
225
+ self.data["formal_model"] = {"type": type, "spec_ref": spec_ref}
226
+ self._provenance("tf_set_formal_model", type)
227
+ return self
228
+
229
+ # -- mirrored public API --------------------------------------------------
230
+ def check(self) -> dict:
231
+ return _check(self.data)
232
+
233
+ def report(self, format: str = "json") -> str:
234
+ return _report(self.data, format=format)
235
+
236
+ def redundancy_check(self) -> list[dict]:
237
+ return _redundancy_check(self.data)
238
+
239
+ def diagram(self, type: str = "nomological_net", engine: str = "graphviz") -> str:
240
+ """Return the diagram IR for ``type`` (one of nomological_net, provenance,
241
+ causal_dag, development_roadmap, pipeline, context, workflow, venn, rigour,
242
+ severity)."""
243
+ return _diagram(self.data, type=type, engine=engine)
244
+
245
+ def severity(self) -> list[dict]:
246
+ """Per-prediction risk and computed severity from the operationalised rubric."""
247
+ return _severity(self.data)
248
+
249
+ def appraise_amendment(self, prior) -> dict:
250
+ """Progressive vs degenerating verdict for this theory relative to a prior version."""
251
+ return _appraise_amendment(self.data, prior)
252
+
253
+ def preregister(self, path=None) -> str:
254
+ """Render a preregistration document (and write it if a path is given)."""
255
+ return _preregister(self.data, path)
256
+
257
+ def landscape(self, corpus, min_link: int = 2) -> dict:
258
+ """Map this theory and its alternatives onto a literature corpus's themes."""
259
+ return _landscape(self.data, corpus, min_link=min_link)
260
+
261
+ def new_evidence_dois(self, candidate_dois: list) -> list:
262
+ """DOIs in `candidate_dois` not already cited by this theory's evidence or alternatives."""
263
+ return _new_evidence_dois(self.data, candidate_dois)
264
+
265
+ def compile_sem(self) -> str:
266
+ """Compile constructs and propositions to lavaan model syntax."""
267
+ return _compile_sem(self.data)
268
+
269
+ def dossier(self) -> str:
270
+ """A reviewer-facing audit bundle of rigour report, severity, provenance, and preregistration."""
271
+ return _dossier(self.data)
272
+
273
+ def simulate(self, steps: int = 10, dt: float = 0.1, k: float = 1.0,
274
+ damping: float = 0.5, init: float = 1.0) -> dict:
275
+ """Integrate the construct network as a linear dynamical system."""
276
+ return _simulate(self.data, steps=steps, dt=dt, k=k, damping=damping, init=init)
277
+
278
+ def embedding_redundancy(self, embedder, threshold=None) -> list[dict]:
279
+ """An opt-in embedding-based redundancy screen; results depend on the supplied embedder."""
280
+ return _embedding_redundancy(self.data, embedder, threshold=threshold)
281
+
282
+ def render_report(self, path, title=None, render: bool = False, to: str = "html") -> str:
283
+ """Write (and optionally render) a Quarto report of the audit dossier."""
284
+ return _render_report(self.data, path, title=title, render=render, to=to)
285
+
286
+ def osf_push(self, token=None, node=None, filename=None, dry_run: bool = True,
287
+ base_url: str | None = None) -> dict:
288
+ """Deposit the dossier on OSF (dry-run by default). A live push needs a token and node."""
289
+ kw = {} if base_url is None else {"base_url": base_url}
290
+ return _osf_push(self.data, token=token, node=node, filename=filename, dry_run=dry_run, **kw)
291
+
292
+ def __repr__(self) -> str:
293
+ return f"Theory(id={self.id!r}, maturity={self.maturity!r})"
294
+
295
+
296
+ def read(path) -> Theory:
297
+ """Read a theory object from a YAML or JSON file."""
298
+ path = Path(path)
299
+ text = path.read_text(encoding="utf-8")
300
+ data = json.loads(text) if path.suffix.lower() == ".json" else yaml.safe_load(text)
301
+ if not isinstance(data, dict):
302
+ raise ValueError("Theory data must be a mapping")
303
+ return Theory(data)
304
+
305
+
306
+ def write(theory: Theory, path) -> None:
307
+ """Write a theory object to YAML or JSON (chosen by file extension)."""
308
+ theory.write(path)
309
+
310
+
311
+ def new_theory(id: str, title: str, maturity: str = "building", theory_form: str = "network") -> Theory:
312
+ """Start a new, empty theory object (BUILDING mode entry point)."""
313
+ t = Theory({
314
+ "schema_version": "1.0",
315
+ "id": id,
316
+ "title": title,
317
+ "maturity": maturity,
318
+ "theory_form": theory_form,
319
+ })
320
+ t._provenance("tf_theory", id)
321
+ return t
theoryforge/develop.py ADDED
@@ -0,0 +1,62 @@
1
+ """Development mode. Progressive-versus-degenerating amendment appraisal.
2
+
3
+ This operationalises the Lakatosian distinction (Lakatos, 1970; Meehl, 1990). An amendment is
4
+ progressive if it yields newly corroborated predictions without ad-hoc immunising assumptions.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from .rigor import _as_list
9
+
10
+
11
+ def _list(d: dict, key: str) -> list:
12
+ v = d.get(key)
13
+ return v if isinstance(v, list) else []
14
+
15
+
16
+ def appraise_amendment(new, prior) -> dict:
17
+ """Appraise an amendment as progressive, degenerating, or neutral relative to a prior version.
18
+
19
+ References:
20
+ Lakatos, I. (1970). Falsification and the methodology of scientific
21
+ research programmes. In Criticism and the growth of knowledge
22
+ (pp. 91-196). Cambridge University Press.
23
+ https://doi.org/10.1017/cbo9781139171434.009
24
+ Meehl, P. E. (1990). Appraising and amending theories. Psychological
25
+ Inquiry, 1(2), 108-141. https://doi.org/10.1207/s15327965pli0102_1
26
+ """
27
+ new = new.data if hasattr(new, "data") else new
28
+ prior = prior.data if hasattr(prior, "data") else prior
29
+
30
+ prior_pred_ids = {p.get("id") for p in _list(prior, "predictions")}
31
+ prior_aux_ids = {a.get("id") for a in _list(prior, "auxiliary_assumptions")}
32
+ tos = _list(new, "test_outcomes")
33
+
34
+ def passed(pid: str) -> bool:
35
+ return any(t.get("prediction_id") == pid and t.get("passed") is True for t in tos)
36
+
37
+ new_predictions = [p.get("id") for p in _list(new, "predictions") if p.get("id") not in prior_pred_ids]
38
+ corroborated_new = [pid for pid in new_predictions if passed(pid)]
39
+
40
+ ad_hoc = []
41
+ for a in _list(new, "auxiliary_assumptions"):
42
+ if a.get("id") in prior_aux_ids:
43
+ continue
44
+ if a.get("added_for") is None:
45
+ continue
46
+ protects = _as_list(a.get("protects"))
47
+ if not any(t.get("prediction_id") in protects and t.get("passed") is True for t in tos):
48
+ ad_hoc.append(a.get("id"))
49
+
50
+ if len(corroborated_new) >= 1 and len(ad_hoc) == 0:
51
+ verdict = "progressive"
52
+ elif len(ad_hoc) >= 1 and len(corroborated_new) == 0:
53
+ verdict = "degenerating"
54
+ else:
55
+ verdict = "neutral"
56
+
57
+ return {
58
+ "verdict": verdict,
59
+ "new_predictions": sorted(new_predictions),
60
+ "corroborated_new": sorted(corroborated_new),
61
+ "ad_hoc_assumptions": sorted(ad_hoc),
62
+ }