File size: 11,716 Bytes
d87f438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4819352
 
d87f438
 
 
4819352
 
d87f438
 
 
 
 
 
 
 
4819352
d87f438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4819352
d87f438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4819352
d87f438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4819352
d87f438
 
 
 
 
 
 
4819352
d87f438
 
 
 
 
 
 
 
 
 
 
 
 
 
4819352
 
d87f438
 
 
 
7a677c0
 
4819352
 
7a677c0
 
 
4819352
7a677c0
 
 
 
 
 
 
4819352
7a677c0
 
 
 
 
 
 
 
 
4819352
7a677c0
 
 
 
 
 
 
 
 
 
 
 
4819352
7a677c0
 
 
 
 
 
 
 
 
 
 
 
4819352
7a677c0
 
 
 
 
 
 
 
 
 
 
 
4819352
7a677c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4819352
 
d87f438
 
 
 
 
 
 
 
 
 
 
7a677c0
 
 
 
 
 
 
 
 
 
 
 
 
d87f438
 
 
4819352
 
d87f438
 
 
 
 
 
 
 
 
7a677c0
 
 
 
 
 
 
d87f438
 
 
 
 
 
7a677c0
d87f438
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
from __future__ import annotations
"""
eval_formula λ“±κ°€μ„± λ‹¨μœ„ ν…ŒμŠ€νŠΈ (Step B).

κΈ°μ‘΄ Python μˆ˜μ‹(bundle Index / cs ruleΒ·boost)을 spec으둜 ν‘œκΈ°ν•˜κ³ 
λ¬΄μž‘μœ„ feature μž…λ ₯μ—μ„œ eval_formula == 원식 μž„μ„ ν™•μ •ν•œλ‹€.

- affine(μ—°μ‚°μˆœμ„œ λ³€ν™˜) : |diff| < 1e-9
- 동일 μƒμˆ˜/μž„κ³„/쑰건/boost : μ™„μ „ 일치 (==)

μ‹€ν–‰: python scripts/test_eval_formula.py   (μ‹€νŒ¨ μ‹œ AssertionError + exit 1)
"""
import random
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent))

from core.engines.common import clamp, clamp01           # noqa: E402
from core.engines.formula import eval_formula            # noqa: E402

EPS = 1e-9
_fails: list[str] = []


def _approx(a: float, b: float, tol: float = EPS) -> bool:
    """두 값이 tol μ΄λ‚΄λ‘œ κ·Όμ‚¬ν•œμ§€ (affine μ—°μ‚°μˆœμ„œ ULP ν—ˆμš©μš©)."""
    return abs(a - b) <= tol


def check(name: str, ref: float, spec, feats: dict, *, exact: bool = False) -> None:
    """eval_formula(spec) κ²°κ³Όλ₯Ό κΈ°μ€€κ°’ ref와 λŒ€μ‘°. exactλ©΄ ==, μ•„λ‹ˆλ©΄ 근사. λΆˆμΌμΉ˜λŠ” _fails에 λˆ„μ ."""
    got = eval_formula(spec, feats)
    ok = (got == ref) if exact else _approx(got, ref)
    if not ok:
        _fails.append(f"{name}: ref={ref!r} got={got!r} feats={feats}")


# ── 1. bundle: Bundle Opportunity Index (affine ν•© + clamp) ──────
# 원식(bundle.py:59): clamp( (fl-1)/3*50 + (1-scr)*30 + hc/2*20 )
def ref_bundle_opp(f: dict) -> float:
    fl  = float(f.get("family_line_count", 1))
    scr = float(f.get("service_coverage_ratio", 0.0))
    hc  = float(f.get("household_change", 0))
    return clamp(((fl - 1) / 3 * 50) + ((1 - scr) * 30) + (hc / 2 * 20))

SPEC_BUNDLE_OPP = {
    "clamp": [0, 100],
    "terms": [
        {"feat": "family_line_count",      "default": 1, "linear": [50 / 3, -50 / 3]},
        {"feat": "service_coverage_ratio", "linear": [-30, 30]},
        {"feat": "household_change",       "linear": [10, 0]},
    ],
}

# ── 2. bundle: Benefit Optimization Index (min/clip + 쑰건) ──────
# 원식(bundle.py:64): clamp( min(gap,3)/3*40 + (2-bu)*35 + (25 if dissat in (톡신비,ν˜œνƒ) else 0) )
def ref_benefit_opt(f: dict) -> float:
    gap = float(f.get("non_mobile_cost_gap", 0))
    bu  = float(f.get("benefit_utilization", 2))
    dissat = str(f.get("dissatisfaction_factor", "μ—†μŒ"))
    return clamp((min(gap, 3) / 3 * 40) + ((2 - bu) * 35) + (25 if dissat in ("톡신비", "ν˜œνƒ") else 0))

