"""derive_lib - 6.0: every Wikidata system through the maths organ (systems.py): constants given their SI value (Wikidata's normalized P1181), then units check, solve, substitution + numeric re-solve. Writes derived.json; refusals keep their reason.""" import json import signal import sys import time import urllib.parse import urllib.request sys.path.insert(0, sys.argv[3] if len(sys.argv) > 3 else ".") import formula_lib as F import systems lib = json.load(open(sys.argv[1], encoding="utf-8")) cq = sorted({c_qid for s in lib["systems"] for n, c_qid in s["qids"].items() if n in s["constants_raw"]}) si = {} if cq: text = "SELECT ?q ?v WHERE { VALUES ?q { %s } ?q p:P1181/psn:P1181/wikibase:quantityAmount ?v }" % " ".join("wd:" + x for x in cq) req = urllib.request.Request("https://query.wikidata.org/sparql?" + urllib.parse.urlencode({"query": text, "format": "json"}), headers={"User-Agent": "Oracle7-research/6.0 (https://prometheus7.com)"}) for b in json.loads(urllib.request.urlopen(req, timeout=120).read().decode("utf-8"))["results"]["bindings"]: si[b["q"]["value"].rsplit("/", 1)[-1]] = float(b["v"]["value"]) out, t0 = [], time.time() for k, s in enumerate(lib["systems"]): consts, ok = {}, True for n, (label, _amt, _u, d) in s["constants_raw"].items(): v = si.get(s["qids"][n]) if v is None: ok = False break consts[n] = [label, v, F.unit_text(tuple(d))] if not ok: out.append({**s, "refused": "a constant without an SI value", "parts": []}) continue sysdef = {"title": s["title"], "equations": s["equations"], "quantities": s["quantities"], "constants": consts} def _late(*_a): raise TimeoutError("over 60 s in the organ") signal.signal(signal.SIGALRM, _late) signal.alarm(60) try: r = systems.derive(sysdef) except Exception as e: # noqa: BLE001 - one system failing (or running over 60 s) never stops the rest r = {"refused": "organ: %s" % e, "parts": []} finally: signal.alarm(0) out.append({**s, "constants": consts, "refused": r.get("refused"), "parts": r.get("parts", [])}) if k % 25 == 0: print(k, "of", len(lib["systems"]), round(time.time() - t0), "s", flush=True) json.dump({"constants_si": si, "systems": out}, open(sys.argv[2], "w", encoding="utf-8"), indent=1, ensure_ascii=False) good = [p for s in out for p in s["parts"] if not p.get("why")] print("systems", len(out), "refused", sum(1 for s in out if s["refused"]), "checked parts", len(good), "systems with a checked part", sum(1 for s in out if any(not p.get("why") for p in s["parts"])))