nonebot-plugin-lavi 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.
- nonebot_plugin_lavi/__init__.py +63 -0
- nonebot_plugin_lavi/command.py +52 -0
- nonebot_plugin_lavi/config.py +148 -0
- nonebot_plugin_lavi/decider_algorithms/__init__.py +13 -0
- nonebot_plugin_lavi/decider_algorithms/dayan.py +156 -0
- nonebot_plugin_lavi/decider_algorithms/geomancy.py +184 -0
- nonebot_plugin_lavi/decider_algorithms/obi_ifa.py +192 -0
- nonebot_plugin_lavi/decider_algorithms/trial.py +128 -0
- nonebot_plugin_lavi/decision.py +94 -0
- nonebot_plugin_lavi/protocol.py +224 -0
- nonebot_plugin_lavi/render.py +63 -0
- nonebot_plugin_lavi/selector.py +134 -0
- nonebot_plugin_lavi-0.1.0.dist-info/METADATA +219 -0
- nonebot_plugin_lavi-0.1.0.dist-info/RECORD +16 -0
- nonebot_plugin_lavi-0.1.0.dist-info/WHEEL +4 -0
- nonebot_plugin_lavi-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""NoneBot integration for LaVI."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from nonebot import logger, require, on_command, get_plugin_config
|
|
6
|
+
from nonebot.params import CommandArg
|
|
7
|
+
from nonebot.plugin import PluginMetadata
|
|
8
|
+
from nonebot.adapters import Message
|
|
9
|
+
|
|
10
|
+
from .config import Config
|
|
11
|
+
from .command import handle_lavi
|
|
12
|
+
from .selector import build_selector
|
|
13
|
+
|
|
14
|
+
require("nonebot_plugin_localstore")
|
|
15
|
+
|
|
16
|
+
import nonebot_plugin_localstore as store
|
|
17
|
+
|
|
18
|
+
__plugin_meta__ = PluginMetadata(
|
|
19
|
+
name="LaVI",
|
|
20
|
+
description="一个面向二元问题的 NoneBot2 决策插件",
|
|
21
|
+
usage=(
|
|
22
|
+
"/lavi — 回答“是”或“否”\n"
|
|
23
|
+
"/lavi 算法名 — 用指定算法回答“是”或“否”\n"
|
|
24
|
+
"/lavi 候选1 候选2 — 从两个空白分隔的候选中选择一个\n"
|
|
25
|
+
"/lavi 算法名 候选1 候选2 — 用指定算法从两个候选中选择一个\n"
|
|
26
|
+
"算法名:dayan(大衍)、geomancy(地占)、obi-ifa(宝螺)、"
|
|
27
|
+
"trial(裁判)、random(随机)"
|
|
28
|
+
),
|
|
29
|
+
type="application",
|
|
30
|
+
homepage="https://github.com/p0rt39/nonebot-plugin-lavi",
|
|
31
|
+
config=Config,
|
|
32
|
+
supported_adapters=None,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
plugin_config = get_plugin_config(Config).lavi
|
|
36
|
+
data_dir = Path(store.get_plugin_data_dir())
|
|
37
|
+
|
|
38
|
+
try:
|
|
39
|
+
algorithm_selector = build_selector(name=plugin_config.algorithm)
|
|
40
|
+
except ValueError as error:
|
|
41
|
+
logger.warning(
|
|
42
|
+
"Invalid LAVI__ALGORITHM={!r}: {}; falling back to random selection",
|
|
43
|
+
plugin_config.algorithm,
|
|
44
|
+
error,
|
|
45
|
+
)
|
|
46
|
+
algorithm_selector = build_selector()
|
|
47
|
+
|
|
48
|
+
lavi = on_command("lavi", priority=10, block=True)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@lavi.handle()
|
|
52
|
+
async def _handle_lavi(args: Message = CommandArg()) -> None:
|
|
53
|
+
try:
|
|
54
|
+
answer = handle_lavi(
|
|
55
|
+
args.extract_plain_text(),
|
|
56
|
+
selector=algorithm_selector,
|
|
57
|
+
detailed=plugin_config.detailed,
|
|
58
|
+
text=plugin_config.text,
|
|
59
|
+
)
|
|
60
|
+
except Exception:
|
|
61
|
+
logger.exception("LaVI failed to decide")
|
|
62
|
+
await lavi.finish(plugin_config.text.unavailable)
|
|
63
|
+
await lavi.finish(answer)
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""The /lavi command handler, independent of NoneBot matchers."""
|
|
2
|
+
|
|
3
|
+
from .config import TextConfig
|
|
4
|
+
from .render import render_answer, render_detailed, render_unknown_algorithm
|
|
5
|
+
from .decision import decide, parse_invocation
|
|
6
|
+
from .protocol import Selector, capture_context
|
|
7
|
+
from .selector import UnknownAlgorithmError, build_selector, available_algorithms
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _available_choices() -> tuple[str, ...]:
|
|
11
|
+
return tuple(
|
|
12
|
+
f"{algorithm.name}({algorithm.label})" for algorithm in available_algorithms()
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def handle_lavi(
|
|
17
|
+
arguments: str,
|
|
18
|
+
*,
|
|
19
|
+
selector: Selector,
|
|
20
|
+
detailed: bool = False,
|
|
21
|
+
text: TextConfig | None = None,
|
|
22
|
+
) -> str:
|
|
23
|
+
"""Resolve an optional per-command algorithm and render one decision."""
|
|
24
|
+
text = text or TextConfig()
|
|
25
|
+
request = parse_invocation(arguments)
|
|
26
|
+
if request.algorithm is not None:
|
|
27
|
+
try:
|
|
28
|
+
selector = build_selector(name=request.algorithm)
|
|
29
|
+
except UnknownAlgorithmError:
|
|
30
|
+
if request.require_algorithm:
|
|
31
|
+
return render_unknown_algorithm(
|
|
32
|
+
request.algorithm,
|
|
33
|
+
available=_available_choices(),
|
|
34
|
+
text=text,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
decision = decide(
|
|
38
|
+
request.text,
|
|
39
|
+
context=capture_context(),
|
|
40
|
+
selector=selector,
|
|
41
|
+
trace=detailed,
|
|
42
|
+
options=(text.affirmative, text.negative),
|
|
43
|
+
)
|
|
44
|
+
if not detailed:
|
|
45
|
+
return render_answer(decision.answer, decider=decision.display_name, text=text)
|
|
46
|
+
return render_detailed(
|
|
47
|
+
decision.answer,
|
|
48
|
+
decider=decision.display_name,
|
|
49
|
+
operator_count=decision.operator_count,
|
|
50
|
+
steps=decision.steps,
|
|
51
|
+
text=text,
|
|
52
|
+
)
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""LaVI plugin configuration model."""
|
|
2
|
+
|
|
3
|
+
from string import Formatter
|
|
4
|
+
|
|
5
|
+
from pydantic import Field, BaseModel
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
from pydantic import field_validator as _field_validator
|
|
9
|
+
except ImportError: # pragma: no cover - pydantic v1 compatibility
|
|
10
|
+
from pydantic import validator as _field_validator
|
|
11
|
+
|
|
12
|
+
_FORMATTER = Formatter()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _validate_template(value: str, *, field: str, placeholder: str) -> str:
|
|
16
|
+
try:
|
|
17
|
+
parsed = list(_FORMATTER.parse(value))
|
|
18
|
+
except ValueError as error:
|
|
19
|
+
raise ValueError(f"{field} must use balanced braces: {error}") from error
|
|
20
|
+
|
|
21
|
+
used = set()
|
|
22
|
+
for _, name, conversion, format_spec in parsed:
|
|
23
|
+
if name is None:
|
|
24
|
+
continue
|
|
25
|
+
if name != placeholder:
|
|
26
|
+
raise ValueError(
|
|
27
|
+
f"{field} supports only the {placeholder!r} placeholder, got {name!r}"
|
|
28
|
+
)
|
|
29
|
+
if conversion or format_spec:
|
|
30
|
+
raise ValueError(
|
|
31
|
+
f"{field} does not support conversions or format specs "
|
|
32
|
+
f"for {placeholder!r}"
|
|
33
|
+
)
|
|
34
|
+
used.add(name)
|
|
35
|
+
|
|
36
|
+
if placeholder not in used:
|
|
37
|
+
raise ValueError(f"{field} must contain the {placeholder!r} placeholder")
|
|
38
|
+
return value
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _validate_not_blank(value: str) -> str:
|
|
42
|
+
if not value.strip():
|
|
43
|
+
raise ValueError("must not be blank")
|
|
44
|
+
return value
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class TextConfig(BaseModel):
|
|
48
|
+
"""Customizable user-facing reply copy.
|
|
49
|
+
|
|
50
|
+
Template fields use ``str.format`` placeholders; each listed placeholder
|
|
51
|
+
must appear exactly as written, while literal braces are doubled.
|
|
52
|
+
Conversions and format specs are rejected. Dynamic values are collapsed
|
|
53
|
+
to one line before formatting.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
header: str = Field(default="🔮 决断仪式:「{decider}」", min_length=1)
|
|
57
|
+
"""First line of a decision reply; must contain ``{decider}``."""
|
|
58
|
+
|
|
59
|
+
result: str = Field(default="✨ 决断结果:「{answer}」", min_length=1)
|
|
60
|
+
"""Answer line; must contain ``{answer}``."""
|
|
61
|
+
|
|
62
|
+
operator_count: str = Field(default="📊 算子数量:{operator_count}", min_length=1)
|
|
63
|
+
"""Detailed-mode line; must contain ``{operator_count}``."""
|
|
64
|
+
|
|
65
|
+
steps_header: str = "📜 演算过程:"
|
|
66
|
+
"""Detailed-mode step heading; an empty string hides the heading."""
|
|
67
|
+
|
|
68
|
+
unknown_algorithm: str = Field(
|
|
69
|
+
default="⚠️ 未知算法:「{requested}」",
|
|
70
|
+
min_length=1,
|
|
71
|
+
)
|
|
72
|
+
"""Unknown-algorithm line; must contain ``{requested}``."""
|
|
73
|
+
|
|
74
|
+
available_algorithms: str = Field(
|
|
75
|
+
default="可用算法:{available};random(随机)",
|
|
76
|
+
min_length=1,
|
|
77
|
+
)
|
|
78
|
+
"""Available algorithm list line; must contain ``{available}``."""
|
|
79
|
+
|
|
80
|
+
unavailable: str = Field(default="决策算法暂时不可用,请稍后再试。", min_length=1)
|
|
81
|
+
"""Reply used when the command handler fails unexpectedly."""
|
|
82
|
+
|
|
83
|
+
affirmative: str = Field(default="是", min_length=1)
|
|
84
|
+
"""Reply for an affirmative yes/no decision."""
|
|
85
|
+
|
|
86
|
+
negative: str = Field(default="否", min_length=1)
|
|
87
|
+
"""Reply for a negative yes/no decision."""
|
|
88
|
+
|
|
89
|
+
@_field_validator("header")
|
|
90
|
+
@classmethod
|
|
91
|
+
def _check_header(cls, value: str) -> str:
|
|
92
|
+
return _validate_template(value, field="header", placeholder="decider")
|
|
93
|
+
|
|
94
|
+
@_field_validator("result")
|
|
95
|
+
@classmethod
|
|
96
|
+
def _check_result(cls, value: str) -> str:
|
|
97
|
+
return _validate_template(value, field="result", placeholder="answer")
|
|
98
|
+
|
|
99
|
+
@_field_validator("operator_count")
|
|
100
|
+
@classmethod
|
|
101
|
+
def _check_operator_count(cls, value: str) -> str:
|
|
102
|
+
return _validate_template(
|
|
103
|
+
value,
|
|
104
|
+
field="operator_count",
|
|
105
|
+
placeholder="operator_count",
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
@_field_validator("unknown_algorithm")
|
|
109
|
+
@classmethod
|
|
110
|
+
def _check_unknown_algorithm(cls, value: str) -> str:
|
|
111
|
+
return _validate_template(
|
|
112
|
+
value,
|
|
113
|
+
field="unknown_algorithm",
|
|
114
|
+
placeholder="requested",
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
@_field_validator("available_algorithms")
|
|
118
|
+
@classmethod
|
|
119
|
+
def _check_available_algorithms(cls, value: str) -> str:
|
|
120
|
+
return _validate_template(
|
|
121
|
+
value,
|
|
122
|
+
field="available_algorithms",
|
|
123
|
+
placeholder="available",
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
@_field_validator("unavailable", "affirmative", "negative")
|
|
127
|
+
@classmethod
|
|
128
|
+
def _check_not_blank_fields(cls, value: str) -> str:
|
|
129
|
+
return _validate_not_blank(value)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class ScopedConfig(BaseModel):
|
|
133
|
+
"""Settings under the ``LAVI__`` dotenv scope."""
|
|
134
|
+
|
|
135
|
+
algorithm: str = "random"
|
|
136
|
+
"""Registered algorithm name, or ``"random"`` to choose per decision."""
|
|
137
|
+
|
|
138
|
+
detailed: bool = False
|
|
139
|
+
"""Show the selected decider, operator count and calculation steps."""
|
|
140
|
+
|
|
141
|
+
text: TextConfig = Field(default_factory=TextConfig)
|
|
142
|
+
"""Customizable reply copy under the ``LAVI__TEXT__`` scope."""
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class Config(BaseModel):
|
|
146
|
+
"""Top-level config holder for NoneBot plugin loading."""
|
|
147
|
+
|
|
148
|
+
lavi: ScopedConfig = Field(default_factory=ScopedConfig)
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Explicit registry of decision algorithms."""
|
|
2
|
+
|
|
3
|
+
from . import dayan, trial, obi_ifa, geomancy
|
|
4
|
+
from ..protocol import Algorithm
|
|
5
|
+
|
|
6
|
+
ALGORITHMS: tuple[Algorithm, ...] = (
|
|
7
|
+
dayan.ALGORITHM,
|
|
8
|
+
geomancy.ALGORITHM,
|
|
9
|
+
obi_ifa.ALGORITHM,
|
|
10
|
+
trial.ALGORITHM,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__all__ = ["ALGORITHMS"]
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""大衍筮法 (Dayan yarrow-stalk) decision algorithm.
|
|
2
|
+
|
|
3
|
+
The traditional procedure sets one of fifty stalks aside, then performs three
|
|
4
|
+
changes for each of six lines. The first change removes five stalks with
|
|
5
|
+
probability 3/4 or nine with 1/4; the second and third remove four or eight
|
|
6
|
+
stalks with probability 1/2 each. After three changes the remaining count is
|
|
7
|
+
24/28/32/36, yielding line values 6/7/8/9 with probabilities
|
|
8
|
+
1/16/5/16/7/16/3/16.
|
|
9
|
+
|
|
10
|
+
Those line values, the changed hexagram and the number of changing lines are
|
|
11
|
+
all skewed, so none of them can drive a fair binary answer directly. Yin/yang
|
|
12
|
+
polarity (6/8 versus 7/9), however, is exactly 8/16 each. This algorithm
|
|
13
|
+
therefore casts one primary hexagram and answers from the parity of its yang
|
|
14
|
+
lines: with six fair polarity bits, exactly half of the 64 primary hexagrams
|
|
15
|
+
answer True. Majority voting (22/64 for four or more yang lines) and
|
|
16
|
+
changed-hexagram readings (5/8 yin) are deliberately not used.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from collections.abc import Sequence
|
|
20
|
+
|
|
21
|
+
from ..protocol import (
|
|
22
|
+
Algorithm,
|
|
23
|
+
Explanation,
|
|
24
|
+
DecisionContext,
|
|
25
|
+
derive_algorithm_bits,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
NAME = "dayan"
|
|
29
|
+
VERSION = 1
|
|
30
|
+
WEIGHT = 1
|
|
31
|
+
|
|
32
|
+
STALKS = 50
|
|
33
|
+
SET_ASIDE = 1
|
|
34
|
+
ACTIVE_STALKS = STALKS - SET_ASIDE
|
|
35
|
+
|
|
36
|
+
LINE_COUNT = 6
|
|
37
|
+
CHANGES_PER_LINE = 3
|
|
38
|
+
FIRST_CHANGE_MARKS = 2
|
|
39
|
+
LATER_CHANGE_MARKS = 1
|
|
40
|
+
LATER_CHANGES = CHANGES_PER_LINE - 1
|
|
41
|
+
LINE_MARKS = FIRST_CHANGE_MARKS + LATER_CHANGES * LATER_CHANGE_MARKS
|
|
42
|
+
CAST_MARKS = LINE_COUNT * LINE_MARKS
|
|
43
|
+
LINE_NAMES = ("初爻", "二爻", "三爻", "四爻", "五爻", "上爻")
|
|
44
|
+
|
|
45
|
+
OLD_YIN = 6
|
|
46
|
+
YOUNG_YANG = 7
|
|
47
|
+
YOUNG_YIN = 8
|
|
48
|
+
OLD_YANG = 9
|
|
49
|
+
|
|
50
|
+
# A two-bit value selects the first-change removal: 5 with probability 3/4 and
|
|
51
|
+
# 9 with probability 1/4. Later changes consume one bit each: 4 or 8.
|
|
52
|
+
FIRST_CHANGE_REMOVALS = (5, 5, 5, 9)
|
|
53
|
+
LATER_CHANGE_REMOVALS = (4, 8)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def first_change_removal(marks: Sequence[int]) -> int:
|
|
57
|
+
"""Return the stalks removed by the first of the three changes."""
|
|
58
|
+
if len(marks) != FIRST_CHANGE_MARKS:
|
|
59
|
+
raise ValueError(f"expected {FIRST_CHANGE_MARKS} first-change marks")
|
|
60
|
+
choice = ((marks[0] & 1) << 1) | (marks[1] & 1)
|
|
61
|
+
return FIRST_CHANGE_REMOVALS[choice]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def later_change_removal(mark: int) -> int:
|
|
65
|
+
"""Return the stalks removed by the second or third change."""
|
|
66
|
+
return LATER_CHANGE_REMOVALS[mark & 1]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def line_changes(marks: Sequence[int]) -> tuple[int, int, int, int]:
|
|
70
|
+
"""Return the three removals and the remaining stalk count for one line."""
|
|
71
|
+
if len(marks) != LINE_MARKS:
|
|
72
|
+
raise ValueError(f"expected {LINE_MARKS} line marks")
|
|
73
|
+
first = first_change_removal(marks[:FIRST_CHANGE_MARKS])
|
|
74
|
+
second = later_change_removal(marks[FIRST_CHANGE_MARKS])
|
|
75
|
+
third = later_change_removal(marks[FIRST_CHANGE_MARKS + LATER_CHANGE_MARKS])
|
|
76
|
+
remaining = ACTIVE_STALKS - first - second - third
|
|
77
|
+
return first, second, third, remaining
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def cast_line(marks: Sequence[int]) -> int:
|
|
81
|
+
"""Cast one line value from its first-change and later-change marks."""
|
|
82
|
+
_, _, _, remaining = line_changes(marks)
|
|
83
|
+
line = remaining // 4
|
|
84
|
+
if line not in (OLD_YIN, YOUNG_YANG, YOUNG_YIN, OLD_YANG):
|
|
85
|
+
raise ValueError(f"derived invalid line value: {line}")
|
|
86
|
+
return line
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def cast_hexagram(marks: Sequence[int]) -> tuple[int, ...]:
|
|
90
|
+
"""Cast six line values, four marks each, in bottom-to-top order."""
|
|
91
|
+
if len(marks) != CAST_MARKS:
|
|
92
|
+
raise ValueError(f"expected {CAST_MARKS} cast marks")
|
|
93
|
+
return tuple(
|
|
94
|
+
cast_line(marks[offset : offset + LINE_MARKS])
|
|
95
|
+
for offset in range(0, CAST_MARKS, LINE_MARKS)
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def is_yang(line: int) -> bool:
|
|
100
|
+
"""Return whether a line value is yang (7 or 9)."""
|
|
101
|
+
if line not in (OLD_YIN, YOUNG_YANG, YOUNG_YIN, OLD_YANG):
|
|
102
|
+
raise ValueError(f"invalid line value: {line}")
|
|
103
|
+
return line in (YOUNG_YANG, OLD_YANG)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def yang_parity(lines: Sequence[int]) -> bool:
|
|
107
|
+
"""Return whether a primary hexagram has an odd number of yang lines."""
|
|
108
|
+
return sum(is_yang(line) for line in lines) % 2 == 1
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _cast(context: DecisionContext) -> tuple[tuple[int, ...], tuple[int, ...]]:
|
|
112
|
+
marks = derive_algorithm_bits(
|
|
113
|
+
context,
|
|
114
|
+
name=NAME,
|
|
115
|
+
version=VERSION,
|
|
116
|
+
stage="hexagram",
|
|
117
|
+
count=CAST_MARKS,
|
|
118
|
+
)
|
|
119
|
+
return marks, cast_hexagram(marks)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def calculate(context: DecisionContext) -> bool:
|
|
123
|
+
"""Cast one hexagram and answer from the parity of its yang lines."""
|
|
124
|
+
return yang_parity(_cast(context)[1])
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def explain(context: DecisionContext) -> Explanation:
|
|
128
|
+
"""Return the line-by-line stalk removals and the yang parity verdict."""
|
|
129
|
+
marks, lines = _cast(context)
|
|
130
|
+
steps: list[str] = []
|
|
131
|
+
for index, line in enumerate(lines):
|
|
132
|
+
chunk = marks[index * LINE_MARKS : (index + 1) * LINE_MARKS]
|
|
133
|
+
first, second, third, remaining = line_changes(chunk)
|
|
134
|
+
polarity = "阳" if is_yang(line) else "阴"
|
|
135
|
+
steps.append(
|
|
136
|
+
f"{LINE_NAMES[index]}:去 {first}+{second}+{third},"
|
|
137
|
+
f"余 {remaining},{remaining}÷4={line}({polarity})"
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
yang_count = sum(is_yang(line) for line in lines)
|
|
141
|
+
affirmative = yang_parity(lines)
|
|
142
|
+
steps.append(
|
|
143
|
+
f"阳爻 {yang_count} 枚,奇偶:{'奇' if affirmative else '偶'} → "
|
|
144
|
+
f"{'肯定' if affirmative else '否定'}"
|
|
145
|
+
)
|
|
146
|
+
return Explanation(affirmative, tuple(steps))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
ALGORITHM = Algorithm(
|
|
150
|
+
name=NAME,
|
|
151
|
+
version=VERSION,
|
|
152
|
+
weight=WEIGHT,
|
|
153
|
+
calculate=calculate,
|
|
154
|
+
display_name="大衍",
|
|
155
|
+
explain=explain,
|
|
156
|
+
)
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""Geomantic shield-chart decision algorithm."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
|
|
6
|
+
from ..protocol import (
|
|
7
|
+
Algorithm,
|
|
8
|
+
Explanation,
|
|
9
|
+
DecisionContext,
|
|
10
|
+
derive_algorithm_bits,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
NAME = "geomancy"
|
|
14
|
+
VERSION = 1
|
|
15
|
+
WEIGHT = 1
|
|
16
|
+
|
|
17
|
+
MOTHER_COUNT = 4
|
|
18
|
+
FIGURE_BITS = 4
|
|
19
|
+
CAST_BITS = MOTHER_COUNT * FIGURE_BITS
|
|
20
|
+
|
|
21
|
+
# Patterns read from the top (Fire) line to the bottom (Earth) line, where 1
|
|
22
|
+
# is a single/active line and 0 a double/passive line. The flag is the
|
|
23
|
+
# traditional stable/mobile quality: in a simple yes/no reading a stable Judge
|
|
24
|
+
# answers affirmatively and a mobile Judge negatively.
|
|
25
|
+
FIGURES: dict[int, tuple[str, bool]] = {
|
|
26
|
+
0b1111: ("Via", False),
|
|
27
|
+
0b0000: ("Populus", True),
|
|
28
|
+
0b0110: ("Coniunctio", False),
|
|
29
|
+
0b1001: ("Carcer", True),
|
|
30
|
+
0b0011: ("Fortuna Maior", True),
|
|
31
|
+
0b1100: ("Fortuna Minor", False),
|
|
32
|
+
0b0101: ("Acquisitio", True),
|
|
33
|
+
0b1010: ("Amissio", False),
|
|
34
|
+
0b1000: ("Laetitia", False),
|
|
35
|
+
0b0001: ("Tristitia", True),
|
|
36
|
+
0b0010: ("Albus", True),
|
|
37
|
+
0b0100: ("Rubeus", False),
|
|
38
|
+
0b1011: ("Puella", True),
|
|
39
|
+
0b1101: ("Puer", False),
|
|
40
|
+
0b0111: ("Caput Draconis", True),
|
|
41
|
+
0b1110: ("Cauda Draconis", False),
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True, slots=True)
|
|
46
|
+
class Chart:
|
|
47
|
+
"""The four Mothers and every figure derived from them."""
|
|
48
|
+
|
|
49
|
+
mothers: tuple[int, int, int, int]
|
|
50
|
+
daughters: tuple[int, int, int, int]
|
|
51
|
+
nieces: tuple[int, int, int, int]
|
|
52
|
+
right_witness: int
|
|
53
|
+
left_witness: int
|
|
54
|
+
judge: int
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _validate_figure(figure: int) -> int:
|
|
58
|
+
if not 0 <= figure < 1 << FIGURE_BITS:
|
|
59
|
+
raise ValueError(f"figure must be a 4-bit unsigned integer: {figure}")
|
|
60
|
+
return figure
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _validated_mothers(mothers: Sequence[int]) -> tuple[int, int, int, int]:
|
|
64
|
+
if len(mothers) != MOTHER_COUNT:
|
|
65
|
+
raise ValueError(f"expected {MOTHER_COUNT} mothers")
|
|
66
|
+
return (
|
|
67
|
+
_validate_figure(mothers[0]),
|
|
68
|
+
_validate_figure(mothers[1]),
|
|
69
|
+
_validate_figure(mothers[2]),
|
|
70
|
+
_validate_figure(mothers[3]),
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def cast_mothers(marks: Sequence[int]) -> tuple[int, int, int, int]:
|
|
75
|
+
"""Assemble four four-line Mothers from sixteen sampled line marks.
|
|
76
|
+
|
|
77
|
+
The first four marks are the first Mother's lines from top (Fire) to bottom
|
|
78
|
+
(Earth), the next four are the second Mother, and so on. Each mark is one
|
|
79
|
+
context-derived bit, so the cast is reproducible without a separate PRNG.
|
|
80
|
+
"""
|
|
81
|
+
if len(marks) != CAST_BITS:
|
|
82
|
+
raise ValueError(f"expected {CAST_BITS} line marks")
|
|
83
|
+
mothers: list[int] = []
|
|
84
|
+
for mother_index in range(MOTHER_COUNT):
|
|
85
|
+
figure = 0
|
|
86
|
+
for line in range(FIGURE_BITS):
|
|
87
|
+
mark = marks[mother_index * FIGURE_BITS + line] & 1
|
|
88
|
+
figure |= mark << (FIGURE_BITS - 1 - line)
|
|
89
|
+
mothers.append(figure)
|
|
90
|
+
return (mothers[0], mothers[1], mothers[2], mothers[3])
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def derive_daughters(mothers: Sequence[int]) -> tuple[int, int, int, int]:
|
|
94
|
+
"""Transpose the four Mothers into the four Daughters."""
|
|
95
|
+
first, second, third, fourth = _validated_mothers(mothers)
|
|
96
|
+
sources = (first, second, third, fourth)
|
|
97
|
+
daughters: list[int] = []
|
|
98
|
+
for line in range(FIGURE_BITS):
|
|
99
|
+
daughter = 0
|
|
100
|
+
for column, mother in enumerate(sources):
|
|
101
|
+
active = (mother >> (FIGURE_BITS - 1 - line)) & 1
|
|
102
|
+
daughter |= active << (FIGURE_BITS - 1 - column)
|
|
103
|
+
daughters.append(daughter)
|
|
104
|
+
return (daughters[0], daughters[1], daughters[2], daughters[3])
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def build_chart(mothers: Sequence[int]) -> Chart:
|
|
108
|
+
"""Derive the shield chart from four Mothers by line-wise XOR addition."""
|
|
109
|
+
first, second, third, fourth = _validated_mothers(mothers)
|
|
110
|
+
daughters = derive_daughters((first, second, third, fourth))
|
|
111
|
+
nieces = (
|
|
112
|
+
first ^ second,
|
|
113
|
+
third ^ fourth,
|
|
114
|
+
daughters[0] ^ daughters[1],
|
|
115
|
+
daughters[2] ^ daughters[3],
|
|
116
|
+
)
|
|
117
|
+
right_witness = nieces[0] ^ nieces[1]
|
|
118
|
+
left_witness = nieces[2] ^ nieces[3]
|
|
119
|
+
judge = right_witness ^ left_witness
|
|
120
|
+
if judge not in FIGURES:
|
|
121
|
+
raise ValueError(f"derived Judge is not an even figure: {judge:#06b}")
|
|
122
|
+
return Chart(
|
|
123
|
+
mothers=(first, second, third, fourth),
|
|
124
|
+
daughters=daughters,
|
|
125
|
+
nieces=nieces,
|
|
126
|
+
right_witness=right_witness,
|
|
127
|
+
left_witness=left_witness,
|
|
128
|
+
judge=judge,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def judge_is_stable(judge: int) -> bool:
|
|
133
|
+
"""Return whether an even Judge is stable (affirmative) or mobile (negative)."""
|
|
134
|
+
try:
|
|
135
|
+
return FIGURES[judge][1]
|
|
136
|
+
except KeyError:
|
|
137
|
+
raise ValueError(f"not an even Judge figure: {judge:#06b}") from None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _chart(context: DecisionContext) -> Chart:
|
|
141
|
+
marks = derive_algorithm_bits(
|
|
142
|
+
context,
|
|
143
|
+
name=NAME,
|
|
144
|
+
version=VERSION,
|
|
145
|
+
stage="mothers",
|
|
146
|
+
count=CAST_BITS,
|
|
147
|
+
)
|
|
148
|
+
return build_chart(cast_mothers(marks))
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _figure(value: int) -> str:
|
|
152
|
+
name, _ = FIGURES[value]
|
|
153
|
+
return f"{name}({value:04b})"
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def calculate(context: DecisionContext) -> bool:
|
|
157
|
+
"""Cast a shield chart and answer from the Judge's stable/mobile quality."""
|
|
158
|
+
return judge_is_stable(_chart(context).judge)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def explain(context: DecisionContext) -> Explanation:
|
|
162
|
+
"""Return the shield chart figures and the Judge's stable/mobile verdict."""
|
|
163
|
+
chart = _chart(context)
|
|
164
|
+
stable = judge_is_stable(chart.judge)
|
|
165
|
+
steps = (
|
|
166
|
+
f"四母:{' / '.join(_figure(figure) for figure in chart.mothers)}",
|
|
167
|
+
f"四女:{' / '.join(_figure(figure) for figure in chart.daughters)}",
|
|
168
|
+
f"四侄:{' / '.join(_figure(figure) for figure in chart.nieces)}",
|
|
169
|
+
f"右见证:{_figure(chart.right_witness)},"
|
|
170
|
+
f"左见证:{_figure(chart.left_witness)}",
|
|
171
|
+
f"裁判:{_figure(chart.judge)},"
|
|
172
|
+
f"{'稳定' if stable else '流动'} → {'肯定' if stable else '否定'}",
|
|
173
|
+
)
|
|
174
|
+
return Explanation(stable, steps)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
ALGORITHM = Algorithm(
|
|
178
|
+
name=NAME,
|
|
179
|
+
version=VERSION,
|
|
180
|
+
weight=WEIGHT,
|
|
181
|
+
calculate=calculate,
|
|
182
|
+
display_name="地占",
|
|
183
|
+
explain=explain,
|
|
184
|
+
)
|