|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import logging |
| 4 | +from collections import defaultdict |
| 5 | +from typing import Annotated |
| 6 | +from uuid import UUID |
| 7 | + |
| 8 | +from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request |
| 9 | +from sqlalchemy import select |
| 10 | + |
| 11 | +import acidwatch_api.database as db |
| 12 | +from acidwatch_api.authentication import OptionalCurrentUser |
| 13 | +from acidwatch_api.database import GetDB |
| 14 | +from acidwatch_api.models import InputError |
| 15 | +from acidwatch_api.models.datamodel import ( |
| 16 | + Conditions, |
| 17 | + CreateSweep, |
| 18 | + ModelInput, |
| 19 | + SweepPoint, |
| 20 | + SweepResult, |
| 21 | +) |
| 22 | +from acidwatch_api.routes.models import ( |
| 23 | + AdapterSet, |
| 24 | + build_adapters, |
| 25 | + build_model_input_rows, |
| 26 | + get_adapters, |
| 27 | + order_chain, |
| 28 | + run_adapters, |
| 29 | +) |
| 30 | + |
| 31 | +router = APIRouter() |
| 32 | + |
| 33 | +logger = logging.getLogger(__name__) |
| 34 | + |
| 35 | + |
| 36 | +def _summarize_point( |
| 37 | + ordered: list[tuple[db.ModelInput, db.ModelResult | None]], |
| 38 | +) -> tuple[str, dict[str, int | float], str | None]: |
| 39 | + """Reduce a simulation's chain to a sweep point status and final output. |
| 40 | +
|
| 41 | + The "output" of a chain is the concentrations of its last model. |
| 42 | + """ |
| 43 | + if not ordered: |
| 44 | + return "pending", {}, None |
| 45 | + |
| 46 | + for _, result in ordered: |
| 47 | + if result is not None and result.error is not None: |
| 48 | + return "error", {}, result.error |
| 49 | + |
| 50 | + if any(result is None for _, result in ordered): |
| 51 | + return "pending", {}, None |
| 52 | + |
| 53 | + final_result = ordered[-1][1] |
| 54 | + assert final_result is not None |
| 55 | + return "done", final_result.concentrations, None |
| 56 | + |
| 57 | + |
| 58 | +@router.post("/sweeps") |
| 59 | +async def run_sweep( |
| 60 | + create_sweep: CreateSweep, |
| 61 | + user: OptionalCurrentUser, |
| 62 | + request: Request, |
| 63 | + session: GetDB, |
| 64 | + background_tasks: BackgroundTasks, |
| 65 | + all_adapters: Annotated[AdapterSet, Depends(get_adapters)], |
| 66 | +) -> UUID: |
| 67 | + jwt_token = user.jwt_token if user else None |
| 68 | + |
| 69 | + # Validate the model chain and concentrations once up front so the caller |
| 70 | + # gets a synchronous 422 instead of a sweep full of failed points. |
| 71 | + adapters = build_adapters( |
| 72 | + create_sweep.models, create_sweep.conditions, all_adapters, jwt_token |
| 73 | + ) |
| 74 | + |
| 75 | + if create_sweep.swept_substance not in adapters[0].valid_substances: |
| 76 | + raise HTTPException( |
| 77 | + status_code=422, |
| 78 | + detail={ |
| 79 | + "sweptSubstance": [ |
| 80 | + f"'{create_sweep.swept_substance}' is not supported by " |
| 81 | + f"the selected model" |
| 82 | + ] |
| 83 | + }, |
| 84 | + ) |
| 85 | + |
| 86 | + try: |
| 87 | + adapters[0].validate_concentrations( |
| 88 | + {**create_sweep.concentrations, create_sweep.swept_substance: 0} |
| 89 | + ) |
| 90 | + except InputError as exc: |
| 91 | + raise HTTPException(status_code=422, detail=exc.detail) |
| 92 | + |
| 93 | + values = create_sweep.range.values() |
| 94 | + |
| 95 | + sweep = db.Sweep( |
| 96 | + owner_id=UUID(user.id) if user else None, |
| 97 | + swept_substance=create_sweep.swept_substance, |
| 98 | + values=values, |
| 99 | + ) |
| 100 | + session.add(sweep) |
| 101 | + |
| 102 | + scheduled: list[tuple[dict[str, int | float], list, list[UUID]]] = [] |
| 103 | + for index, value in enumerate(values): |
| 104 | + point_concentrations = { |
| 105 | + **create_sweep.concentrations, |
| 106 | + create_sweep.swept_substance: value, |
| 107 | + } |
| 108 | + model_input_rows = build_model_input_rows(create_sweep.models) |
| 109 | + session.add( |
| 110 | + db.Simulation( |
| 111 | + owner_id=UUID(user.id) if user else None, |
| 112 | + concentrations=point_concentrations, |
| 113 | + conditions=create_sweep.conditions.model_dump(), |
| 114 | + sweep=sweep, |
| 115 | + sweep_value_index=index, |
| 116 | + model_inputs=model_input_rows, |
| 117 | + ) |
| 118 | + ) |
| 119 | + point_adapters = build_adapters( |
| 120 | + create_sweep.models, create_sweep.conditions, all_adapters, jwt_token |
| 121 | + ) |
| 122 | + scheduled.append( |
| 123 | + ( |
| 124 | + point_concentrations, |
| 125 | + point_adapters, |
| 126 | + [row.id for row in model_input_rows], |
| 127 | + ) |
| 128 | + ) |
| 129 | + |
| 130 | + session.commit() |
| 131 | + |
| 132 | + for point_concentrations, point_adapters, model_input_ids in scheduled: |
| 133 | + background_tasks.add_task( |
| 134 | + run_adapters, |
| 135 | + request.state.session, |
| 136 | + point_concentrations, |
| 137 | + point_adapters, |
| 138 | + model_input_ids, |
| 139 | + ) |
| 140 | + |
| 141 | + return sweep.id |
| 142 | + |
| 143 | + |
| 144 | +@router.get("/sweeps/{sweep_id}/result") |
| 145 | +def get_sweep_result( |
| 146 | + sweep_id: UUID, |
| 147 | + session: GetDB, |
| 148 | +) -> SweepResult: |
| 149 | + sweep = session.get_one(db.Sweep, sweep_id) |
| 150 | + |
| 151 | + simulations = ( |
| 152 | + session.execute( |
| 153 | + select(db.Simulation).where(db.Simulation.sweep_id == sweep_id) |
| 154 | + ) |
| 155 | + .scalars() |
| 156 | + .all() |
| 157 | + ) |
| 158 | + simulation_by_index = {sim.sweep_value_index: sim for sim in simulations} |
| 159 | + |
| 160 | + rows_by_simulation: dict[ |
| 161 | + UUID, list[tuple[db.ModelInput, db.ModelResult | None]] |
| 162 | + ] = defaultdict(list) |
| 163 | + simulation_ids = [sim.id for sim in simulations] |
| 164 | + if simulation_ids: |
| 165 | + q = ( |
| 166 | + select(db.ModelInput, db.ModelResult) |
| 167 | + .where(db.ModelInput.simulation_id.in_(simulation_ids)) |
| 168 | + .outerjoin(db.ModelResult) |
| 169 | + ) |
| 170 | + for model_input, result in session.execute(q): |
| 171 | + rows_by_simulation[model_input.simulation_id].append( |
| 172 | + (model_input, result) |
| 173 | + ) |
| 174 | + |
| 175 | + points: list[SweepPoint] = [] |
| 176 | + overall_pending = False |
| 177 | + for index, value in enumerate(sweep.values): |
| 178 | + simulation = simulation_by_index.get(index) |
| 179 | + if simulation is None: |
| 180 | + overall_pending = True |
| 181 | + continue |
| 182 | + |
| 183 | + ordered = order_chain(rows_by_simulation.get(simulation.id, [])) |
| 184 | + status, concentrations, error = _summarize_point(ordered) |
| 185 | + if status == "pending": |
| 186 | + overall_pending = True |
| 187 | + |
| 188 | + points.append( |
| 189 | + SweepPoint( |
| 190 | + value=value, |
| 191 | + simulation_id=simulation.id, |
| 192 | + status=status, # type: ignore[arg-type] |
| 193 | + error=error, |
| 194 | + concentrations=concentrations, |
| 195 | + ) |
| 196 | + ) |
| 197 | + |
| 198 | + first_simulation = simulation_by_index.get(0) |
| 199 | + if first_simulation is not None: |
| 200 | + models = [ |
| 201 | + ModelInput(model_id=mi.model_id, parameters=mi.parameters) |
| 202 | + for mi, _ in order_chain(rows_by_simulation.get(first_simulation.id, [])) |
| 203 | + ] |
| 204 | + base_concentrations = dict(first_simulation.concentrations or {}) |
| 205 | + conditions = Conditions(**(first_simulation.conditions or {})) |
| 206 | + else: |
| 207 | + models = [] |
| 208 | + base_concentrations = {} |
| 209 | + conditions = Conditions() |
| 210 | + |
| 211 | + return SweepResult( |
| 212 | + status="pending" if overall_pending else "done", |
| 213 | + swept_substance=sweep.swept_substance, |
| 214 | + values=list(sweep.values), |
| 215 | + concentrations=base_concentrations, |
| 216 | + conditions=conditions, |
| 217 | + models=models, |
| 218 | + points=points, |
| 219 | + ) |
0 commit comments