完善仿真交互、结果展示与模型元数据

This commit is contained in:
ljz committed 2026-07-22 19:33:38 +08:00
1 parent f1256a121d
commit f7f1078911
26 files changed
+9042 -575

No files matched your search

+136
View File
@@ -0,0 +1,136 @@
from __future__ import annotations
import unittest
from PythonModels.components.cylinder import Cylinder
from PythonModels.components.orifice import Orifice
from PythonModels.components.pipe import Pipe
from PythonModels.components.resistive_pipe import ResistivePipe
from PythonModels.components.tank import Tank
from PythonModels.components.tee import Tee
from PythonModels.core.medium import IdealGasMedium
from PythonModels.core.ports import PortVariableDefinition
from PythonModels.registry import COMPONENT_MODEL_REGISTRY
class ComponentMetadataTests(unittest.TestCase):
def setUp(self) -> None:
self.medium = IdealGasMedium()
def component_instances(self):
return (
Cylinder("cylinder_1", self.medium),
Tank("tank_1", self.medium),
Pipe("pipe_dynamic_1", self.medium),
ResistivePipe("pipe_1", self.medium),
Orifice("orifice_1"),
Tee("tee_1"),
)
def test_every_component_declares_a_complete_model_contract(self) -> None:
for component in self.component_instances():
with self.subTest(component=component.name):
for attribute in (
"MODEL_TYPE",
"PORTS",
"PARAMETERS",
"RESULT_VARIABLES",
):
self.assertIn(attribute, type(component).__dict__)
self.assertTrue(component.MODEL_TYPE)
self.assertEqual(component.model_type, component.MODEL_TYPE)
self.assertEqual(component.port_definitions, component.PORTS)
self.assertEqual(
set(component.parameter_values),
{definition.name for definition in component.PARAMETERS},
)
self.assertTrue(
all(definition.label for definition in component.PARAMETERS)
)
self.assertTrue(
all(definition.quantity for definition in component.PARAMETERS)
)
def test_registry_reuses_component_parameter_and_port_declarations(self) -> None:
registered_classes = {
"cylinder": Cylinder,
"tank": Tank,
"pipe": ResistivePipe,
"orifice": Orifice,
"tee": Tee,
}
for model_type, component_class in registered_classes.items():
with self.subTest(model_type=model_type):
spec = COMPONENT_MODEL_REGISTRY[model_type]
self.assertEqual(spec.model_type, component_class.MODEL_TYPE)
self.assertEqual(spec.ports, component_class.PORTS)
self.assertEqual(spec.parameters, component_class.PARAMETERS)
component = spec.create(f"{model_type}_1", self.medium, {})
self.assertEqual(
component.parameter_values,
{
definition.name: definition.default
for definition in component_class.PARAMETERS
},
)
def test_result_metadata_exactly_describes_each_exposed_value(self) -> None:
for component in self.component_instances():
with self.subTest(component=component.name):
values = component.result_values()
metadata = component.result_variable_metadata()
keys = [variable.key for variable in metadata]
self.assertEqual(len(keys), len(set(keys)))
self.assertEqual(
set(values),
{
variable.key.removeprefix(f"{component.name}.")
for variable in metadata
},
)
self.assertTrue(all(variable.label for variable in metadata))
self.assertTrue(all(variable.quantity for variable in metadata))
def test_storage_and_port_variables_include_display_metadata(self) -> None:
cylinder = Cylinder("cylinder_1", self.medium)
metadata = {
variable.key: variable
for variable in cylinder.result_variable_metadata()
}
pressure = metadata["cylinder_1.p"]
self.assertEqual(pressure.scope, "component")
self.assertEqual(pressure.label, "压力")
self.assertEqual(pressure.quantity, "pressure")
self.assertEqual(pressure.unit, "Pa")
mass_flow = metadata["cylinder_1.port_b.m_flow"]
self.assertEqual(mass_flow.scope, "port")
self.assertEqual(mass_flow.port_name, "port_b")
self.assertEqual(mass_flow.label, "质量流量")
self.assertEqual(mass_flow.quantity, "mass_flow")
self.assertEqual(mass_flow.unit, "kg/s")
def test_port_display_metadata_is_not_part_of_the_physical_contract(self) -> None:
first = PortVariableDefinition(
"p",
"effort",
"equal",
label="压力",
quantity="pressure",
unit="Pa",
)
second = PortVariableDefinition(
"p",
"effort",
"equal",
label="Pressure",
quantity="absolute_pressure",
unit="kPa",
)
self.assertEqual(first, second)
if __name__ == "__main__":
unittest.main()
+198
View File
@@ -1,15 +1,26 @@
from __future__ import annotations
import asyncio
import json
import threading
import time
import unittest
from unittest.mock import patch
from uuid import uuid4
from fastapi import HTTPException, Request
from app.main import (
ReactFlowEdgePayload,
ReactFlowProjectPayload,
SimulationCancellationPayload,
_mark_simulation_task_result,
_register_simulation_task,
build_reactflow_system_xml,
cancel_system_xml_simulation,
compile_reactflow_network,
get_system_xml_simulation,
simulation_event_stream,
simulate_system_xml,
)
from PythonModels.components.resistive_pipe import ResistivePipe
@@ -242,6 +253,7 @@ class GenericSystemXmlSimulationTests(unittest.TestCase):
def test_generic_chain_simulation_conserves_mass_and_moves_pressures(self) -> None:
network = compile_reactflow_network(chain_project())
progress: list[tuple[float, str]] = []
result = GenericFluidSystem(network).simulate(
SolveIVPConfig(
t_start=0.0,
@@ -250,9 +262,20 @@ class GenericSystemXmlSimulationTests(unittest.TestCase):
max_step=0.001,
),
sample_step=0.005,
progress_callback=lambda value, phase: progress.append((value, phase)),
)
self.assertTrue(result.success)
self.assertEqual(progress[0], (0.0, "initializing"))
self.assertEqual(progress[-1], (1.0, "complete"))
self.assertTrue(
all(
current[0] <= following[0]
for current, following in zip(progress, progress[1:])
)
)
self.assertIn("integrating", {phase for _, phase in progress})
self.assertIn("postprocessing", {phase for _, phase in progress})
self.assertLess(result.series["cylinder_1.p"][-1], 500000.0)
self.assertGreater(result.series["tank_1.p"][-1], 100000.0)
total_mass = [
@@ -276,6 +299,58 @@ class GenericSystemXmlSimulationTests(unittest.TestCase):
1e-7,
)
def test_cancelled_simulation_returns_accepted_partial_samples(self) -> None:
cancel_event = threading.Event()
def request_cancel_after_progress(progress: float, phase: str) -> None:
if phase == "integrating" and progress >= 0.2:
cancel_event.set()
result = GenericFluidSystem(
compile_reactflow_network(chain_project())
).simulate(
SolveIVPConfig(t_stop=0.05, method="BDF", max_step=0.001),
sample_step=0.005,
progress_callback=request_cancel_after_progress,
cancel_check=cancel_event.is_set,
)
self.assertFalse(result.success)
self.assertEqual(result.status, "cancelled")
self.assertGreaterEqual(result.diagnostics["sampleCount"], 2)
self.assertGreater(result.simulated_until, 0.0)
self.assertLess(result.simulated_until, 0.05)
self.assertEqual(
len(result.series["time"]),
len(result.series["cylinder_1.p"]),
)
def test_task_registry_distinguishes_user_stop_and_stalled_stop(self) -> None:
for reason, expected_status in (("user", "stopped"), ("stalled", "stalled")):
simulation_id = f"test-{uuid4().hex}"
task = _register_simulation_task(simulation_id)
response = cancel_system_xml_simulation(
simulation_id,
SimulationCancellationPayload(reason=reason),
)
self.assertTrue(response["accepted"])
result = _mark_simulation_task_result(
task,
{
"success": False,
"status": "cancelled",
"partial": True,
"series": {"time": [0.0, 0.1]},
},
)
snapshot = get_system_xml_simulation(simulation_id)
self.assertEqual(result["status"], expected_status)
self.assertEqual(snapshot["status"], expected_status)
self.assertEqual(snapshot["cancelReason"], reason)
self.assertEqual(snapshot["result"]["series"]["time"], [0.0, 0.1])
def test_physical_edge_order_does_not_change_simulation(self) -> None:
forward = GenericFluidSystem(
compile_reactflow_network(chain_project())
@@ -344,6 +419,129 @@ class GenericSystemXmlSimulationTests(unittest.TestCase):
self.assertEqual(response["model"]["pressureFlowSystem"]["unknownCount"], 12)
self.assertEqual(response["diagnostics"]["stateCount"], 4)
self.assertGreater(response["final"]["tank_1.p"], 100000.0)
variables = {variable["key"]: variable for variable in response["variables"]}
self.assertEqual(set(variables), set(response["series"]) - {"time"})
self.assertEqual(variables["cylinder_1.p"]["componentId"], "cylinder_1")
self.assertEqual(variables["cylinder_1.p"]["label"], "压力")
self.assertEqual(variables["cylinder_1.p"]["unit"], "Pa")
self.assertEqual(variables["pipe_1.port_a.m_flow"]["scope"], "port")
self.assertEqual(
variables["pipe_1.port_a.m_flow"]["portName"],
"port_a",
)
def test_streaming_endpoint_events_have_monotonic_progress_and_result(self) -> None:
project = chain_project()
xml = build_reactflow_system_xml(project)
events = [json.loads(line) for line in simulation_event_stream(xml)]
progress_events = [
event for event in events if event["event"] == "progress"
]
progress = [event["progress"] for event in progress_events]
self.assertGreater(len(progress), 3)
self.assertTrue(
all(current <= following for current, following in zip(progress, progress[1:]))
)
preparation_events = [
event
for event in progress_events
if event["phase"] in {"validation", "compilation", "initialization"}
]
self.assertTrue(preparation_events)
self.assertTrue(all(event["progress"] == 0 for event in preparation_events))
timed_events = [
event
for event in progress_events
if event.get("simulatedTime") is not None
]
self.assertGreater(len(timed_events), 1)
for event in timed_events:
self.assertEqual(event["totalTime"], project.simulation.t_stop)
expected_progress = round(
100
* (event["simulatedTime"] - project.simulation.t_start)
/ (project.simulation.t_stop - project.simulation.t_start)
)
self.assertEqual(event["progress"], expected_progress)
self.assertEqual(events[-1]["event"], "result")
self.assertEqual(events[-1]["progress"], 100)
self.assertTrue(events[-1]["result"]["success"])
def test_streaming_task_stop_returns_partial_result(self) -> None:
project = branched_project()
project.simulation.t_stop = 2.0
project.simulation.step = 0.02
project.simulation.max_step = 0.01
xml = build_reactflow_system_xml(project)
simulation_id = f"test-{uuid4().hex}"
task = _register_simulation_task(simulation_id)
events: list[dict[str, object]] = []
stop_requested = False
for line in simulation_event_stream(xml, task=task):
event = json.loads(line)
events.append(event)
if (
not stop_requested
and event["event"] == "progress"
and event["phase"] == "integrating"
and event["progress"] >= 20
):
response = cancel_system_xml_simulation(
simulation_id,
SimulationCancellationPayload(reason="user"),
)
self.assertTrue(response["accepted"])
stop_requested = True
result_event = next(event for event in events if event["event"] == "result")
result = result_event["result"]
snapshot = get_system_xml_simulation(simulation_id)
self.assertTrue(stop_requested)
self.assertEqual(result["status"], "stopped")
self.assertTrue(result["partial"])
self.assertGreaterEqual(result["diagnostics"]["sampleCount"], 2)
self.assertGreater(result["simulatedUntil"], 0.0)
self.assertLess(result["simulatedUntil"], 2.0)
self.assertEqual(snapshot["status"], "stopped")
self.assertEqual(snapshot["result"]["status"], "stopped")
def test_streaming_endpoint_keeps_quiet_solver_connection_alive(self) -> None:
def delayed_simulation(_xml_bytes, progress_callback, _cancel_check=None):
progress_callback(49, "integrating", "正在进行时间积分与压力流量求解")
time.sleep(0.03)
return {"success": True}
with (
patch("app.main.SIMULATION_STREAM_HEARTBEAT_SECONDS", 0.005),
patch(
"app.main.run_system_xml_simulation",
side_effect=delayed_simulation,
),
):
events = [
json.loads(line)
for line in simulation_event_stream(b"<System />")
]
heartbeats = [event for event in events if event.get("heartbeat") is True]
self.assertGreaterEqual(len(heartbeats), 1)
self.assertTrue(all(event["progress"] == 49 for event in heartbeats))
self.assertTrue(all(event["phase"] == "integrating" for event in heartbeats))
self.assertEqual(events[-1]["event"], "result")
def test_streaming_endpoint_returns_structured_validation_error(self) -> None:
events = [
json.loads(line)
for line in simulation_event_stream(b"<System schemaVersion='2'>")
]
self.assertEqual(events[-1]["event"], "error")
self.assertEqual(events[-1]["status"], 422)
self.assertIn("issues", events[-1]["detail"])
def test_simulation_endpoint_returns_422_for_ideal_storage_coupling(self) -> None:
project = chain_project()
+94
View File
@@ -0,0 +1,94 @@
from __future__ import annotations
import csv
import io
import unittest
from fastapi import HTTPException
from app.main import (
SimulationResultCsvPayload,
SimulationResultVariablePayload,
export_simulation_results_csv,
)
def result_variable(
key: str,
component_id: str,
name: str,
label: str,
unit: str,
) -> SimulationResultVariablePayload:
return SimulationResultVariablePayload(
key=key,
componentId=component_id,
componentType="tank",
scope="component",
name=name,
label=label,
quantity="pressure",
unit=unit,
)
class ResultCsvExportTests(unittest.TestCase):
def valid_payload(self) -> SimulationResultCsvPayload:
return SimulationResultCsvPayload(
projectName="储气系统",
variables=[
result_variable(
"cylinder_1.p",
"cylinder_1",
"p",
"压力",
"Pa",
),
result_variable("tank_1.p", "tank_1", "p", "压力", "Pa"),
],
series={
"time": [0.0, 0.1],
"cylinder_1.p": [35000000.0, 34900000.0],
"tank_1.p": [100000.0, 101000.0],
},
)
def test_csv_export_preserves_result_keys_and_rows(self) -> None:
response = export_simulation_results_csv(self.valid_payload())
text = response.body.decode("utf-8-sig")
rows = list(csv.reader(io.StringIO(text)))
self.assertEqual(
rows[0],
["time", "cylinder_1.p", "tank_1.p"],
)
self.assertEqual(rows[1], ["0.0", "35000000.0", "100000.0"])
self.assertEqual(rows[2], ["0.1", "34900000.0", "101000.0"])
self.assertIn(
"filename*=UTF-8''",
response.headers["content-disposition"],
)
def test_csv_export_rejects_inconsistent_column_lengths(self) -> None:
payload = self.valid_payload()
payload.series["tank_1.p"] = [100000.0]
with self.assertRaises(HTTPException) as caught:
export_simulation_results_csv(payload)
self.assertEqual(caught.exception.status_code, 422)
self.assertIn("inconsistent length", str(caught.exception.detail))
def test_csv_export_requires_metadata_for_every_result_column(self) -> None:
payload = self.valid_payload()
payload.series["orphan.value"] = [1.0, 2.0]
with self.assertRaises(HTTPException) as caught:
export_simulation_results_csv(payload)
self.assertEqual(caught.exception.status_code, 422)
self.assertIn("unmapped orphan.value", str(caught.exception.detail))
if __name__ == "__main__":
unittest.main()