fix: коэффициенты как статистика применения, а не свойство расценки
Аудит вскрыл: дедуп брал коэф из одного репрезентативного вхождения, но 6.5% расценок (97) применялись И с коэф, И без (01-02-061-01: 3 раза с, 851 без). Хранить один коэф на расценку — вводит в заблуждение («всегда демонтаж»). Теперь ресурсы = БАЗОВЫЕ нормы ГЭСН (свойство расценки), а коэф вынесен в coef_applications: with/without + частоты [обоснование, target, factor] по ВСЕМ вхождениям. Также проверено измерением: ОСР (279) = свод без расценок (0 позиций, корректно), тихих потерь нет (10270=10270), непокрытые теги — только производные/ID. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -8,7 +8,7 @@
|
||||
|
||||
| Файл | Что | Источник |
|
||||
|------|-----|----------|
|
||||
| `estimates_index.json` (~12 МБ) | 3097 расценок с ПОЛНЫМ составом: работа→код ГЭСН→ед→**ресурсы** (рабочие/машины/материалы + нормы + цены база/тек + индекс пересчёта + **коэф к норме**: демонтаж/условия 571/421пр, Target+обоснование, эфф.норма = норма×коэф + машинисты)→цена/ед→**структура стоимости**→трудозатраты→накладные/прибыль (обоснование+руб)→коэффициенты позиции (с Target)→comment→Transport→freq→объём. + 6796 прямых материалов | 2519 `.gge` ЛСР/ОСР (67 256 позиций) |
|
||||
| `estimates_index.json` (~11 МБ) | 3097 расценок: работа→код ГЭСН→ед→**ресурсы** (рабочие/машины/материалы + БАЗОВЫЕ нормы ГЭСН + цены база/тек + индекс пересчёта + машинисты)→цена/ед→**структура стоимости**→трудозатраты→накладные/прибыль (обоснование+руб)→comment→Transport→freq→объём + **`coef_applications`** (коэф к нормам как СТАТИСТИКА применения: with/without + [обоснование 571/421пр, Target, factor, freq] — т.к. расценка в 6.5% случаев применялась и с коэф, и без). + 6796 прямых материалов. ОСР (279 файлов) = свод без расценок, в индекс не идут | 2519 `.gge` ЛСР/ОСР (67 256 позиций) |
|
||||
| `ka_index.json` (~5.3 МБ) | 3922 материала: **сметная цена** (EstimateWithoutVAT) min/median/max/**winner** + рыночная + склад + перевозка→обезличенные офферы→регион→квартал | 181 zip КА |
|
||||
| `vor_index.json` (~8.5 МБ) | 25 834 работы: ед→объём (min/median/max)→**формула расчёта**→ссылка на лист (с номером) | 1951 `.gge` ВОР, схема QuantityTakeoff |
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
+1
-1
@@ -130,7 +130,7 @@ def find_in_real_estimates(query: str, top_k: int = 5) -> list[dict]:
|
||||
keys = ("code", "name", "unit", "prefix", "kind", "freq", "norm_sets", "regions",
|
||||
"qty", "comment", "unit_cost_cur", "cost_structure", "labor_ch",
|
||||
"machinist_ch", "price_base", "price_cur", "overhead", "profit",
|
||||
"coefficients", "resources", "examples")
|
||||
"coef_applications", "resources", "examples")
|
||||
return [{k: it.get(k) for k in keys} for _, _, it in results[:top_k]]
|
||||
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ import argparse
|
||||
import json
|
||||
import statistics
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
@@ -33,13 +33,35 @@ def _norm_set(code: str) -> str:
|
||||
|
||||
|
||||
def _scrub_resources(res: dict) -> dict:
|
||||
# Состав = БАЗОВЫЕ нормы (свойство расценки). Coef убираем отсюда —
|
||||
# он свойство ПРИМЕНЕНИЯ (одна и та же расценка в 6.5% случаев применялась
|
||||
# и с коэф, и без), агрегируется отдельно в coef_applications.
|
||||
for lst in res.values():
|
||||
for r in lst:
|
||||
if r.get("name"):
|
||||
r["name"] = scrub(r["name"])
|
||||
r.pop("coef", None)
|
||||
if r.get("machinist"):
|
||||
r["machinist"].pop("coef", None)
|
||||
return {k: v[:MAX_RES] for k, v in res.items()}
|
||||
|
||||
|
||||
def _coef_apps(position: dict) -> list[tuple]:
|
||||
"""Коэффициенты применения позиции (позиционные + ресурсные) как
|
||||
список (reason, target, factor) для частотной агрегации по расценке."""
|
||||
apps = []
|
||||
for c in position.get("coefficients", []):
|
||||
if c.get("value"):
|
||||
apps.append((scrub(c.get("reason", "")), c.get("target", ""), str(c["value"])))
|
||||
for lst in position["resources"].values():
|
||||
for r in lst:
|
||||
for src in (r.get("coef"), (r.get("machinist") or {}).get("coef")):
|
||||
if src and src.get("factors"):
|
||||
for target, factor in src["factors"].items():
|
||||
apps.append((scrub(src.get("reason", "")), target, str(factor)))
|
||||
return apps
|
||||
|
||||
|
||||
def build(root: Path, out_dir: Path) -> dict:
|
||||
agg: dict[str, dict] = {}
|
||||
mat_agg: dict[str, dict] = {}
|
||||
@@ -73,11 +95,13 @@ def build(root: Path, out_dir: Path) -> dict:
|
||||
"norm_sets": defaultdict(int),
|
||||
"regions": defaultdict(int), "qtys": [], "examples": [],
|
||||
"freq": 0, "_best_res": -1,
|
||||
# коэф применения — агрегат по ВСЕМ вхождениям (не из одного)
|
||||
"coef_with": 0, "coef_without": 0, "coef_counter": Counter(),
|
||||
# обогащённые поля (из самого полного вхождения)
|
||||
"unit_cost_cur": 0.0, "labor_ch": 0.0, "machinist_ch": 0.0,
|
||||
"price_base": "", "price_cur": "", "comment": "",
|
||||
"cost_structure": None,
|
||||
"overhead": None, "profit": None, "coefficients": [],
|
||||
"overhead": None, "profit": None,
|
||||
"resources": {"workers": [], "machines": [], "materials": []},
|
||||
}
|
||||
rec["names"][name] += 1
|
||||
@@ -91,7 +115,15 @@ def build(root: Path, out_dir: Path) -> dict:
|
||||
rec["freq"] += 1
|
||||
if len(rec["examples"]) < 3 and est_code:
|
||||
rec["examples"].append({"est": est_code, "qty": p["quantity"], "unit": p["unit"]})
|
||||
# состав — из вхождения с максимумом ресурсов
|
||||
# коэф применения — агрегируем по ВСЕМ вхождениям (а не из одного,
|
||||
# т.к. одна расценка применялась и с коэф, и без)
|
||||
apps = _coef_apps(p)
|
||||
if apps:
|
||||
rec["coef_with"] += 1
|
||||
rec["coef_counter"].update(apps)
|
||||
else:
|
||||
rec["coef_without"] += 1
|
||||
# состав — из вхождения с максимумом ресурсов (БАЗОВЫЕ нормы)
|
||||
res = p["resources"]
|
||||
res_n = len(res["workers"]) + len(res["machines"]) + len(res["materials"])
|
||||
if res_n > rec["_best_res"]:
|
||||
@@ -105,7 +137,6 @@ def build(root: Path, out_dir: Path) -> dict:
|
||||
rec["cost_structure"] = p.get("cost_structure")
|
||||
rec["overhead"] = p["overhead"]
|
||||
rec["profit"] = p["profit"]
|
||||
rec["coefficients"] = p["coefficients"][:5]
|
||||
rec["resources"] = _scrub_resources(res)
|
||||
|
||||
for m in data.get("direct_materials", []):
|
||||
@@ -147,7 +178,11 @@ def build(root: Path, out_dir: Path) -> dict:
|
||||
"labor_ch": rec["labor_ch"], "machinist_ch": rec["machinist_ch"],
|
||||
"price_base": rec["price_base"], "price_cur": rec["price_cur"],
|
||||
"overhead": rec["overhead"], "profit": rec["profit"],
|
||||
"coefficients": rec["coefficients"],
|
||||
"coef_applications": {
|
||||
"with": rec["coef_with"], "without": rec["coef_without"],
|
||||
"coefs": [{"reason": r, "target": t, "factor": f, "freq": c}
|
||||
for (r, t, f), c in rec["coef_counter"].most_common(6)],
|
||||
} if rec["coef_with"] else None,
|
||||
"resources": rec["resources"],
|
||||
"examples": rec["examples"],
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user