实现test_mql PNL0001管路动态

This commit is contained in:
huojiarong committed 2026-07-17 03:28:36 +00:00
1 parent 2d33a8f4bc
commit 1193b2dcee
8 files changed
+995

No files matched your search

+90
View File
@@ -3859,6 +3859,7 @@ class TestMqlSystem:
def __init__(self, archive_path: Path | None = None) -> None:
self.archive_path = archive_path or Path(__file__).resolve().parents[2] / AMESIM_ARCHIVE_RELATIVE_PATH
self.network = SimulationNetwork(name=MODEL_NAME)
self.pnl0001_assembly = self._build_pnl0001_assembly()
self.pneumatic_assembly = self._build_pneumatic_assembly()
pneumatic_components = self._pneumatic_components_by_alias()
for spec in COMPONENT_SPECS:
@@ -3881,6 +3882,13 @@ class TestMqlSystem:
return build_test_mql_pneumatic_assembly()
def _build_pnl0001_assembly(self):
from PythonModels.systems.test_mql_pneumatic_lines import (
build_test_mql_pnl0001_assembly,
)
return build_test_mql_pnl0001_assembly(self.archive_path)
def _pneumatic_components_by_alias(self) -> dict[str, Component]:
return {
**self.pneumatic_assembly.fixed_chambers,
@@ -3893,6 +3901,10 @@ class TestMqlSystem:
def typed_pneumatic_component_count(self) -> int:
return len(self._pneumatic_components_by_alias())
@property
def typed_pnl0001_line_count(self) -> int:
return len(self.pnl0001_assembly.lines)
def pneumatic_state_vector(self) -> list[float]:
return self.network.initial_state_vector()
@@ -4071,6 +4083,84 @@ class TestMqlSystem:
t_eval=t_eval,
)
def pnl0001_chamber_segment_closure_from_spec(
self,
spec,
*,
inlet_node_pressure_pa: float,
outlet_pressure_pa: float,
inlet_node_temperature_k: float = 293.15,
outlet_temperature_k: float = 293.15,
):
"""Insert the topology-derived inlet PNL0001 into a chamber segment."""
from PythonModels.components.amesim_pneumatic import (
AmesimPneumaticOrifice,
AmesimPneumaticVolume,
)
from PythonModels.systems.test_mql_closure import (
TestMqlPneumaticBoundaryCondition,
TestMqlPnl0001ChamberSegmentClosure,
TestMqlPnl0001ChamberSegmentComponents,
)
inlet_line = self.pnl0001_assembly.lines[spec.inlet_line_alias]
volume = self.network.components[spec.volume_alias]
inlet_orifice = self.network.components[spec.inlet_orifice_alias]
outlet_orifice = self.network.components[spec.outlet_orifice_alias]
if not isinstance(volume, AmesimPneumaticVolume):
raise TypeError(f"{spec.volume_alias} is not an AMESim pneumatic volume")
if not isinstance(inlet_orifice, AmesimPneumaticOrifice):
raise TypeError(
f"{spec.inlet_orifice_alias} is not an AMESim pneumatic orifice"
)
if not isinstance(outlet_orifice, AmesimPneumaticOrifice):
raise TypeError(
f"{spec.outlet_orifice_alias} is not an AMESim pneumatic orifice"
)
return TestMqlPnl0001ChamberSegmentClosure(
components=TestMqlPnl0001ChamberSegmentComponents(
inlet_line=inlet_line,
volume=volume,
inlet_orifice=inlet_orifice,
outlet_orifice=outlet_orifice,
spec=spec,
),
inlet_node=TestMqlPneumaticBoundaryCondition(
pressure_pa=inlet_node_pressure_pa,
temperature_k=inlet_node_temperature_k,
),
outlet_boundary=TestMqlPneumaticBoundaryCondition(
pressure_pa=outlet_pressure_pa,
temperature_k=outlet_temperature_k,
),
)
def simulate_pnl0001_chamber_segment_from_spec(
self,
spec,
*,
inlet_node_pressure_pa: float,
outlet_pressure_pa: float,
inlet_node_temperature_k: float = 293.15,
outlet_temperature_k: float = 293.15,
config: SolveIVPConfig | None = None,
t_eval: list[float] | None = None,
):
closure = self.pnl0001_chamber_segment_closure_from_spec(
spec,
inlet_node_pressure_pa=inlet_node_pressure_pa,
outlet_pressure_pa=outlet_pressure_pa,
inlet_node_temperature_k=inlet_node_temperature_k,
outlet_temperature_k=outlet_temperature_k,
)
run_config = config or SolveIVPConfig(t_stop=1.0e-4, max_step=1.0e-5)
return integrate_ode(
rhs=lambda t, state: closure.rhs(state),
initial_state=closure.initial_state_vector(),
config=run_config,
t_eval=t_eval,
)
def pneumatic_branch_closure_from_spec(self, spec):
return self.pneumatic_branch_closure(
name=spec.name,
+176
View File
@@ -8,6 +8,7 @@ from PythonModels.components.amesim_pneumatic import (
AmesimPneumaticOrifice,
AmesimPneumaticVolume,
)
from PythonModels.components.amesim_pneumatic_line import AmesimPnl0001Pipe
from PythonModels.core.medium import ThermodynamicProperties
from PythonModels.core.ports import PortState
from PythonModels.core.state import VolumeState
@@ -98,6 +99,26 @@ class TestMqlPneumaticChamberSegmentSnapshot:
outlet_flow: float
@dataclass(frozen=True)
class TestMqlPnl0001ChamberSegmentComponents:
inlet_line: AmesimPnl0001Pipe
volume: AmesimPneumaticVolume
inlet_orifice: AmesimPneumaticOrifice
outlet_orifice: AmesimPneumaticOrifice
spec: TestMqlPneumaticChamberSegmentSpec
@dataclass(frozen=True)
class TestMqlPnl0001ChamberSegmentSnapshot:
inlet_line: ThermodynamicProperties
chamber: ThermodynamicProperties
inlet_node: ThermodynamicProperties
outlet_boundary: ThermodynamicProperties
node_to_line_flow: float
line_to_chamber_flow: float
outlet_flow: float
@dataclass(frozen=True)
class TestMqlPneumaticBranchComponents:
name: str
@@ -379,3 +400,158 @@ class TestMqlPneumaticChamberSegmentClosure:
internal_h=snapshot.chamber.h,
)
return derivative.as_vector()
class TestMqlPnl0001ChamberSegmentClosure:
"""Fixed chamber segment with the topology-derived inlet PNL0001 state.
The inlet line has a closed causal boundary here: port-1 pressure and
temperature come from the PN3 node boundary, while port-2 flow comes from
the fixed orifice. The outlet line remains a boundary until its three-line
PN3 node balance is assembled.
"""
def __init__(
self,
*,
components: TestMqlPnl0001ChamberSegmentComponents,
inlet_node: TestMqlPneumaticBoundaryCondition,
outlet_boundary: TestMqlPneumaticBoundaryCondition,
) -> None:
self.components = components
self.inlet_node = inlet_node
self.outlet_boundary = outlet_boundary
def initial_state_vector(self) -> list[float]:
return [
*self.components.inlet_line.get_state_vector(),
*self.components.volume.get_state_vector(),
]
def apply_state_vector(self, values: list[float]) -> None:
if len(values) != 4:
raise ValueError("PNL0001/chamber segment state vector requires four values")
self.components.inlet_line.set_state_vector(values[:2])
self.components.volume.set_state_vector(values[2:])
def snapshot(
self,
state_vector: list[float] | None = None,
) -> TestMqlPnl0001ChamberSegmentSnapshot:
if state_vector is not None:
self.apply_state_vector(state_vector)
line = self.components.inlet_line.properties()
chamber = self.components.volume.properties()
inlet_node = self.inlet_node.properties(self.components.inlet_line.gas)
outlet_boundary = self.outlet_boundary.properties(self.components.volume.gas)
node_to_line_flow = self.components.inlet_line.resistance_mass_flow(
port_1_pressure_pa=inlet_node.p,
port_1_temperature_k=inlet_node.T,
)
inlet_temperature = line.T if line.p >= chamber.p else chamber.T
line_to_chamber_flow = self.components.inlet_orifice.mass_flow(
line.p,
chamber.p,
inlet_temperature,
)
outlet_temperature = (
chamber.T if chamber.p >= outlet_boundary.p else outlet_boundary.T
)
outlet_flow = self.components.outlet_orifice.mass_flow(
chamber.p,
outlet_boundary.p,
outlet_temperature,
)
snapshot = TestMqlPnl0001ChamberSegmentSnapshot(
inlet_line=line,
chamber=chamber,
inlet_node=inlet_node,
outlet_boundary=outlet_boundary,
node_to_line_flow=node_to_line_flow,
line_to_chamber_flow=line_to_chamber_flow,
outlet_flow=outlet_flow,
)
self._write_port_states(snapshot)
return snapshot
@staticmethod
def _port(
component: AmesimPneumaticVolume | AmesimPneumaticOrifice,
port_name: str,
) -> PortState:
return TestMqlPneumaticChamberSegmentClosure._port(component, port_name)
def _write_port_states(
self,
snapshot: TestMqlPnl0001ChamberSegmentSnapshot,
) -> None:
spec = self.components.spec
line = self.components.inlet_line
chamber = self.components.volume
inlet_orifice = self.components.inlet_orifice
outlet_orifice = self.components.outlet_orifice
line.port_1.p = snapshot.inlet_node.p
line.port_1.m_flow = snapshot.node_to_line_flow
line.port_1.h_outflow = snapshot.inlet_line.h
line.port_2.p = snapshot.inlet_line.p
line.port_2.m_flow = -snapshot.line_to_chamber_flow
inlet_boundary_port = self._port(
inlet_orifice,
spec.inlet_orifice_boundary_port,
)
inlet_volume_port = self._port(inlet_orifice, spec.inlet_orifice_volume_port)
inlet_boundary_port.p = snapshot.inlet_line.p
inlet_boundary_port.m_flow = snapshot.line_to_chamber_flow
inlet_boundary_port.h_outflow = snapshot.inlet_line.h
inlet_volume_port.p = snapshot.chamber.p
inlet_volume_port.m_flow = -snapshot.line_to_chamber_flow
inlet_volume_port.h_outflow = snapshot.chamber.h
chamber_inlet_port = self._port(chamber, spec.volume_inlet_port)
chamber_outlet_port = self._port(chamber, spec.volume_outlet_port)
chamber_inlet_port.m_flow = snapshot.line_to_chamber_flow
chamber_outlet_port.m_flow = -snapshot.outlet_flow
outlet_volume_port = self._port(
outlet_orifice,
spec.outlet_orifice_volume_port,
)
outlet_boundary_port = self._port(
outlet_orifice,
spec.outlet_orifice_boundary_port,
)
outlet_volume_port.p = snapshot.chamber.p
outlet_volume_port.m_flow = snapshot.outlet_flow
outlet_volume_port.h_outflow = snapshot.chamber.h
outlet_boundary_port.p = snapshot.outlet_boundary.p
outlet_boundary_port.m_flow = -snapshot.outlet_flow
outlet_boundary_port.h_outflow = snapshot.outlet_boundary.h
def rhs(self, state_vector: list[float]) -> list[float]:
snapshot = self.snapshot(state_vector)
line_derivative = self.components.inlet_line.derivatives_from_connections(
port_1_m_flow=snapshot.node_to_line_flow,
connected_h_1=snapshot.inlet_node.h,
port_2_m_flow=-snapshot.line_to_chamber_flow,
connected_h_2=snapshot.chamber.h,
)
chamber = self.components.volume
spec = self.components.spec
chamber_derivative = chamber.derivatives_from_two_connections(
port_a_m_flow=self._port(chamber, "port_1").m_flow,
connected_h_a=(
snapshot.inlet_line.h
if spec.volume_inlet_port == "port_1"
else snapshot.outlet_boundary.h
),
port_b_m_flow=self._port(chamber, "port_2").m_flow,
connected_h_b=(
snapshot.inlet_line.h
if spec.volume_inlet_port == "port_2"
else snapshot.outlet_boundary.h
),
internal_h=snapshot.chamber.h,
)
return [*line_derivative.as_vector(), *chamber_derivative.as_vector()]
@@ -0,0 +1,162 @@
from __future__ import annotations
import re
import tarfile
from dataclasses import dataclass
from pathlib import Path
from PythonModels.systems.test_mql import CONNECTION_SPECS, GLOBAL_PARAMETERS
from PythonModels.systems.test_mql_config import resolve_numeric_expression
AMESIM_REFERENCE_PRESSURE_PA = 101_300.0
@dataclass(frozen=True)
class TestMqlPnl0001Spec:
alias: str
source_component: str
source_port: str
target_component: str
target_port: str
diameter_mm: float
length_m: float
relative_roughness: float
polytropic_constant: float
heat_transfer_coefficient: float
external_temperature_k: float
gas_type_index: int
mode: int
initial_temperature_k: float
initial_gauge_pressure_pa: float
@property
def initial_absolute_pressure_pa(self) -> float:
return self.initial_gauge_pressure_pa + AMESIM_REFERENCE_PRESSURE_PA
def load_test_mql_pnl0001_specs(
archive_path: str | Path,
*,
cir_member: str = "test_mql_.cir",
) -> tuple[TestMqlPnl0001Spec, ...]:
"""Load resolved PNL0001 geometry and initial states from the AMESim source."""
with tarfile.open(archive_path) as archive:
cir_file = archive.extractfile(cir_member)
if cir_file is None:
raise ValueError(f"Missing AMESim circuit member: {cir_member}")
cir_text = cir_file.read().decode("latin1")
numeric_globals = {
name: value
for name, expression in GLOBAL_PARAMETERS.items()
if (value := resolve_numeric_expression(expression, {})) is not None
}
connections = {
str(connection["alias"]): connection
for connection in CONNECTION_SPECS
if connection["submodel"] == "PNL0001"
}
specs = []
for block in re.findall(r"<LINE>.*?</LINE>", cir_text, flags=re.DOTALL):
if _optional_text(block, "SUB_NAME") != "PNL0001":
continue
alias = _required_text(block, "ALIAS")
connection = connections.get(alias)
if connection is None:
raise ValueError(f"PNL0001 line {alias!r} is absent from CONNECTION_SPECS")
real_parameters = _parameter_expressions(block, "RPARAM")
integer_parameters = _parameter_expressions(block, "IPARAM")
state_values = _evar_values(block)
specs.append(
TestMqlPnl0001Spec(
alias=alias,
source_component=str(connection["source_component"]),
source_port=str(connection["source_port"]),
target_component=str(connection["target_component"]),
target_port=str(connection["target_port"]),
diameter_mm=_required_numeric(
alias, "diam", real_parameters, numeric_globals
),
length_m=_required_numeric(alias, "le", real_parameters, numeric_globals),
relative_roughness=_required_numeric(
alias, "rr", real_parameters, numeric_globals
),
polytropic_constant=_required_numeric(
alias, "k", real_parameters, numeric_globals
),
heat_transfer_coefficient=_required_numeric(
alias, "kth", real_parameters, numeric_globals
),
external_temperature_k=_required_numeric(
alias, "extemp", real_parameters, numeric_globals
),
gas_type_index=int(
_required_numeric(alias, "gi", integer_parameters, numeric_globals)
),
mode=int(
_required_numeric(alias, "mode", integer_parameters, numeric_globals)
),
initial_temperature_k=_required_numeric(
alias, "t2", state_values, numeric_globals
),
initial_gauge_pressure_pa=_required_numeric(
alias, "p2", state_values, numeric_globals
),
)
)
if set(connections) != {spec.alias for spec in specs}:
missing = sorted(set(connections) - {spec.alias for spec in specs})
raise ValueError(f"Missing PNL0001 parameter blocks: {missing}")
return tuple(specs)
def _parameter_expressions(block: str, tag_name: str) -> dict[str, str]:
parameters = {}
for parameter_block in re.findall(
rf"<{tag_name}>.*?</{tag_name}>",
block,
flags=re.DOTALL,
):
parameters[_required_text(parameter_block, "VARNAME")] = _required_text(
parameter_block,
"VALUE",
)
return parameters
def _evar_values(block: str) -> dict[str, str]:
values = {}
for variable_block in re.findall(r"<EVAR>.*?</EVAR>", block, flags=re.DOTALL):
value = _optional_text(variable_block, "VALUE")
if value:
values[_required_text(variable_block, "VARNAME")] = value
return values
def _required_numeric(
alias: str,
name: str,
expressions: dict[str, str],
variables: dict[str, float],
) -> float:
if name not in expressions:
raise ValueError(f"Missing {name!r} on PNL0001 line {alias!r}")
value = resolve_numeric_expression(expressions[name], variables)
if value is None:
raise ValueError(
f"Cannot resolve {name!r}={expressions[name]!r} on PNL0001 line {alias!r}"
)
return value
def _required_text(block: str, tag_name: str) -> str:
value = _optional_text(block, tag_name)
if value is None:
raise ValueError(f"Missing AMESim circuit element: {tag_name}")
return value
def _optional_text(block: str, tag_name: str) -> str | None:
match = re.search(rf"<{tag_name}>(.*?)</{tag_name}>", block, flags=re.DOTALL)
return match.group(1).strip() if match is not None else None
@@ -0,0 +1,50 @@
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from PythonModels.components.amesim_pneumatic import (
HELIUM_PNEUMATIC_GAS,
AmesimPneumaticGas,
)
from PythonModels.components.amesim_pneumatic_line import AmesimPnl0001Pipe
from PythonModels.systems.test_mql_line_parameters import (
TestMqlPnl0001Spec,
load_test_mql_pnl0001_specs,
)
@dataclass(frozen=True)
class TestMqlPnl0001Assembly:
specs: tuple[TestMqlPnl0001Spec, ...]
lines: dict[str, AmesimPnl0001Pipe]
def spec(self, alias: str) -> TestMqlPnl0001Spec:
for spec in self.specs:
if spec.alias == alias:
return spec
raise KeyError(alias)
def build_test_mql_pnl0001_assembly(
archive_path: str | Path,
*,
gas: AmesimPneumaticGas = HELIUM_PNEUMATIC_GAS,
) -> TestMqlPnl0001Assembly:
specs = load_test_mql_pnl0001_specs(archive_path)
lines = {
spec.alias: AmesimPnl0001Pipe(
name=spec.alias,
diameter_mm=spec.diameter_mm,
length_m=spec.length_m,
relative_roughness=spec.relative_roughness,
polytropic_constant=spec.polytropic_constant,
heat_transfer_coefficient=spec.heat_transfer_coefficient,
external_temperature_k=spec.external_temperature_k,
gas=gas,
p0=spec.initial_absolute_pressure_pa,
T0=spec.initial_temperature_k,
)
for spec in specs
}
return TestMqlPnl0001Assembly(specs=specs, lines=lines)