"""Replay the adaptive birth-time questionnaire against engine-derived intervals.""" from __future__ import annotations from collections import Counter from datetime import datetime from functools import lru_cache from scripts.chart_choice import astrologer, chart_questions, interview from scripts.chart_choice.boundaries import ChartChoiceInputError, ChartRequest, Line, TRACKED_DIVISIONS, representative_time from scripts.chart_choice.chart_questions import SECOND, Possibility, Segment CHARTS = ("D1", "D9", "D10", "D2", "D6", "D8") DIVISIONS = (*TRACKED_DIVISIONS, 7, 30) MAX_ANSWERS = 12 DOMAINS = { "education": ("D24", 1.0, ("education",)), "residence": ("D4", 0.95, ("travel",)), "relationship": ("D9", 0.95, ("relationship", "marriage", "divorce")), "career": ("D10", 0.9, ("career", "job_change", "business")), "public_work": ("D10", 0.82, ("fame",)), "finance": ("D2", 0.8, ("finance_pos", "finance_neg")), "children": ("D7", 0.85, ("child",)), "parents": ("D12", 0.75, ("father", "mother")), "health_pressure": ("D30", 0.72, ("health",)), } HEALTH_SPEC = {**astrologer.EVENT_CATEGORIES["health"], "houses": (6, 8)} HEALTH_CATEGORIES = [ {"id": "surgery", "value": "health", "text": "手术"}, {"id": "hospitalization", "value": "health", "text": "住院"}, {"id": "injury", "value": "health", "text": "意外受伤"}, ] ALLOWED_IDS = frozenset({"D1", "D1-marks", *( f"{chart}-{category}-{rank}" for chart, _, topics in DOMAINS.values() for category in topics for rank in (1, 2) )}) EVENT_LABELS = { "relationship": "开始恋爱", "marriage": "结婚", "divorce": "分开", "career": "入职或升职", "job_change": "换工作或离职", "business": "创业或开店", "finance_pos": "收入明显增加", "finance_neg": "较大的支出或损失", "education": "升学、毕业或换专业", "travel": "搬家、离乡或长期异地", "fame": "获奖或作品公开", "child": "孩子出生", "father": "父亲的重大变故", "mother": "母亲的重大变故", } @lru_cache(maxsize=128) def _event_ranks(req: ChartRequest, moments: tuple[datetime, ...], birth: datetime, today: datetime, category: str) -> tuple[tuple, ...]: rows = [_minute_row(req, at) for at in moments] spec = HEALTH_SPEC if category == "health" else None return tuple(tuple(group) for group in chart_questions._ranked_ages(rows, birth, today, (category,), spec=spec)) @lru_cache(maxsize=128) def _minute_row(req: ChartRequest, at: datetime) -> dict: return astrologer._minute_row(req, at) def _event_questions(req: ChartRequest, domain: str, choices: list[Possibility], birth: datetime, today: datetime): # Re-rank when an answer removes a contender. Equal signs can still have # different timing evidence, so evaluate each remaining interval. moments = tuple(representative_time(choice.segment, birth) for choice in choices) chart, _, topics = DOMAINS[domain] for category in topics: ranked = _event_ranks(req, moments, birth, today, category) options_by_rank = [[], []] for i, group in enumerate(ranked): if not group: continue first = group[0][2] options_by_rank[0].append((first, i)) alternate = next((ages for _, _, ages in group if ages[1] < first[0] or ages[0] > first[1]), None) if alternate is not None: options_by_rank[1].append((alternate, i)) health = domain == "health_pressure" prompt = ("你在哪个年龄段有过比较大的健康变故,比如手术、住院、意外受伤?" if health else f"你在哪个年龄段有过{EVENT_LABELS[category]}的经历?") categories = HEALTH_CATEGORIES if health else [ item for item in interview._follow_up_options(chart, (category,)) if item["value"] == category] for rank, ages in enumerate(options_by_rank, 1): options = chart_questions.merge_age_options(ages) if not options: continue for option in options: option["value"] = f"age-{option['ages'][0]}-{option['ages'][1]}" yield { "id": f"{chart}-{category}-{rank}", "chart": chart, "kind": "event", "domain": domain, "prompt": prompt, "options": [*options, {"value": "none", "text": "都没有"}, {"value": "unsure", "text": "不想回答" if health else "记不清"}], "categories": categories, "possibilities": [choice.view() for choice in choices], } def _possibilities(choices: list[Possibility], live: list[Segment]) -> list[Possibility]: return [ Possibility((max(lo, start), min(hi, end)), choice.sign) for lo, hi in live for choice in choices for start, end in (choice.segment,) if max(lo, start) <= min(hi, end) ] def _intervals(question: dict, indexes: list[int]) -> tuple[Segment, ...]: return tuple((datetime.fromisoformat(item["start_at"]), datetime.fromisoformat(item["end_at"])) for index in indexes for item in (question["possibilities"][index],)) def confidence(req: ChartRequest, birth: datetime, selected: Segment, candidates: list[Segment], raw_events: list[dict]) -> str: events, _ = astrologer._independent_events(astrologer.parse_events(raw_events, birth)) if len(events) < 3: return "tendency_only" domains = {domain for event in events for domain, (_, _, categories) in DOMAINS.items() if event["category"] in categories} width = (selected[1] - selected[0]).total_seconds() / 60 if len(domains) < 2 or width > 15: return "low" for event in events: if event["category"] == "health": event["spec"] = HEALTH_SPEC base = _minute_row(req, birth) row = _minute_row(req, representative_time(selected, birth)) score = astrologer.score_minute(events, row, base) rivals = [_minute_row(req, representative_time(part, birth)) for part in candidates if part[1] < selected[0] or part[0] > selected[1]] second = max((astrologer.score_minute(events, rival, base)["total"] for rival in rivals), default=score["total"]) margin = 100 * (score["total"] - second) / max(abs(score["total"]), 1) chains = [item["chain"] for item in score["events"]] disagreement = any( chain["activates"]["md"] and chain["activates"]["ad"] and not chain.get("unavailable") and not (chain["activates"]["narayana_md"] or chain["activates"]["narayana_ad"]) for chain in chains ) if margin < 10 or disagreement or any(chain.get("unavailable") for chain in chains): return "low" return "high" if len(events) >= 4 and len(domains) >= 3 and width <= 5 and margin >= 20 else "medium" def _next_question(req: ChartRequest, birth: datetime, today: datetime, remaining: dict[str, list[Possibility]], atoms: list[Segment], asked: set[str], domains: Counter[str], health_allowed: bool) -> dict | None: candidates = [] groups = [] for domain, (chart, reliability, _) in DOMAINS.items(): if domain == "health_pressure" and not health_allowed: continue choices = remaining[chart] if len(choices) > 1: groups.append((domain, reliability, _event_questions(req, domain, choices, birth, today))) if len({choice.sign for choice in remaining["D1"]}) > 1: groups.append(("appearance", 0.75, chart_questions.questions(req, birth, {"D1": remaining["D1"]}))) for domain, reliability, questions in groups: for question in questions: if question["id"] in asked: continue options = [] sizes = [] for option in question["options"]: indexes = option.get("possibilities") if indexes is None: options.append(option) continue intervals = _intervals(question, indexes) if not intervals: continue options.append(option) sizes.append(sum(any(lo <= start <= hi for lo, hi in intervals) for start, _ in atoms)) if not sizes or max(sizes) >= len(atoms): continue separation = 1 - max(sizes) / len(atoms) effort = max(0.35, 1 - len(question["prompt"]) / 120) score = 3 * separation + 2.5 * reliability + 1.5 * effort - 2.5 * domains[domain] if score >= 4: chart = question["chart"] rank = (-score, question["kind"] != "event", CHARTS.index(chart) if chart in CHARTS else len(CHARTS)) candidates.append((rank, {**question, "domain": domain, "options": options})) return min(candidates, key=lambda item: item[0])[1] if candidates else None def replay(req: ChartRequest, birth: datetime, original: Segment, lines: list[Line], answers: object, *, stop: bool, include_health: bool = True) -> dict: if not isinstance(answers, dict) or len(answers) > MAX_ANSWERS or any( not isinstance(key, str) or not isinstance(answer, dict) for key, answer in answers.items() ): raise ChartChoiceInputError("invalid adaptive chart answers") chart_keys = dict.fromkeys((*CHARTS, *(chart for chart, _, _ in DOMAINS.values()))) by_chart = {chart: chart_questions.possibilities(chart, original, lines) for chart in chart_keys} points = sorted({original[0], original[1] + SECOND, *(line.at for line in lines if original[0] < line.at <= original[1] and line.flips.keys() & chart_keys.keys())}) atoms = [(start, end - SECOND) for start, end in zip(points, points[1:])] live = [original] constraints = [] events = [] asked = [] conflicts = [] answered = set() domains: Counter[str] = Counter() has_narrowing_event = False health_events = [] today = interview._today(req) while True: remaining = {chart: _possibilities(choices, live) for chart, choices in by_chart.items()} unsettled = {chart: remaining[chart] for chart in CHARTS if len({choice.sign for choice in remaining[chart]}) > 1} active_atoms = [atom for atom in atoms if any(lo <= atom[0] <= hi for lo, hi in live)] health_allowed = (include_health and has_narrowing_event and 1 < len(active_atoms) <= 24 and not domains["health_pressure"]) question = (_next_question(req, birth, today, remaining, active_atoms, answered, domains, health_allowed) if unsettled and len(asked) < MAX_ANSWERS and (not stop or answered != answers.keys()) else None) if question is None or question["id"] not in answers: break qid = question["id"] answered.add(qid) answer = answers[qid] domain = question["domain"] health = domain == "health_pressure" domains[domain] += 1 try: evidence, dated = chart_questions.evidence({qid: answer}, [question], birth, today) except ChartChoiceInputError: offered = {option["value"] for option in question["options"]} selected = answer.get("marks") if question["kind"] == "birthmarks" else [answer.get("choice")] if not isinstance(selected, list) or not all(isinstance(value, str) for value in selected) or set(selected) <= offered: raise evidence, dated = [], [] conflicts.append({"chart": question["chart"], "question": qid, "kind": question["kind"]}) before = live narrowed = chart_questions._intersection(original, [*constraints, *evidence]) if narrowed: live = narrowed constraints.extend(evidence) if health: health_events.extend(dated) else: events.extend(dated) has_narrowing_event = has_narrowing_event or (bool(dated) and live != before) else: conflicts.append({"chart": question["chart"], "question": qid, "kind": question["kind"]}) stored_answer = ({"date": answer["date"][:4], "category": answer["category"]} if health and dated else {} if health else answer) asked.append({"id": qid, "chart": question["chart"], "answer": stored_answer, "before": before, "after": live}) for qid in sorted(answers.keys() - answered): chart = qid.split("-", 1)[0] if qid not in ALLOWED_IDS: raise ChartChoiceInputError("chart_answers must match offered questions") kind = "birthmarks" if qid == "D1-marks" else "appearance" if chart == "D1" else "event" conflicts.append({"chart": chart, "question": qid, "kind": kind}) reason = ("stopped" if stop else "settled" if not unsettled else "round_limit" if len(asked) == MAX_ANSWERS else "no_answer_can_improve_separation" if not question else None) return {"next": None if stop else question, "unsettled": unsettled, "live": live, "atoms": atoms, "events": events, "health_events": health_events, "asked": asked, "conflict": conflicts, "constraints": constraints, "stop_reason": reason}