Coverage for backend/ahuora-builder/src/ahuora_builder/solver.py: 86%
40 statements
« prev ^ index » next coverage.py v7.10.7, created at 2026-06-23 21:51 +0000
« prev ^ index » next coverage.py v7.10.7, created at 2026-06-23 21:51 +0000
1import traceback
2from typing import Optional
3from ahuora_builder_types.id_types import PropertyValueId
4import idaes.logger as idaeslog
5from pydantic import BaseModel
6from ahuora_builder_types import FlowsheetSchema
7from ahuora_builder_types.flowsheet_schema import SolvedFlowsheetSchema, UnitDiagnosticsFinding
8from ahuora_builder_types.payloads.solve_request_schema import IdaesSolveRequestPayload
9from .flowsheet_manager import FlowsheetManager
10from pyomo.environ import assert_optimal_termination, check_optimal_termination
11_log = idaeslog.getLogger(__name__)
14class SolveModelResult(BaseModel):
15 success: bool = True
16 input_flowsheet: FlowsheetSchema
17 output_flowsheet: SolvedFlowsheetSchema
18 solve_index: Optional[int] = None
19 scenario_id: Optional[int] = None
20 task_id: int
21 timing: dict
22 unit_diagnostics: list[UnitDiagnosticsFinding] = []
24def solve_model(solve_request: IdaesSolveRequestPayload) -> SolveModelResult:
25 """Solves the model and returns the results"""
26 flowsheet = FlowsheetManager(solve_request.flowsheet)
27 #print(solve_request.flowsheet.model_dump_json())
29 def run_phase(name: str, fn):
30 try:
31 return fn()
32 except Exception as e:
33 details = f"[solve_model:{name}] {type(e).__name__}: {e}"
34 _log.exception(details)
35 raise RuntimeError(details) from e
37 run_phase("load", flowsheet.load)
38 run_phase("initialise", flowsheet.initialise)
39 run_phase("report_statistics", flowsheet.report_statistics)
40 if solve_request.perform_diagnostics: 40 ↛ 41line 40 didn't jump to line 41 because the condition on line 40 was never true
41 run_phase("diagnose_problems", flowsheet.diagnose_problems)
42 run_phase("check_model_valid", flowsheet.check_model_valid)
43 success = run_phase("solve", flowsheet.solve)
44 unit_diagnostics = run_phase("get_unit_diagnostics_report", flowsheet.get_unit_diagnostics_report)
46 run_phase("optimize", flowsheet.optimize)
47 result = run_phase("serialise", flowsheet.serialise)
49 return SolveModelResult(
50 success=success,
51 input_flowsheet=solve_request.flowsheet,
52 output_flowsheet=result,
53 solve_index=solve_request.solve_index,
54 scenario_id=solve_request.scenario_id,
55 task_id=solve_request.task_id,
56 timing=flowsheet.timing.close(),
57 unit_diagnostics=unit_diagnostics if unit_diagnostics else []
58 )