SPEC_BENEFIT_OPT = {
    "clamp": [0, 100],
    "terms": [
        {"feat": "non_mobile_cost_gap", "clip": [None, 3], "linear": [40 / 3, 0]},
        {"feat": "benefit_utilization", "default": 2, "linear": [-35, 70]},
        {"if": {"feat": "dissatisfaction_factor", "in": ["톡신비", "ν˜œνƒ"]}, "then": 25},
    ],
}

# ── 3. cs: _rule_1110 (λ‹€λΆ„κΈ° threshold) ────────────────────────
# 원식(cs.py:478): rate>=.85β†’.65 / >=.65β†’.45 / >=.40β†’.25 / else .10
def ref_rule_1110(f: dict) -> float:
    rate = float(f.get("데이터 μ‚¬μš©λ₯ ", 0))
    if rate >= 0.85: return 0.65
    if rate >= 0.65: return 0.45
    if rate >= 0.40: return 0.25
    return 0.10

SPEC_RULE_1110 = {
    "feat": "데이터 μ‚¬μš©λ₯ ",
    "threshold": [[0.85, 0.65], [0.65, 0.45], [0.40, 0.25]],
    "default": 0.10,
}

# ── 4. cs: _pattern_boost (boost, mult=1.5) ─────────────────────
# 원식(cs.py:452): min(v*scale*1.5, cap*1.5)
PBM = 1.5
def ref_boost(f: dict) -> float:
    v = float(f.get("churn_page_view_count", 0))
    return min(v * 0.12 * PBM, 0.30 * PBM)

SPEC_BOOST = {"boost": {"feat": "churn_page_view_count", "scale": 0.12, "cap": 0.30, "mult": PBM}}

# ── 5. bundle: λ£° INT-B1110 (affine + clamp01 + 쑰건) ────────────
# 원식(bundle.py:199): clamp01(0.20 + BOI/100*0.55 + (0.1 if fl>=2 else 0))
def ref_b1110(f: dict) -> float:
    boi = float(f.get("Bundle Opportunity Index", 0))
    fl  = float(f.get("family_line_count", 0))
    return clamp01(0.20 + boi / 100 * 0.55 + (0.1 if fl >= 2 else 0))

SPEC_B1110 = {
    "clamp": [0, 1],
    "terms": [
        0.20,
        {"feat": "Bundle Opportunity Index", "linear": [0.55 / 100, 0]},
        {"if": {"feat": "family_line_count", "gte": 2}, "then": 0.1},
    ],
}

# ── 6. py escape hatch ──────────────────────────────────────────
def custom_formula(features: dict) -> float:
    """py escape κ²€μ¦μš© μ½œλŸ¬λΈ” (spec {"py": "...:custom_formula"}μ—μ„œ 호좜)."""
    return features.get("x", 0) * 2 + 1
SPEC_PY = {"py": "scripts.test_eval_formula:custom_formula"}


# ══════════════ ν™•μž₯ λ…Έλ“œ: 볡합 쑰건 / λΆ„κΈ° 식 (cs λ£° 6μ’…) ══════════════
PBM = 1.5  # PATTERN_BOOST_MULTIPLIER
def _boost(f: dict, key: str, scale: float, cap: float) -> float:
    """cs _pattern_boost μž¬ν˜„(Γ—PBM): min(v*scale*PBM, cap*PBM)."""
    return min(float(f.get(key, 0)) * scale * PBM, cap * PBM)

# 7. _rule_1340: AND 쑰건 (cs.py:537)
def ref_1340(f: dict) -> float:
    return 0.55 if f.get("κ²°ν•© μ—¬λΆ€", False) and int(f.get("κ°€μ‘± νšŒμ„  수", 1)) >= 2 else 0.20
SPEC_1340 = {
    "if": {"all": [{"feat": "κ²°ν•© μ—¬λΆ€", "gte": 1}, {"feat": "κ°€μ‘± νšŒμ„  수", "gte": 2}]},
    "then": 0.55, "else": 0.20,
}

# 8. _rule_3110: AND + bool not (cs.py:645)
def ref_3110(f: dict) -> float:
    if float(f.get("λ―Έλ‚© κΈˆμ•‘", 0)) > 0 and not f.get("μžλ™λ‚©λΆ€ 등둝 μ—¬λΆ€", True):
        return 0.70
    return 0.0
