[GAP-047]: offline weight rescore study complete
- tools/rescore: add offline equal-vs-designed weight rescore script - tools/rescore: write GAP-047 JSON and markdown evidence - docs/00-governance: propose DEC-20260823-01 and update status - SPRINT_BOARD.md: mark GAP-047 Part 1 complete Build: clean | Tests: 511 passing; Core 422 passing | Runtime change: no
This commit is contained in:
516
tools/rescore/rescore_weights.py
Normal file
516
tools/rescore/rescore_weights.py
Normal file
@@ -0,0 +1,516 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline GAP-047 confluence weight re-scoring study."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
|
||||
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(REPO_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(REPO_ROOT))
|
||||
|
||||
from tools.dashboard.parsers import ( # noqa: E402
|
||||
SIGNAL_DETAIL_RE,
|
||||
SIGNAL_RE,
|
||||
STATE_RE,
|
||||
parse_state_factors,
|
||||
split_log_line,
|
||||
)
|
||||
|
||||
|
||||
DEFAULT_LOG_DIR = Path(r"C:\Users\billy\Documents\NinjaTrader 8\log\nt8-sdk")
|
||||
DEFAULT_OUTPUT_JSON = Path(__file__).with_name("GAP-047_weight_rescore_output.json")
|
||||
DEFAULT_OUTPUT_MD = Path(__file__).with_name("GAP-047_weight_rescore_output.md")
|
||||
|
||||
FACTOR_ORDER = [
|
||||
"Setup",
|
||||
"Trend",
|
||||
"Volatility",
|
||||
"Timing",
|
||||
"ExecutionQuality",
|
||||
"NarrowRange",
|
||||
"OrbRangeVsAtr",
|
||||
"GapDirectionAlignment",
|
||||
"BreakoutVolumeStrength",
|
||||
"PriorDayCloseStrength",
|
||||
]
|
||||
|
||||
DESIGNED_WEIGHTS = {
|
||||
"Setup": 1.0,
|
||||
"Trend": 1.0,
|
||||
"Volatility": 1.0,
|
||||
"Timing": 1.0,
|
||||
"ExecutionQuality": 1.0,
|
||||
"NarrowRange": 0.20,
|
||||
"OrbRangeVsAtr": 0.15,
|
||||
"GapDirectionAlignment": 0.15,
|
||||
"BreakoutVolumeStrength": 0.20,
|
||||
"PriorDayCloseStrength": 0.15,
|
||||
}
|
||||
|
||||
EQUAL_WEIGHT = 1.0
|
||||
DESIGNED_TOTAL_WEIGHT = sum(DESIGNED_WEIGHTS[name] for name in FACTOR_ORDER)
|
||||
FACTOR_LINE_RE = re.compile(r"\bFactors:\s*(.*)$", re.IGNORECASE)
|
||||
SIGNAL_SCORE_RE = re.compile(r"\bScore=([0-9.]+)", re.IGNORECASE)
|
||||
SIGNAL_GRADE_RE = re.compile(r"\bGrade=([^\s|]+)", re.IGNORECASE)
|
||||
|
||||
|
||||
def parse_args(argv: Sequence[str]) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description="Run GAP-047 offline equal-vs-designed weight re-scoring.")
|
||||
parser.add_argument("--log-dir", default=str(DEFAULT_LOG_DIR), help="NT8 SDK log directory containing session_*.log and ARCHIVE")
|
||||
parser.add_argument("--json-output", default=str(DEFAULT_OUTPUT_JSON), help="JSON output path")
|
||||
parser.add_argument("--markdown-output", default=str(DEFAULT_OUTPUT_MD), help="Markdown output path")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def discover_session_logs(log_dir: Path) -> List[Path]:
|
||||
if not log_dir.exists():
|
||||
return []
|
||||
return sorted(path for path in log_dir.rglob("session_*.log") if path.is_file())
|
||||
|
||||
|
||||
def grade_for_score(score: float) -> str:
|
||||
if score >= 0.90:
|
||||
return "A+"
|
||||
if score >= 0.80:
|
||||
return "A"
|
||||
if score >= 0.70:
|
||||
return "B"
|
||||
if score >= 0.60:
|
||||
return "C"
|
||||
if score > 0.0:
|
||||
return "D"
|
||||
return "F"
|
||||
|
||||
|
||||
def grade_rank(grade: str) -> int:
|
||||
ranks = {"F": 1, "D": 2, "C": 3, "B": 4, "A": 5, "A+": 6}
|
||||
return ranks.get(str(grade or "").upper(), 0)
|
||||
|
||||
|
||||
def parse_float(text: Optional[str]) -> Optional[float]:
|
||||
if text is None:
|
||||
return None
|
||||
try:
|
||||
return float(str(text).strip())
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def parse_legacy_factor_line(text: str) -> List[Dict[str, Any]]:
|
||||
factors: List[Dict[str, Any]] = []
|
||||
for match in re.finditer(r"([^=\s]+)=([0-9.]+)", text or ""):
|
||||
factors.append({"name": match.group(1), "score": float(match.group(2)), "weight": 1.0})
|
||||
return factors
|
||||
|
||||
|
||||
def factors_by_name(factors: Sequence[Dict[str, Any]]) -> Dict[str, float]:
|
||||
result: Dict[str, float] = {}
|
||||
for factor in factors:
|
||||
name = str(factor.get("name") or "")
|
||||
if not name:
|
||||
continue
|
||||
try:
|
||||
result[name] = float(factor.get("score"))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return result
|
||||
|
||||
|
||||
def has_all_required_factors(factors: Sequence[Dict[str, Any]]) -> bool:
|
||||
scores = factors_by_name(factors)
|
||||
return all(name in scores for name in FACTOR_ORDER)
|
||||
|
||||
|
||||
def compute_scores(factors: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
scores = factors_by_name(factors)
|
||||
equal_sum = sum(scores[name] * EQUAL_WEIGHT for name in FACTOR_ORDER)
|
||||
designed_sum = sum(scores[name] * DESIGNED_WEIGHTS[name] for name in FACTOR_ORDER)
|
||||
equal_score = equal_sum / float(len(FACTOR_ORDER))
|
||||
designed_score = designed_sum / DESIGNED_TOTAL_WEIGHT
|
||||
factor_results: List[Dict[str, Any]] = []
|
||||
for name in FACTOR_ORDER:
|
||||
score = scores[name]
|
||||
factor_results.append({
|
||||
"name": name,
|
||||
"score": score,
|
||||
"equal_contribution": score * EQUAL_WEIGHT,
|
||||
"designed_contribution": score * DESIGNED_WEIGHTS[name],
|
||||
})
|
||||
return {
|
||||
"equal_score": equal_score,
|
||||
"equal_grade": grade_for_score(equal_score),
|
||||
"designed_score": designed_score,
|
||||
"designed_grade": grade_for_score(designed_score),
|
||||
"factors": factor_results,
|
||||
}
|
||||
|
||||
|
||||
def make_sample(population: str, session: Path, line_number: int, timestamp: Optional[str], factors: Sequence[Dict[str, Any]], logged_score: Optional[float], logged_grade: Optional[str], direction_degraded: bool) -> Dict[str, Any]:
|
||||
scores = compute_scores(factors)
|
||||
sample = {
|
||||
"population": population,
|
||||
"session": str(session),
|
||||
"session_name": session.name,
|
||||
"line": line_number,
|
||||
"timestamp": timestamp,
|
||||
"logged_score": logged_score,
|
||||
"logged_grade": logged_grade,
|
||||
"equal_score": scores["equal_score"],
|
||||
"equal_grade": scores["equal_grade"],
|
||||
"designed_score": scores["designed_score"],
|
||||
"designed_grade": scores["designed_grade"],
|
||||
"direction_degraded": direction_degraded,
|
||||
"factors": scores["factors"],
|
||||
}
|
||||
return sample
|
||||
|
||||
|
||||
def parse_session(path: Path) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], int, int, bool]:
|
||||
state_samples: List[Dict[str, Any]] = []
|
||||
signal_samples: List[Dict[str, Any]] = []
|
||||
signal_detail_lines = 0
|
||||
signal_lines = 0
|
||||
pending_signal: Optional[Dict[str, Any]] = None
|
||||
try:
|
||||
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
|
||||
except OSError:
|
||||
return state_samples, signal_samples, signal_detail_lines, signal_lines, False
|
||||
|
||||
for line_number, line in enumerate(lines, start=1):
|
||||
timestamp, message = split_log_line(line)
|
||||
state = STATE_RE.search(message)
|
||||
if state:
|
||||
factors = parse_state_factors(state.group(6))
|
||||
if has_all_required_factors(factors):
|
||||
state_samples.append(make_sample("state", path, line_number, timestamp, factors, parse_float(state.group(4)), state.group(5), True))
|
||||
pending_signal = None
|
||||
continue
|
||||
|
||||
signal_detail = SIGNAL_DETAIL_RE.search(message)
|
||||
if signal_detail:
|
||||
signal_detail_lines += 1
|
||||
continue
|
||||
|
||||
signal = SIGNAL_RE.search(message)
|
||||
if signal:
|
||||
signal_lines += 1
|
||||
score_match = SIGNAL_SCORE_RE.search(message)
|
||||
grade_match = SIGNAL_GRADE_RE.search(message)
|
||||
pending_signal = {
|
||||
"timestamp": timestamp,
|
||||
"line": line_number,
|
||||
"logged_score": parse_float(score_match.group(1)) if score_match else None,
|
||||
"logged_grade": grade_match.group(1) if grade_match else None,
|
||||
}
|
||||
continue
|
||||
|
||||
factor_line = FACTOR_LINE_RE.search(message)
|
||||
if factor_line and pending_signal is not None:
|
||||
factors = parse_legacy_factor_line(factor_line.group(1))
|
||||
if has_all_required_factors(factors):
|
||||
signal_samples.append(make_sample("signal", path, pending_signal["line"], pending_signal["timestamp"], factors, pending_signal["logged_score"], pending_signal["logged_grade"], False))
|
||||
pending_signal = None
|
||||
|
||||
return state_samples, signal_samples, signal_detail_lines, signal_lines, signal_lines > 0
|
||||
|
||||
|
||||
def empty_grade_counts() -> Dict[str, int]:
|
||||
return {"A+": 0, "A": 0, "B": 0, "C": 0, "D": 0, "F": 0}
|
||||
|
||||
|
||||
def summarize_samples(samples: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
equal_counts = empty_grade_counts()
|
||||
designed_counts = empty_grade_counts()
|
||||
per_session: Dict[str, Dict[str, Any]] = {}
|
||||
factor_totals: Dict[str, Dict[str, float]] = {}
|
||||
|
||||
for sample in samples:
|
||||
equal_counts[sample["equal_grade"]] += 1
|
||||
designed_counts[sample["designed_grade"]] += 1
|
||||
session_name = sample["session_name"]
|
||||
if session_name not in per_session:
|
||||
per_session[session_name] = {
|
||||
"session": sample["session"],
|
||||
"sample_count": 0,
|
||||
"equal_grade_distribution": empty_grade_counts(),
|
||||
"designed_grade_distribution": empty_grade_counts(),
|
||||
"best_equal_score": None,
|
||||
"best_designed_score": None,
|
||||
"best_designed_grade": None,
|
||||
}
|
||||
session = per_session[session_name]
|
||||
session["sample_count"] += 1
|
||||
session["equal_grade_distribution"][sample["equal_grade"]] += 1
|
||||
session["designed_grade_distribution"][sample["designed_grade"]] += 1
|
||||
if session["best_equal_score"] is None or sample["equal_score"] > session["best_equal_score"]:
|
||||
session["best_equal_score"] = sample["equal_score"]
|
||||
if session["best_designed_score"] is None or sample["designed_score"] > session["best_designed_score"]:
|
||||
session["best_designed_score"] = sample["designed_score"]
|
||||
session["best_designed_grade"] = sample["designed_grade"]
|
||||
|
||||
for factor in sample["factors"]:
|
||||
name = factor["name"]
|
||||
if name not in factor_totals:
|
||||
factor_totals[name] = {"score_sum": 0.0, "equal_contribution_sum": 0.0, "designed_contribution_sum": 0.0}
|
||||
factor_totals[name]["score_sum"] += factor["score"]
|
||||
factor_totals[name]["equal_contribution_sum"] += factor["equal_contribution"]
|
||||
factor_totals[name]["designed_contribution_sum"] += factor["designed_contribution"]
|
||||
|
||||
equal_total = sum(values["equal_contribution_sum"] for values in factor_totals.values())
|
||||
designed_total = sum(values["designed_contribution_sum"] for values in factor_totals.values())
|
||||
factor_summary: List[Dict[str, Any]] = []
|
||||
for name in FACTOR_ORDER:
|
||||
values = factor_totals.get(name, {"score_sum": 0.0, "equal_contribution_sum": 0.0, "designed_contribution_sum": 0.0})
|
||||
count = float(len(samples)) if samples else 0.0
|
||||
factor_summary.append({
|
||||
"name": name,
|
||||
"mean_score": values["score_sum"] / count if count else None,
|
||||
"equal_contribution_share": values["equal_contribution_sum"] / equal_total if equal_total else None,
|
||||
"designed_contribution_share": values["designed_contribution_sum"] / designed_total if designed_total else None,
|
||||
})
|
||||
|
||||
a_cross = [sample for sample in samples if grade_rank(sample["designed_grade"]) >= grade_rank("A") and grade_rank(sample["equal_grade"]) < grade_rank("A")]
|
||||
b_cross = [sample for sample in samples if grade_rank(sample["designed_grade"]) >= grade_rank("B") and grade_rank(sample["equal_grade"]) < grade_rank("B")]
|
||||
return {
|
||||
"sample_count": len(samples),
|
||||
"equal_grade_distribution": equal_counts,
|
||||
"designed_grade_distribution": designed_counts,
|
||||
"designed_crosses_a_not_equal_count": len(a_cross),
|
||||
"designed_crosses_b_not_equal_count": len(b_cross),
|
||||
"factor_summary": factor_summary,
|
||||
"per_session": [per_session[name] for name in sorted(per_session.keys())],
|
||||
"top_a_cross_samples": top_samples(a_cross, 10),
|
||||
"top_b_cross_samples": top_samples(b_cross, 10),
|
||||
}
|
||||
|
||||
|
||||
def top_samples(samples: Sequence[Dict[str, Any]], limit: int) -> List[Dict[str, Any]]:
|
||||
ordered = sorted(samples, key=lambda sample: (sample["designed_score"], sample["equal_score"]), reverse=True)
|
||||
return [compact_sample(sample) for sample in ordered[:limit]]
|
||||
|
||||
|
||||
def compact_sample(sample: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return {
|
||||
"session_name": sample["session_name"],
|
||||
"line": sample["line"],
|
||||
"timestamp": sample["timestamp"],
|
||||
"equal_score": sample["equal_score"],
|
||||
"equal_grade": sample["equal_grade"],
|
||||
"designed_score": sample["designed_score"],
|
||||
"designed_grade": sample["designed_grade"],
|
||||
}
|
||||
|
||||
|
||||
def silent_sessions(session_logs: Sequence[Path], state_samples: Sequence[Dict[str, Any]], signal_session_names: Iterable[str]) -> List[Dict[str, Any]]:
|
||||
signal_names = set(signal_session_names)
|
||||
best_by_session: Dict[str, Dict[str, Any]] = {}
|
||||
for sample in state_samples:
|
||||
name = sample["session_name"]
|
||||
if name in signal_names:
|
||||
continue
|
||||
if name not in best_by_session or sample["designed_score"] > best_by_session[name]["best_designed_score"]:
|
||||
best_by_session[name] = {
|
||||
"session": sample["session"],
|
||||
"session_name": name,
|
||||
"state_sample_count": 0,
|
||||
"best_designed_score": sample["designed_score"],
|
||||
"best_designed_grade": sample["designed_grade"],
|
||||
"best_equal_score": sample["equal_score"],
|
||||
"best_equal_grade": sample["equal_grade"],
|
||||
"best_line": sample["line"],
|
||||
"best_timestamp": sample["timestamp"],
|
||||
}
|
||||
best_by_session[name]["state_sample_count"] += 1
|
||||
for path in session_logs:
|
||||
if path.name not in signal_names and path.name not in best_by_session:
|
||||
best_by_session[path.name] = {
|
||||
"session": str(path),
|
||||
"session_name": path.name,
|
||||
"state_sample_count": 0,
|
||||
"best_designed_score": None,
|
||||
"best_designed_grade": None,
|
||||
"best_equal_score": None,
|
||||
"best_equal_grade": None,
|
||||
"best_line": None,
|
||||
"best_timestamp": None,
|
||||
}
|
||||
return sorted(best_by_session.values(), key=lambda item: (item["best_designed_score"] is not None, item["best_designed_score"] or -1.0), reverse=True)
|
||||
|
||||
|
||||
def arithmetic_check(samples: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
for sample in samples:
|
||||
if sample["session_name"] == "session_20260818_071117.log" and sample["timestamp"] == "10:10:11.833":
|
||||
equal_ok = abs(sample["equal_score"] - 0.640) < 0.0005
|
||||
designed_ok = abs(sample["designed_score"] - 0.7273504273504273) < 0.0005
|
||||
return {
|
||||
"found": True,
|
||||
"passed": equal_ok and designed_ok,
|
||||
"equal_score": sample["equal_score"],
|
||||
"designed_score": sample["designed_score"],
|
||||
"expected_equal_score": 0.640,
|
||||
"expected_designed_score": 0.727,
|
||||
"session_name": sample["session_name"],
|
||||
"line": sample["line"],
|
||||
}
|
||||
return {"found": False, "passed": False, "message": "Required 2026-08-18 10:10:11.833 worked example was not found."}
|
||||
|
||||
|
||||
def fmt_pct(value: Optional[float]) -> str:
|
||||
if value is None:
|
||||
return "n/a"
|
||||
return "{0:.1f}%".format(value * 100.0)
|
||||
|
||||
|
||||
def fmt_score(value: Optional[float]) -> str:
|
||||
if value is None or (isinstance(value, float) and math.isnan(value)):
|
||||
return "n/a"
|
||||
return "{0:.3f}".format(value)
|
||||
|
||||
|
||||
def render_grade_counts(counts: Dict[str, int]) -> str:
|
||||
return ", ".join("{0}={1}".format(grade, counts.get(grade, 0)) for grade in ["A+", "A", "B", "C", "D", "F"])
|
||||
|
||||
|
||||
def render_markdown(payload: Dict[str, Any]) -> str:
|
||||
lines: List[str] = []
|
||||
lines.append("# GAP-047 Weight Re-Scoring Study")
|
||||
lines.append("")
|
||||
lines.append("Analysis-only offline study. Runtime source code was not changed.")
|
||||
lines.append("")
|
||||
lines.append("## Inputs")
|
||||
lines.append("- Log directory: `{0}`".format(payload["input"]["log_dir"]))
|
||||
lines.append("- Session logs scanned: {0}".format(payload["input"]["session_log_count"]))
|
||||
lines.append("- Designed total weight: {0:.2f}".format(DESIGNED_TOTAL_WEIGHT))
|
||||
lines.append("")
|
||||
lines.append("## Arithmetic Check")
|
||||
check = payload["arithmetic_check"]
|
||||
if check.get("passed"):
|
||||
lines.append("PASS: `session_20260818_071117.log` 10:10:11.833 reproduced equal={0:.3f}, designed={1:.3f}.".format(check["equal_score"], check["designed_score"]))
|
||||
else:
|
||||
lines.append("FAIL: worked example was not reproduced. Details: `{0}`".format(json.dumps(check, sort_keys=True)))
|
||||
lines.append("")
|
||||
lines.append("## Population Caveat")
|
||||
lines.append("- `STATE:` telemetry is direction-degraded by GAP-049 and must not be pooled with signal samples.")
|
||||
lines.append("- Signal samples are parsed only when a real `SIGNAL` line is followed by its `Factors:` breakdown. `SIGNAL_DETAIL:` carries reasons, not numeric scores, in the current log format.")
|
||||
lines.append("- `SIGNAL_DETAIL:` lines observed: {0}. `SIGNAL` lines observed: {1}. Signal factor samples scored: {2}.".format(payload["input"]["signal_detail_line_count"], payload["input"]["signal_line_count"], payload["signal"]["sample_count"]))
|
||||
lines.append("")
|
||||
append_population_markdown(lines, "STATE Telemetry Population", payload["state"])
|
||||
append_population_markdown(lines, "Signal Population", payload["signal"])
|
||||
lines.append("## Silent Sessions")
|
||||
lines.append("Sessions with zero `SIGNAL` lines, ranked by best designed-weight telemetry score.")
|
||||
lines.append("")
|
||||
lines.append("| Session | State Samples | Best Equal | Best Equal Grade | Best Designed | Best Designed Grade | Time | Line |")
|
||||
lines.append("|---|---:|---:|---|---:|---|---|---:|")
|
||||
for item in payload["silent_sessions"][:25]:
|
||||
lines.append("| {0} | {1} | {2} | {3} | {4} | {5} | {6} | {7} |".format(
|
||||
item["session_name"],
|
||||
item["state_sample_count"],
|
||||
fmt_score(item["best_equal_score"]),
|
||||
item["best_equal_grade"] or "n/a",
|
||||
fmt_score(item["best_designed_score"]),
|
||||
item["best_designed_grade"] or "n/a",
|
||||
item["best_timestamp"] or "n/a",
|
||||
item["best_line"] or "n/a",
|
||||
))
|
||||
lines.append("")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def append_population_markdown(lines: List[str], title: str, summary: Dict[str, Any]) -> None:
|
||||
lines.append("## {0}".format(title))
|
||||
lines.append("- Samples: {0}".format(summary["sample_count"]))
|
||||
lines.append("- Equal grade distribution: {0}".format(render_grade_counts(summary["equal_grade_distribution"])))
|
||||
lines.append("- Designed grade distribution: {0}".format(render_grade_counts(summary["designed_grade_distribution"])))
|
||||
lines.append("- Designed crosses A while equal does not: {0}".format(summary["designed_crosses_a_not_equal_count"]))
|
||||
lines.append("- Designed crosses B while equal does not: {0}".format(summary["designed_crosses_b_not_equal_count"]))
|
||||
lines.append("")
|
||||
lines.append("| Factor | Mean Score | Equal Contribution Share | Designed Contribution Share |")
|
||||
lines.append("|---|---:|---:|---:|")
|
||||
for factor in summary["factor_summary"]:
|
||||
lines.append("| {0} | {1} | {2} | {3} |".format(
|
||||
factor["name"],
|
||||
fmt_score(factor["mean_score"]),
|
||||
fmt_pct(factor["equal_contribution_share"]),
|
||||
fmt_pct(factor["designed_contribution_share"]),
|
||||
))
|
||||
lines.append("")
|
||||
lines.append("### Per-Session Grade Distribution")
|
||||
lines.append("")
|
||||
lines.append("| Session | Samples | Equal Grades | Designed Grades | Best Equal | Best Designed | Best Designed Grade |")
|
||||
lines.append("|---|---:|---|---|---:|---:|---|")
|
||||
for session in summary["per_session"]:
|
||||
lines.append("| {0} | {1} | {2} | {3} | {4} | {5} | {6} |".format(
|
||||
Path(session["session"]).name,
|
||||
session["sample_count"],
|
||||
render_grade_counts(session["equal_grade_distribution"]),
|
||||
render_grade_counts(session["designed_grade_distribution"]),
|
||||
fmt_score(session["best_equal_score"]),
|
||||
fmt_score(session["best_designed_score"]),
|
||||
session["best_designed_grade"] or "n/a",
|
||||
))
|
||||
lines.append("")
|
||||
|
||||
|
||||
def build_payload(log_dir: Path) -> Dict[str, Any]:
|
||||
session_logs = discover_session_logs(log_dir)
|
||||
state_samples: List[Dict[str, Any]] = []
|
||||
signal_samples: List[Dict[str, Any]] = []
|
||||
signal_detail_line_count = 0
|
||||
signal_line_count = 0
|
||||
signal_line_session_names = set()
|
||||
for path in session_logs:
|
||||
states, signals, signal_details, signal_lines, has_signal = parse_session(path)
|
||||
state_samples.extend(states)
|
||||
signal_samples.extend(signals)
|
||||
signal_detail_line_count += signal_details
|
||||
signal_line_count += signal_lines
|
||||
if has_signal:
|
||||
signal_line_session_names.add(path.name)
|
||||
|
||||
payload = {
|
||||
"input": {
|
||||
"log_dir": str(log_dir),
|
||||
"session_log_count": len(session_logs),
|
||||
"signal_detail_line_count": signal_detail_line_count,
|
||||
"signal_line_count": signal_line_count,
|
||||
"factor_order": FACTOR_ORDER,
|
||||
"designed_weights": DESIGNED_WEIGHTS,
|
||||
"designed_total_weight": DESIGNED_TOTAL_WEIGHT,
|
||||
},
|
||||
"arithmetic_check": arithmetic_check(state_samples),
|
||||
"state": summarize_samples(state_samples),
|
||||
"signal": summarize_samples(signal_samples),
|
||||
"silent_sessions": silent_sessions(session_logs, state_samples, signal_line_session_names),
|
||||
}
|
||||
return payload
|
||||
|
||||
|
||||
def main(argv: Sequence[str]) -> int:
|
||||
args = parse_args(argv)
|
||||
log_dir = Path(args.log_dir)
|
||||
json_output = Path(args.json_output)
|
||||
markdown_output = Path(args.markdown_output)
|
||||
payload = build_payload(log_dir)
|
||||
if not payload["arithmetic_check"].get("passed"):
|
||||
sys.stderr.write("Arithmetic check failed; refusing to write study outputs.\n")
|
||||
sys.stderr.write(json.dumps(payload["arithmetic_check"], indent=2, sort_keys=True) + "\n")
|
||||
return 1
|
||||
json_output.parent.mkdir(parents=True, exist_ok=True)
|
||||
markdown_output.parent.mkdir(parents=True, exist_ok=True)
|
||||
json_output.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
markdown_output.write_text(render_markdown(payload), encoding="utf-8")
|
||||
sys.stdout.write("Wrote {0}\n".format(json_output))
|
||||
sys.stdout.write("Wrote {0}\n".format(markdown_output))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
Reference in New Issue
Block a user