gendesign/backend/app/services/generative/placement.py
Light1YT d4068a255b
All checks were successful
CI / frontend-tests (pull_request) Successful in 57s
CI / backend-tests (pull_request) Successful in 9m54s
CI / changes (pull_request) Successful in 6s
CI / openapi-codegen-check (pull_request) Successful in 1m53s
feat(finmodel): monthly DCF — real NPV/IRR/PBP, replace IRR-proxy (epic #1881 PR-3)
Hand-rolled детерминированный DCF (без numpy-financial/новых deps): _npv /
_irr_monthly (bisection с bracket-guard) / _payback_months над помесячным
cashflow, построенным из статического каскада (PR-1) + калиброванной цены
(PR-2) по дефолтным нормативам фаз (ПИР 6мес → СМР по development_type
24/36/48 → распродажа, дисконт 15%).

- Налоги прорейтятся на признание выручки → Σ недисконтированного cashflow ==
  net_profit (ИНВАРИАНТ, тест — гарантия что DCF не разошёлся со статикой).
- IRR настоящий когда есть смена знака; вырожденный поток → fallback на
  roi-proxy (irr_is_proxy=True). Честно помечено.
- График продаж привязан к завершению стройки: sales_end = max(sales_start +
  длительность, construction_end) — продажи не заканчиваются раньше ввода
  (РФ ДДУ/эскроу). Без этого high_rise распродавался за 12 мес ДО ввода →
  двойная смена знака → profitable-проект молча падал в proxy + инверсия NPV.
- FinancialModel +npv_rub/payback_months/discount_rate_used/schedule_is_default
  (additive). development_type проброшен через placement.
- UI/PDF: NPV/IRR/PBP + честный caveat «график — типовое допущение, точность
  зависит от него». api-types регенерён авторитетно.

mypy strict clean (generative.*), +15 тестов (DCF helpers на учебных значениях,
ИНВАРИАНТ, IRR real-vs-proxy обе ветки, PBP, sales≥construction для всех типов,
profitable high_rise → настоящий IRR). 48 passed.

Refs #1881
2026-06-23 21:52:04 +05:00

294 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Generative Design — Stage 1b: greedy section placement with STRtree collisions.
Given a parsed :class:`~app.services.generative.geometry.Parcel` (Stage 1a) we place
rectangular residential sections (секции МКД) onto the placement grid using a greedy
sweep. Three strategies trade plot density against insolation comfort:
* ``max_area`` — tight gaps, deep building footprint -> maximum buildable area.
* ``max_insolation`` — wide gaps + slimmer footprint -> light/air between buildings.
* ``balanced`` — the middle ground.
Collisions (overlap + minimum inter-section gap) are checked with a Shapely STRtree
spatial index, rebuilt as placements accumulate. The greedy sweep is fully
deterministic: candidate anchors are visited in a fixed grid order and the first
non-colliding footprint that stays inside the buildable area wins.
Each placed footprint is reprojected back to WGS84 and emitted as a GeoJSON Feature
in ``ConceptVariant.buildings_geojson``; the metric footprints feed Stage 1c
(``teap`` + ``financial``) so the variant is filled with real numbers, not zeros.
Deterministic, no LLM / no external API / no DB.
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from shapely.geometry import Polygon, box
from shapely.strtree import STRtree
from app.schemas.concept import ConceptInput, ConceptVariant
from app.services.generative import financial, teap
from app.services.generative.geometry import Parcel, ParcelGeometryError
logger = logging.getLogger(__name__)
# Тип стратегии должен совпадать с Literal в ConceptVariant.strategy.
StrategyName = str
# Высота этажа (м) — для перевода target_floors в метрическую высоту/площади.
FLOOR_HEIGHT_M: float = 3.0
# ── Потолок коэффициента застройки (built / buildable) по типу застройки ──────
# Контракт не несёт явного FAR/max_coverage, поэтому используем development_type как
# естественный регулятор плотности. Жадная раскладка перестаёт ставить секции, как
# только пятно достигает доли buildable area ниже. Без этого max_area патологически
# забивает участок и даёт нереалистичный FAR. MVP-упрощение (нормативный proxy).
_COVERAGE_CAP_BY_TYPE: dict[str, float] = {
"spot": 0.35, # точечная застройка — низкое покрытие
"mid_rise": 0.45, # среднеэтажная
"high_rise": 0.50, # высотная — компактнее пятно, выше этажность
}
_DEFAULT_COVERAGE_CAP: float = 0.45
@dataclass(frozen=True)
class StrategySpec:
"""Параметры одной стратегии размещения.
section_w/section_d — габариты секции (ширина x глубина), метры.
gap_m — минимальный разрыв между секциями (инсоляция/противопожарный), метры.
floors_factor — множитель к target_floors (комфорт-класс «садит» этажность,
макс-площадь «тянет» вверх); этажность клампится к [1, 30] контракта.
"""
name: StrategyName
section_w: float
section_d: float
gap_m: float
floors_factor: float
# ── Три стратегии (упрощённо для MVP, габариты типовых панельных/монолитных секций) ──
_STRATEGIES: tuple[StrategySpec, ...] = (
# Максимум площади: глубокий корпус, минимальные противопожарные разрывы.
StrategySpec(name="max_area", section_w=24.0, section_d=18.0, gap_m=6.0, floors_factor=1.15),
# Максимум инсоляции: тонкий корпус, широкие разрывы между секциями.
StrategySpec(
name="max_insolation", section_w=18.0, section_d=12.0, gap_m=15.0, floors_factor=0.85
),
# Баланс.
StrategySpec(name="balanced", section_w=21.0, section_d=15.0, gap_m=10.0, floors_factor=1.0),
)
_FLOORS_MIN = 1
_FLOORS_MAX = 30
def _resolve_floors(target_floors: int, factor: float) -> int:
"""target_floors * factor, округление к ближайшему, клампинг к [1, 30]."""
floors = round(target_floors * factor)
return max(_FLOORS_MIN, min(_FLOORS_MAX, floors))
def _greedy_place(
parcel: Parcel,
spec: StrategySpec,
coverage_cap: float,
) -> list[Polygon]:
"""Жадно разложить секции ``spec`` по сетке участка. Возвращает footprints (метры).
Алгоритм:
* кандидат-якоря — центры ячеек сетки в фиксированном порядке;
* footprint строится центрированно на якоре;
* принимается, если целиком внутри buildable area И не нарушает разрыв ``gap_m``
с уже принятыми (проверка через STRtree по buffered-footprints);
* раскладка останавливается, когда пятно достигает ``coverage_cap`` от buildable
area (регулятор плотности по типу застройки) — это также ограничивает число
размещений и держит O(n^2)-перестройку STRtree в бюджете.
"""
buildable = parcel.buildable_m
max_built = buildable.area * coverage_cap
placed: list[Polygon] = []
built_area = 0.0
# Буферизованные footprints для проверки разрыва; индекс STRtree по ним.
buffered: list[Polygon] = []
tree: STRtree | None = None
half_w = spec.section_w / 2.0
half_d = spec.section_d / 2.0
half_gap = spec.gap_m / 2.0
for cell in parcel.grid:
if built_area >= max_built:
break
footprint = box(
cell.cx - half_w,
cell.cy - half_d,
cell.cx + half_w,
cell.cy + half_d,
)
# Целиком внутри пятна застройки (covers допускает касание границы).
if not buildable.covers(footprint):
continue
# Разрыв между секциями: буферим кандидата на half_gap и проверяем пересечение
# с буферизованными соседями — две секции с зазором >= gap_m не пересекутся.
candidate_buf = footprint.buffer(half_gap, join_style="mitre")
if tree is not None:
collision = False
for idx in tree.query(candidate_buf):
if candidate_buf.intersects(buffered[idx]):
collision = True
break
if collision:
continue
placed.append(footprint)
built_area += footprint.area
buffered.append(candidate_buf)
tree = STRtree(buffered)
logger.info(
"strategy=%s placed %d sections (%.0fx%.0f m, gap=%.0f m, coverage<=%.0f%%)",
spec.name,
len(placed),
spec.section_w,
spec.section_d,
spec.gap_m,
coverage_cap * 100,
)
return placed
def _footprints_to_geojson(
parcel: Parcel,
footprints: list[Polygon],
floors: int,
spec: StrategySpec,
) -> dict[str, object]:
"""Метрические footprints -> WGS84 FeatureCollection (контракт buildings_geojson)."""
features: list[dict[str, object]] = []
for i, fp in enumerate(footprints):
geom_wgs = parcel.metric_geom_to_wgs84(fp)
features.append(
{
"type": "Feature",
"geometry": geom_wgs,
"properties": {
"section_id": i + 1,
"floors": floors,
"footprint_sqm": round(float(fp.area), 1),
"strategy": spec.name,
},
}
)
return {"type": "FeatureCollection", "features": features}
def place_strategy(
parcel: Parcel,
payload: ConceptInput,
spec: StrategySpec,
*,
market_price_per_sqm: float | None = None,
price_source: str = "class_norm",
) -> ConceptVariant | None:
"""Полный проход одной стратегии: размещение -> ТЭП -> финмодель -> ConceptVariant.
Возвращает ``None``, если ни одна секция не легла в пятно застройки (узкий/мелкий
участок, footprint стратегии целиком не помещается). Без этого вырожденный вариант
с нулевым размещением (revenue=0, margin=-land, IRR<0) выдавался бы как валидный —
ложь в отчёте. Отбраковку делает вызывающий :func:`place_all_strategies`.
``market_price_per_sqm`` / ``price_source`` прокидываются в :func:`compute_financial`
для калибровки цены продажи жилья по рынку (PR-2). Lookup делает API-слой; здесь
только проброс. ``None`` → норматив класса.
"""
floors = _resolve_floors(payload.target_floors, spec.floors_factor)
coverage_cap = _COVERAGE_CAP_BY_TYPE.get(payload.development_type, _DEFAULT_COVERAGE_CAP)
footprints = _greedy_place(parcel, spec, coverage_cap)
if not footprints:
logger.warning(
"strategy=%s placed 0 sections (footprint %.0fx%.0f m not buildable) — отбраковка",
spec.name,
spec.section_w,
spec.section_d,
)
return None
teap_result = teap.compute_teap(
footprints=footprints,
floors=floors,
site_area_sqm=parcel.site_area_sqm,
housing_class=payload.housing_class,
)
financial_result = financial.compute_financial(
teap=teap_result,
housing_class=payload.housing_class,
land_cost_rub=payload.land_cost_rub,
market_price_per_sqm=market_price_per_sqm,
price_source=price_source,
# development_type задаёт длительность СМР в DCF-графике финмодели (PR-3).
development_type=payload.development_type,
)
buildings_geojson = _footprints_to_geojson(parcel, footprints, floors, spec)
# spec.name строится из фиксированного литерала -> совпадает с Literal контракта.
return ConceptVariant(
strategy=spec.name, # type: ignore[arg-type]
buildings_geojson=buildings_geojson,
teap=teap_result,
financial=financial_result,
)
def place_all_strategies(
parcel: Parcel,
payload: ConceptInput,
*,
market_price_per_sqm: float | None = None,
price_source: str = "class_norm",
) -> list[ConceptVariant]:
"""Stage 1b entry: построить три варианта (max_area / max_insolation / balanced).
Вырожденные стратегии (нулевое размещение) отбраковываются — в результат попадают
только варианты с реальными секциями. Если ни одна стратегия не легла (участок не
вмещает даже самую компактную секцию), это вырожденный участок: поднимаем
:class:`ParcelGeometryError` (API мапит в 422) — лучше отказ, чем пустой/лживый ответ.
``market_price_per_sqm`` / ``price_source`` (рыночная калибровка цены жилья, PR-2)
прокидываются неизменными в каждую стратегию — цена едина для участка.
"""
variants = [
variant
for spec in _STRATEGIES
if (
variant := place_strategy(
parcel,
payload,
spec,
market_price_per_sqm=market_price_per_sqm,
price_source=price_source,
)
)
is not None
]
if not variants:
raise ParcelGeometryError(
"ни одна стратегия размещения не вместила секцию — участок слишком узкий/мелкий"
)
logger.info(
"placed all strategies: %s",
", ".join(f"{v.strategy}={v.teap.apartments_count}кв" for v in variants),
)
return variants
__all__ = [
"FLOOR_HEIGHT_M",
"StrategySpec",
"place_all_strategies",
"place_strategy",
]