openforma 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- forma_cli/__init__.py +5 -0
- forma_cli/app.py +1139 -0
- forma_cli/config.py +112 -0
- forma_cli/credentials.py +141 -0
- forma_cli/local.py +562 -0
- forma_cli/metadata_api.py +138 -0
- forma_cli/project_artifacts.py +182 -0
- forma_cli/sdk.py +571 -0
- forma_core/__init__.py +9 -0
- forma_core/__main__.py +4 -0
- forma_core/_version.py +3 -0
- forma_core/agents/__init__.py +50 -0
- forma_core/agents/clarification.py +194 -0
- forma_core/agents/component_reconciliation.py +99 -0
- forma_core/agents/context_gathering.py +115 -0
- forma_core/agents/continuous.py +537 -0
- forma_core/agents/contracts.py +247 -0
- forma_core/agents/firecrawl_mcp.py +484 -0
- forma_core/agents/lattice.py +239 -0
- forma_core/agents/orchestrator.py +3724 -0
- forma_core/agents/pipeline.py +843 -0
- forma_core/agents/project_correction.py +83 -0
- forma_core/agents/prompt_compaction.py +428 -0
- forma_core/agents/system_architecture.py +345 -0
- forma_core/agents/video_correction.py +119 -0
- forma_core/agents/web_research_workflow.py +1256 -0
- forma_core/agents/workflows.py +176 -0
- forma_core/assets/__init__.py +1 -0
- forma_core/assets/models.py +156 -0
- forma_core/assets/project.py +17 -0
- forma_core/assets/repository.py +48 -0
- forma_core/assets/service.py +142 -0
- forma_core/assets/validation.py +35 -0
- forma_core/benchmarks/__init__.py +5 -0
- forma_core/benchmarks/ir_triad_v1.py +477 -0
- forma_core/biology/__init__.py +28 -0
- forma_core/biology/benchmark.py +80 -0
- forma_core/biology/ewart_liverchip.py +279 -0
- forma_core/biology/ir.py +25 -0
- forma_core/biology/liverbench.py +416 -0
- forma_core/biology/liverbench_assay.py +251 -0
- forma_core/biology/liverbench_baselines.py +133 -0
- forma_core/biology/liverbench_independent.py +229 -0
- forma_core/biology/liverchip_demo.py +154 -0
- forma_core/biology/liverchip_evidence.py +149 -0
- forma_core/biology/models.py +247 -0
- forma_core/biology/validation.py +72 -0
- forma_core/cad_migrations/__init__.py +6 -0
- forma_core/cad_migrations/cli.py +101 -0
- forma_core/cad_migrations/emitters.py +227 -0
- forma_core/cad_migrations/models.py +121 -0
- forma_core/cad_migrations/planner.py +68 -0
- forma_core/chemistry/__init__.py +5 -0
- forma_core/chemistry/models.py +215 -0
- forma_core/chemistry/stoichiometry.py +272 -0
- forma_core/chemistry/validation.py +179 -0
- forma_core/cli/__init__.py +1 -0
- forma_core/cli/__main__.py +4 -0
- forma_core/cli/main.py +370 -0
- forma_core/config/__init__.py +28 -0
- forma_core/config/compatibility.py +282 -0
- forma_core/config/contract.py +184 -0
- forma_core/config/environment.py +129 -0
- forma_core/config/parti.py +34 -0
- forma_core/config/runtime.py +303 -0
- forma_core/control/__init__.py +10 -0
- forma_core/control/actions.py +136 -0
- forma_core/control/adapters.py +36 -0
- forma_core/control/cli.py +49 -0
- forma_core/control/client.py +124 -0
- forma_core/control/models.py +168 -0
- forma_core/control/opencode_worker.py +80 -0
- forma_core/control/package.py +318 -0
- forma_core/control/rover_scene/__init__.py +1 -0
- forma_core/control/rover_scene/__main__.py +34 -0
- forma_core/control/rover_scene/assets.py +65 -0
- forma_core/control/rover_scene/fleet.py +214 -0
- forma_core/control/rover_scene/host.py +258 -0
- forma_core/control/rover_scene/kinematics.py +35 -0
- forma_core/control/rover_scene/machine.py +347 -0
- forma_core/control/rover_scene/robot.py +166 -0
- forma_core/control/rover_scene/scene.py +206 -0
- forma_core/control/rover_scene/view.py +80 -0
- forma_core/control/rover_scene/web/index.html +25 -0
- forma_core/control/rover_scene/web/viewer.js +148 -0
- forma_core/control/runtime.py +356 -0
- forma_core/control/so101.py +235 -0
- forma_core/control/tasks.py +287 -0
- forma_core/database.py +2362 -0
- forma_core/debug.py +314 -0
- forma_core/domains/__init__.py +7 -0
- forma_core/domains/agents.py +85 -0
- forma_core/domains/base.py +69 -0
- forma_core/domains/benchmark.py +87 -0
- forma_core/domains/cli.py +48 -0
- forma_core/domains/compatibility.py +234 -0
- forma_core/domains/composition.py +372 -0
- forma_core/domains/diagnostics.py +15 -0
- forma_core/domains/generation.py +479 -0
- forma_core/domains/interaction.py +301 -0
- forma_core/domains/planning.py +140 -0
- forma_core/domains/providers.py +214 -0
- forma_core/domains/registry.py +267 -0
- forma_core/domains/selection.py +75 -0
- forma_core/domains/storage.py +60 -0
- forma_core/domains/tools.py +180 -0
- forma_core/electronics/__init__.py +1 -0
- forma_core/electronics/models.py +84 -0
- forma_core/electronics/primitives.py +43 -0
- forma_core/electronics/rules.py +340 -0
- forma_core/external_sources.py +497 -0
- forma_core/fabricator/__init__.py +33 -0
- forma_core/fabricator/__main__.py +7 -0
- forma_core/fabricator/main.py +578 -0
- forma_core/firmware/__init__.py +60 -0
- forma_core/firmware/drivers.py +140 -0
- forma_core/firmware/examples.py +503 -0
- forma_core/firmware/generate.py +520 -0
- forma_core/firmware/models.py +34 -0
- forma_core/firmware/sil/__init__.py +5 -0
- forma_core/firmware/sil/adapter.py +71 -0
- forma_core/firmware/sil/build.py +49 -0
- forma_core/firmware/sil/native/CMakeLists.txt +9 -0
- forma_core/firmware/sil/native/bridge.cpp +112 -0
- forma_core/firmware/sil/native/controller.cpp +123 -0
- forma_core/firmware/sil/native/controller.h +49 -0
- forma_core/firmware/sil/simulator.py +139 -0
- forma_core/firmware/targets.py +111 -0
- forma_core/firmware/validation.py +130 -0
- forma_core/fluidics/__init__.py +6 -0
- forma_core/fluidics/benchmark.py +217 -0
- forma_core/fluidics/calculations.py +79 -0
- forma_core/fluidics/examples.py +54 -0
- forma_core/fluidics/ir.py +25 -0
- forma_core/fluidics/models.py +132 -0
- forma_core/fluidics/topology.py +47 -0
- forma_core/fluidics/validation.py +134 -0
- forma_core/generation.py +32 -0
- forma_core/geometry_bindings/__init__.py +20 -0
- forma_core/geometry_bindings/cad_adapter.py +80 -0
- forma_core/geometry_bindings/models.py +163 -0
- forma_core/geometry_bindings/resolution.py +340 -0
- forma_core/geometry_bindings/tools.py +125 -0
- forma_core/image_providers.py +3049 -0
- forma_core/images.py +3 -0
- forma_core/integrations/__init__.py +1 -0
- forma_core/integrations/huggingface/__init__.py +29 -0
- forma_core/integrations/huggingface/huggingface_artifacts.py +272 -0
- forma_core/jobs/__init__.py +1 -0
- forma_core/jobs/context.py +277 -0
- forma_core/jobs/continuous.py +719 -0
- forma_core/jobs/metrics.py +124 -0
- forma_core/jobs/migrations.py +161 -0
- forma_core/jobs/persistence.py +28 -0
- forma_core/jobs/repositories.py +422 -0
- forma_core/jobs/schema.py +28 -0
- forma_core/jobs/source_usage.py +230 -0
- forma_core/jobs/store.py +476 -0
- forma_core/llm.py +3 -0
- forma_core/llm_providers.py +2682 -0
- forma_core/logs.py +107 -0
- forma_core/mechanics/__init__.py +1 -0
- forma_core/mechanics/gear_benchmark.py +85 -0
- forma_core/mechanics/mechanism_benchmarks.py +345 -0
- forma_core/mechanics/models.py +72 -0
- forma_core/mechanics/primitives.py +109 -0
- forma_core/mechanics/solid_cad.py +83 -0
- forma_core/observability.py +237 -0
- forma_core/openai_streams.py +780 -0
- forma_core/opencode/__init__.py +25 -0
- forma_core/opencode/architecture.py +82 -0
- forma_core/opencode/capabilities.py +130 -0
- forma_core/opencode/models.py +419 -0
- forma_core/opencode/persistence.py +62 -0
- forma_core/opencode/public_events.py +91 -0
- forma_core/opencode/schema.py +28 -0
- forma_core/opencode/store.py +874 -0
- forma_core/persistence/__init__.py +16 -0
- forma_core/persistence/base.py +38 -0
- forma_core/persistence/images.py +598 -0
- forma_core/persistence/migrations.py +200 -0
- forma_core/persistence/models.py +439 -0
- forma_core/persistence/project_artifacts.py +341 -0
- forma_core/persistence/project_reconciliation.py +1094 -0
- forma_core/persistence/providers/__init__.py +4 -0
- forma_core/persistence/providers/sqlite.py +114 -0
- forma_core/persistence/providers/supabase.py +31 -0
- forma_core/persistence/repositories/__init__.py +9 -0
- forma_core/persistence/repositories/base.py +335 -0
- forma_core/persistence/repositories/sqlite.py +1571 -0
- forma_core/persistence/repositories/supabase.py +1576 -0
- forma_core/persistence/schema.py +176 -0
- forma_core/processes/__init__.py +5 -0
- forma_core/processes/models.py +338 -0
- forma_core/processes/validation.py +141 -0
- forma_core/project_list_cache.py +316 -0
- forma_core/prompt_continuity.py +387 -0
- forma_core/providers/__init__.py +39 -0
- forma_core/providers/base.py +28 -0
- forma_core/providers/models.py +138 -0
- forma_core/providers/openai.py +92 -0
- forma_core/providers/openai_compatible.py +190 -0
- forma_core/providers/registry.py +68 -0
- forma_core/providers/registry_utils.py +46 -0
- forma_core/py.typed +1 -0
- forma_core/runtime.py +3 -0
- forma_core/selectors.py +36 -0
- forma_core/signups/__init__.py +5 -0
- forma_core/signups/models.py +49 -0
- forma_core/terminal/__init__.py +1 -0
- forma_core/terminal/dashboard.py +475 -0
- forma_core/terminal/images.py +156 -0
- forma_core/thermal/__init__.py +5 -0
- forma_core/thermal/models.py +361 -0
- forma_core/thermal/validation.py +175 -0
- forma_core/user_integrations.py +2069 -0
- forma_core/utils.py +291 -0
- forma_core/validation.py +83 -0
- forma_core/vertex_auth.py +92 -0
- forma_core/video_prompts.py +193 -0
- forma_core/video_review.py +1006 -0
- forma_core/wiring.py +356 -0
- forma_core/workers/__init__.py +120 -0
- forma_core/workers/contracts.py +183 -0
- forma_core/workers/generation.py +753 -0
- forma_core/workers/orchestration.py +805 -0
- forma_core/workers/registry.py +222 -0
- forma_core/workers/reverse_engineering.py +272 -0
- forma_core/workers/validation.py +291 -0
- forma_core/workspaces/__init__.py +5 -0
- forma_core/workspaces/chats/__init__.py +11 -0
- forma_core/workspaces/chats/models.py +48 -0
- forma_core/workspaces/context/__init__.py +15 -0
- forma_core/workspaces/context/agent.py +260 -0
- forma_core/workspaces/context/models.py +117 -0
- forma_core/workspaces/context/pdf.py +418 -0
- forma_core/workspaces/design_briefs/__init__.py +25 -0
- forma_core/workspaces/design_briefs/models.py +85 -0
- forma_core/workspaces/design_briefs/references.py +56 -0
- forma_core/workspaces/models.py +41 -0
- forma_core/workspaces/projects/__init__.py +88 -0
- forma_core/workspaces/projects/cad_generation.py +1016 -0
- forma_core/workspaces/projects/context_governance.py +365 -0
- forma_core/workspaces/projects/design_lifecycle.py +668 -0
- forma_core/workspaces/projects/fabrication/__init__.py +54 -0
- forma_core/workspaces/projects/fabrication/demo_printers.py +236 -0
- forma_core/workspaces/projects/fabrication/models.py +120 -0
- forma_core/workspaces/projects/fabrication/printer_config.py +205 -0
- forma_core/workspaces/projects/fabrication/slicers/__init__.py +7 -0
- forma_core/workspaces/projects/fabrication/slicers/base.py +25 -0
- forma_core/workspaces/projects/fabrication/slicers/cura.py +125 -0
- forma_core/workspaces/projects/fabrication/slicers/orca.py +208 -0
- forma_core/workspaces/projects/fabrication/slicing.py +202 -0
- forma_core/workspaces/projects/fabrication/validation.py +103 -0
- forma_core/workspaces/projects/gear_benchmark.py +6 -0
- forma_core/workspaces/projects/generation_mode.py +70 -0
- forma_core/workspaces/projects/identity.py +28 -0
- forma_core/workspaces/projects/iteration.py +680 -0
- forma_core/workspaces/projects/manifest.py +362 -0
- forma_core/workspaces/projects/mechanism_benchmarks.py +12 -0
- forma_core/workspaces/projects/models.py +913 -0
- forma_core/workspaces/projects/objects.py +731 -0
- forma_core/workspaces/projects/outcomes.py +47 -0
- forma_core/workspaces/projects/output.py +735 -0
- forma_core/workspaces/projects/resolver.py +397 -0
- forma_core/workspaces/projects/solid_cad.py +8 -0
- forma_core/workspaces/projects/state.py +622 -0
- forma_core/workspaces/readiness/__init__.py +28 -0
- forma_core/workspaces/readiness/evaluator.py +103 -0
- forma_core/workspaces/readiness/models.py +97 -0
- forma_core/workspaces/readiness/service.py +225 -0
- forma_core/workspaces/reverse_engineering/__init__.py +37 -0
- forma_core/workspaces/reverse_engineering/analyzer.py +246 -0
- forma_core/workspaces/reverse_engineering/models.py +128 -0
- forma_core/workspaces/validation/__init__.py +37 -0
- forma_core/workspaces/validation/evaluator.py +327 -0
- forma_core/workspaces/validation/models.py +146 -0
- forma_core/workspaces/validation/service.py +212 -0
- forma_core/workspaces/workflow/__init__.py +29 -0
- forma_core/workspaces/workflow/guard.py +33 -0
- forma_core/workspaces/workflow/models.py +77 -0
- forma_core/workspaces/workflow/service.py +287 -0
- openforma-0.4.0.dist-info/METADATA +247 -0
- openforma-0.4.0.dist-info/RECORD +288 -0
- openforma-0.4.0.dist-info/WHEEL +5 -0
- openforma-0.4.0.dist-info/entry_points.txt +4 -0
- openforma-0.4.0.dist-info/licenses/LICENSE +373 -0
- openforma-0.4.0.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""Offline, deterministic scoring against external fluid-system requirements."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Literal
|
|
10
|
+
|
|
11
|
+
from pydantic import BaseModel, Field, ValidationError, model_validator
|
|
12
|
+
|
|
13
|
+
from .models import FluidicModel, FluidicSystem, Identifier, NonNegative, Positive
|
|
14
|
+
from .topology import build_topology, reachable
|
|
15
|
+
from .validation import FluidicIssue, validate_fluidic_system
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class RequiredPath(FluidicModel):
|
|
19
|
+
"""Requested directed node-to-node path, optionally ending at an outlet kind."""
|
|
20
|
+
|
|
21
|
+
source_id: Identifier
|
|
22
|
+
target_id: Identifier
|
|
23
|
+
outlet_kind: Literal["waste", "product", "exhaust"] | None = None
|
|
24
|
+
|
|
25
|
+
@model_validator(mode="before")
|
|
26
|
+
@classmethod
|
|
27
|
+
def accept_legacy_waste_path(cls, value: Any) -> Any:
|
|
28
|
+
"""Read the original waste_id contract without weakening its semantics."""
|
|
29
|
+
if not isinstance(value, dict) or "waste_id" not in value:
|
|
30
|
+
return value
|
|
31
|
+
payload = dict(value)
|
|
32
|
+
waste_id = payload.pop("waste_id")
|
|
33
|
+
if "target_id" in payload and payload["target_id"] != waste_id:
|
|
34
|
+
raise ValueError("target_id and legacy waste_id must identify the same node.")
|
|
35
|
+
if payload.get("outlet_kind") not in (None, "waste"):
|
|
36
|
+
raise ValueError("Legacy waste_id requires outlet_kind='waste'.")
|
|
37
|
+
payload.update(target_id=waste_id, outlet_kind="waste")
|
|
38
|
+
return payload
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def waste_id(self) -> str | None:
|
|
42
|
+
"""Compatibility accessor for callers using the original waste-only API."""
|
|
43
|
+
return self.target_id if self.outlet_kind == "waste" else None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class RequiredMembrane(FluidicModel):
|
|
47
|
+
"""Task-required porous interface between two channel or chamber IDs."""
|
|
48
|
+
|
|
49
|
+
side_a_id: Identifier
|
|
50
|
+
side_b_id: Identifier
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class DimensionRange(FluidicModel):
|
|
54
|
+
"""Inclusive positive bounds in mm; at least one bound must be supplied."""
|
|
55
|
+
|
|
56
|
+
minimum: Positive | None = None
|
|
57
|
+
maximum: Positive | None = None
|
|
58
|
+
|
|
59
|
+
@model_validator(mode="after")
|
|
60
|
+
def validate_bounds(self) -> DimensionRange:
|
|
61
|
+
"""Reject empty or inverted ranges instead of silently passing them."""
|
|
62
|
+
if self.minimum is None and self.maximum is None:
|
|
63
|
+
raise ValueError("A dimension range requires a minimum or maximum in mm.")
|
|
64
|
+
if self.minimum is not None and self.maximum is not None and self.minimum > self.maximum:
|
|
65
|
+
raise ValueError("Dimension minimum must not exceed maximum.")
|
|
66
|
+
return self
|
|
67
|
+
|
|
68
|
+
def contains(self, value: float) -> bool:
|
|
69
|
+
"""Check a finite dimension against every supplied inclusive bound."""
|
|
70
|
+
return math.isfinite(value) and (self.minimum is None or value >= self.minimum) and (
|
|
71
|
+
self.maximum is None or value <= self.maximum
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class ChannelDimensionConstraints(FluidicModel):
|
|
76
|
+
"""Requested bounds for at least one rectangular channel dimension."""
|
|
77
|
+
|
|
78
|
+
length_mm: DimensionRange | None = None
|
|
79
|
+
width_mm: DimensionRange | None = None
|
|
80
|
+
height_mm: DimensionRange | None = None
|
|
81
|
+
|
|
82
|
+
@model_validator(mode="after")
|
|
83
|
+
def require_dimension(self) -> ChannelDimensionConstraints:
|
|
84
|
+
"""Reject constraints that do not select a dimension to evaluate."""
|
|
85
|
+
if self.length_mm is None and self.width_mm is None and self.height_mm is None:
|
|
86
|
+
raise ValueError("Supply at least one of length_mm, width_mm or height_mm.")
|
|
87
|
+
return self
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class FluidicBenchmarkSpec(FluidicModel):
|
|
91
|
+
"""Requirements come from the task, never inferred from the candidate itself."""
|
|
92
|
+
|
|
93
|
+
required_paths: list[RequiredPath] = Field(default_factory=list)
|
|
94
|
+
expected_flow_rates_ul_min: dict[Identifier, NonNegative] = Field(default_factory=dict)
|
|
95
|
+
required_membranes: list[RequiredMembrane] = Field(default_factory=list)
|
|
96
|
+
expected_channel_count: int | None = Field(
|
|
97
|
+
None, ge=1, strict=True, description="Exact number of all declared channel segments, including feed tubing.",
|
|
98
|
+
)
|
|
99
|
+
channel_dimensions: dict[Identifier, ChannelDimensionConstraints] = Field(
|
|
100
|
+
default_factory=dict, description="External dimension bounds in mm, keyed by required channel ID.",
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class FluidicBenchmarkResult(BaseModel):
|
|
105
|
+
"""Deterministic per-check scores and actionable failures for one candidate."""
|
|
106
|
+
|
|
107
|
+
score: float
|
|
108
|
+
passed: bool
|
|
109
|
+
checks: dict[str, bool]
|
|
110
|
+
issues: list[FluidicIssue] = Field(default_factory=list)
|
|
111
|
+
schema_errors: list[str] = Field(default_factory=list)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def score_fluidic_system(payload: Any, spec: FluidicBenchmarkSpec) -> FluidicBenchmarkResult:
|
|
115
|
+
"""Score raw fluidic JSON or a full IR; malformed schemas score zero."""
|
|
116
|
+
checks = dict.fromkeys([
|
|
117
|
+
"schema", "topology", "flow_constraints", "pressure_constraints",
|
|
118
|
+
"requested_paths", "requested_flows", "membranes", "isolation",
|
|
119
|
+
], False)
|
|
120
|
+
# Preserve the original eight-check score for specifications without these
|
|
121
|
+
# optional requirements; supplied requirements must never be skipped.
|
|
122
|
+
if spec.expected_channel_count is not None:
|
|
123
|
+
checks["channel_count"] = False
|
|
124
|
+
if spec.channel_dimensions:
|
|
125
|
+
checks["channel_dimensions"] = False
|
|
126
|
+
if isinstance(payload, dict) and "fluidic_system" in payload:
|
|
127
|
+
payload = payload["fluidic_system"]
|
|
128
|
+
try:
|
|
129
|
+
# Reparse models too, so mutated instances cannot bypass schema checks.
|
|
130
|
+
system = FluidicSystem.model_validate(payload.model_dump() if isinstance(payload, FluidicSystem) else payload)
|
|
131
|
+
except ValidationError as exc:
|
|
132
|
+
return FluidicBenchmarkResult(score=0, passed=False, checks=checks, schema_errors=[
|
|
133
|
+
f"{'.'.join(map(str, error['loc']))}: {error['msg']}" for error in exc.errors()
|
|
134
|
+
])
|
|
135
|
+
issues = validate_fluidic_system(system)
|
|
136
|
+
codes = {issue.code for issue in issues}
|
|
137
|
+
checks["schema"] = True
|
|
138
|
+
flow_codes = {code for code in codes if code.startswith(("flow_", "pump_flow_"))}
|
|
139
|
+
pressure_codes = {code for code in codes if code.startswith("pressure_")}
|
|
140
|
+
membrane_codes = {code for code in codes if code.startswith("membrane_")}
|
|
141
|
+
checks["topology"] = not (codes - flow_codes - pressure_codes - membrane_codes - {"circuit_mixing"})
|
|
142
|
+
checks["flow_constraints"] = not flow_codes
|
|
143
|
+
checks["pressure_constraints"] = not pressure_codes
|
|
144
|
+
graph = build_topology(system)
|
|
145
|
+
outlet_kinds = {outlet.id: outlet.kind for outlet in system.outlets}
|
|
146
|
+
outlet_kinds.update({r.id: "waste" for r in system.reservoirs if r.role == "waste"})
|
|
147
|
+
checks["requested_paths"] = all(
|
|
148
|
+
path.source_id in graph.nodes and path.target_id in graph.nodes
|
|
149
|
+
and path.target_id in reachable(graph.forward, {path.source_id})
|
|
150
|
+
and (path.outlet_kind is None or outlet_kinds.get(path.target_id) == path.outlet_kind)
|
|
151
|
+
for path in spec.required_paths
|
|
152
|
+
)
|
|
153
|
+
channels = {c.id: c for c in system.channels}
|
|
154
|
+
checks["requested_flows"] = all(
|
|
155
|
+
channel_id in channels and channels[channel_id].target_flow_rate_ul_min is not None
|
|
156
|
+
and math.isclose(channels[channel_id].target_flow_rate_ul_min, flow, rel_tol=1e-6, abs_tol=1e-9)
|
|
157
|
+
for channel_id, flow in spec.expected_flow_rates_ul_min.items()
|
|
158
|
+
)
|
|
159
|
+
membrane_pairs = {frozenset((m.side_a_id, m.side_b_id)) for m in system.membranes}
|
|
160
|
+
checks["membranes"] = not membrane_codes and all(
|
|
161
|
+
frozenset((m.side_a_id, m.side_b_id)) in membrane_pairs for m in spec.required_membranes
|
|
162
|
+
)
|
|
163
|
+
circuits = {c.id: graph.nodes[c.source_id].circuit_id for c in system.channels if c.source_id in graph.nodes}
|
|
164
|
+
circuits.update({c.id: c.circuit_id for c in system.chambers})
|
|
165
|
+
checks["isolation"] = "circuit_mixing" not in codes and all(
|
|
166
|
+
m.side_a_id in circuits and m.side_b_id in circuits and circuits[m.side_a_id] != circuits[m.side_b_id]
|
|
167
|
+
for m in spec.required_membranes
|
|
168
|
+
)
|
|
169
|
+
if spec.expected_channel_count is not None:
|
|
170
|
+
checks["channel_count"] = len(channels) == spec.expected_channel_count
|
|
171
|
+
if not checks["channel_count"]:
|
|
172
|
+
issues.append(FluidicIssue(
|
|
173
|
+
code="requested_channel_count", entity_id="system",
|
|
174
|
+
message=f"Expected {spec.expected_channel_count} channel segments; found {len(channels)}.",
|
|
175
|
+
))
|
|
176
|
+
if spec.channel_dimensions:
|
|
177
|
+
checks["channel_dimensions"] = True
|
|
178
|
+
for channel_id, dimensions in sorted(spec.channel_dimensions.items()):
|
|
179
|
+
channel = channels.get(channel_id)
|
|
180
|
+
if channel is None:
|
|
181
|
+
checks["channel_dimensions"] = False
|
|
182
|
+
issues.append(FluidicIssue(
|
|
183
|
+
code="requested_channel_missing", entity_id=channel_id,
|
|
184
|
+
message="Channel required by dimension constraints is missing.",
|
|
185
|
+
))
|
|
186
|
+
continue
|
|
187
|
+
for name in ("length_mm", "width_mm", "height_mm"):
|
|
188
|
+
bounds: DimensionRange | None = getattr(dimensions, name)
|
|
189
|
+
value: float = getattr(channel, name)
|
|
190
|
+
if bounds is not None and not bounds.contains(value):
|
|
191
|
+
checks["channel_dimensions"] = False
|
|
192
|
+
issues.append(FluidicIssue(
|
|
193
|
+
code="requested_dimension", entity_id=channel_id,
|
|
194
|
+
message=(f"{name}={value:g} mm violates inclusive bounds "
|
|
195
|
+
f"minimum={bounds.minimum}, maximum={bounds.maximum} mm "
|
|
196
|
+
"(None means unbounded)."),
|
|
197
|
+
))
|
|
198
|
+
return FluidicBenchmarkResult(
|
|
199
|
+
score=sum(checks.values()) / len(checks), passed=all(checks.values()), checks=checks,
|
|
200
|
+
issues=sorted(issues, key=lambda issue: (issue.code, issue.entity_id, issue.message)),
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def main() -> int:
|
|
205
|
+
"""Print a benchmark result and exit nonzero when a candidate fails."""
|
|
206
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
207
|
+
parser.add_argument("project", type=Path)
|
|
208
|
+
parser.add_argument("--spec", required=True, type=Path)
|
|
209
|
+
args = parser.parse_args()
|
|
210
|
+
spec = FluidicBenchmarkSpec.model_validate_json(args.spec.read_text(encoding="utf-8"))
|
|
211
|
+
result = score_fluidic_system(json.loads(args.project.read_text(encoding="utf-8")), spec)
|
|
212
|
+
print(result.model_dump_json(indent=2))
|
|
213
|
+
return 0 if result.passed else 1
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
if __name__ == "__main__":
|
|
217
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""SI-based estimates for rigid, straight, fully developed Newtonian liquid flow.
|
|
2
|
+
|
|
3
|
+
Rectangular resistance approximation: 12 mu L / (w h^3 (1 - 0.63 h/w)),
|
|
4
|
+
where h <= w. See docs/fluidics.md for sources, assumptions and limitations.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
|
|
11
|
+
from .models import FluidicChannel, FluidProperties
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class FlowCalculationError(ValueError):
|
|
15
|
+
"""A calculation is unsupported or lacks required physical inputs."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _number(value: float | None, name: str, *, zero: bool = False) -> float:
|
|
19
|
+
if value is None or not math.isfinite(value) or (value < 0 if zero else value <= 0):
|
|
20
|
+
raise FlowCalculationError(f"{name} must be supplied, finite and {'nonnegative' if zero else 'positive'}.")
|
|
21
|
+
return value
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def cross_sectional_area_mm2(channel: FluidicChannel) -> float:
|
|
25
|
+
"""Rectangular area in mm²."""
|
|
26
|
+
return _number(channel.width_mm, "width_mm") * _number(channel.height_mm, "height_mm")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def channel_volume_ul(channel: FluidicChannel) -> float:
|
|
30
|
+
"""Internal channel volume; 1 mm³ = 1 µL."""
|
|
31
|
+
return cross_sectional_area_mm2(channel) * _number(channel.length_mm, "length_mm")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def average_velocity_mm_s(channel: FluidicChannel) -> float:
|
|
35
|
+
"""Mean velocity using the supplied target flow (µL/min)."""
|
|
36
|
+
return _number(channel.target_flow_rate_ul_min, "target_flow_rate_ul_min", zero=True) / 60 / cross_sectional_area_mm2(channel)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def residence_time_s(channel: FluidicChannel) -> float:
|
|
40
|
+
"""Nominal volume/flow time; zero flow has no finite residence time."""
|
|
41
|
+
return channel_volume_ul(channel) * 60 / _number(channel.target_flow_rate_ul_min, "target_flow_rate_ul_min")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _liquid_properties(fluid: FluidProperties) -> tuple[float, float]:
|
|
45
|
+
if fluid.phase != "liquid" or not fluid.newtonian:
|
|
46
|
+
raise FlowCalculationError("This estimate requires an incompressible Newtonian liquid.")
|
|
47
|
+
return (
|
|
48
|
+
_number(fluid.dynamic_viscosity_pa_s, "dynamic_viscosity_pa_s"),
|
|
49
|
+
_number(fluid.density_kg_m3, "density_kg_m3"),
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def reynolds_number(channel: FluidicChannel, fluid: FluidProperties) -> float:
|
|
54
|
+
"""Re based on hydraulic diameter, using explicit viscosity and density."""
|
|
55
|
+
if channel.fluid != fluid.id:
|
|
56
|
+
raise FlowCalculationError(f"Channel fluid '{channel.fluid}' does not match properties '{fluid.id}'.")
|
|
57
|
+
viscosity, density = _liquid_properties(fluid)
|
|
58
|
+
area = cross_sectional_area_mm2(channel)
|
|
59
|
+
diameter_m = 2 * area / (channel.width_mm + channel.height_mm) * 1e-3
|
|
60
|
+
return density * average_velocity_mm_s(channel) * 1e-3 * diameter_m / viscosity
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def pressure_drop_kpa(channel: FluidicChannel, fluid: FluidProperties) -> float:
|
|
64
|
+
"""Approximate rectangular-channel Δp; reject Re >= 2000 rather than extrapolate."""
|
|
65
|
+
if reynolds_number(channel, fluid) >= 2000:
|
|
66
|
+
raise FlowCalculationError("Laminar estimate requires Reynolds number < 2000.")
|
|
67
|
+
viscosity, _ = _liquid_properties(fluid)
|
|
68
|
+
height, width = sorted((channel.height_mm * 1e-3, channel.width_mm * 1e-3))
|
|
69
|
+
length = _number(channel.length_mm, "length_mm") * 1e-3
|
|
70
|
+
flow = _number(channel.target_flow_rate_ul_min, "target_flow_rate_ul_min", zero=True) * 1e-9 / 60
|
|
71
|
+
return 12 * viscosity * length * flow / (width * height**3 * (1 - 0.63 * height / width)) / 1000
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def mean_wall_shear_stress_pa(channel: FluidicChannel, fluid: FluidProperties) -> float:
|
|
75
|
+
"""Wetted-perimeter mean Δp A/(L P), not the local cell-surface shear."""
|
|
76
|
+
pressure_pa = pressure_drop_kpa(channel, fluid) * 1000
|
|
77
|
+
area_m2 = cross_sectional_area_mm2(channel) * 1e-6
|
|
78
|
+
perimeter_m = 2 * (channel.width_mm + channel.height_mm) * 1e-3
|
|
79
|
+
return pressure_pa * area_m2 / (channel.length_mm * 1e-3 * perimeter_m)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Reproducible organ-chip fixture; values are declared demonstration inputs."""
|
|
2
|
+
|
|
3
|
+
from .models import (
|
|
4
|
+
FluidicChannel, FluidicChamber, FluidicInlet, FluidicMembrane,
|
|
5
|
+
FluidicOutlet, FluidicPump, FluidicSystem, FluidicValve, FluidProperties,
|
|
6
|
+
)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def organ_on_chip_system(*, dosing: bool = False) -> FluidicSystem:
|
|
10
|
+
"""Two liquid circuits with separate waste outlets and a porous interface.
|
|
11
|
+
|
|
12
|
+
Optional dosing joins the vascular chamber only. It adds 5 µL/min to the
|
|
13
|
+
downstream vascular channel; the independent epithelial circuit is unchanged.
|
|
14
|
+
"""
|
|
15
|
+
system = FluidicSystem(fluids=[FluidProperties(
|
|
16
|
+
id="demo_medium", dynamic_viscosity_pa_s=0.001, density_kg_m3=1000,
|
|
17
|
+
temperature_c=22, provenance="Illustrative water-like inputs at 22 C; not measured culture-medium data.",
|
|
18
|
+
)])
|
|
19
|
+
for circuit, flow in [("vascular", 30.0), ("epithelial", 10.0)]:
|
|
20
|
+
inlet, pump, chamber, waste = [f"{circuit}_{suffix}" for suffix in ("inlet", "pump", "chamber", "waste")]
|
|
21
|
+
system.inlets.append(FluidicInlet(id=inlet, circuit_id=circuit))
|
|
22
|
+
system.pumps.append(FluidicPump(id=pump, circuit_id=circuit, target_flow_rate_ul_min=flow, max_flow_rate_ul_min=60))
|
|
23
|
+
system.chambers.append(FluidicChamber(
|
|
24
|
+
id=chamber, circuit_id=circuit, volume_ul=2, inlet_ids=[f"{circuit}_feed"],
|
|
25
|
+
outlet_ids=[f"{circuit}_channel"], contents=f"{circuit.title()} perfusion distribution chamber", temperature_c=22,
|
|
26
|
+
))
|
|
27
|
+
system.outlets.append(FluidicOutlet(id=waste, circuit_id=circuit))
|
|
28
|
+
for suffix, source, target, length in [
|
|
29
|
+
("supply", inlet, pump, 5), ("feed", pump, chamber, 5), ("channel", chamber, waste, 20),
|
|
30
|
+
]:
|
|
31
|
+
system.channels.append(FluidicChannel(
|
|
32
|
+
id=f"{circuit}_{suffix}", source_id=source, target_id=target,
|
|
33
|
+
length_mm=length, width_mm=1, height_mm=0.2, material="PDMS", fluid="demo_medium",
|
|
34
|
+
target_flow_rate_ul_min=flow, max_flow_rate_ul_min=60, max_pressure_kpa=5,
|
|
35
|
+
pump_id=pump if pump in (source, target) else None,
|
|
36
|
+
))
|
|
37
|
+
system.membranes.append(FluidicMembrane(
|
|
38
|
+
id="porous_interface", side_a_id="vascular_channel", side_b_id="epithelial_channel",
|
|
39
|
+
material="porous PET", thickness_mm=0.01, pore_size_um=0.4, porosity=0.1,
|
|
40
|
+
))
|
|
41
|
+
if dosing:
|
|
42
|
+
system.inlets.append(FluidicInlet(id="dose_inlet", circuit_id="vascular"))
|
|
43
|
+
system.valves.append(FluidicValve(id="dose_valve", circuit_id="vascular"))
|
|
44
|
+
for name, source, target in [
|
|
45
|
+
("dose_supply", "dose_inlet", "dose_valve"),
|
|
46
|
+
("dose_channel", "dose_valve", "vascular_chamber"),
|
|
47
|
+
]:
|
|
48
|
+
system.channels.append(FluidicChannel(
|
|
49
|
+
id=name, source_id=source, target_id=target, length_mm=5, width_mm=1, height_mm=0.2,
|
|
50
|
+
material="PDMS", fluid="demo_medium", target_flow_rate_ul_min=5, valve_id="dose_valve",
|
|
51
|
+
))
|
|
52
|
+
system.chambers[0].inlet_ids.append("dose_channel")
|
|
53
|
+
next(c for c in system.channels if c.id == "vascular_channel").target_flow_rate_ul_min = 35
|
|
54
|
+
return FluidicSystem.model_validate(system.model_dump())
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Versioned domain envelope around the existing reusable fluid network."""
|
|
2
|
+
|
|
3
|
+
from typing import Literal
|
|
4
|
+
|
|
5
|
+
from pydantic import Field
|
|
6
|
+
|
|
7
|
+
from forma_core.domains.base import DomainDocument, DomainModel, Text
|
|
8
|
+
from .models import FluidicSystem
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class FluidicContext(DomainModel):
|
|
12
|
+
"""Fluid-specific authoring inputs, with explicit operating requirements."""
|
|
13
|
+
|
|
14
|
+
scope: Text
|
|
15
|
+
fluid_properties: list[Text] = Field(min_length=1)
|
|
16
|
+
operating_conditions: list[Text] = Field(min_length=1)
|
|
17
|
+
flow_requirements: list[Text] = Field(min_length=1)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class FluidicIR(DomainDocument):
|
|
21
|
+
"""Version the envelope while retaining FluidicSystem and its validators."""
|
|
22
|
+
|
|
23
|
+
domain: Literal["fluidic"] = "fluidic"
|
|
24
|
+
schema_version: Literal["1.0"] = "1.0"
|
|
25
|
+
system: FluidicSystem
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Reusable fluid-network primitives behind an additive Hardware IR boundary."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Annotated, Literal
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
|
8
|
+
|
|
9
|
+
Identifier = Annotated[str, Field(min_length=1, pattern=r"^[A-Za-z0-9][A-Za-z0-9_.-]*$")]
|
|
10
|
+
Positive = Annotated[float, Field(gt=0, allow_inf_nan=False)]
|
|
11
|
+
NonNegative = Annotated[float, Field(ge=0, allow_inf_nan=False)]
|
|
12
|
+
Text = Annotated[str, Field(min_length=1)]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class FluidicModel(BaseModel):
|
|
16
|
+
"""Shared strict-field, finite-number contract for fluid-specific models."""
|
|
17
|
+
|
|
18
|
+
model_config = ConfigDict(extra="forbid", allow_inf_nan=False, str_strip_whitespace=True)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class FluidProperties(FluidicModel):
|
|
22
|
+
"""Explicit properties at the declared temperature; no water-like defaults."""
|
|
23
|
+
|
|
24
|
+
id: Identifier
|
|
25
|
+
phase: Literal["liquid", "gas"] = "liquid"
|
|
26
|
+
dynamic_viscosity_pa_s: Positive | None = None
|
|
27
|
+
density_kg_m3: Positive | None = None
|
|
28
|
+
temperature_c: float | None = None
|
|
29
|
+
newtonian: bool = True
|
|
30
|
+
provenance: Text | None = None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class FluidicNode(FluidicModel):
|
|
34
|
+
"""Addressable bulk-flow component belonging to one isolation circuit."""
|
|
35
|
+
|
|
36
|
+
id: Identifier
|
|
37
|
+
circuit_id: Identifier = Field("default", description="Bulk-fluid isolation group. Channels cannot cross groups.")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class FluidicInlet(FluidicNode):
|
|
41
|
+
"""Boundary source. Every declared inlet requires a path to a sink."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class FluidicOutlet(FluidicNode):
|
|
45
|
+
"""Terminal boundary that collects waste, product or exhaust."""
|
|
46
|
+
|
|
47
|
+
kind: Literal["waste", "product", "exhaust"] = "waste"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class FluidicReservoir(FluidicNode):
|
|
51
|
+
"""Supply, mixing junction or waste container with volume in microlitres."""
|
|
52
|
+
|
|
53
|
+
volume_ul: Positive
|
|
54
|
+
role: Literal["supply", "junction", "waste"] = "junction"
|
|
55
|
+
contents: Text
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class FluidicPump(FluidicNode):
|
|
59
|
+
"""Inline flow source with optional target and capacity in microlitres/min."""
|
|
60
|
+
|
|
61
|
+
target_flow_rate_ul_min: NonNegative | None = None
|
|
62
|
+
max_flow_rate_ul_min: NonNegative | None = None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class FluidicValve(FluidicNode):
|
|
66
|
+
"""Inline valve in the nominal open flow configuration (no control simulation)."""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class FluidicChannel(FluidicModel):
|
|
70
|
+
"""Directed rectangular conduit with mm geometry and explicit flow metadata."""
|
|
71
|
+
|
|
72
|
+
id: Identifier
|
|
73
|
+
source_id: Identifier
|
|
74
|
+
target_id: Identifier
|
|
75
|
+
length_mm: Positive
|
|
76
|
+
width_mm: Positive
|
|
77
|
+
height_mm: Positive
|
|
78
|
+
material: Text
|
|
79
|
+
fluid: Text = Field(description="Fluid name; match FluidProperties.id to enable pressure calculations.")
|
|
80
|
+
target_flow_rate_ul_min: NonNegative | None = None
|
|
81
|
+
min_flow_rate_ul_min: NonNegative | None = None
|
|
82
|
+
max_flow_rate_ul_min: NonNegative | None = None
|
|
83
|
+
max_pressure_kpa: Positive | None = Field(None, description="Maximum channel pressure DROP, not absolute pressure.")
|
|
84
|
+
pump_id: Identifier | None = Field(None, description="Optional inline pump; must be a channel endpoint.")
|
|
85
|
+
valve_id: Identifier | None = Field(None, description="Optional inline valve; must be a channel endpoint.")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class FluidicChamber(FluidicNode):
|
|
89
|
+
"""Flow-through volume in microlitres with incident channel IDs as ports."""
|
|
90
|
+
|
|
91
|
+
volume_ul: Positive
|
|
92
|
+
inlet_ids: list[Identifier] = Field(min_length=1, description="All incoming channel IDs, not boundary inlet IDs.")
|
|
93
|
+
outlet_ids: list[Identifier] = Field(min_length=1, description="All outgoing channel IDs.")
|
|
94
|
+
contents: Text
|
|
95
|
+
temperature_c: float | None = None
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class FluidicMembrane(FluidicModel):
|
|
99
|
+
"""Interface between isolated channels/chambers, never a bulk-flow graph edge."""
|
|
100
|
+
|
|
101
|
+
id: Identifier
|
|
102
|
+
side_a_id: Identifier
|
|
103
|
+
side_b_id: Identifier
|
|
104
|
+
material: Text
|
|
105
|
+
thickness_mm: Positive
|
|
106
|
+
pore_size_um: Positive | None = None
|
|
107
|
+
porosity: Annotated[float, Field(gt=0, le=1, allow_inf_nan=False)] | None = None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class FluidicSystem(FluidicModel):
|
|
111
|
+
"""Optional Hardware IR subsystem; run validation to check its network."""
|
|
112
|
+
|
|
113
|
+
inlets: list[FluidicInlet] = Field(default_factory=list)
|
|
114
|
+
outlets: list[FluidicOutlet] = Field(default_factory=list)
|
|
115
|
+
reservoirs: list[FluidicReservoir] = Field(default_factory=list)
|
|
116
|
+
channels: list[FluidicChannel] = Field(default_factory=list)
|
|
117
|
+
chambers: list[FluidicChamber] = Field(default_factory=list)
|
|
118
|
+
pumps: list[FluidicPump] = Field(default_factory=list)
|
|
119
|
+
valves: list[FluidicValve] = Field(default_factory=list)
|
|
120
|
+
membranes: list[FluidicMembrane] = Field(default_factory=list)
|
|
121
|
+
fluids: list[FluidProperties] = Field(default_factory=list)
|
|
122
|
+
|
|
123
|
+
@model_validator(mode="after")
|
|
124
|
+
def unique_ids(self) -> FluidicSystem:
|
|
125
|
+
"""Reject duplicate identifiers across every fluidic entity collection."""
|
|
126
|
+
seen: set[str] = set()
|
|
127
|
+
for collection in type(self).model_fields:
|
|
128
|
+
for entity in getattr(self, collection):
|
|
129
|
+
if entity.id in seen:
|
|
130
|
+
raise ValueError(f"Duplicate fluidic ID '{entity.id}'.")
|
|
131
|
+
seen.add(entity.id)
|
|
132
|
+
return self
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Directed bulk-flow graph. Membranes are deliberately not flow edges."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from .models import FluidicNode, FluidicSystem
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class FluidicTopology:
|
|
12
|
+
"""Node indexes and forward/reverse adjacency for declared bulk-flow edges."""
|
|
13
|
+
|
|
14
|
+
nodes: dict[str, FluidicNode]
|
|
15
|
+
sources: set[str]
|
|
16
|
+
sinks: set[str]
|
|
17
|
+
forward: dict[str, set[str]]
|
|
18
|
+
reverse: dict[str, set[str]]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def reachable(adjacency: dict[str, set[str]], starts: set[str]) -> set[str]:
|
|
22
|
+
"""Iterative traversal that terminates even for recirculating networks."""
|
|
23
|
+
visited: set[str] = set()
|
|
24
|
+
pending = list(starts)
|
|
25
|
+
while pending:
|
|
26
|
+
current = pending.pop()
|
|
27
|
+
if current not in visited:
|
|
28
|
+
visited.add(current)
|
|
29
|
+
pending.extend(adjacency.get(current, set()) - visited)
|
|
30
|
+
return visited
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def build_topology(system: FluidicSystem) -> FluidicTopology:
|
|
34
|
+
"""Build indexes without treating unresolved references as real nodes."""
|
|
35
|
+
nodes = {node.id: node for node in [
|
|
36
|
+
*system.inlets, *system.outlets, *system.reservoirs,
|
|
37
|
+
*system.chambers, *system.pumps, *system.valves,
|
|
38
|
+
]}
|
|
39
|
+
sources = {item.id for item in system.inlets} | {r.id for r in system.reservoirs if r.role == "supply"}
|
|
40
|
+
sinks = {item.id for item in system.outlets} | {r.id for r in system.reservoirs if r.role == "waste"}
|
|
41
|
+
forward: dict[str, set[str]] = {node: set() for node in nodes}
|
|
42
|
+
reverse: dict[str, set[str]] = {node: set() for node in nodes}
|
|
43
|
+
for channel in system.channels:
|
|
44
|
+
if channel.source_id in nodes and channel.target_id in nodes:
|
|
45
|
+
forward[channel.source_id].add(channel.target_id)
|
|
46
|
+
reverse[channel.target_id].add(channel.source_id)
|
|
47
|
+
return FluidicTopology(nodes, sources, sinks, forward, reverse)
|