catopt-graph-graph-calculus.../core/bridge.py

64 lines
2.5 KiB
Python

from typing import Dict, Any
def to_canonical(local_problem: Dict[str, Any]) -> Dict[str, Any]:
"""
Minimal bridge: map a LocalProblem into a canonical representation.
In a full MVP this would be a richer translation; here we preserve shape.
"""
# Canonicalize to an object_id form, accommodating both dicts and objects.
if isinstance(local_problem, dict):
object_id = local_problem.get("object_id") or local_problem.get("id")
domain = local_problem.get("domain", "unknown")
objective = local_problem.get("objective")
variables = local_problem.get("variables", {})
else:
object_id = getattr(local_problem, "asset_id", None) or getattr(local_problem, "id", None)
domain = getattr(local_problem, "domain", "unknown")
objective = getattr(local_problem, "objective", None)
variables = getattr(local_problem, "variables", {})
canonical = {
"LocalProblem": {
"object_id": object_id,
"domain": domain,
"objective": objective,
"variables": variables,
}
}
return canonical
def from_canonical(canonical: Dict[str, Any]) -> Dict[str, Any]:
"""
Inverse mapping from canonical representation back to a LocalProblem-like dict.
"""
lp = canonical.get("LocalProblem", {})
if isinstance(lp, dict):
asset_id = lp.get("object_id") or lp.get("id") or lp.get("asset_id")
payload = lp.get("variables") if "variables" in lp else lp.get("payload", {})
try:
from .contracts import LocalProblem as DomainLocalProblem # type: ignore
return DomainLocalProblem(asset_id=asset_id or "", payload=payload or {})
except Exception:
# Fallback to a dict-like response if domain class couldn't be imported
return {"asset_id": asset_id or "", "payload": payload or {}}
# Fallback: return input as-is
return canonical
class CatOptBridge:
"""Backward-compatible bridge facade for CatOpt-Graph canonical mapping.
This class exposes the canonical mapping methods expected by the tests
(static methods to_canonical / from_canonical) and delegates to the
module-level implementations for the actual logic.
"""
@staticmethod
def to_canonical(local_problem: Dict[str, Any]) -> Dict[str, Any]:
return to_canonical(local_problem)
@staticmethod
def from_canonical(canonical: Dict[str, Any]) -> Any:
return from_canonical(canonical)