# -*- coding: utf-8 -*- """ initial_cost.py — Initial Investment Estimator v1.0 ─────────────────────────────────────────────────── 작물·전략별 초기투자비를 low/base/high 3구간으로, 항목별 근거와 함께 산출한다. 원칙(사양): - 단일 숫자 금지 → low/base/high. 초기투자비 vs 연간관리비 vs 1~3년 운영자금 구분. - 직접비/공통비/운영자금 구분. 포트폴리오에서 공통비 중복계산 금지. - 데이터 부족 시 좋은 값으로 가정하지 말고 오차범위↑·신뢰도↓. - 세금/인허가/탄소/태양광/바이오차는 확정비용이 아니라 '예상 검토비/전문가 견적 필요'. ※ 작물 단가는 모델 기본값(source_quality=E, ±50%)이며 지역 견적 DB로 교체 가능(MVP). 금액 단위: 원(KRW). """ from __future__ import annotations try: import risk_v2 except Exception: risk_v2 = None _M = 10_000 # 만원 → 원 # ────────────────────────────────────────────────────────────── # 5. 조정 계수 # ────────────────────────────────────────────────────────────── def apply_area_scale_multiplier(area_ha): a = float(area_ha or 0) if a < 1: return 1.35 if a < 3: return 1.15 if a <= 10: return 1.00 if a <= 30: return 0.90 return 0.85 def apply_slope_multiplier(slope): if slope is None: return 1.15 # 미상 → 약간 보수적(중간 경사 가정) + 신뢰도는 별도 하락 s = float(slope) if s < 10: return 1.00 if s < 20: return 1.10 if s < 30: return 1.25 if s < 35: return 1.45 return 1.70 def apply_access_multiplier(road_distance=None, forest_road_distance=None): d = forest_road_distance if forest_road_distance is not None else road_distance if d is None: return 1.20 # 미상 → 보수적 if d < 100: return 1.00 if d < 500: return 1.15 if d < 1000: return 1.30 return 1.60 def apply_legal_multiplier(legal_zone): m = {"일반산지": 1.00, "준보전산지": 1.05, "보전산지_임업용": 1.15, "보전산지_공익용": 1.30, "개발제한구역": 1.50, "상수원보호구역": 1.50, "백두대간보호구역": 1.50, "기타보호구역": 1.50} if legal_zone is None: return 1.20 return m.get(legal_zone, 1.20) def _protection_multiplier(theft_risk, wildlife_risk): t = theft_risk or 0 w = wildlife_risk or 0 if t > 80 or w > 80: return 1.50 if t > 60 or w > 60: return 1.25 return 1.00 def _logistics_multiplier(access_m, slope_m): return 0.5 * access_m + 0.5 * slope_m # 4. Contingency def calculate_contingency_rate(confidence_score, strategy_type="generic"): if strategy_type in ("uncertain",): # 인허가/탄소/태양광/바이오차 return 0.30 if confidence_score is None: return 0.20 if confidence_score >= 75: return 0.10 if confidence_score >= 55: return 0.15 return 0.20 # 6. source_quality → ± 오차율 _SRC_PM = {"A": 0.10, "B": 0.15, "C": 0.25, "D": 0.35, "E": 0.50} # ────────────────────────────────────────────────────────────── # 7. 공통 사전비용 (사양에 금액 명시 — 한 번만 계산) # ────────────────────────────────────────────────────────────── # (category, basis, low, base, high, src, mult_keys) COMMON_PRE = [ ("토양정밀검사", "flat", 50*_M, 100*_M, 200*_M, "C", []), ("필지경계/GIS 확인", "flat", 30*_M, 70*_M, 150*_M, "C", []), ("현장답사", "flat", 30*_M, 80*_M, 150*_M, "D", []), ("산지구분/법적검토", "flat", 30*_M, 100*_M, 300*_M, "C", ["legal"]), ("산림경영계획 검토", "flat", 50*_M, 150*_M, 400*_M, "C", ["legal"]), ("기본 컨설팅", "flat", 30*_M, 100*_M, 300*_M, "D", []), ] # 2-2. 공통 인프라 (per_ha 또는 flat). irrigation은 작물 needs_irrigation일 때만. # (category, basis, low, base, high, src, mult_keys, tag) SHARED_INFRA = [ ("작업로/진입로 정비", "per_ha", 100*_M, 200*_M, 400*_M, "D", ["logistics", "area"], "infra"), ("배수로 정비", "per_ha", 50*_M, 100*_M, 200*_M, "D", ["slope", "area"], "infra"), ("관수 인프라", "per_ha", 80*_M, 150*_M, 300*_M, "E", ["area"], "irrigation"), ("울타리(경계)", "per_ha", 60*_M, 120*_M, 250*_M, "D", ["protection", "area"], "protection"), ("야생동물 방지시설", "per_ha", 40*_M, 80*_M, 160*_M, "D", ["protection", "area"], "protection"), ("도난방지(표지·CCTV)", "flat", 30*_M, 70*_M, 150*_M, "D", ["protection"], "protection_theft"), ("간이 작업·저장 공간", "flat", 50*_M, 100*_M, 200*_M, "E", [], "infra"), ("공구·장비", "flat", 30*_M, 80*_M, 150*_M, "E", [], "infra"), ] # ────────────────────────────────────────────────────────────── # 8. 작물별 직접비 (per_ha 기본값, source=E). archetype + 작물 override # ────────────────────────────────────────────────────────────── def _mushroom_items(oak=False): items = [ ("종균", "per_ha", 150*_M, 250*_M, 400*_M, "E", ["area"]), ("원목/배지", "per_ha", 200*_M, 350*_M, 600*_M, "E", ["logistics", "area"]), ("접종 인건비", "per_ha", 150*_M, 250*_M, 400*_M, "D", ["slope", "area"]), ("그늘·습도 관리", "per_ha", 100*_M, 200*_M, 350*_M, "E", ["area"]), ("병해충 예방·도구", "per_ha", 50*_M, 100*_M, 200*_M, "E", ["area"]), ] if oak: # 표고: 참나무 원목 비중↑ + 운반·적치 items[1] = ("참나무 원목", "per_ha", 250*_M, 450*_M, 750*_M, "D", ["logistics", "area"]) items.append(("원목 운반·적치", "per_ha", 50*_M, 100*_M, 200*_M, "D", ["logistics", "area"])) return items def _veg_items(): return [ ("묘종/종자", "per_ha", 120*_M, 200*_M, 350*_M, "E", ["area"]), ("식재 인건비", "per_ha", 150*_M, 250*_M, 400*_M, "D", ["slope", "area"]), ("토양개량·제초", "per_ha", 60*_M, 120*_M, 200*_M, "D", ["slope", "area"]), ("관수/배수", "per_ha", 50*_M, 100*_M, 200*_M, "E", ["area"]), ("수확·포장 도구", "per_ha", 20*_M, 50*_M, 100*_M, "E", ["area"]), ] def _root_items(): return [ ("종자/묘근", "per_ha", 150*_M, 250*_M, 400*_M, "E", ["area"]), ("토양정리·배수", "per_ha", 80*_M, 150*_M, 250*_M, "D", ["slope", "area"]), ("식재 인건비", "per_ha", 120*_M, 200*_M, 350*_M, "D", ["slope", "area"]), ("제초/하예", "per_ha", 50*_M, 100*_M, 180*_M, "D", ["area"]), ("세척·건조·포장 장비", "flat", 50*_M, 100*_M, 200*_M, "E", []), ] def _ginseng_items(): return [ ("종자/종묘(고가)", "per_ha", 300*_M, 500*_M, 900*_M, "D", ["area"]), ("적지정리·파종 인건비", "per_ha", 150*_M, 300*_M, 500*_M, "D", ["slope", "area"]), ("피해방지(울타리·CCTV·순찰)", "per_ha", 200*_M, 400*_M, 800*_M, "D", ["protection", "area"]), ("생산이력·모니터링", "flat", 50*_M, 100*_M, 200*_M, "E", []), ] # 작물 → (archetype items, needs_irrigation, long_term_years, annual_mgmt_per_ha base) def _crop_template(crop): veg = ("취나물(참취)", "취나물", "곰취", "곤드레", "원추리", "산마늘(명이)", "산마늘", "산나물(두릅·참나물)", "산나물") root = ("더덕", "도라지") if crop in ("목이버섯",): return _mushroom_items(False), True, 1, 80*_M if crop in ("표고버섯",): return _mushroom_items(True), True, 1, 80*_M if crop in ("산양삼",): return _ginseng_items(), False, 6, 120*_M # 6년 누적 관리 핵심 if crop in root: return _root_items(), False, 3, 70*_M if crop in veg: return _veg_items(), True, 1, 60*_M # 미지원 작물 → 산나물 일반으로 폴백 return _veg_items(), True, 1, 60*_M # ────────────────────────────────────────────────────────────── # 9. 전략별(비작물) 초기비용 템플릿 # ────────────────────────────────────────────────────────────── def _strategy_items(strat, area_ha): """(items, strategy_type, note). strategy_type='uncertain'이면 contingency↑.""" if strat == "logging": # 벌채비는 운영비 → 초기는 허가·조사·재조림 return ([("벌채 허가/신고 검토", "flat", 30*_M, 100*_M, 300*_M, "C", ["legal"]), ("현장조사·작업로 점검", "flat", 30*_M, 80*_M, 150*_M, "D", ["access"]), ("재조림 계획·식재", "per_ha", 200*_M, 350*_M, 600*_M, "C", ["slope", "area"])], "generic", "벌채 운영비(벌목·집재·운반)는 매출 차감 운영비로 별도 처리") if strat == "landscape": return ([("묘목/특용수 구입", "per_ha", 200*_M, 400*_M, 700*_M, "D", ["area"]), ("식재·관수·지주대", "per_ha", 150*_M, 280*_M, 500*_M, "D", ["slope", "area"]), ("전정·수형 초기관리", "per_ha", 50*_M, 120*_M, 250*_M, "D", ["area"]), ("운반로 정비", "per_ha", 80*_M, 150*_M, 300*_M, "D", ["logistics", "area"])], "generic", "기존 수목 가치와 신규 조성비를 구분") if strat == "carbon": return ([("탄소사업 가능성 검토", "flat", 100*_M, 200*_M, 400*_M, "D", []), ("베이스라인·표본조사", "flat", 100*_M, 250*_M, 500*_M, "D", []), ("MRV 예비검토·등록문서", "flat", 150*_M, 300*_M, 600*_M, "E", [])], "uncertain", "확정 배출권 아님 — 탄소잠재가치 분석비/정밀 MRV 필요비로 표시") if strat == "solar": return ([("일사량·산지전용 검토", "flat", 50*_M, 100*_M, 200*_M, "D", []), ("계통연계 검토", "flat", 50*_M, 120*_M, 300*_M, "D", []), ("법적 인허가 사전검토", "flat", 100*_M, 200*_M, 500*_M, "D", ["legal"])], "uncertain", "1차 검토비만 산정 — 실제 개발비(토목·모듈·계통)는 법적 가능성 확인 후 별도") if strat == "biomass": return ([("부산물량 산정", "flat", 30*_M, 80*_M, 150*_M, "E", []), ("수거·집재·파쇄", "per_ha", 80*_M, 150*_M, 300*_M, "D", ["logistics", "area"]), ("운반·수요처 연결", "flat", 50*_M, 120*_M, 300*_M, "E", ["access"])], "uncertain", "수거·연결형 기준. 바이오차 직접생산은 별도 고비용 전략") if strat == "tourism": return ([("법적 가능성·동선 검토", "flat", 100*_M, 200*_M, 500*_M, "D", ["legal"]), ("안전시설·안내판", "flat", 100*_M, 250*_M, 600*_M, "D", []), ("보험·예약·홍보 기초", "flat", 50*_M, 120*_M, 300*_M, "E", [])], "uncertain", "시설 설치가 법적으로 어려우면 검토비만 표시") if strat == "consignment": return ([("산림경영 진단서", "flat", 30*_M, 70*_M, 150*_M, "D", []), ("위탁계약·법률/세무 검토", "flat", 50*_M, 150*_M, 400*_M, "D", ["legal"]), ("임업인 매칭·현장실사", "flat", 30*_M, 80*_M, 200*_M, "E", [])], "generic", "산주 부담 초기비용과 운영자 부담 투자비를 구분") return ([], "generic", "") # ────────────────────────────────────────────────────────────── # 공통 계산 엔진 # ────────────────────────────────────────────────────────────── def _mult_value(key, ctx): return {"area": ctx["area_m"], "slope": ctx["slope_m"], "access": ctx["access_m"], "legal": ctx["legal_m"], "protection": ctx["protect_m"], "logistics": ctx["logi_m"]}.get(key, 1.0) def _item_costs(item, ctx): """item=(cat,basis,low,base,high,src,mult_keys) → dict(low/base/high/...).""" cat, basis, lo, ba, hi, src, mkeys = item qty = ctx["area"] if basis == "per_ha" else 1.0 m = 1.0 for k in mkeys: m *= _mult_value(k, ctx) return { "category": cat, "basis": basis, "quantity": round(qty, 2), "unit_cost_low": lo, "unit_cost_base": ba, "unit_cost_high": hi, "cost_low": int(qty * lo * m), "cost_base": int(qty * ba * m), "cost_high": int(qty * hi * m), "source_quality": src, "multiplier": round(m, 3), "required": True, } def _ctx(parcel_data, area_ha): p = parcel_data or {} slope_m = apply_slope_multiplier(p.get("slope")) access_m = apply_access_multiplier(p.get("road_distance"), p.get("forest_road_distance")) legal_m = apply_legal_multiplier(p.get("legal_zone")) # 도난·야생동물 위험 → 보호 멀티플라이어 (risk_v2 있으면 사용) theft = wild = None if risk_v2 is not None: try: theft = risk_v2.calculate_theft_risk(p, "forest_product")["score"] wild = risk_v2.calculate_wildlife_risk(p, "forest_product")["score"] except Exception: pass return { "area": float(area_ha or 0), "area_m": apply_area_scale_multiplier(area_ha), "slope_m": slope_m, "access_m": access_m, "legal_m": legal_m, "protect_m": _protection_multiplier(theft, wild), "logi_m": _logistics_multiplier(access_m, slope_m), } def _sum(items): return (sum(i["cost_low"] for i in items), sum(i["cost_base"] for i in items), sum(i["cost_high"] for i in items)) # 11. 신뢰도 def calculate_cost_confidence_score(parcel_data, cost_items, strategy_type="generic"): p = parcel_data or {} e_count = sum(1 for i in cost_items if i["source_quality"] in ("E",)) no_vendor = 15 # 업체 견적 없음(모델 기본값) no_field = 10 legal_unc = 10 if p.get("legal_zone") is None else 0 high_slope = 10 if (p.get("slope") or 0) >= 30 else 0 access_unc = 10 if p.get("forest_road_distance") is None else 0 uncertain = 10 if strategy_type == "uncertain" else 0 score = int(max(0, min(100, 100 - e_count * 4 - no_vendor - no_field - legal_unc - high_slope - access_unc - uncertain))) level = ("높음" if score >= 80 else "중간" if score >= 60 else "낮음" if score >= 40 else "매우 낮음") return score, level # 12. 민감도 TOP5 def generate_cost_sensitivity_analysis(items, base_total, top=5): if base_total <= 0: return [] out = [] for i in items: delta = i["cost_base"] * 0.20 out.append({"item": i["category"], "pct": round(100 * delta / base_total, 1)}) out.sort(key=lambda x: x["pct"], reverse=True) return out[:top] def _round_won(x): return int(round(x / 10000.0) * 10000) # 만원 단위 반올림 # ────────────────────────────────────────────────────────────── # 메인: 작물/전략 초기투자비 # ────────────────────────────────────────────────────────────── _CROPS = {"목이버섯", "표고버섯", "취나물(참취)", "취나물", "곰취", "곤드레", "원추리", "산마늘(명이)", "산마늘", "산나물(두릅·참나물)", "산나물", "더덕", "도라지", "산양삼"} def estimate_common_pre_cost(parcel_data, area_ha=None): ctx = _ctx(parcel_data, area_ha) return [_item_costs(it, ctx) for it in COMMON_PRE] def estimate_shared_infrastructure_cost(parcel_data, area_ha, needs_irrigation=True, needs_protection=True): ctx = _ctx(parcel_data, area_ha) items = [] for cat, basis, lo, ba, hi, src, mk, tag in SHARED_INFRA: if tag == "irrigation" and not needs_irrigation: continue if tag in ("protection", "protection_theft") and not needs_protection: continue items.append(_item_costs((cat, basis, lo, ba, hi, src, mk), ctx)) return items def estimate_initial_investment(name, area_ha, parcel_data, include_common=True, include_shared=True): """작물명 또는 전략키 → 사양 §1 출력 dict (low/base/high·breakdown·신뢰도·민감도).""" ctx = _ctx(parcel_data, area_ha) is_crop = name in _CROPS if is_crop: items_def, needs_irr, long_years, ann_per_ha = _crop_template(name) direct = [_item_costs(it, ctx) for it in items_def] heavy_protect = (name == "산양삼") shared = estimate_shared_infrastructure_cost(parcel_data, area_ha, needs_irr, True) if include_shared else [] stype = "generic" note = "" else: items_def, stype, note = _strategy_items(name, area_ha) direct = [_item_costs(it, ctx) for it in items_def] long_years, ann_per_ha = 1, 50*_M shared = estimate_shared_infrastructure_cost(parcel_data, area_ha, False, False) if (include_shared and name in ("landscape",)) else [] common = estimate_common_pre_cost(parcel_data, area_ha) if include_common else [] all_items = common + shared + direct sub_lo, sub_ba, sub_hi = _sum(all_items) conf, conf_lvl = calculate_cost_confidence_score(parcel_data, all_items, stype) cont = calculate_contingency_rate(conf, stype) contingency_item = {"category": "예비비(Contingency)", "basis": "rate", "cost_low": int(sub_lo * cont), "cost_base": int(sub_ba * cont), "cost_high": int(sub_hi * cont), "source_quality": "-", "rate": cont, "required": True} tot_lo = _round_won(sub_lo * (1 + cont)) tot_ba = _round_won(sub_ba * (1 + cont)) tot_hi = _round_won(sub_hi * (1 + cont)) a = float(area_ha or 1) or 1 # 1~3년차 운영자금 (연간관리비 = per_ha × area; 산양삼은 6년 누적 별도) ann = int(ann_per_ha * a * ctx["slope_m"]) year1 = int(ann + (sub_ba * 0.05)) # 관리비 + 운영버퍼 year2 = int(ann * 0.9 + (sub_ba * 0.04)) cumulative_until_revenue = None if long_years and long_years > 1: cumulative_until_revenue = _round_won(tot_ba + ann * long_years) sens = generate_cost_sensitivity_analysis(all_items, sub_ba) return { "strategy_or_crop": name, "is_crop": is_crop, "area_ha": a, "initial_investment": {"low": tot_lo, "base": tot_ba, "high": tot_hi}, "per_ha_cost": {"low": _round_won(tot_lo / a), "base": _round_won(tot_ba / a), "high": _round_won(tot_hi / a)}, "year_0_cash_need": tot_ba, "year_1_cash_need": _round_won(year1), "year_2_cash_need": _round_won(year2), "cumulative_until_first_revenue": cumulative_until_revenue, "first_revenue_years": long_years, "cost_breakdown": all_items + [contingency_item], "contingency_rate": cont, "confidence_score": conf, "confidence_level": conf_lvl, "cost_sensitivity": sens, "main_cost_drivers": [s["item"] for s in sens], "excluded_costs": ["토지 매입비", "세금 최종 자문비", "정밀 인허가 대행비", "실제 시공 견적 초과분"], "required_quotes": _required_quotes(name, is_crop), "strategy_type": stype, "note": note, "disclaimer": "본 비용은 공공데이터·기본 단가표 기반 1차 추정이며, 실제 착수 전 현장견적이 필요합니다.", } def _required_quotes(name, is_crop): if is_crop: q = ["종묘/종균 업체 견적", "현장 인건비 견적", "임도/진입로 정비 견적"] if name == "산양삼": q.append("울타리·CCTV·순찰 등 피해방지 견적") return q return {"logging": ["벌채업체 견적", "재조림 단가 견적"], "carbon": ["MRV 검증기관 견적"], "solar": ["EPC·계통연계 견적"], "biomass": ["수거·운송·수요처 견적"], "tourism": ["인허가·시공 견적"], "landscape": ["조경수 묘목·굴취 견적"], "consignment": ["위탁계약·법무/세무 견적"] }.get(name, ["전문가 견적"]) # 10. 포트폴리오 초기투자비 (공통비·공유인프라 1회만) def estimate_portfolio_initial_cost(portfolio, parcel_data, total_area_ha): """portfolio={label:ratio%}. 공통/공유는 한 번, 직접비는 구역 면적별.""" ctx = _ctx(parcel_data, total_area_ha) common = estimate_common_pre_cost(parcel_data, total_area_ha) # 공유 인프라: 임산물/생산 구역이 있으면 전체 기준 1회 label_to_crop = {"임산물 복합경영": parcel_data.get("crop_name") or "산나물"} has_production = any("임산물" in k or "생산" in k or "조경" in k for k in portfolio) shared = estimate_shared_infrastructure_cost(parcel_data, total_area_ha, True, True) if has_production else [] direct_items = [] for label, ratio in portfolio.items(): area_i = total_area_ha * (ratio / 100.0) if "임산물" in label or "생산" in label: crop = parcel_data.get("crop_name") crop = crop if crop in _CROPS else "산나물" est = estimate_initial_investment(crop, area_i, parcel_data, include_common=False, include_shared=False) for it in est["cost_breakdown"]: if it.get("basis") == "rate": continue it = dict(it); it["category"] = f"[{label}] {it['category']}" direct_items.append(it) elif "복원" in label or "조림" in label: est = estimate_initial_investment("logging", area_i, parcel_data, include_common=False, include_shared=False) for it in est["cost_breakdown"]: if it.get("basis") == "rate": continue it = dict(it); it["category"] = f"[{label}] {it['category']}" direct_items.append(it) # 보존/저강도: 직접 조성비 0 (모니터링만 소액) elif "보존" in label or "저강도" in label: direct_items.append({"category": f"[{label}] 모니터링", "basis": "flat", "cost_low": 20*_M, "cost_base": 50*_M, "cost_high": 100*_M, "source_quality": "E", "required": True}) all_items = common + shared + direct_items sub_lo, sub_ba, sub_hi = _sum(all_items) conf, lvl = calculate_cost_confidence_score(parcel_data, all_items) cont = calculate_contingency_rate(conf) tot_ba = _round_won(sub_ba * (1 + cont)) return { "portfolio": portfolio, "area_ha": total_area_ha, "initial_investment": {"low": _round_won(sub_lo*(1+cont)), "base": tot_ba, "high": _round_won(sub_hi*(1+cont))}, "per_ha_cost": {"base": _round_won(tot_ba / (total_area_ha or 1))}, "cost_breakdown": all_items, "contingency_rate": cont, "confidence_score": conf, "confidence_level": lvl, "common_counted_once": True, "disclaimer": "공통비·공유 인프라는 1회만 계산. 실제 착수 전 현장견적 필요.", } def generate_cost_explanation_text(est): """사양 §15 설명 문구.""" base_won = est["initial_investment"]["base"] drivers = "·".join(est["main_cost_drivers"][:4]) txt = (f"{est['strategy_or_crop']}의 초기투자비는 기준 시나리오 약 " f"{base_won//10000:,}만원으로 추정됩니다. 주요 비용은 {drivers} 입니다.") if est.get("cumulative_until_first_revenue"): cum = est["cumulative_until_first_revenue"] // 10000 txt += (f" 다만 {est['strategy_or_crop']}은 첫 수익 전 " f"{est['first_revenue_years']}년간 관리·피해방지 비용이 누적되어, " f"6년 누적 현금소요는 약 {cum:,}만원 수준을 함께 고려해야 합니다.") if est.get("strategy_type") == "uncertain": txt += " 인허가·인증 불확실성이 커 예비비를 높였으며, 확정비용이 아니라 전문가 견적이 필요합니다." txt += " 실제 착수 전에는 관련 업체·산림조합 현장견적이 필요합니다." return txt