SPEC_3110 = {
    "if": {"all": [{"feat": "λ―Έλ‚© κΈˆμ•‘", "gt": 0}, {"feat": "μžλ™λ‚©λΆ€ 등둝 μ—¬λΆ€", "eq": False}]},
    "then": 0.70, "else": 0.0,
}

# 9. _rule_5140: AND + then이 식(boost+clamp) (cs.py:710)
def ref_5140(f: dict) -> float:
    bundle = str(f.get("κ²°ν•© ν˜•νƒœ", "none"))
    if bundle in ("home", "full") and float(f.get("ν’ˆμ§ˆ λ§Œμ‘±λ„", 1)) <= 0.4:
        return min(0.55 + _boost(f, "quality_action_count", 0.10, 0.25), 0.95)
    return 0.05
SPEC_5140 = {
    "if": {"all": [{"feat": "κ²°ν•© ν˜•νƒœ", "in": ["home", "full"]}, {"feat": "ν’ˆμ§ˆ λ§Œμ‘±λ„", "lte": 0.4}]},
    "then": {"clamp": [0, 0.95], "terms": [
        0.55, {"boost": {"feat": "quality_action_count", "scale": 0.10, "cap": 0.25, "mult": PBM}}]},
    "else": 0.05,
}

# 10. _rule_6130: then이 affine 식 (cs.py:?)
def ref_6130(f: dict) -> float:
    family = int(f.get("κ°€μ‘± νšŒμ„  수", 1))
    rem = float(f.get("μž”μ—¬ 데이터 λΉ„μœ¨", 1))
    if family >= 2:
        return 0.30 + (1 - rem) * 0.3
    return 0.05
SPEC_6130 = {
    "if": {"feat": "κ°€μ‘± νšŒμ„  수", "gte": 2},
    "then": {"terms": [0.30, {"feat": "μž”μ—¬ 데이터 λΉ„μœ¨", "linear": [-0.3, 0.3]}]},
    "else": 0.05,
}

# 11. _rule_2240: 쀑첩 λΆ„κΈ° β†’ switch (cs.py:?)
def ref_2240(f: dict) -> float:
    if f.get("κ²°ν•© μ—¬λΆ€"):
        return 0.20
    return 0.45 if int(f.get("κ°€μ‘± νšŒμ„  수", 1)) >= 2 else 0.20
SPEC_2240 = {
    "switch": [
        {"if": {"feat": "κ²°ν•© μ—¬λΆ€", "gte": 1}, "then": 0.20},
        {"if": {"feat": "κ°€μ‘± νšŒμ„  수", "gte": 2}, "then": 0.45},
    ],
    "else": 0.20,
}

# 12. _rule_2120: OR 쑰건 + λΆ„κΈ°λ§ˆλ‹€ λ‹€λ₯Έ 식 (cs.py:563)
def ref_2120(f: dict) -> float:
    upsell = float(f.get("μ—…μ…€ 적합도 Score", 0))
    fee = float(f.get("μš”κΈˆμ œ μ›”μ •μ•‘", 0))
    tier = str(f.get("μš”κΈˆμ œ ꡬ간", ""))
    is_5g_like = tier in ("premium", "mid") or fee >= 55000
    if is_5g_like:
        return min(0.20 + _boost(f, "product_explore_count", 0.04, 0.10), 0.40)
    base = min(upsell * 0.7 + 0.15, 0.70)
    return min(base + _boost(f, "product_explore_count", 0.08, 0.20), 0.95)
SPEC_2120 = {
    "if": {"any": [{"feat": "μš”κΈˆμ œ ꡬ간", "in": ["premium", "mid"]}, {"feat": "μš”κΈˆμ œ μ›”μ •μ•‘", "gte": 55000}]},
    "then": {"clamp": [0, 0.40], "terms": [
        0.20, {"boost": {"feat": "product_explore_count", "scale": 0.04, "cap": 0.10, "mult": PBM}}]},
    "else": {"clamp": [0, 0.95], "terms": [
        {"clamp": [0, 0.70], "value": {"terms": [{"feat": "μ—…μ…€ 적합도 Score", "linear": [0.7, 0]}, 0.15]}},
        {"boost": {"feat": "product_explore_count", "scale": 0.08, "cap": 0.20, "mult": PBM}}]},
}


def _rand_feats(rng: random.Random) -> dict:
    """λ“±κ°€μ„± λŒ€μ‘°μš© λ¬΄μž‘μœ„ feature dict 생성."""
    return {
        "family_line_count":        rng.choice([1, 2, 3]),
        "service_coverage_ratio":   round(rng.uniform(0, 1), 4),
        "household_change":         rng.choice([0, 1, 2]),
        "non_mobile_cost_gap":      round(rng.uniform(-1, 5), 3),
        "benefit_utilization":      rng.choice([0, 1, 2, 3]),
        "dissatisfaction_factor":   rng.choice(["μ—†μŒ", "톡신비", "ν˜œνƒ", "IPTV ν’ˆμ§ˆ"]),
        "데이터 μ‚¬μš©λ₯ ":             round(rng.uniform(0, 1), 4),
        "churn_page_view_count":    rng.choice([0, 1, 2, 3, 5]),
        "Bundle Opportunity Index": round(rng.uniform(0, 100), 2),
        "x":                        rng.randint(0, 10),
        # ν™•μž₯ λ…Έλ“œ ν…ŒμŠ€νŠΈμš©
        "κ²°ν•© μ—¬λΆ€":                 rng.choice([0, 1]),
        "κ°€μ‘± νšŒμ„  수":              rng.choice([1, 2, 3, 4, 5]),
        "λ―Έλ‚© κΈˆμ•‘":                 rng.choice([0, 0, 12000, 50000]),
        "μžλ™λ‚©λΆ€ 등둝 μ—¬λΆ€":         rng.choice([True, False]),
        "κ²°ν•© ν˜•νƒœ":                 rng.choice(["none", "mobile_only", "home", "full"]),
        "ν’ˆμ§ˆ λ§Œμ‘±λ„":               round(rng.uniform(0, 1), 4),
        "quality_action_count":     rng.choice([0, 1, 2, 3, 5]),
        "μž”μ—¬ 데이터 λΉ„μœ¨":           round(rng.uniform(0, 1), 4),
        "μ—…μ…€ 적합도 Score":          round(rng.uniform(0, 1), 4),
        "μš”κΈˆμ œ μ›”μ •μ•‘":             rng.choice([35000, 55000, 80000, 100000]),
        "μš”κΈˆμ œ ꡬ간":               rng.choice(["premium", "mid", "standard", "lite"]),
        "product_explore_count":    rng.choice([0, 1, 2, 4]),
    }


def main() -> None:
    """6+6 μˆ˜μ‹ νŒ¨ν„΄μ„ 2000개 λ¬΄μž‘μœ„ μΌ€μ΄μŠ€λ‘œ eval_formula ≑ 원식 λŒ€μ‘° (μ‹€νŒ¨ μ‹œ exit 1)."""
    rng = random.Random(42)
    for _ in range(2000):
        f = _rand_feats(rng)
        check("bundle_opp",  ref_bundle_opp(f),  SPEC_BUNDLE_OPP,  f)            # affine λ³€ν™˜ β†’ tol
        check("benefit_opt", ref_benefit_opt(f), SPEC_BENEFIT_OPT, f)            # min/clip+쑰건 β†’ tol
        check("rule_1110",   ref_rule_1110(f),   SPEC_RULE_1110,   f, exact=True)
        check("boost",       ref_boost(f),       SPEC_BOOST,       f, exact=True)
        check("b1110",       ref_b1110(f),        SPEC_B1110,       f)
        check("py_escape",   custom_formula(f),  SPEC_PY,          f, exact=True)
        # ν™•μž₯ λ…Έλ“œ (볡합 쑰건 / λΆ„κΈ° 식)
        check("rule_1340",   ref_1340(f),  SPEC_1340, f, exact=True)
        check("rule_3110",   ref_3110(f),  SPEC_3110, f, exact=True)
        check("rule_5140",   ref_5140(f),  SPEC_5140, f)             # then에 affine μ—†μŒ β†’ 사싀상 exactμ§€λ§Œ boost*1.5 μ•ˆμ „ tol
        check("rule_6130",   ref_6130(f),  SPEC_6130, f)             # affine λ³€ν™˜ β†’ tol
        check("rule_2240",   ref_2240(f),  SPEC_2240, f, exact=True)
        check("rule_2120",   ref_2120(f),  SPEC_2120, f)             # affine(upsell*0.7) λ³€ν™˜ β†’ tol

    if _fails:
        print(f"❌ {len(_fails)}건 뢈일치 (μ΅œλŒ€ 10건):")
        for e in _fails[:10]:
            print("  " + e)
        sys.exit(1)
    print("βœ… eval_formula λ“±κ°€μ„± 톡과 β€” 12개 μˆ˜μ‹ νŒ¨ν„΄(볡합쑰건·뢄기 포함) Γ— 2000 λ¬΄μž‘μœ„ μΌ€μ΄μŠ€")


if __name__ == "__main__":
    main()