206 changes: 171 additions & 35 deletions bionetgen/core/tools/bngsim_bridge.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1201,6 +1201,21 @@ def _nfsim_session_kwargs(nf_params):

_BNGSIM_NETWORK_METHODS = frozenset({"ode", "ssa", "psa", "rm"})

# Every method string BNG2.pl's simulate() accepts: its $METHODS hash keys
# (cvode, ssa, pla, psa, nf) plus the documented 'ode' alias for 'cvode',
# extended with 'rm' (RuleMonkey), which the bridge rewrites onto the nf
# backend. A method outside this set is malformed — BNG2.pl itself rejects it
# ("Simulation method '...' is not a valid option.") — so the router surfaces
# it as an error rather than silently shipping it to the legacy stack.
_KNOWN_BNGL_METHODS = frozenset({"ode", "cvode", "ssa", "psa", "pla", "nf", "rm"})

# Methods that need an optional BNGsim component the build may lack: nf needs
# NFsim, rm (RuleMonkey) needs the RuleMonkey session. BNGsim *can* run these
# when the component is present, so an absent component is a build incapability
# (surfaced as an error under strict simulator='bngsim', legacy fallback under
# auto) rather than a categorical one like pla.
_BNGSIM_OPTIONAL_COMPONENT_METHODS = frozenset({"nf", "rm"})

_BNGL_ROUTING_COMPLEX_ACTIONS = frozenset(
{
"parameter_scan",
Expand DownExpand Up@@ -1235,8 +1250,15 @@ def _nfsim_session_kwargs(nf_params):
)


def _method_supported_by_bngsim_for_routing(method, bngsim_has_nfsim=None):
def _method_supported_by_bngsim_for_routing(
method, bngsim_has_nfsim=None, bngsim_has_rulemonkey=None
):
"""Return True if a normalized method can be handed to BNGsim."""
if method == "rm":
# RuleMonkey is an optional BNGsim component, like NFsim for nf.
if bngsim_has_rulemonkey is None:
bngsim_has_rulemonkey = BNGSIM_HAS_RULEMONKEY
return bool(bngsim_has_rulemonkey)
if method in _BNGSIM_NETWORK_METHODS:
return True
if _is_nf_method(method):
Expand All@@ -1246,6 +1268,49 @@ def _method_supported_by_bngsim_for_routing(method, bngsim_has_nfsim=None):
return False


def _unsupported_method_route(method_name, simulator="auto"):
"""Route a (non-PLA) method the direct BNGsim path can't run.

Three cases:

* A valid method that needs an optional BNGsim component the build lacks
(``nf`` without NFsim, ``rm`` without RuleMonkey) is a *build*
incapability: BNGsim could run it with the component installed, so a
strict ``simulator='bngsim'`` request surfaces it as an error while
``auto`` falls back to legacy.
* Another known method the BNGsim path doesn't drive directly (e.g. the
``cvode`` alias) keeps the legacy subprocess route in every mode.
* A method outside the valid BNG universe is malformed — BNG2.pl rejects
it too — so it errors in every mode rather than silently going legacy.
"""
if method_name not in _KNOWN_BNGL_METHODS:
return BngsimRouteDecision(
ROUTE_ERROR,
f"BNGL method '{method_name}' is not a recognized simulation method "
"(expected one of ode, ssa, pla, psa, nf).",
method=method_name,
)
if method_name in _BNGSIM_OPTIONAL_COMPONENT_METHODS:
component = "NFsim" if _is_nf_method(method_name) else "RuleMonkey"
if simulator == "bngsim":
return BngsimRouteDecision(
ROUTE_ERROR,
f"simulator='bngsim' was requested but method '{method_name}' "
f"requires BNGsim {component} support, which this build lacks.",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGsim {component} support is unavailable; using legacy route.",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)


def _bngl_action_method_for_routing(action):
"""Extract only the method hint needed for conservative routing.

Expand DownExpand Up@@ -1310,9 +1375,16 @@ def _bngl_has_protocol_block(bngl_path):
# on its next run (matters for long-lived consumers like the VS Code
# extension).
_CACHE_MISS = object()
# key: (abspath, st_mtime_ns, st_size); value: parsed actions list (or None).
_ROUTING_ACTIONS_CACHE: dict[tuple[str, int, int], list | None] = {}
# key: (abspath, st_mtime_ns, st_size); value: (actions list or None, parse
# failure reason or None). The reason rides along so a strict
# ``simulator='bngsim'`` request can surface *why* inspection failed instead
# of silently downgrading to the legacy subprocess route (see issue #109).
_ROUTING_ACTIONS_CACHE: dict[tuple[str, int, int], tuple[list | None, str | None]] = {}
_ROUTING_ACTIONS_CACHE_MAX = 128
# Paths already warned about in auto mode, so a model whose actions can't be
# inspected for BNGsim routing produces one WARNING per run, not one per the
# ~4 routing queries each ``bionetgen.run`` makes for the same file.
_ROUTING_INSPECT_WARNED: set[str] = set()


def _clear_routing_actions_cache():
Expand All@@ -1321,16 +1393,18 @@ def _clear_routing_actions_cache():
never needs this because the cache key invalidates on file change.
"""
_ROUTING_ACTIONS_CACHE.clear()
_ROUTING_INSPECT_WARNED.clear()


def _load_bngl_actions_for_routing(bngl_path):
"""Parse BNGL actions for routing only — memoized per file identity.
def _load_bngl_routing_actions(bngl_path):
"""Parse BNGL actions for routing — memoized per file identity.

Returns the parsed action items (treat the list as read-only — routing
callers never mutate it) or ``None`` when the file cannot be parsed.
Parse failures fall back to BNG2.pl rather than blocking the legacy
path, and the ``None`` is cached too so a failing parse is not retried
several times per run.
Returns ``(actions, reason)``: the parsed action items (treat the list as
read-only — routing callers never mutate it) with ``reason=None``, or
``(None, reason)`` when the file cannot be parsed, where ``reason`` is the
underlying parse message. Parse failures fall back to BNG2.pl rather than
blocking the legacy path, and the failure is cached too so a failing parse
is not retried several times per run.
"""
try:
st = os.stat(bngl_path)
Expand All@@ -1341,46 +1415,85 @@ def _load_bngl_actions_for_routing(bngl_path):
cached = _ROUTING_ACTIONS_CACHE.get(key, _CACHE_MISS)
if cached is not _CACHE_MISS:
return cached
actions = _parse_bngl_actions_for_routing(bngl_path)
result = _parse_bngl_actions_for_routing(bngl_path)
if len(_ROUTING_ACTIONS_CACHE) >= _ROUTING_ACTIONS_CACHE_MAX:
# FIFO eviction — drop the oldest entry (dicts keep insertion order).
_ROUTING_ACTIONS_CACHE.pop(next(iter(_ROUTING_ACTIONS_CACHE)), None)
_ROUTING_ACTIONS_CACHE[key] = actions
return actions
_ROUTING_ACTIONS_CACHE[key] = result
return result


def _load_bngl_actions_for_routing(bngl_path):
"""Memoized routing action list (or ``None`` on parse failure).

Thin wrapper over :func:`_load_bngl_routing_actions` for callers that
only need the action items, not the parse-failure reason.
"""
return _load_bngl_routing_actions(bngl_path)[0]


def _parse_bngl_actions_for_routing(bngl_path):
"""Parse a BNGL file's action items via a throwaway ``bngmodel``.

Uncached — :func:`_load_bngl_actions_for_routing` is the memoized
entry point callers should use.
Returns ``(actions, reason)`` — the action list with ``reason=None`` on
success, or ``(None, reason)`` with the parse message on failure. Uncached
— :func:`_load_bngl_routing_actions` is the memoized entry point callers
should use.
"""
try:
import bionetgen.modelapi.model as mdl

model = mdl.bngmodel(bngl_path)
except Exception as exc:
logger.debug("could not parse BNGL for BNGsim routing (%s): %s", bngl_path, exc)
return None
return None, str(exc) or exc.__class__.__name__
try:
return list(model.actions.items)
return list(model.actions.items), None
except Exception as exc:
logger.debug(
"could not read BNGL actions for BNGsim routing (%s): %s", bngl_path, exc
)
return None
return None, str(exc) or exc.__class__.__name__


def _warn_routing_inspection_fallback_once(bngl_path, reason):
"""Warn once per file when auto-mode can't inspect a BNGL's actions for
BNGsim routing and falls back to the legacy subprocess engine."""
try:
key = os.path.abspath(bngl_path)
except Exception:
key = bngl_path
if key in _ROUTING_INSPECT_WARNED:
return
_ROUTING_INSPECT_WARNED.add(key)
logger.warning(
"Could not inspect BNGL actions for BNGsim routing (%s): %s. Using the "
"legacy subprocess (BNG2.pl) route. Pass simulator='bngsim' to require "
"BNGsim and surface this as an error instead.",
bngl_path,
reason,
)


def _classify_bngl_actions_for_bngsim(
actions_items,
method=None,
has_protocol=False,
bngsim_has_nfsim=None,
bngsim_has_rulemonkey=None,
simulator="auto",
):
"""Classify whether BNGL can use the BNG2.pl-owned BNGsim backend hook.

This routing pass only reads action names and method hints. It does not
evaluate BNGL expressions or replay any action semantics in Python.

``simulator`` affects the declines BNGsim *could* satisfy: under a strict
``simulator='bngsim'`` request an *unrecognized action* (runnable via the
BNG2.pl backend hook) and a *build incapability* (``nf`` without NFsim,
``rm`` without RuleMonkey) are surfaced as ``ROUTE_ERROR`` instead of
silently running legacy; ``auto`` falls back. PLA is a categorical BNGsim
incapability and stays on the subprocess route in every mode.
"""
if actions_items is None:
return BngsimRouteDecision(
Expand DownExpand Up@@ -1416,10 +1529,17 @@ def _classify_bngl_actions_for_bngsim(
continue

if atype is not None:
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL action '{atype}' is not a conservative BNGsim route",
)
reason = f"BNGL action '{atype}' is not a conservative BNGsim route"
if simulator == "bngsim":
# Strict mode: BNGsim could run this through the BNG2.pl
# backend hook, but the router can't confirm an unrecognized
# action is safe to delegate. Surface it instead of silently
# downgrading to legacy (issue #109 contract).
return BngsimRouteDecision(
ROUTE_ERROR,
f"simulator='bngsim' was requested but {reason}.",
)
return BngsimRouteDecision(ROUTE_SUBPROCESS, reason)

if len(sim_actions) > 1:
has_backend_hook_workflow = True
Expand DownExpand Up@@ -1458,17 +1578,15 @@ def _classify_bngl_actions_for_bngsim(
"BNGL PLA is not supported by BNGsim",
method="pla",
)
if _method_supported_by_bngsim_for_routing(method_name, bngsim_has_nfsim):
if _method_supported_by_bngsim_for_routing(
method_name, bngsim_has_nfsim, bngsim_has_rulemonkey
):
return BngsimRouteDecision(
ROUTE_BNGL_BNGSIM,
"BNGL method override is a BNGsim-supported simulation",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)
return _unsupported_method_route(method_name, simulator)

candidate_methods = []
for action in sim_actions:
Expand DownExpand Up@@ -1498,12 +1616,10 @@ def _classify_bngl_actions_for_bngsim(
)

for method_name in candidate_methods:
if not _method_supported_by_bngsim_for_routing(method_name, bngsim_has_nfsim):
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)
if not _method_supported_by_bngsim_for_routing(
method_name, bngsim_has_nfsim, bngsim_has_rulemonkey
):
return _unsupported_method_route(method_name, simulator)

if has_backend_hook_workflow:
return BngsimRouteDecision(
Expand All@@ -1529,12 +1645,15 @@ def classify_bngsim_route(
bngsim_has_nfsim=None,
bngl_actions=None,
has_protocol=None,
bngsim_has_rulemonkey=None,
):
"""Choose the conservative Stage 1 route for a simulation request."""
if bngsim_available is None:
bngsim_available = BNGSIM_AVAILABLE
if bngsim_has_nfsim is None:
bngsim_has_nfsim = BNGSIM_HAS_NFSIM
if bngsim_has_rulemonkey is None:
bngsim_has_rulemonkey = BNGSIM_HAS_RULEMONKEY

if simulator not in {"auto", "bngsim", "subprocess"}:
raise ValueError(
Expand DownExpand Up@@ -1628,13 +1747,30 @@ def classify_bngsim_route(

if has_protocol is None:
has_protocol = _bngl_has_protocol_block(input_path)
parse_reason = None
if bngl_actions is None:
bngl_actions, parse_reason = _load_bngl_routing_actions(input_path)
if bngl_actions is None:
bngl_actions = _load_bngl_actions_for_routing(input_path)
# Action inspection failed: the Python parser rejects this BNGL even
# though BNG2.pl may tolerate it (e.g. a typo'd or unknown ``simulate``
# argument). A strict ``simulator='bngsim'`` request must not silently
# downgrade to legacy BNG2.pl — surface why instead (issue #109). For
# ``auto`` the subprocess fallback stays, with a one-time warning.
detail = parse_reason or "the BNGL actions could not be parsed"
if simulator == "bngsim":
return BngsimRouteDecision(
ROUTE_ERROR,
"simulator='bngsim' was requested but the BNGL actions could "
f"not be inspected for BNGsim routing: {detail}",
)
_warn_routing_inspection_fallback_once(input_path, detail)
return _classify_bngl_actions_for_bngsim(
bngl_actions,
method=method,
has_protocol=has_protocol,
bngsim_has_nfsim=bngsim_has_nfsim,
bngsim_has_rulemonkey=bngsim_has_rulemonkey,
simulator=simulator,
)


Expand Down
13 changes: 12 additions & 1 deletion bionetgen/core/utils/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,7 +576,18 @@ def define_parser(self):
arg_type_expr = pp.Word(
pp.nums + "." + "+" + "-" + "e" + "E" + "(" + ")" + "/" + "*" + "^"
)
arg_type_list = "[" + pp.delimitedList((quote_word ^ arg_type_float)) + "]"
# Match BNG2.pl/Perl list syntax: elements may be quoted strings or
# numeric expressions including scientific notation (arg_type_expr
# covers e/E and +/-), an empty list `[]` is allowed, and a single
# trailing comma `[1,2,]` is tolerated. arg_type_float only spans
# digits and '.', so it rejected `2.3e-10`; delimitedList rejected the
# trailing comma — both are valid Perl that BNG2.pl runs (issue #110).
arg_type_list = (
"["
+ pp.Optional(pp.delimitedList(quote_word ^ arg_type_expr))
+ pp.Optional(",")
+ "]"
)
arg_type_string = quote_word
#
# BNGL/Perl `=>` auto-quotes its left operand, so dict keys
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
206 changes: 171 additions & 35 deletions bionetgen/core/tools/bngsim_bridge.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1201,6 +1201,21 @@ def _nfsim_session_kwargs(nf_params):

_BNGSIM_NETWORK_METHODS = frozenset({"ode", "ssa", "psa", "rm"})

# Every method string BNG2.pl's simulate() accepts: its $METHODS hash keys
# (cvode, ssa, pla, psa, nf) plus the documented 'ode' alias for 'cvode',
# extended with 'rm' (RuleMonkey), which the bridge rewrites onto the nf
# backend. A method outside this set is malformed — BNG2.pl itself rejects it
# ("Simulation method '...' is not a valid option.") — so the router surfaces
# it as an error rather than silently shipping it to the legacy stack.
_KNOWN_BNGL_METHODS = frozenset({"ode", "cvode", "ssa", "psa", "pla", "nf", "rm"})

# Methods that need an optional BNGsim component the build may lack: nf needs
# NFsim, rm (RuleMonkey) needs the RuleMonkey session. BNGsim *can* run these
# when the component is present, so an absent component is a build incapability
# (surfaced as an error under strict simulator='bngsim', legacy fallback under
# auto) rather than a categorical one like pla.
_BNGSIM_OPTIONAL_COMPONENT_METHODS = frozenset({"nf", "rm"})

_BNGL_ROUTING_COMPLEX_ACTIONS = frozenset(
{
"parameter_scan",
Expand DownExpand Up@@ -1235,8 +1250,15 @@ def _nfsim_session_kwargs(nf_params):
)


def _method_supported_by_bngsim_for_routing(method, bngsim_has_nfsim=None):
def _method_supported_by_bngsim_for_routing(
method, bngsim_has_nfsim=None, bngsim_has_rulemonkey=None
):
"""Return True if a normalized method can be handed to BNGsim."""
if method == "rm":
# RuleMonkey is an optional BNGsim component, like NFsim for nf.
if bngsim_has_rulemonkey is None:
bngsim_has_rulemonkey = BNGSIM_HAS_RULEMONKEY
return bool(bngsim_has_rulemonkey)
if method in _BNGSIM_NETWORK_METHODS:
return True
if _is_nf_method(method):
Expand All@@ -1246,6 +1268,49 @@ def _method_supported_by_bngsim_for_routing(method, bngsim_has_nfsim=None):
return False


def _unsupported_method_route(method_name, simulator="auto"):
"""Route a (non-PLA) method the direct BNGsim path can't run.

Three cases:

* A valid method that needs an optional BNGsim component the build lacks
(``nf`` without NFsim, ``rm`` without RuleMonkey) is a *build*
incapability: BNGsim could run it with the component installed, so a
strict ``simulator='bngsim'`` request surfaces it as an error while
``auto`` falls back to legacy.
* Another known method the BNGsim path doesn't drive directly (e.g. the
``cvode`` alias) keeps the legacy subprocess route in every mode.
* A method outside the valid BNG universe is malformed — BNG2.pl rejects
it too — so it errors in every mode rather than silently going legacy.
"""
if method_name not in _KNOWN_BNGL_METHODS:
return BngsimRouteDecision(
ROUTE_ERROR,
f"BNGL method '{method_name}' is not a recognized simulation method "
"(expected one of ode, ssa, pla, psa, nf).",
method=method_name,
)
if method_name in _BNGSIM_OPTIONAL_COMPONENT_METHODS:
component = "NFsim" if _is_nf_method(method_name) else "RuleMonkey"
if simulator == "bngsim":
return BngsimRouteDecision(
ROUTE_ERROR,
f"simulator='bngsim' was requested but method '{method_name}' "
f"requires BNGsim {component} support, which this build lacks.",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGsim {component} support is unavailable; using legacy route.",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)


def _bngl_action_method_for_routing(action):
"""Extract only the method hint needed for conservative routing.

Expand DownExpand Up@@ -1310,9 +1375,16 @@ def _bngl_has_protocol_block(bngl_path):
# on its next run (matters for long-lived consumers like the VS Code
# extension).
_CACHE_MISS = object()
# key: (abspath, st_mtime_ns, st_size); value: parsed actions list (or None).
_ROUTING_ACTIONS_CACHE: dict[tuple[str, int, int], list | None] = {}
# key: (abspath, st_mtime_ns, st_size); value: (actions list or None, parse
# failure reason or None). The reason rides along so a strict
# ``simulator='bngsim'`` request can surface *why* inspection failed instead
# of silently downgrading to the legacy subprocess route (see issue #109).
_ROUTING_ACTIONS_CACHE: dict[tuple[str, int, int], tuple[list | None, str | None]] = {}
_ROUTING_ACTIONS_CACHE_MAX = 128
# Paths already warned about in auto mode, so a model whose actions can't be
# inspected for BNGsim routing produces one WARNING per run, not one per the
# ~4 routing queries each ``bionetgen.run`` makes for the same file.
_ROUTING_INSPECT_WARNED: set[str] = set()


def _clear_routing_actions_cache():
Expand All@@ -1321,16 +1393,18 @@ def _clear_routing_actions_cache():
never needs this because the cache key invalidates on file change.
"""
_ROUTING_ACTIONS_CACHE.clear()
_ROUTING_INSPECT_WARNED.clear()


def _load_bngl_actions_for_routing(bngl_path):
"""Parse BNGL actions for routing only — memoized per file identity.
def _load_bngl_routing_actions(bngl_path):
"""Parse BNGL actions for routing — memoized per file identity.

Returns the parsed action items (treat the list as read-only — routing
callers never mutate it) or ``None`` when the file cannot be parsed.
Parse failures fall back to BNG2.pl rather than blocking the legacy
path, and the ``None`` is cached too so a failing parse is not retried
several times per run.
Returns ``(actions, reason)``: the parsed action items (treat the list as
read-only — routing callers never mutate it) with ``reason=None``, or
``(None, reason)`` when the file cannot be parsed, where ``reason`` is the
underlying parse message. Parse failures fall back to BNG2.pl rather than
blocking the legacy path, and the failure is cached too so a failing parse
is not retried several times per run.
"""
try:
st = os.stat(bngl_path)
Expand All@@ -1341,46 +1415,85 @@ def _load_bngl_actions_for_routing(bngl_path):
cached = _ROUTING_ACTIONS_CACHE.get(key, _CACHE_MISS)
if cached is not _CACHE_MISS:
return cached
actions = _parse_bngl_actions_for_routing(bngl_path)
result = _parse_bngl_actions_for_routing(bngl_path)
if len(_ROUTING_ACTIONS_CACHE) >= _ROUTING_ACTIONS_CACHE_MAX:
# FIFO eviction — drop the oldest entry (dicts keep insertion order).
_ROUTING_ACTIONS_CACHE.pop(next(iter(_ROUTING_ACTIONS_CACHE)), None)
_ROUTING_ACTIONS_CACHE[key] = actions
return actions
_ROUTING_ACTIONS_CACHE[key] = result
return result


def _load_bngl_actions_for_routing(bngl_path):
"""Memoized routing action list (or ``None`` on parse failure).

Thin wrapper over :func:`_load_bngl_routing_actions` for callers that
only need the action items, not the parse-failure reason.
"""
return _load_bngl_routing_actions(bngl_path)[0]


def _parse_bngl_actions_for_routing(bngl_path):
"""Parse a BNGL file's action items via a throwaway ``bngmodel``.

Uncached — :func:`_load_bngl_actions_for_routing` is the memoized
entry point callers should use.
Returns ``(actions, reason)`` — the action list with ``reason=None`` on
success, or ``(None, reason)`` with the parse message on failure. Uncached
— :func:`_load_bngl_routing_actions` is the memoized entry point callers
should use.
"""
try:
import bionetgen.modelapi.model as mdl

model = mdl.bngmodel(bngl_path)
except Exception as exc:
logger.debug("could not parse BNGL for BNGsim routing (%s): %s", bngl_path, exc)
return None
return None, str(exc) or exc.__class__.__name__
try:
return list(model.actions.items)
return list(model.actions.items), None
except Exception as exc:
logger.debug(
"could not read BNGL actions for BNGsim routing (%s): %s", bngl_path, exc
)
return None
return None, str(exc) or exc.__class__.__name__


def _warn_routing_inspection_fallback_once(bngl_path, reason):
"""Warn once per file when auto-mode can't inspect a BNGL's actions for
BNGsim routing and falls back to the legacy subprocess engine."""
try:
key = os.path.abspath(bngl_path)
except Exception:
key = bngl_path
if key in _ROUTING_INSPECT_WARNED:
return
_ROUTING_INSPECT_WARNED.add(key)
logger.warning(
"Could not inspect BNGL actions for BNGsim routing (%s): %s. Using the "
"legacy subprocess (BNG2.pl) route. Pass simulator='bngsim' to require "
"BNGsim and surface this as an error instead.",
bngl_path,
reason,
)


def _classify_bngl_actions_for_bngsim(
actions_items,
method=None,
has_protocol=False,
bngsim_has_nfsim=None,
bngsim_has_rulemonkey=None,
simulator="auto",
):
"""Classify whether BNGL can use the BNG2.pl-owned BNGsim backend hook.

This routing pass only reads action names and method hints. It does not
evaluate BNGL expressions or replay any action semantics in Python.

``simulator`` affects the declines BNGsim *could* satisfy: under a strict
``simulator='bngsim'`` request an *unrecognized action* (runnable via the
BNG2.pl backend hook) and a *build incapability* (``nf`` without NFsim,
``rm`` without RuleMonkey) are surfaced as ``ROUTE_ERROR`` instead of
silently running legacy; ``auto`` falls back. PLA is a categorical BNGsim
incapability and stays on the subprocess route in every mode.
"""
if actions_items is None:
return BngsimRouteDecision(
Expand DownExpand Up@@ -1416,10 +1529,17 @@ def _classify_bngl_actions_for_bngsim(
continue

if atype is not None:
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL action '{atype}' is not a conservative BNGsim route",
)
reason = f"BNGL action '{atype}' is not a conservative BNGsim route"
if simulator == "bngsim":
# Strict mode: BNGsim could run this through the BNG2.pl
# backend hook, but the router can't confirm an unrecognized
# action is safe to delegate. Surface it instead of silently
# downgrading to legacy (issue #109 contract).
return BngsimRouteDecision(
ROUTE_ERROR,
f"simulator='bngsim' was requested but {reason}.",
)
return BngsimRouteDecision(ROUTE_SUBPROCESS, reason)

if len(sim_actions) > 1:
has_backend_hook_workflow = True
Expand DownExpand Up@@ -1458,17 +1578,15 @@ def _classify_bngl_actions_for_bngsim(
"BNGL PLA is not supported by BNGsim",
method="pla",
)
if _method_supported_by_bngsim_for_routing(method_name, bngsim_has_nfsim):
if _method_supported_by_bngsim_for_routing(
method_name, bngsim_has_nfsim, bngsim_has_rulemonkey
):
return BngsimRouteDecision(
ROUTE_BNGL_BNGSIM,
"BNGL method override is a BNGsim-supported simulation",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)
return _unsupported_method_route(method_name, simulator)

candidate_methods = []
for action in sim_actions:
Expand DownExpand Up@@ -1498,12 +1616,10 @@ def _classify_bngl_actions_for_bngsim(
)

for method_name in candidate_methods:
if not _method_supported_by_bngsim_for_routing(method_name, bngsim_has_nfsim):
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)
if not _method_supported_by_bngsim_for_routing(
method_name, bngsim_has_nfsim, bngsim_has_rulemonkey
):
return _unsupported_method_route(method_name, simulator)

if has_backend_hook_workflow:
return BngsimRouteDecision(
Expand All@@ -1529,12 +1645,15 @@ def classify_bngsim_route(
bngsim_has_nfsim=None,
bngl_actions=None,
has_protocol=None,
bngsim_has_rulemonkey=None,
):
"""Choose the conservative Stage 1 route for a simulation request."""
if bngsim_available is None:
bngsim_available = BNGSIM_AVAILABLE
if bngsim_has_nfsim is None:
bngsim_has_nfsim = BNGSIM_HAS_NFSIM
if bngsim_has_rulemonkey is None:
bngsim_has_rulemonkey = BNGSIM_HAS_RULEMONKEY

if simulator not in {"auto", "bngsim", "subprocess"}:
raise ValueError(
Expand DownExpand Up@@ -1628,13 +1747,30 @@ def classify_bngsim_route(

if has_protocol is None:
has_protocol = _bngl_has_protocol_block(input_path)
parse_reason = None
if bngl_actions is None:
bngl_actions, parse_reason = _load_bngl_routing_actions(input_path)
if bngl_actions is None:
bngl_actions = _load_bngl_actions_for_routing(input_path)
# Action inspection failed: the Python parser rejects this BNGL even
# though BNG2.pl may tolerate it (e.g. a typo'd or unknown ``simulate``
# argument). A strict ``simulator='bngsim'`` request must not silently
# downgrade to legacy BNG2.pl — surface why instead (issue #109). For
# ``auto`` the subprocess fallback stays, with a one-time warning.
detail = parse_reason or "the BNGL actions could not be parsed"
if simulator == "bngsim":
return BngsimRouteDecision(
ROUTE_ERROR,
"simulator='bngsim' was requested but the BNGL actions could "
f"not be inspected for BNGsim routing: {detail}",
)
_warn_routing_inspection_fallback_once(input_path, detail)
return _classify_bngl_actions_for_bngsim(
bngl_actions,
method=method,
has_protocol=has_protocol,
bngsim_has_nfsim=bngsim_has_nfsim,
bngsim_has_rulemonkey=bngsim_has_rulemonkey,
simulator=simulator,
)


Expand Down
13 changes: 12 additions & 1 deletion bionetgen/core/utils/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,7 +576,18 @@ def define_parser(self):
arg_type_expr = pp.Word(
pp.nums + "." + "+" + "-" + "e" + "E" + "(" + ")" + "/" + "*" + "^"
)
arg_type_list = "[" + pp.delimitedList((quote_word ^ arg_type_float)) + "]"
# Match BNG2.pl/Perl list syntax: elements may be quoted strings or
# numeric expressions including scientific notation (arg_type_expr
# covers e/E and +/-), an empty list `[]` is allowed, and a single
# trailing comma `[1,2,]` is tolerated. arg_type_float only spans
# digits and '.', so it rejected `2.3e-10`; delimitedList rejected the
# trailing comma — both are valid Perl that BNG2.pl runs (issue #110).
arg_type_list = (
"["
+ pp.Optional(pp.delimitedList(quote_word ^ arg_type_expr))
+ pp.Optional(",")
+ "]"
)
arg_type_string = quote_word
#
# BNGL/Perl `=>` auto-quotes its left operand, so dict keys
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
206 changes: 171 additions & 35 deletions bionetgen/core/tools/bngsim_bridge.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1201,6 +1201,21 @@ def _nfsim_session_kwargs(nf_params):

_BNGSIM_NETWORK_METHODS = frozenset({"ode", "ssa", "psa", "rm"})

# Every method string BNG2.pl's simulate() accepts: its $METHODS hash keys
# (cvode, ssa, pla, psa, nf) plus the documented 'ode' alias for 'cvode',
# extended with 'rm' (RuleMonkey), which the bridge rewrites onto the nf
# backend. A method outside this set is malformed — BNG2.pl itself rejects it
# ("Simulation method '...' is not a valid option.") — so the router surfaces
# it as an error rather than silently shipping it to the legacy stack.
_KNOWN_BNGL_METHODS = frozenset({"ode", "cvode", "ssa", "psa", "pla", "nf", "rm"})

# Methods that need an optional BNGsim component the build may lack: nf needs
# NFsim, rm (RuleMonkey) needs the RuleMonkey session. BNGsim *can* run these
# when the component is present, so an absent component is a build incapability
# (surfaced as an error under strict simulator='bngsim', legacy fallback under
# auto) rather than a categorical one like pla.
_BNGSIM_OPTIONAL_COMPONENT_METHODS = frozenset({"nf", "rm"})

_BNGL_ROUTING_COMPLEX_ACTIONS = frozenset(
{
"parameter_scan",
Expand DownExpand Up@@ -1235,8 +1250,15 @@ def _nfsim_session_kwargs(nf_params):
)


def _method_supported_by_bngsim_for_routing(method, bngsim_has_nfsim=None):
def _method_supported_by_bngsim_for_routing(
method, bngsim_has_nfsim=None, bngsim_has_rulemonkey=None
):
"""Return True if a normalized method can be handed to BNGsim."""
if method == "rm":
# RuleMonkey is an optional BNGsim component, like NFsim for nf.
if bngsim_has_rulemonkey is None:
bngsim_has_rulemonkey = BNGSIM_HAS_RULEMONKEY
return bool(bngsim_has_rulemonkey)
if method in _BNGSIM_NETWORK_METHODS:
return True
if _is_nf_method(method):
Expand All@@ -1246,6 +1268,49 @@ def _method_supported_by_bngsim_for_routing(method, bngsim_has_nfsim=None):
return False


def _unsupported_method_route(method_name, simulator="auto"):
"""Route a (non-PLA) method the direct BNGsim path can't run.

Three cases:

* A valid method that needs an optional BNGsim component the build lacks
(``nf`` without NFsim, ``rm`` without RuleMonkey) is a *build*
incapability: BNGsim could run it with the component installed, so a
strict ``simulator='bngsim'`` request surfaces it as an error while
``auto`` falls back to legacy.
* Another known method the BNGsim path doesn't drive directly (e.g. the
``cvode`` alias) keeps the legacy subprocess route in every mode.
* A method outside the valid BNG universe is malformed — BNG2.pl rejects
it too — so it errors in every mode rather than silently going legacy.
"""
if method_name not in _KNOWN_BNGL_METHODS:
return BngsimRouteDecision(
ROUTE_ERROR,
f"BNGL method '{method_name}' is not a recognized simulation method "
"(expected one of ode, ssa, pla, psa, nf).",
method=method_name,
)
if method_name in _BNGSIM_OPTIONAL_COMPONENT_METHODS:
component = "NFsim" if _is_nf_method(method_name) else "RuleMonkey"
if simulator == "bngsim":
return BngsimRouteDecision(
ROUTE_ERROR,
f"simulator='bngsim' was requested but method '{method_name}' "
f"requires BNGsim {component} support, which this build lacks.",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGsim {component} support is unavailable; using legacy route.",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)


def _bngl_action_method_for_routing(action):
"""Extract only the method hint needed for conservative routing.

Expand DownExpand Up@@ -1310,9 +1375,16 @@ def _bngl_has_protocol_block(bngl_path):
# on its next run (matters for long-lived consumers like the VS Code
# extension).
_CACHE_MISS = object()
# key: (abspath, st_mtime_ns, st_size); value: parsed actions list (or None).
_ROUTING_ACTIONS_CACHE: dict[tuple[str, int, int], list | None] = {}
# key: (abspath, st_mtime_ns, st_size); value: (actions list or None, parse
# failure reason or None). The reason rides along so a strict
# ``simulator='bngsim'`` request can surface *why* inspection failed instead
# of silently downgrading to the legacy subprocess route (see issue #109).
_ROUTING_ACTIONS_CACHE: dict[tuple[str, int, int], tuple[list | None, str | None]] = {}
_ROUTING_ACTIONS_CACHE_MAX = 128
# Paths already warned about in auto mode, so a model whose actions can't be
# inspected for BNGsim routing produces one WARNING per run, not one per the
# ~4 routing queries each ``bionetgen.run`` makes for the same file.
_ROUTING_INSPECT_WARNED: set[str] = set()


def _clear_routing_actions_cache():
Expand All@@ -1321,16 +1393,18 @@ def _clear_routing_actions_cache():
never needs this because the cache key invalidates on file change.
"""
_ROUTING_ACTIONS_CACHE.clear()
_ROUTING_INSPECT_WARNED.clear()


def _load_bngl_actions_for_routing(bngl_path):
"""Parse BNGL actions for routing only — memoized per file identity.
def _load_bngl_routing_actions(bngl_path):
"""Parse BNGL actions for routing — memoized per file identity.

Returns the parsed action items (treat the list as read-only — routing
callers never mutate it) or ``None`` when the file cannot be parsed.
Parse failures fall back to BNG2.pl rather than blocking the legacy
path, and the ``None`` is cached too so a failing parse is not retried
several times per run.
Returns ``(actions, reason)``: the parsed action items (treat the list as
read-only — routing callers never mutate it) with ``reason=None``, or
``(None, reason)`` when the file cannot be parsed, where ``reason`` is the
underlying parse message. Parse failures fall back to BNG2.pl rather than
blocking the legacy path, and the failure is cached too so a failing parse
is not retried several times per run.
"""
try:
st = os.stat(bngl_path)
Expand All@@ -1341,46 +1415,85 @@ def _load_bngl_actions_for_routing(bngl_path):
cached = _ROUTING_ACTIONS_CACHE.get(key, _CACHE_MISS)
if cached is not _CACHE_MISS:
return cached
actions = _parse_bngl_actions_for_routing(bngl_path)
result = _parse_bngl_actions_for_routing(bngl_path)
if len(_ROUTING_ACTIONS_CACHE) >= _ROUTING_ACTIONS_CACHE_MAX:
# FIFO eviction — drop the oldest entry (dicts keep insertion order).
_ROUTING_ACTIONS_CACHE.pop(next(iter(_ROUTING_ACTIONS_CACHE)), None)
_ROUTING_ACTIONS_CACHE[key] = actions
return actions
_ROUTING_ACTIONS_CACHE[key] = result
return result


def _load_bngl_actions_for_routing(bngl_path):
"""Memoized routing action list (or ``None`` on parse failure).

Thin wrapper over :func:`_load_bngl_routing_actions` for callers that
only need the action items, not the parse-failure reason.
"""
return _load_bngl_routing_actions(bngl_path)[0]


def _parse_bngl_actions_for_routing(bngl_path):
"""Parse a BNGL file's action items via a throwaway ``bngmodel``.

Uncached — :func:`_load_bngl_actions_for_routing` is the memoized
entry point callers should use.
Returns ``(actions, reason)`` — the action list with ``reason=None`` on
success, or ``(None, reason)`` with the parse message on failure. Uncached
— :func:`_load_bngl_routing_actions` is the memoized entry point callers
should use.
"""
try:
import bionetgen.modelapi.model as mdl

model = mdl.bngmodel(bngl_path)
except Exception as exc:
logger.debug("could not parse BNGL for BNGsim routing (%s): %s", bngl_path, exc)
return None
return None, str(exc) or exc.__class__.__name__
try:
return list(model.actions.items)
return list(model.actions.items), None
except Exception as exc:
logger.debug(
"could not read BNGL actions for BNGsim routing (%s): %s", bngl_path, exc
)
return None
return None, str(exc) or exc.__class__.__name__


def _warn_routing_inspection_fallback_once(bngl_path, reason):
"""Warn once per file when auto-mode can't inspect a BNGL's actions for
BNGsim routing and falls back to the legacy subprocess engine."""
try:
key = os.path.abspath(bngl_path)
except Exception:
key = bngl_path
if key in _ROUTING_INSPECT_WARNED:
return
_ROUTING_INSPECT_WARNED.add(key)
logger.warning(
"Could not inspect BNGL actions for BNGsim routing (%s): %s. Using the "
"legacy subprocess (BNG2.pl) route. Pass simulator='bngsim' to require "
"BNGsim and surface this as an error instead.",
bngl_path,
reason,
)


def _classify_bngl_actions_for_bngsim(
actions_items,
method=None,
has_protocol=False,
bngsim_has_nfsim=None,
bngsim_has_rulemonkey=None,
simulator="auto",
):
"""Classify whether BNGL can use the BNG2.pl-owned BNGsim backend hook.

This routing pass only reads action names and method hints. It does not
evaluate BNGL expressions or replay any action semantics in Python.

``simulator`` affects the declines BNGsim *could* satisfy: under a strict
``simulator='bngsim'`` request an *unrecognized action* (runnable via the
BNG2.pl backend hook) and a *build incapability* (``nf`` without NFsim,
``rm`` without RuleMonkey) are surfaced as ``ROUTE_ERROR`` instead of
silently running legacy; ``auto`` falls back. PLA is a categorical BNGsim
incapability and stays on the subprocess route in every mode.
"""
if actions_items is None:
return BngsimRouteDecision(
Expand DownExpand Up@@ -1416,10 +1529,17 @@ def _classify_bngl_actions_for_bngsim(
continue

if atype is not None:
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL action '{atype}' is not a conservative BNGsim route",
)
reason = f"BNGL action '{atype}' is not a conservative BNGsim route"
if simulator == "bngsim":
# Strict mode: BNGsim could run this through the BNG2.pl
# backend hook, but the router can't confirm an unrecognized
# action is safe to delegate. Surface it instead of silently
# downgrading to legacy (issue #109 contract).
return BngsimRouteDecision(
ROUTE_ERROR,
f"simulator='bngsim' was requested but {reason}.",
)
return BngsimRouteDecision(ROUTE_SUBPROCESS, reason)

if len(sim_actions) > 1:
has_backend_hook_workflow = True
Expand DownExpand Up@@ -1458,17 +1578,15 @@ def _classify_bngl_actions_for_bngsim(
"BNGL PLA is not supported by BNGsim",
method="pla",
)
if _method_supported_by_bngsim_for_routing(method_name, bngsim_has_nfsim):
if _method_supported_by_bngsim_for_routing(
method_name, bngsim_has_nfsim, bngsim_has_rulemonkey
):
return BngsimRouteDecision(
ROUTE_BNGL_BNGSIM,
"BNGL method override is a BNGsim-supported simulation",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)
return _unsupported_method_route(method_name, simulator)

candidate_methods = []
for action in sim_actions:
Expand DownExpand Up@@ -1498,12 +1616,10 @@ def _classify_bngl_actions_for_bngsim(
)

for method_name in candidate_methods:
if not _method_supported_by_bngsim_for_routing(method_name, bngsim_has_nfsim):
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)
if not _method_supported_by_bngsim_for_routing(
method_name, bngsim_has_nfsim, bngsim_has_rulemonkey
):
return _unsupported_method_route(method_name, simulator)

if has_backend_hook_workflow:
return BngsimRouteDecision(
Expand All@@ -1529,12 +1645,15 @@ def classify_bngsim_route(
bngsim_has_nfsim=None,
bngl_actions=None,
has_protocol=None,
bngsim_has_rulemonkey=None,
):
"""Choose the conservative Stage 1 route for a simulation request."""
if bngsim_available is None:
bngsim_available = BNGSIM_AVAILABLE
if bngsim_has_nfsim is None:
bngsim_has_nfsim = BNGSIM_HAS_NFSIM
if bngsim_has_rulemonkey is None:
bngsim_has_rulemonkey = BNGSIM_HAS_RULEMONKEY

if simulator not in {"auto", "bngsim", "subprocess"}:
raise ValueError(
Expand DownExpand Up@@ -1628,13 +1747,30 @@ def classify_bngsim_route(

if has_protocol is None:
has_protocol = _bngl_has_protocol_block(input_path)
parse_reason = None
if bngl_actions is None:
bngl_actions, parse_reason = _load_bngl_routing_actions(input_path)
if bngl_actions is None:
bngl_actions = _load_bngl_actions_for_routing(input_path)
# Action inspection failed: the Python parser rejects this BNGL even
# though BNG2.pl may tolerate it (e.g. a typo'd or unknown ``simulate``
# argument). A strict ``simulator='bngsim'`` request must not silently
# downgrade to legacy BNG2.pl — surface why instead (issue #109). For
# ``auto`` the subprocess fallback stays, with a one-time warning.
detail = parse_reason or "the BNGL actions could not be parsed"
if simulator == "bngsim":
return BngsimRouteDecision(
ROUTE_ERROR,
"simulator='bngsim' was requested but the BNGL actions could "
f"not be inspected for BNGsim routing: {detail}",
)
_warn_routing_inspection_fallback_once(input_path, detail)
return _classify_bngl_actions_for_bngsim(
bngl_actions,
method=method,
has_protocol=has_protocol,
bngsim_has_nfsim=bngsim_has_nfsim,
bngsim_has_rulemonkey=bngsim_has_rulemonkey,
simulator=simulator,
)


Expand Down
13 changes: 12 additions & 1 deletion bionetgen/core/utils/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,7 +576,18 @@ def define_parser(self):
arg_type_expr = pp.Word(
pp.nums + "." + "+" + "-" + "e" + "E" + "(" + ")" + "/" + "*" + "^"
)
arg_type_list = "[" + pp.delimitedList((quote_word ^ arg_type_float)) + "]"
# Match BNG2.pl/Perl list syntax: elements may be quoted strings or
# numeric expressions including scientific notation (arg_type_expr
# covers e/E and +/-), an empty list `[]` is allowed, and a single
# trailing comma `[1,2,]` is tolerated. arg_type_float only spans
# digits and '.', so it rejected `2.3e-10`; delimitedList rejected the
# trailing comma — both are valid Perl that BNG2.pl runs (issue #110).
arg_type_list = (
"["
+ pp.Optional(pp.delimitedList(quote_word ^ arg_type_expr))
+ pp.Optional(",")
+ "]"
)
arg_type_string = quote_word
#
# BNGL/Perl `=>` auto-quotes its left operand, so dict keys
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
206 changes: 171 additions & 35 deletions bionetgen/core/tools/bngsim_bridge.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1201,6 +1201,21 @@ def _nfsim_session_kwargs(nf_params):

_BNGSIM_NETWORK_METHODS = frozenset({"ode", "ssa", "psa", "rm"})

# Every method string BNG2.pl's simulate() accepts: its $METHODS hash keys
# (cvode, ssa, pla, psa, nf) plus the documented 'ode' alias for 'cvode',
# extended with 'rm' (RuleMonkey), which the bridge rewrites onto the nf
# backend. A method outside this set is malformed — BNG2.pl itself rejects it
# ("Simulation method '...' is not a valid option.") — so the router surfaces
# it as an error rather than silently shipping it to the legacy stack.
_KNOWN_BNGL_METHODS = frozenset({"ode", "cvode", "ssa", "psa", "pla", "nf", "rm"})

# Methods that need an optional BNGsim component the build may lack: nf needs
# NFsim, rm (RuleMonkey) needs the RuleMonkey session. BNGsim *can* run these
# when the component is present, so an absent component is a build incapability
# (surfaced as an error under strict simulator='bngsim', legacy fallback under
# auto) rather than a categorical one like pla.
_BNGSIM_OPTIONAL_COMPONENT_METHODS = frozenset({"nf", "rm"})

_BNGL_ROUTING_COMPLEX_ACTIONS = frozenset(
{
"parameter_scan",
Expand DownExpand Up@@ -1235,8 +1250,15 @@ def _nfsim_session_kwargs(nf_params):
)


def _method_supported_by_bngsim_for_routing(method, bngsim_has_nfsim=None):
def _method_supported_by_bngsim_for_routing(
method, bngsim_has_nfsim=None, bngsim_has_rulemonkey=None
):
"""Return True if a normalized method can be handed to BNGsim."""
if method == "rm":
# RuleMonkey is an optional BNGsim component, like NFsim for nf.
if bngsim_has_rulemonkey is None:
bngsim_has_rulemonkey = BNGSIM_HAS_RULEMONKEY
return bool(bngsim_has_rulemonkey)
if method in _BNGSIM_NETWORK_METHODS:
return True
if _is_nf_method(method):
Expand All@@ -1246,6 +1268,49 @@ def _method_supported_by_bngsim_for_routing(method, bngsim_has_nfsim=None):
return False


def _unsupported_method_route(method_name, simulator="auto"):
"""Route a (non-PLA) method the direct BNGsim path can't run.

Three cases:

* A valid method that needs an optional BNGsim component the build lacks
(``nf`` without NFsim, ``rm`` without RuleMonkey) is a *build*
incapability: BNGsim could run it with the component installed, so a
strict ``simulator='bngsim'`` request surfaces it as an error while
``auto`` falls back to legacy.
* Another known method the BNGsim path doesn't drive directly (e.g. the
``cvode`` alias) keeps the legacy subprocess route in every mode.
* A method outside the valid BNG universe is malformed — BNG2.pl rejects
it too — so it errors in every mode rather than silently going legacy.
"""
if method_name not in _KNOWN_BNGL_METHODS:
return BngsimRouteDecision(
ROUTE_ERROR,
f"BNGL method '{method_name}' is not a recognized simulation method "
"(expected one of ode, ssa, pla, psa, nf).",
method=method_name,
)
if method_name in _BNGSIM_OPTIONAL_COMPONENT_METHODS:
component = "NFsim" if _is_nf_method(method_name) else "RuleMonkey"
if simulator == "bngsim":
return BngsimRouteDecision(
ROUTE_ERROR,
f"simulator='bngsim' was requested but method '{method_name}' "
f"requires BNGsim {component} support, which this build lacks.",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGsim {component} support is unavailable; using legacy route.",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)


def _bngl_action_method_for_routing(action):
"""Extract only the method hint needed for conservative routing.

Expand DownExpand Up@@ -1310,9 +1375,16 @@ def _bngl_has_protocol_block(bngl_path):
# on its next run (matters for long-lived consumers like the VS Code
# extension).
_CACHE_MISS = object()
# key: (abspath, st_mtime_ns, st_size); value: parsed actions list (or None).
_ROUTING_ACTIONS_CACHE: dict[tuple[str, int, int], list | None] = {}
# key: (abspath, st_mtime_ns, st_size); value: (actions list or None, parse
# failure reason or None). The reason rides along so a strict
# ``simulator='bngsim'`` request can surface *why* inspection failed instead
# of silently downgrading to the legacy subprocess route (see issue #109).
_ROUTING_ACTIONS_CACHE: dict[tuple[str, int, int], tuple[list | None, str | None]] = {}
_ROUTING_ACTIONS_CACHE_MAX = 128
# Paths already warned about in auto mode, so a model whose actions can't be
# inspected for BNGsim routing produces one WARNING per run, not one per the
# ~4 routing queries each ``bionetgen.run`` makes for the same file.
_ROUTING_INSPECT_WARNED: set[str] = set()


def _clear_routing_actions_cache():
Expand All@@ -1321,16 +1393,18 @@ def _clear_routing_actions_cache():
never needs this because the cache key invalidates on file change.
"""
_ROUTING_ACTIONS_CACHE.clear()
_ROUTING_INSPECT_WARNED.clear()


def _load_bngl_actions_for_routing(bngl_path):
"""Parse BNGL actions for routing only — memoized per file identity.
def _load_bngl_routing_actions(bngl_path):
"""Parse BNGL actions for routing — memoized per file identity.

Returns the parsed action items (treat the list as read-only — routing
callers never mutate it) or ``None`` when the file cannot be parsed.
Parse failures fall back to BNG2.pl rather than blocking the legacy
path, and the ``None`` is cached too so a failing parse is not retried
several times per run.
Returns ``(actions, reason)``: the parsed action items (treat the list as
read-only — routing callers never mutate it) with ``reason=None``, or
``(None, reason)`` when the file cannot be parsed, where ``reason`` is the
underlying parse message. Parse failures fall back to BNG2.pl rather than
blocking the legacy path, and the failure is cached too so a failing parse
is not retried several times per run.
"""
try:
st = os.stat(bngl_path)
Expand All@@ -1341,46 +1415,85 @@ def _load_bngl_actions_for_routing(bngl_path):
cached = _ROUTING_ACTIONS_CACHE.get(key, _CACHE_MISS)
if cached is not _CACHE_MISS:
return cached
actions = _parse_bngl_actions_for_routing(bngl_path)
result = _parse_bngl_actions_for_routing(bngl_path)
if len(_ROUTING_ACTIONS_CACHE) >= _ROUTING_ACTIONS_CACHE_MAX:
# FIFO eviction — drop the oldest entry (dicts keep insertion order).
_ROUTING_ACTIONS_CACHE.pop(next(iter(_ROUTING_ACTIONS_CACHE)), None)
_ROUTING_ACTIONS_CACHE[key] = actions
return actions
_ROUTING_ACTIONS_CACHE[key] = result
return result


def _load_bngl_actions_for_routing(bngl_path):
"""Memoized routing action list (or ``None`` on parse failure).

Thin wrapper over :func:`_load_bngl_routing_actions` for callers that
only need the action items, not the parse-failure reason.
"""
return _load_bngl_routing_actions(bngl_path)[0]


def _parse_bngl_actions_for_routing(bngl_path):
"""Parse a BNGL file's action items via a throwaway ``bngmodel``.

Uncached — :func:`_load_bngl_actions_for_routing` is the memoized
entry point callers should use.
Returns ``(actions, reason)`` — the action list with ``reason=None`` on
success, or ``(None, reason)`` with the parse message on failure. Uncached
— :func:`_load_bngl_routing_actions` is the memoized entry point callers
should use.
"""
try:
import bionetgen.modelapi.model as mdl

model = mdl.bngmodel(bngl_path)
except Exception as exc:
logger.debug("could not parse BNGL for BNGsim routing (%s): %s", bngl_path, exc)
return None
return None, str(exc) or exc.__class__.__name__
try:
return list(model.actions.items)
return list(model.actions.items), None
except Exception as exc:
logger.debug(
"could not read BNGL actions for BNGsim routing (%s): %s", bngl_path, exc
)
return None
return None, str(exc) or exc.__class__.__name__


def _warn_routing_inspection_fallback_once(bngl_path, reason):
"""Warn once per file when auto-mode can't inspect a BNGL's actions for
BNGsim routing and falls back to the legacy subprocess engine."""
try:
key = os.path.abspath(bngl_path)
except Exception:
key = bngl_path
if key in _ROUTING_INSPECT_WARNED:
return
_ROUTING_INSPECT_WARNED.add(key)
logger.warning(
"Could not inspect BNGL actions for BNGsim routing (%s): %s. Using the "
"legacy subprocess (BNG2.pl) route. Pass simulator='bngsim' to require "
"BNGsim and surface this as an error instead.",
bngl_path,
reason,
)


def _classify_bngl_actions_for_bngsim(
actions_items,
method=None,
has_protocol=False,
bngsim_has_nfsim=None,
bngsim_has_rulemonkey=None,
simulator="auto",
):
"""Classify whether BNGL can use the BNG2.pl-owned BNGsim backend hook.

This routing pass only reads action names and method hints. It does not
evaluate BNGL expressions or replay any action semantics in Python.

``simulator`` affects the declines BNGsim *could* satisfy: under a strict
``simulator='bngsim'`` request an *unrecognized action* (runnable via the
BNG2.pl backend hook) and a *build incapability* (``nf`` without NFsim,
``rm`` without RuleMonkey) are surfaced as ``ROUTE_ERROR`` instead of
silently running legacy; ``auto`` falls back. PLA is a categorical BNGsim
incapability and stays on the subprocess route in every mode.
"""
if actions_items is None:
return BngsimRouteDecision(
Expand DownExpand Up@@ -1416,10 +1529,17 @@ def _classify_bngl_actions_for_bngsim(
continue

if atype is not None:
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL action '{atype}' is not a conservative BNGsim route",
)
reason = f"BNGL action '{atype}' is not a conservative BNGsim route"
if simulator == "bngsim":
# Strict mode: BNGsim could run this through the BNG2.pl
# backend hook, but the router can't confirm an unrecognized
# action is safe to delegate. Surface it instead of silently
# downgrading to legacy (issue #109 contract).
return BngsimRouteDecision(
ROUTE_ERROR,
f"simulator='bngsim' was requested but {reason}.",
)
return BngsimRouteDecision(ROUTE_SUBPROCESS, reason)

if len(sim_actions) > 1:
has_backend_hook_workflow = True
Expand DownExpand Up@@ -1458,17 +1578,15 @@ def _classify_bngl_actions_for_bngsim(
"BNGL PLA is not supported by BNGsim",
method="pla",
)
if _method_supported_by_bngsim_for_routing(method_name, bngsim_has_nfsim):
if _method_supported_by_bngsim_for_routing(
method_name, bngsim_has_nfsim, bngsim_has_rulemonkey
):
return BngsimRouteDecision(
ROUTE_BNGL_BNGSIM,
"BNGL method override is a BNGsim-supported simulation",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)
return _unsupported_method_route(method_name, simulator)

candidate_methods = []
for action in sim_actions:
Expand DownExpand Up@@ -1498,12 +1616,10 @@ def _classify_bngl_actions_for_bngsim(
)

for method_name in candidate_methods:
if not _method_supported_by_bngsim_for_routing(method_name, bngsim_has_nfsim):
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)
if not _method_supported_by_bngsim_for_routing(
method_name, bngsim_has_nfsim, bngsim_has_rulemonkey
):
return _unsupported_method_route(method_name, simulator)

if has_backend_hook_workflow:
return BngsimRouteDecision(
Expand All@@ -1529,12 +1645,15 @@ def classify_bngsim_route(
bngsim_has_nfsim=None,
bngl_actions=None,
has_protocol=None,
bngsim_has_rulemonkey=None,
):
"""Choose the conservative Stage 1 route for a simulation request."""
if bngsim_available is None:
bngsim_available = BNGSIM_AVAILABLE
if bngsim_has_nfsim is None:
bngsim_has_nfsim = BNGSIM_HAS_NFSIM
if bngsim_has_rulemonkey is None:
bngsim_has_rulemonkey = BNGSIM_HAS_RULEMONKEY

if simulator not in {"auto", "bngsim", "subprocess"}:
raise ValueError(
Expand DownExpand Up@@ -1628,13 +1747,30 @@ def classify_bngsim_route(

if has_protocol is None:
has_protocol = _bngl_has_protocol_block(input_path)
parse_reason = None
if bngl_actions is None:
bngl_actions, parse_reason = _load_bngl_routing_actions(input_path)
if bngl_actions is None:
bngl_actions = _load_bngl_actions_for_routing(input_path)
# Action inspection failed: the Python parser rejects this BNGL even
# though BNG2.pl may tolerate it (e.g. a typo'd or unknown ``simulate``
# argument). A strict ``simulator='bngsim'`` request must not silently
# downgrade to legacy BNG2.pl — surface why instead (issue #109). For
# ``auto`` the subprocess fallback stays, with a one-time warning.
detail = parse_reason or "the BNGL actions could not be parsed"
if simulator == "bngsim":
return BngsimRouteDecision(
ROUTE_ERROR,
"simulator='bngsim' was requested but the BNGL actions could "
f"not be inspected for BNGsim routing: {detail}",
)
_warn_routing_inspection_fallback_once(input_path, detail)
return _classify_bngl_actions_for_bngsim(
bngl_actions,
method=method,
has_protocol=has_protocol,
bngsim_has_nfsim=bngsim_has_nfsim,
bngsim_has_rulemonkey=bngsim_has_rulemonkey,
simulator=simulator,
)


Expand Down
13 changes: 12 additions & 1 deletion bionetgen/core/utils/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,7 +576,18 @@ def define_parser(self):
arg_type_expr = pp.Word(
pp.nums + "." + "+" + "-" + "e" + "E" + "(" + ")" + "/" + "*" + "^"
)
arg_type_list = "[" + pp.delimitedList((quote_word ^ arg_type_float)) + "]"
# Match BNG2.pl/Perl list syntax: elements may be quoted strings or
# numeric expressions including scientific notation (arg_type_expr
# covers e/E and +/-), an empty list `[]` is allowed, and a single
# trailing comma `[1,2,]` is tolerated. arg_type_float only spans
# digits and '.', so it rejected `2.3e-10`; delimitedList rejected the
# trailing comma — both are valid Perl that BNG2.pl runs (issue #110).
arg_type_list = (
"["
+ pp.Optional(pp.delimitedList(quote_word ^ arg_type_expr))
+ pp.Optional(",")
+ "]"
)
arg_type_string = quote_word
#
# BNGL/Perl `=>` auto-quotes its left operand, so dict keys
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
206 changes: 171 additions & 35 deletions bionetgen/core/tools/bngsim_bridge.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1201,6 +1201,21 @@ def _nfsim_session_kwargs(nf_params):

_BNGSIM_NETWORK_METHODS = frozenset({"ode", "ssa", "psa", "rm"})

# Every method string BNG2.pl's simulate() accepts: its $METHODS hash keys
# (cvode, ssa, pla, psa, nf) plus the documented 'ode' alias for 'cvode',
# extended with 'rm' (RuleMonkey), which the bridge rewrites onto the nf
# backend. A method outside this set is malformed — BNG2.pl itself rejects it
# ("Simulation method '...' is not a valid option.") — so the router surfaces
# it as an error rather than silently shipping it to the legacy stack.
_KNOWN_BNGL_METHODS = frozenset({"ode", "cvode", "ssa", "psa", "pla", "nf", "rm"})

# Methods that need an optional BNGsim component the build may lack: nf needs
# NFsim, rm (RuleMonkey) needs the RuleMonkey session. BNGsim *can* run these
# when the component is present, so an absent component is a build incapability
# (surfaced as an error under strict simulator='bngsim', legacy fallback under
# auto) rather than a categorical one like pla.
_BNGSIM_OPTIONAL_COMPONENT_METHODS = frozenset({"nf", "rm"})

_BNGL_ROUTING_COMPLEX_ACTIONS = frozenset(
{
"parameter_scan",
Expand DownExpand Up@@ -1235,8 +1250,15 @@ def _nfsim_session_kwargs(nf_params):
)


def _method_supported_by_bngsim_for_routing(method, bngsim_has_nfsim=None):
def _method_supported_by_bngsim_for_routing(
method, bngsim_has_nfsim=None, bngsim_has_rulemonkey=None
):
"""Return True if a normalized method can be handed to BNGsim."""
if method == "rm":
# RuleMonkey is an optional BNGsim component, like NFsim for nf.
if bngsim_has_rulemonkey is None:
bngsim_has_rulemonkey = BNGSIM_HAS_RULEMONKEY
return bool(bngsim_has_rulemonkey)
if method in _BNGSIM_NETWORK_METHODS:
return True
if _is_nf_method(method):
Expand All@@ -1246,6 +1268,49 @@ def _method_supported_by_bngsim_for_routing(method, bngsim_has_nfsim=None):
return False


def _unsupported_method_route(method_name, simulator="auto"):
"""Route a (non-PLA) method the direct BNGsim path can't run.

Three cases:

* A valid method that needs an optional BNGsim component the build lacks
(``nf`` without NFsim, ``rm`` without RuleMonkey) is a *build*
incapability: BNGsim could run it with the component installed, so a
strict ``simulator='bngsim'`` request surfaces it as an error while
``auto`` falls back to legacy.
* Another known method the BNGsim path doesn't drive directly (e.g. the
``cvode`` alias) keeps the legacy subprocess route in every mode.
* A method outside the valid BNG universe is malformed — BNG2.pl rejects
it too — so it errors in every mode rather than silently going legacy.
"""
if method_name not in _KNOWN_BNGL_METHODS:
return BngsimRouteDecision(
ROUTE_ERROR,
f"BNGL method '{method_name}' is not a recognized simulation method "
"(expected one of ode, ssa, pla, psa, nf).",
method=method_name,
)
if method_name in _BNGSIM_OPTIONAL_COMPONENT_METHODS:
component = "NFsim" if _is_nf_method(method_name) else "RuleMonkey"
if simulator == "bngsim":
return BngsimRouteDecision(
ROUTE_ERROR,
f"simulator='bngsim' was requested but method '{method_name}' "
f"requires BNGsim {component} support, which this build lacks.",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGsim {component} support is unavailable; using legacy route.",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)


def _bngl_action_method_for_routing(action):
"""Extract only the method hint needed for conservative routing.

Expand DownExpand Up@@ -1310,9 +1375,16 @@ def _bngl_has_protocol_block(bngl_path):
# on its next run (matters for long-lived consumers like the VS Code
# extension).
_CACHE_MISS = object()
# key: (abspath, st_mtime_ns, st_size); value: parsed actions list (or None).
_ROUTING_ACTIONS_CACHE: dict[tuple[str, int, int], list | None] = {}
# key: (abspath, st_mtime_ns, st_size); value: (actions list or None, parse
# failure reason or None). The reason rides along so a strict
# ``simulator='bngsim'`` request can surface *why* inspection failed instead
# of silently downgrading to the legacy subprocess route (see issue #109).
_ROUTING_ACTIONS_CACHE: dict[tuple[str, int, int], tuple[list | None, str | None]] = {}
_ROUTING_ACTIONS_CACHE_MAX = 128
# Paths already warned about in auto mode, so a model whose actions can't be
# inspected for BNGsim routing produces one WARNING per run, not one per the
# ~4 routing queries each ``bionetgen.run`` makes for the same file.
_ROUTING_INSPECT_WARNED: set[str] = set()


def _clear_routing_actions_cache():
Expand All@@ -1321,16 +1393,18 @@ def _clear_routing_actions_cache():
never needs this because the cache key invalidates on file change.
"""
_ROUTING_ACTIONS_CACHE.clear()
_ROUTING_INSPECT_WARNED.clear()


def _load_bngl_actions_for_routing(bngl_path):
"""Parse BNGL actions for routing only — memoized per file identity.
def _load_bngl_routing_actions(bngl_path):
"""Parse BNGL actions for routing — memoized per file identity.

Returns the parsed action items (treat the list as read-only — routing
callers never mutate it) or ``None`` when the file cannot be parsed.
Parse failures fall back to BNG2.pl rather than blocking the legacy
path, and the ``None`` is cached too so a failing parse is not retried
several times per run.
Returns ``(actions, reason)``: the parsed action items (treat the list as
read-only — routing callers never mutate it) with ``reason=None``, or
``(None, reason)`` when the file cannot be parsed, where ``reason`` is the
underlying parse message. Parse failures fall back to BNG2.pl rather than
blocking the legacy path, and the failure is cached too so a failing parse
is not retried several times per run.
"""
try:
st = os.stat(bngl_path)
Expand All@@ -1341,46 +1415,85 @@ def _load_bngl_actions_for_routing(bngl_path):
cached = _ROUTING_ACTIONS_CACHE.get(key, _CACHE_MISS)
if cached is not _CACHE_MISS:
return cached
actions = _parse_bngl_actions_for_routing(bngl_path)
result = _parse_bngl_actions_for_routing(bngl_path)
if len(_ROUTING_ACTIONS_CACHE) >= _ROUTING_ACTIONS_CACHE_MAX:
# FIFO eviction — drop the oldest entry (dicts keep insertion order).
_ROUTING_ACTIONS_CACHE.pop(next(iter(_ROUTING_ACTIONS_CACHE)), None)
_ROUTING_ACTIONS_CACHE[key] = actions
return actions
_ROUTING_ACTIONS_CACHE[key] = result
return result


def _load_bngl_actions_for_routing(bngl_path):
"""Memoized routing action list (or ``None`` on parse failure).

Thin wrapper over :func:`_load_bngl_routing_actions` for callers that
only need the action items, not the parse-failure reason.
"""
return _load_bngl_routing_actions(bngl_path)[0]


def _parse_bngl_actions_for_routing(bngl_path):
"""Parse a BNGL file's action items via a throwaway ``bngmodel``.

Uncached — :func:`_load_bngl_actions_for_routing` is the memoized
entry point callers should use.
Returns ``(actions, reason)`` — the action list with ``reason=None`` on
success, or ``(None, reason)`` with the parse message on failure. Uncached
— :func:`_load_bngl_routing_actions` is the memoized entry point callers
should use.
"""
try:
import bionetgen.modelapi.model as mdl

model = mdl.bngmodel(bngl_path)
except Exception as exc:
logger.debug("could not parse BNGL for BNGsim routing (%s): %s", bngl_path, exc)
return None
return None, str(exc) or exc.__class__.__name__
try:
return list(model.actions.items)
return list(model.actions.items), None
except Exception as exc:
logger.debug(
"could not read BNGL actions for BNGsim routing (%s): %s", bngl_path, exc
)
return None
return None, str(exc) or exc.__class__.__name__


def _warn_routing_inspection_fallback_once(bngl_path, reason):
"""Warn once per file when auto-mode can't inspect a BNGL's actions for
BNGsim routing and falls back to the legacy subprocess engine."""
try:
key = os.path.abspath(bngl_path)
except Exception:
key = bngl_path
if key in _ROUTING_INSPECT_WARNED:
return
_ROUTING_INSPECT_WARNED.add(key)
logger.warning(
"Could not inspect BNGL actions for BNGsim routing (%s): %s. Using the "
"legacy subprocess (BNG2.pl) route. Pass simulator='bngsim' to require "
"BNGsim and surface this as an error instead.",
bngl_path,
reason,
)


def _classify_bngl_actions_for_bngsim(
actions_items,
method=None,
has_protocol=False,
bngsim_has_nfsim=None,
bngsim_has_rulemonkey=None,
simulator="auto",
):
"""Classify whether BNGL can use the BNG2.pl-owned BNGsim backend hook.

This routing pass only reads action names and method hints. It does not
evaluate BNGL expressions or replay any action semantics in Python.

``simulator`` affects the declines BNGsim *could* satisfy: under a strict
``simulator='bngsim'`` request an *unrecognized action* (runnable via the
BNG2.pl backend hook) and a *build incapability* (``nf`` without NFsim,
``rm`` without RuleMonkey) are surfaced as ``ROUTE_ERROR`` instead of
silently running legacy; ``auto`` falls back. PLA is a categorical BNGsim
incapability and stays on the subprocess route in every mode.
"""
if actions_items is None:
return BngsimRouteDecision(
Expand DownExpand Up@@ -1416,10 +1529,17 @@ def _classify_bngl_actions_for_bngsim(
continue

if atype is not None:
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL action '{atype}' is not a conservative BNGsim route",
)
reason = f"BNGL action '{atype}' is not a conservative BNGsim route"
if simulator == "bngsim":
# Strict mode: BNGsim could run this through the BNG2.pl
# backend hook, but the router can't confirm an unrecognized
# action is safe to delegate. Surface it instead of silently
# downgrading to legacy (issue #109 contract).
return BngsimRouteDecision(
ROUTE_ERROR,
f"simulator='bngsim' was requested but {reason}.",
)
return BngsimRouteDecision(ROUTE_SUBPROCESS, reason)

if len(sim_actions) > 1:
has_backend_hook_workflow = True
Expand DownExpand Up@@ -1458,17 +1578,15 @@ def _classify_bngl_actions_for_bngsim(
"BNGL PLA is not supported by BNGsim",
method="pla",
)
if _method_supported_by_bngsim_for_routing(method_name, bngsim_has_nfsim):
if _method_supported_by_bngsim_for_routing(
method_name, bngsim_has_nfsim, bngsim_has_rulemonkey
):
return BngsimRouteDecision(
ROUTE_BNGL_BNGSIM,
"BNGL method override is a BNGsim-supported simulation",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)
return _unsupported_method_route(method_name, simulator)

candidate_methods = []
for action in sim_actions:
Expand DownExpand Up@@ -1498,12 +1616,10 @@ def _classify_bngl_actions_for_bngsim(
)

for method_name in candidate_methods:
if not _method_supported_by_bngsim_for_routing(method_name, bngsim_has_nfsim):
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)
if not _method_supported_by_bngsim_for_routing(
method_name, bngsim_has_nfsim, bngsim_has_rulemonkey
):
return _unsupported_method_route(method_name, simulator)

if has_backend_hook_workflow:
return BngsimRouteDecision(
Expand All@@ -1529,12 +1645,15 @@ def classify_bngsim_route(
bngsim_has_nfsim=None,
bngl_actions=None,
has_protocol=None,
bngsim_has_rulemonkey=None,
):
"""Choose the conservative Stage 1 route for a simulation request."""
if bngsim_available is None:
bngsim_available = BNGSIM_AVAILABLE
if bngsim_has_nfsim is None:
bngsim_has_nfsim = BNGSIM_HAS_NFSIM
if bngsim_has_rulemonkey is None:
bngsim_has_rulemonkey = BNGSIM_HAS_RULEMONKEY

if simulator not in {"auto", "bngsim", "subprocess"}:
raise ValueError(
Expand DownExpand Up@@ -1628,13 +1747,30 @@ def classify_bngsim_route(

if has_protocol is None:
has_protocol = _bngl_has_protocol_block(input_path)
parse_reason = None
if bngl_actions is None:
bngl_actions, parse_reason = _load_bngl_routing_actions(input_path)
if bngl_actions is None:
bngl_actions = _load_bngl_actions_for_routing(input_path)
# Action inspection failed: the Python parser rejects this BNGL even
# though BNG2.pl may tolerate it (e.g. a typo'd or unknown ``simulate``
# argument). A strict ``simulator='bngsim'`` request must not silently
# downgrade to legacy BNG2.pl — surface why instead (issue #109). For
# ``auto`` the subprocess fallback stays, with a one-time warning.
detail = parse_reason or "the BNGL actions could not be parsed"
if simulator == "bngsim":
return BngsimRouteDecision(
ROUTE_ERROR,
"simulator='bngsim' was requested but the BNGL actions could "
f"not be inspected for BNGsim routing: {detail}",
)
_warn_routing_inspection_fallback_once(input_path, detail)
return _classify_bngl_actions_for_bngsim(
bngl_actions,
method=method,
has_protocol=has_protocol,
bngsim_has_nfsim=bngsim_has_nfsim,
bngsim_has_rulemonkey=bngsim_has_rulemonkey,
simulator=simulator,
)


Expand Down
13 changes: 12 additions & 1 deletion bionetgen/core/utils/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,7 +576,18 @@ def define_parser(self):
arg_type_expr = pp.Word(
pp.nums + "." + "+" + "-" + "e" + "E" + "(" + ")" + "/" + "*" + "^"
)
arg_type_list = "[" + pp.delimitedList((quote_word ^ arg_type_float)) + "]"
# Match BNG2.pl/Perl list syntax: elements may be quoted strings or
# numeric expressions including scientific notation (arg_type_expr
# covers e/E and +/-), an empty list `[]` is allowed, and a single
# trailing comma `[1,2,]` is tolerated. arg_type_float only spans
# digits and '.', so it rejected `2.3e-10`; delimitedList rejected the
# trailing comma — both are valid Perl that BNG2.pl runs (issue #110).
arg_type_list = (
"["
+ pp.Optional(pp.delimitedList(quote_word ^ arg_type_expr))
+ pp.Optional(",")
+ "]"
)
arg_type_string = quote_word
#
# BNGL/Perl `=>` auto-quotes its left operand, so dict keys
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
206 changes: 171 additions & 35 deletions bionetgen/core/tools/bngsim_bridge.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1201,6 +1201,21 @@ def _nfsim_session_kwargs(nf_params):

_BNGSIM_NETWORK_METHODS = frozenset({"ode", "ssa", "psa", "rm"})

# Every method string BNG2.pl's simulate() accepts: its $METHODS hash keys
# (cvode, ssa, pla, psa, nf) plus the documented 'ode' alias for 'cvode',
# extended with 'rm' (RuleMonkey), which the bridge rewrites onto the nf
# backend. A method outside this set is malformed — BNG2.pl itself rejects it
# ("Simulation method '...' is not a valid option.") — so the router surfaces
# it as an error rather than silently shipping it to the legacy stack.
_KNOWN_BNGL_METHODS = frozenset({"ode", "cvode", "ssa", "psa", "pla", "nf", "rm"})

# Methods that need an optional BNGsim component the build may lack: nf needs
# NFsim, rm (RuleMonkey) needs the RuleMonkey session. BNGsim *can* run these
# when the component is present, so an absent component is a build incapability
# (surfaced as an error under strict simulator='bngsim', legacy fallback under
# auto) rather than a categorical one like pla.
_BNGSIM_OPTIONAL_COMPONENT_METHODS = frozenset({"nf", "rm"})

_BNGL_ROUTING_COMPLEX_ACTIONS = frozenset(
{
"parameter_scan",
Expand DownExpand Up@@ -1235,8 +1250,15 @@ def _nfsim_session_kwargs(nf_params):
)


def _method_supported_by_bngsim_for_routing(method, bngsim_has_nfsim=None):
def _method_supported_by_bngsim_for_routing(
method, bngsim_has_nfsim=None, bngsim_has_rulemonkey=None
):
"""Return True if a normalized method can be handed to BNGsim."""
if method == "rm":
# RuleMonkey is an optional BNGsim component, like NFsim for nf.
if bngsim_has_rulemonkey is None:
bngsim_has_rulemonkey = BNGSIM_HAS_RULEMONKEY
return bool(bngsim_has_rulemonkey)
if method in _BNGSIM_NETWORK_METHODS:
return True
if _is_nf_method(method):
Expand All@@ -1246,6 +1268,49 @@ def _method_supported_by_bngsim_for_routing(method, bngsim_has_nfsim=None):
return False


def _unsupported_method_route(method_name, simulator="auto"):
"""Route a (non-PLA) method the direct BNGsim path can't run.

Three cases:

* A valid method that needs an optional BNGsim component the build lacks
(``nf`` without NFsim, ``rm`` without RuleMonkey) is a *build*
incapability: BNGsim could run it with the component installed, so a
strict ``simulator='bngsim'`` request surfaces it as an error while
``auto`` falls back to legacy.
* Another known method the BNGsim path doesn't drive directly (e.g. the
``cvode`` alias) keeps the legacy subprocess route in every mode.
* A method outside the valid BNG universe is malformed — BNG2.pl rejects
it too — so it errors in every mode rather than silently going legacy.
"""
if method_name not in _KNOWN_BNGL_METHODS:
return BngsimRouteDecision(
ROUTE_ERROR,
f"BNGL method '{method_name}' is not a recognized simulation method "
"(expected one of ode, ssa, pla, psa, nf).",
method=method_name,
)
if method_name in _BNGSIM_OPTIONAL_COMPONENT_METHODS:
component = "NFsim" if _is_nf_method(method_name) else "RuleMonkey"
if simulator == "bngsim":
return BngsimRouteDecision(
ROUTE_ERROR,
f"simulator='bngsim' was requested but method '{method_name}' "
f"requires BNGsim {component} support, which this build lacks.",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGsim {component} support is unavailable; using legacy route.",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)


def _bngl_action_method_for_routing(action):
"""Extract only the method hint needed for conservative routing.

Expand DownExpand Up@@ -1310,9 +1375,16 @@ def _bngl_has_protocol_block(bngl_path):
# on its next run (matters for long-lived consumers like the VS Code
# extension).
_CACHE_MISS = object()
# key: (abspath, st_mtime_ns, st_size); value: parsed actions list (or None).
_ROUTING_ACTIONS_CACHE: dict[tuple[str, int, int], list | None] = {}
# key: (abspath, st_mtime_ns, st_size); value: (actions list or None, parse
# failure reason or None). The reason rides along so a strict
# ``simulator='bngsim'`` request can surface *why* inspection failed instead
# of silently downgrading to the legacy subprocess route (see issue #109).
_ROUTING_ACTIONS_CACHE: dict[tuple[str, int, int], tuple[list | None, str | None]] = {}
_ROUTING_ACTIONS_CACHE_MAX = 128
# Paths already warned about in auto mode, so a model whose actions can't be
# inspected for BNGsim routing produces one WARNING per run, not one per the
# ~4 routing queries each ``bionetgen.run`` makes for the same file.
_ROUTING_INSPECT_WARNED: set[str] = set()


def _clear_routing_actions_cache():
Expand All@@ -1321,16 +1393,18 @@ def _clear_routing_actions_cache():
never needs this because the cache key invalidates on file change.
"""
_ROUTING_ACTIONS_CACHE.clear()
_ROUTING_INSPECT_WARNED.clear()


def _load_bngl_actions_for_routing(bngl_path):
"""Parse BNGL actions for routing only — memoized per file identity.
def _load_bngl_routing_actions(bngl_path):
"""Parse BNGL actions for routing — memoized per file identity.

Returns the parsed action items (treat the list as read-only — routing
callers never mutate it) or ``None`` when the file cannot be parsed.
Parse failures fall back to BNG2.pl rather than blocking the legacy
path, and the ``None`` is cached too so a failing parse is not retried
several times per run.
Returns ``(actions, reason)``: the parsed action items (treat the list as
read-only — routing callers never mutate it) with ``reason=None``, or
``(None, reason)`` when the file cannot be parsed, where ``reason`` is the
underlying parse message. Parse failures fall back to BNG2.pl rather than
blocking the legacy path, and the failure is cached too so a failing parse
is not retried several times per run.
"""
try:
st = os.stat(bngl_path)
Expand All@@ -1341,46 +1415,85 @@ def _load_bngl_actions_for_routing(bngl_path):
cached = _ROUTING_ACTIONS_CACHE.get(key, _CACHE_MISS)
if cached is not _CACHE_MISS:
return cached
actions = _parse_bngl_actions_for_routing(bngl_path)
result = _parse_bngl_actions_for_routing(bngl_path)
if len(_ROUTING_ACTIONS_CACHE) >= _ROUTING_ACTIONS_CACHE_MAX:
# FIFO eviction — drop the oldest entry (dicts keep insertion order).
_ROUTING_ACTIONS_CACHE.pop(next(iter(_ROUTING_ACTIONS_CACHE)), None)
_ROUTING_ACTIONS_CACHE[key] = actions
return actions
_ROUTING_ACTIONS_CACHE[key] = result
return result


def _load_bngl_actions_for_routing(bngl_path):
"""Memoized routing action list (or ``None`` on parse failure).

Thin wrapper over :func:`_load_bngl_routing_actions` for callers that
only need the action items, not the parse-failure reason.
"""
return _load_bngl_routing_actions(bngl_path)[0]


def _parse_bngl_actions_for_routing(bngl_path):
"""Parse a BNGL file's action items via a throwaway ``bngmodel``.

Uncached — :func:`_load_bngl_actions_for_routing` is the memoized
entry point callers should use.
Returns ``(actions, reason)`` — the action list with ``reason=None`` on
success, or ``(None, reason)`` with the parse message on failure. Uncached
— :func:`_load_bngl_routing_actions` is the memoized entry point callers
should use.
"""
try:
import bionetgen.modelapi.model as mdl

model = mdl.bngmodel(bngl_path)
except Exception as exc:
logger.debug("could not parse BNGL for BNGsim routing (%s): %s", bngl_path, exc)
return None
return None, str(exc) or exc.__class__.__name__
try:
return list(model.actions.items)
return list(model.actions.items), None
except Exception as exc:
logger.debug(
"could not read BNGL actions for BNGsim routing (%s): %s", bngl_path, exc
)
return None
return None, str(exc) or exc.__class__.__name__


def _warn_routing_inspection_fallback_once(bngl_path, reason):
"""Warn once per file when auto-mode can't inspect a BNGL's actions for
BNGsim routing and falls back to the legacy subprocess engine."""
try:
key = os.path.abspath(bngl_path)
except Exception:
key = bngl_path
if key in _ROUTING_INSPECT_WARNED:
return
_ROUTING_INSPECT_WARNED.add(key)
logger.warning(
"Could not inspect BNGL actions for BNGsim routing (%s): %s. Using the "
"legacy subprocess (BNG2.pl) route. Pass simulator='bngsim' to require "
"BNGsim and surface this as an error instead.",
bngl_path,
reason,
)


def _classify_bngl_actions_for_bngsim(
actions_items,
method=None,
has_protocol=False,
bngsim_has_nfsim=None,
bngsim_has_rulemonkey=None,
simulator="auto",
):
"""Classify whether BNGL can use the BNG2.pl-owned BNGsim backend hook.

This routing pass only reads action names and method hints. It does not
evaluate BNGL expressions or replay any action semantics in Python.

``simulator`` affects the declines BNGsim *could* satisfy: under a strict
``simulator='bngsim'`` request an *unrecognized action* (runnable via the
BNG2.pl backend hook) and a *build incapability* (``nf`` without NFsim,
``rm`` without RuleMonkey) are surfaced as ``ROUTE_ERROR`` instead of
silently running legacy; ``auto`` falls back. PLA is a categorical BNGsim
incapability and stays on the subprocess route in every mode.
"""
if actions_items is None:
return BngsimRouteDecision(
Expand DownExpand Up@@ -1416,10 +1529,17 @@ def _classify_bngl_actions_for_bngsim(
continue

if atype is not None:
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL action '{atype}' is not a conservative BNGsim route",
)
reason = f"BNGL action '{atype}' is not a conservative BNGsim route"
if simulator == "bngsim":
# Strict mode: BNGsim could run this through the BNG2.pl
# backend hook, but the router can't confirm an unrecognized
# action is safe to delegate. Surface it instead of silently
# downgrading to legacy (issue #109 contract).
return BngsimRouteDecision(
ROUTE_ERROR,
f"simulator='bngsim' was requested but {reason}.",
)
return BngsimRouteDecision(ROUTE_SUBPROCESS, reason)

if len(sim_actions) > 1:
has_backend_hook_workflow = True
Expand DownExpand Up@@ -1458,17 +1578,15 @@ def _classify_bngl_actions_for_bngsim(
"BNGL PLA is not supported by BNGsim",
method="pla",
)
if _method_supported_by_bngsim_for_routing(method_name, bngsim_has_nfsim):
if _method_supported_by_bngsim_for_routing(
method_name, bngsim_has_nfsim, bngsim_has_rulemonkey
):
return BngsimRouteDecision(
ROUTE_BNGL_BNGSIM,
"BNGL method override is a BNGsim-supported simulation",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)
return _unsupported_method_route(method_name, simulator)

candidate_methods = []
for action in sim_actions:
Expand DownExpand Up@@ -1498,12 +1616,10 @@ def _classify_bngl_actions_for_bngsim(
)

for method_name in candidate_methods:
if not _method_supported_by_bngsim_for_routing(method_name, bngsim_has_nfsim):
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)
if not _method_supported_by_bngsim_for_routing(
method_name, bngsim_has_nfsim, bngsim_has_rulemonkey
):
return _unsupported_method_route(method_name, simulator)

if has_backend_hook_workflow:
return BngsimRouteDecision(
Expand All@@ -1529,12 +1645,15 @@ def classify_bngsim_route(
bngsim_has_nfsim=None,
bngl_actions=None,
has_protocol=None,
bngsim_has_rulemonkey=None,
):
"""Choose the conservative Stage 1 route for a simulation request."""
if bngsim_available is None:
bngsim_available = BNGSIM_AVAILABLE
if bngsim_has_nfsim is None:
bngsim_has_nfsim = BNGSIM_HAS_NFSIM
if bngsim_has_rulemonkey is None:
bngsim_has_rulemonkey = BNGSIM_HAS_RULEMONKEY

if simulator not in {"auto", "bngsim", "subprocess"}:
raise ValueError(
Expand DownExpand Up@@ -1628,13 +1747,30 @@ def classify_bngsim_route(

if has_protocol is None:
has_protocol = _bngl_has_protocol_block(input_path)
parse_reason = None
if bngl_actions is None:
bngl_actions, parse_reason = _load_bngl_routing_actions(input_path)
if bngl_actions is None:
bngl_actions = _load_bngl_actions_for_routing(input_path)
# Action inspection failed: the Python parser rejects this BNGL even
# though BNG2.pl may tolerate it (e.g. a typo'd or unknown ``simulate``
# argument). A strict ``simulator='bngsim'`` request must not silently
# downgrade to legacy BNG2.pl — surface why instead (issue #109). For
# ``auto`` the subprocess fallback stays, with a one-time warning.
detail = parse_reason or "the BNGL actions could not be parsed"
if simulator == "bngsim":
return BngsimRouteDecision(
ROUTE_ERROR,
"simulator='bngsim' was requested but the BNGL actions could "
f"not be inspected for BNGsim routing: {detail}",
)
_warn_routing_inspection_fallback_once(input_path, detail)
return _classify_bngl_actions_for_bngsim(
bngl_actions,
method=method,
has_protocol=has_protocol,
bngsim_has_nfsim=bngsim_has_nfsim,
bngsim_has_rulemonkey=bngsim_has_rulemonkey,
simulator=simulator,
)


Expand Down
13 changes: 12 additions & 1 deletion bionetgen/core/utils/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,7 +576,18 @@ def define_parser(self):
arg_type_expr = pp.Word(
pp.nums + "." + "+" + "-" + "e" + "E" + "(" + ")" + "/" + "*" + "^"
)
arg_type_list = "[" + pp.delimitedList((quote_word ^ arg_type_float)) + "]"
# Match BNG2.pl/Perl list syntax: elements may be quoted strings or
# numeric expressions including scientific notation (arg_type_expr
# covers e/E and +/-), an empty list `[]` is allowed, and a single
# trailing comma `[1,2,]` is tolerated. arg_type_float only spans
# digits and '.', so it rejected `2.3e-10`; delimitedList rejected the
# trailing comma — both are valid Perl that BNG2.pl runs (issue #110).
arg_type_list = (
"["
+ pp.Optional(pp.delimitedList(quote_word ^ arg_type_expr))
+ pp.Optional(",")
+ "]"
)
arg_type_string = quote_word
#
# BNGL/Perl `=>` auto-quotes its left operand, so dict keys
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
206 changes: 171 additions & 35 deletions bionetgen/core/tools/bngsim_bridge.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1201,6 +1201,21 @@ def _nfsim_session_kwargs(nf_params):

_BNGSIM_NETWORK_METHODS = frozenset({"ode", "ssa", "psa", "rm"})

# Every method string BNG2.pl's simulate() accepts: its $METHODS hash keys
# (cvode, ssa, pla, psa, nf) plus the documented 'ode' alias for 'cvode',
# extended with 'rm' (RuleMonkey), which the bridge rewrites onto the nf
# backend. A method outside this set is malformed — BNG2.pl itself rejects it
# ("Simulation method '...' is not a valid option.") — so the router surfaces
# it as an error rather than silently shipping it to the legacy stack.
_KNOWN_BNGL_METHODS = frozenset({"ode", "cvode", "ssa", "psa", "pla", "nf", "rm"})

# Methods that need an optional BNGsim component the build may lack: nf needs
# NFsim, rm (RuleMonkey) needs the RuleMonkey session. BNGsim *can* run these
# when the component is present, so an absent component is a build incapability
# (surfaced as an error under strict simulator='bngsim', legacy fallback under
# auto) rather than a categorical one like pla.
_BNGSIM_OPTIONAL_COMPONENT_METHODS = frozenset({"nf", "rm"})

_BNGL_ROUTING_COMPLEX_ACTIONS = frozenset(
{
"parameter_scan",
Expand DownExpand Up@@ -1235,8 +1250,15 @@ def _nfsim_session_kwargs(nf_params):
)


def _method_supported_by_bngsim_for_routing(method, bngsim_has_nfsim=None):
def _method_supported_by_bngsim_for_routing(
method, bngsim_has_nfsim=None, bngsim_has_rulemonkey=None
):
"""Return True if a normalized method can be handed to BNGsim."""
if method == "rm":
# RuleMonkey is an optional BNGsim component, like NFsim for nf.
if bngsim_has_rulemonkey is None:
bngsim_has_rulemonkey = BNGSIM_HAS_RULEMONKEY
return bool(bngsim_has_rulemonkey)
if method in _BNGSIM_NETWORK_METHODS:
return True
if _is_nf_method(method):
Expand All@@ -1246,6 +1268,49 @@ def _method_supported_by_bngsim_for_routing(method, bngsim_has_nfsim=None):
return False


def _unsupported_method_route(method_name, simulator="auto"):
"""Route a (non-PLA) method the direct BNGsim path can't run.

Three cases:

* A valid method that needs an optional BNGsim component the build lacks
(``nf`` without NFsim, ``rm`` without RuleMonkey) is a *build*
incapability: BNGsim could run it with the component installed, so a
strict ``simulator='bngsim'`` request surfaces it as an error while
``auto`` falls back to legacy.
* Another known method the BNGsim path doesn't drive directly (e.g. the
``cvode`` alias) keeps the legacy subprocess route in every mode.
* A method outside the valid BNG universe is malformed — BNG2.pl rejects
it too — so it errors in every mode rather than silently going legacy.
"""
if method_name not in _KNOWN_BNGL_METHODS:
return BngsimRouteDecision(
ROUTE_ERROR,
f"BNGL method '{method_name}' is not a recognized simulation method "
"(expected one of ode, ssa, pla, psa, nf).",
method=method_name,
)
if method_name in _BNGSIM_OPTIONAL_COMPONENT_METHODS:
component = "NFsim" if _is_nf_method(method_name) else "RuleMonkey"
if simulator == "bngsim":
return BngsimRouteDecision(
ROUTE_ERROR,
f"simulator='bngsim' was requested but method '{method_name}' "
f"requires BNGsim {component} support, which this build lacks.",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGsim {component} support is unavailable; using legacy route.",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)


def _bngl_action_method_for_routing(action):
"""Extract only the method hint needed for conservative routing.

Expand DownExpand Up@@ -1310,9 +1375,16 @@ def _bngl_has_protocol_block(bngl_path):
# on its next run (matters for long-lived consumers like the VS Code
# extension).
_CACHE_MISS = object()
# key: (abspath, st_mtime_ns, st_size); value: parsed actions list (or None).
_ROUTING_ACTIONS_CACHE: dict[tuple[str, int, int], list | None] = {}
# key: (abspath, st_mtime_ns, st_size); value: (actions list or None, parse
# failure reason or None). The reason rides along so a strict
# ``simulator='bngsim'`` request can surface *why* inspection failed instead
# of silently downgrading to the legacy subprocess route (see issue #109).
_ROUTING_ACTIONS_CACHE: dict[tuple[str, int, int], tuple[list | None, str | None]] = {}
_ROUTING_ACTIONS_CACHE_MAX = 128
# Paths already warned about in auto mode, so a model whose actions can't be
# inspected for BNGsim routing produces one WARNING per run, not one per the
# ~4 routing queries each ``bionetgen.run`` makes for the same file.
_ROUTING_INSPECT_WARNED: set[str] = set()


def _clear_routing_actions_cache():
Expand All@@ -1321,16 +1393,18 @@ def _clear_routing_actions_cache():
never needs this because the cache key invalidates on file change.
"""
_ROUTING_ACTIONS_CACHE.clear()
_ROUTING_INSPECT_WARNED.clear()


def _load_bngl_actions_for_routing(bngl_path):
"""Parse BNGL actions for routing only — memoized per file identity.
def _load_bngl_routing_actions(bngl_path):
"""Parse BNGL actions for routing — memoized per file identity.

Returns the parsed action items (treat the list as read-only — routing
callers never mutate it) or ``None`` when the file cannot be parsed.
Parse failures fall back to BNG2.pl rather than blocking the legacy
path, and the ``None`` is cached too so a failing parse is not retried
several times per run.
Returns ``(actions, reason)``: the parsed action items (treat the list as
read-only — routing callers never mutate it) with ``reason=None``, or
``(None, reason)`` when the file cannot be parsed, where ``reason`` is the
underlying parse message. Parse failures fall back to BNG2.pl rather than
blocking the legacy path, and the failure is cached too so a failing parse
is not retried several times per run.
"""
try:
st = os.stat(bngl_path)
Expand All@@ -1341,46 +1415,85 @@ def _load_bngl_actions_for_routing(bngl_path):
cached = _ROUTING_ACTIONS_CACHE.get(key, _CACHE_MISS)
if cached is not _CACHE_MISS:
return cached
actions = _parse_bngl_actions_for_routing(bngl_path)
result = _parse_bngl_actions_for_routing(bngl_path)
if len(_ROUTING_ACTIONS_CACHE) >= _ROUTING_ACTIONS_CACHE_MAX:
# FIFO eviction — drop the oldest entry (dicts keep insertion order).
_ROUTING_ACTIONS_CACHE.pop(next(iter(_ROUTING_ACTIONS_CACHE)), None)
_ROUTING_ACTIONS_CACHE[key] = actions
return actions
_ROUTING_ACTIONS_CACHE[key] = result
return result


def _load_bngl_actions_for_routing(bngl_path):
"""Memoized routing action list (or ``None`` on parse failure).

Thin wrapper over :func:`_load_bngl_routing_actions` for callers that
only need the action items, not the parse-failure reason.
"""
return _load_bngl_routing_actions(bngl_path)[0]


def _parse_bngl_actions_for_routing(bngl_path):
"""Parse a BNGL file's action items via a throwaway ``bngmodel``.

Uncached — :func:`_load_bngl_actions_for_routing` is the memoized
entry point callers should use.
Returns ``(actions, reason)`` — the action list with ``reason=None`` on
success, or ``(None, reason)`` with the parse message on failure. Uncached
— :func:`_load_bngl_routing_actions` is the memoized entry point callers
should use.
"""
try:
import bionetgen.modelapi.model as mdl

model = mdl.bngmodel(bngl_path)
except Exception as exc:
logger.debug("could not parse BNGL for BNGsim routing (%s): %s", bngl_path, exc)
return None
return None, str(exc) or exc.__class__.__name__
try:
return list(model.actions.items)
return list(model.actions.items), None
except Exception as exc:
logger.debug(
"could not read BNGL actions for BNGsim routing (%s): %s", bngl_path, exc
)
return None
return None, str(exc) or exc.__class__.__name__


def _warn_routing_inspection_fallback_once(bngl_path, reason):
"""Warn once per file when auto-mode can't inspect a BNGL's actions for
BNGsim routing and falls back to the legacy subprocess engine."""
try:
key = os.path.abspath(bngl_path)
except Exception:
key = bngl_path
if key in _ROUTING_INSPECT_WARNED:
return
_ROUTING_INSPECT_WARNED.add(key)
logger.warning(
"Could not inspect BNGL actions for BNGsim routing (%s): %s. Using the "
"legacy subprocess (BNG2.pl) route. Pass simulator='bngsim' to require "
"BNGsim and surface this as an error instead.",
bngl_path,
reason,
)


def _classify_bngl_actions_for_bngsim(
actions_items,
method=None,
has_protocol=False,
bngsim_has_nfsim=None,
bngsim_has_rulemonkey=None,
simulator="auto",
):
"""Classify whether BNGL can use the BNG2.pl-owned BNGsim backend hook.

This routing pass only reads action names and method hints. It does not
evaluate BNGL expressions or replay any action semantics in Python.

``simulator`` affects the declines BNGsim *could* satisfy: under a strict
``simulator='bngsim'`` request an *unrecognized action* (runnable via the
BNG2.pl backend hook) and a *build incapability* (``nf`` without NFsim,
``rm`` without RuleMonkey) are surfaced as ``ROUTE_ERROR`` instead of
silently running legacy; ``auto`` falls back. PLA is a categorical BNGsim
incapability and stays on the subprocess route in every mode.
"""
if actions_items is None:
return BngsimRouteDecision(
Expand DownExpand Up@@ -1416,10 +1529,17 @@ def _classify_bngl_actions_for_bngsim(
continue

if atype is not None:
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL action '{atype}' is not a conservative BNGsim route",
)
reason = f"BNGL action '{atype}' is not a conservative BNGsim route"
if simulator == "bngsim":
# Strict mode: BNGsim could run this through the BNG2.pl
# backend hook, but the router can't confirm an unrecognized
# action is safe to delegate. Surface it instead of silently
# downgrading to legacy (issue #109 contract).
return BngsimRouteDecision(
ROUTE_ERROR,
f"simulator='bngsim' was requested but {reason}.",
)
return BngsimRouteDecision(ROUTE_SUBPROCESS, reason)

if len(sim_actions) > 1:
has_backend_hook_workflow = True
Expand DownExpand Up@@ -1458,17 +1578,15 @@ def _classify_bngl_actions_for_bngsim(
"BNGL PLA is not supported by BNGsim",
method="pla",
)
if _method_supported_by_bngsim_for_routing(method_name, bngsim_has_nfsim):
if _method_supported_by_bngsim_for_routing(
method_name, bngsim_has_nfsim, bngsim_has_rulemonkey
):
return BngsimRouteDecision(
ROUTE_BNGL_BNGSIM,
"BNGL method override is a BNGsim-supported simulation",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)
return _unsupported_method_route(method_name, simulator)

candidate_methods = []
for action in sim_actions:
Expand DownExpand Up@@ -1498,12 +1616,10 @@ def _classify_bngl_actions_for_bngsim(
)

for method_name in candidate_methods:
if not _method_supported_by_bngsim_for_routing(method_name, bngsim_has_nfsim):
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)
if not _method_supported_by_bngsim_for_routing(
method_name, bngsim_has_nfsim, bngsim_has_rulemonkey
):
return _unsupported_method_route(method_name, simulator)

if has_backend_hook_workflow:
return BngsimRouteDecision(
Expand All@@ -1529,12 +1645,15 @@ def classify_bngsim_route(
bngsim_has_nfsim=None,
bngl_actions=None,
has_protocol=None,
bngsim_has_rulemonkey=None,
):
"""Choose the conservative Stage 1 route for a simulation request."""
if bngsim_available is None:
bngsim_available = BNGSIM_AVAILABLE
if bngsim_has_nfsim is None:
bngsim_has_nfsim = BNGSIM_HAS_NFSIM
if bngsim_has_rulemonkey is None:
bngsim_has_rulemonkey = BNGSIM_HAS_RULEMONKEY

if simulator not in {"auto", "bngsim", "subprocess"}:
raise ValueError(
Expand DownExpand Up@@ -1628,13 +1747,30 @@ def classify_bngsim_route(

if has_protocol is None:
has_protocol = _bngl_has_protocol_block(input_path)
parse_reason = None
if bngl_actions is None:
bngl_actions, parse_reason = _load_bngl_routing_actions(input_path)
if bngl_actions is None:
bngl_actions = _load_bngl_actions_for_routing(input_path)
# Action inspection failed: the Python parser rejects this BNGL even
# though BNG2.pl may tolerate it (e.g. a typo'd or unknown ``simulate``
# argument). A strict ``simulator='bngsim'`` request must not silently
# downgrade to legacy BNG2.pl — surface why instead (issue #109). For
# ``auto`` the subprocess fallback stays, with a one-time warning.
detail = parse_reason or "the BNGL actions could not be parsed"
if simulator == "bngsim":
return BngsimRouteDecision(
ROUTE_ERROR,
"simulator='bngsim' was requested but the BNGL actions could "
f"not be inspected for BNGsim routing: {detail}",
)
_warn_routing_inspection_fallback_once(input_path, detail)
return _classify_bngl_actions_for_bngsim(
bngl_actions,
method=method,
has_protocol=has_protocol,
bngsim_has_nfsim=bngsim_has_nfsim,
bngsim_has_rulemonkey=bngsim_has_rulemonkey,
simulator=simulator,
)


Expand Down
13 changes: 12 additions & 1 deletion bionetgen/core/utils/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,7 +576,18 @@ def define_parser(self):
arg_type_expr = pp.Word(
pp.nums + "." + "+" + "-" + "e" + "E" + "(" + ")" + "/" + "*" + "^"
)
arg_type_list = "[" + pp.delimitedList((quote_word ^ arg_type_float)) + "]"
# Match BNG2.pl/Perl list syntax: elements may be quoted strings or
# numeric expressions including scientific notation (arg_type_expr
# covers e/E and +/-), an empty list `[]` is allowed, and a single
# trailing comma `[1,2,]` is tolerated. arg_type_float only spans
# digits and '.', so it rejected `2.3e-10`; delimitedList rejected the
# trailing comma — both are valid Perl that BNG2.pl runs (issue #110).
arg_type_list = (
"["
+ pp.Optional(pp.delimitedList(quote_word ^ arg_type_expr))
+ pp.Optional(",")
+ "]"
)
arg_type_string = quote_word
#
# BNGL/Perl `=>` auto-quotes its left operand, so dict keys
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
206 changes: 171 additions & 35 deletions bionetgen/core/tools/bngsim_bridge.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1201,6 +1201,21 @@ def _nfsim_session_kwargs(nf_params):

_BNGSIM_NETWORK_METHODS = frozenset({"ode", "ssa", "psa", "rm"})

# Every method string BNG2.pl's simulate() accepts: its $METHODS hash keys
# (cvode, ssa, pla, psa, nf) plus the documented 'ode' alias for 'cvode',
# extended with 'rm' (RuleMonkey), which the bridge rewrites onto the nf
# backend. A method outside this set is malformed — BNG2.pl itself rejects it
# ("Simulation method '...' is not a valid option.") — so the router surfaces
# it as an error rather than silently shipping it to the legacy stack.
_KNOWN_BNGL_METHODS = frozenset({"ode", "cvode", "ssa", "psa", "pla", "nf", "rm"})

# Methods that need an optional BNGsim component the build may lack: nf needs
# NFsim, rm (RuleMonkey) needs the RuleMonkey session. BNGsim *can* run these
# when the component is present, so an absent component is a build incapability
# (surfaced as an error under strict simulator='bngsim', legacy fallback under
# auto) rather than a categorical one like pla.
_BNGSIM_OPTIONAL_COMPONENT_METHODS = frozenset({"nf", "rm"})

_BNGL_ROUTING_COMPLEX_ACTIONS = frozenset(
{
"parameter_scan",
Expand DownExpand Up@@ -1235,8 +1250,15 @@ def _nfsim_session_kwargs(nf_params):
)


def _method_supported_by_bngsim_for_routing(method, bngsim_has_nfsim=None):
def _method_supported_by_bngsim_for_routing(
method, bngsim_has_nfsim=None, bngsim_has_rulemonkey=None
):
"""Return True if a normalized method can be handed to BNGsim."""
if method == "rm":
# RuleMonkey is an optional BNGsim component, like NFsim for nf.
if bngsim_has_rulemonkey is None:
bngsim_has_rulemonkey = BNGSIM_HAS_RULEMONKEY
return bool(bngsim_has_rulemonkey)
if method in _BNGSIM_NETWORK_METHODS:
return True
if _is_nf_method(method):
Expand All@@ -1246,6 +1268,49 @@ def _method_supported_by_bngsim_for_routing(method, bngsim_has_nfsim=None):
return False


def _unsupported_method_route(method_name, simulator="auto"):
"""Route a (non-PLA) method the direct BNGsim path can't run.

Three cases:

* A valid method that needs an optional BNGsim component the build lacks
(``nf`` without NFsim, ``rm`` without RuleMonkey) is a *build*
incapability: BNGsim could run it with the component installed, so a
strict ``simulator='bngsim'`` request surfaces it as an error while
``auto`` falls back to legacy.
* Another known method the BNGsim path doesn't drive directly (e.g. the
``cvode`` alias) keeps the legacy subprocess route in every mode.
* A method outside the valid BNG universe is malformed — BNG2.pl rejects
it too — so it errors in every mode rather than silently going legacy.
"""
if method_name not in _KNOWN_BNGL_METHODS:
return BngsimRouteDecision(
ROUTE_ERROR,
f"BNGL method '{method_name}' is not a recognized simulation method "
"(expected one of ode, ssa, pla, psa, nf).",
method=method_name,
)
if method_name in _BNGSIM_OPTIONAL_COMPONENT_METHODS:
component = "NFsim" if _is_nf_method(method_name) else "RuleMonkey"
if simulator == "bngsim":
return BngsimRouteDecision(
ROUTE_ERROR,
f"simulator='bngsim' was requested but method '{method_name}' "
f"requires BNGsim {component} support, which this build lacks.",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGsim {component} support is unavailable; using legacy route.",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)


def _bngl_action_method_for_routing(action):
"""Extract only the method hint needed for conservative routing.

Expand DownExpand Up@@ -1310,9 +1375,16 @@ def _bngl_has_protocol_block(bngl_path):
# on its next run (matters for long-lived consumers like the VS Code
# extension).
_CACHE_MISS = object()
# key: (abspath, st_mtime_ns, st_size); value: parsed actions list (or None).
_ROUTING_ACTIONS_CACHE: dict[tuple[str, int, int], list | None] = {}
# key: (abspath, st_mtime_ns, st_size); value: (actions list or None, parse
# failure reason or None). The reason rides along so a strict
# ``simulator='bngsim'`` request can surface *why* inspection failed instead
# of silently downgrading to the legacy subprocess route (see issue #109).
_ROUTING_ACTIONS_CACHE: dict[tuple[str, int, int], tuple[list | None, str | None]] = {}
_ROUTING_ACTIONS_CACHE_MAX = 128
# Paths already warned about in auto mode, so a model whose actions can't be
# inspected for BNGsim routing produces one WARNING per run, not one per the
# ~4 routing queries each ``bionetgen.run`` makes for the same file.
_ROUTING_INSPECT_WARNED: set[str] = set()


def _clear_routing_actions_cache():
Expand All@@ -1321,16 +1393,18 @@ def _clear_routing_actions_cache():
never needs this because the cache key invalidates on file change.
"""
_ROUTING_ACTIONS_CACHE.clear()
_ROUTING_INSPECT_WARNED.clear()


def _load_bngl_actions_for_routing(bngl_path):
"""Parse BNGL actions for routing only — memoized per file identity.
def _load_bngl_routing_actions(bngl_path):
"""Parse BNGL actions for routing — memoized per file identity.

Returns the parsed action items (treat the list as read-only — routing
callers never mutate it) or ``None`` when the file cannot be parsed.
Parse failures fall back to BNG2.pl rather than blocking the legacy
path, and the ``None`` is cached too so a failing parse is not retried
several times per run.
Returns ``(actions, reason)``: the parsed action items (treat the list as
read-only — routing callers never mutate it) with ``reason=None``, or
``(None, reason)`` when the file cannot be parsed, where ``reason`` is the
underlying parse message. Parse failures fall back to BNG2.pl rather than
blocking the legacy path, and the failure is cached too so a failing parse
is not retried several times per run.
"""
try:
st = os.stat(bngl_path)
Expand All@@ -1341,46 +1415,85 @@ def _load_bngl_actions_for_routing(bngl_path):
cached = _ROUTING_ACTIONS_CACHE.get(key, _CACHE_MISS)
if cached is not _CACHE_MISS:
return cached
actions = _parse_bngl_actions_for_routing(bngl_path)
result = _parse_bngl_actions_for_routing(bngl_path)
if len(_ROUTING_ACTIONS_CACHE) >= _ROUTING_ACTIONS_CACHE_MAX:
# FIFO eviction — drop the oldest entry (dicts keep insertion order).
_ROUTING_ACTIONS_CACHE.pop(next(iter(_ROUTING_ACTIONS_CACHE)), None)
_ROUTING_ACTIONS_CACHE[key] = actions
return actions
_ROUTING_ACTIONS_CACHE[key] = result
return result


def _load_bngl_actions_for_routing(bngl_path):
"""Memoized routing action list (or ``None`` on parse failure).

Thin wrapper over :func:`_load_bngl_routing_actions` for callers that
only need the action items, not the parse-failure reason.
"""
return _load_bngl_routing_actions(bngl_path)[0]


def _parse_bngl_actions_for_routing(bngl_path):
"""Parse a BNGL file's action items via a throwaway ``bngmodel``.

Uncached — :func:`_load_bngl_actions_for_routing` is the memoized
entry point callers should use.
Returns ``(actions, reason)`` — the action list with ``reason=None`` on
success, or ``(None, reason)`` with the parse message on failure. Uncached
— :func:`_load_bngl_routing_actions` is the memoized entry point callers
should use.
"""
try:
import bionetgen.modelapi.model as mdl

model = mdl.bngmodel(bngl_path)
except Exception as exc:
logger.debug("could not parse BNGL for BNGsim routing (%s): %s", bngl_path, exc)
return None
return None, str(exc) or exc.__class__.__name__
try:
return list(model.actions.items)
return list(model.actions.items), None
except Exception as exc:
logger.debug(
"could not read BNGL actions for BNGsim routing (%s): %s", bngl_path, exc
)
return None
return None, str(exc) or exc.__class__.__name__


def _warn_routing_inspection_fallback_once(bngl_path, reason):
"""Warn once per file when auto-mode can't inspect a BNGL's actions for
BNGsim routing and falls back to the legacy subprocess engine."""
try:
key = os.path.abspath(bngl_path)
except Exception:
key = bngl_path
if key in _ROUTING_INSPECT_WARNED:
return
_ROUTING_INSPECT_WARNED.add(key)
logger.warning(
"Could not inspect BNGL actions for BNGsim routing (%s): %s. Using the "
"legacy subprocess (BNG2.pl) route. Pass simulator='bngsim' to require "
"BNGsim and surface this as an error instead.",
bngl_path,
reason,
)


def _classify_bngl_actions_for_bngsim(
actions_items,
method=None,
has_protocol=False,
bngsim_has_nfsim=None,
bngsim_has_rulemonkey=None,
simulator="auto",
):
"""Classify whether BNGL can use the BNG2.pl-owned BNGsim backend hook.

This routing pass only reads action names and method hints. It does not
evaluate BNGL expressions or replay any action semantics in Python.

``simulator`` affects the declines BNGsim *could* satisfy: under a strict
``simulator='bngsim'`` request an *unrecognized action* (runnable via the
BNG2.pl backend hook) and a *build incapability* (``nf`` without NFsim,
``rm`` without RuleMonkey) are surfaced as ``ROUTE_ERROR`` instead of
silently running legacy; ``auto`` falls back. PLA is a categorical BNGsim
incapability and stays on the subprocess route in every mode.
"""
if actions_items is None:
return BngsimRouteDecision(
Expand DownExpand Up@@ -1416,10 +1529,17 @@ def _classify_bngl_actions_for_bngsim(
continue

if atype is not None:
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL action '{atype}' is not a conservative BNGsim route",
)
reason = f"BNGL action '{atype}' is not a conservative BNGsim route"
if simulator == "bngsim":
# Strict mode: BNGsim could run this through the BNG2.pl
# backend hook, but the router can't confirm an unrecognized
# action is safe to delegate. Surface it instead of silently
# downgrading to legacy (issue #109 contract).
return BngsimRouteDecision(
ROUTE_ERROR,
f"simulator='bngsim' was requested but {reason}.",
)
return BngsimRouteDecision(ROUTE_SUBPROCESS, reason)

if len(sim_actions) > 1:
has_backend_hook_workflow = True
Expand DownExpand Up@@ -1458,17 +1578,15 @@ def _classify_bngl_actions_for_bngsim(
"BNGL PLA is not supported by BNGsim",
method="pla",
)
if _method_supported_by_bngsim_for_routing(method_name, bngsim_has_nfsim):
if _method_supported_by_bngsim_for_routing(
method_name, bngsim_has_nfsim, bngsim_has_rulemonkey
):
return BngsimRouteDecision(
ROUTE_BNGL_BNGSIM,
"BNGL method override is a BNGsim-supported simulation",
method=method_name,
)
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)
return _unsupported_method_route(method_name, simulator)

candidate_methods = []
for action in sim_actions:
Expand DownExpand Up@@ -1498,12 +1616,10 @@ def _classify_bngl_actions_for_bngsim(
)

for method_name in candidate_methods:
if not _method_supported_by_bngsim_for_routing(method_name, bngsim_has_nfsim):
return BngsimRouteDecision(
ROUTE_SUBPROCESS,
f"BNGL method '{method_name}' is not supported by the BNGsim route",
method=method_name,
)
if not _method_supported_by_bngsim_for_routing(
method_name, bngsim_has_nfsim, bngsim_has_rulemonkey
):
return _unsupported_method_route(method_name, simulator)

if has_backend_hook_workflow:
return BngsimRouteDecision(
Expand All@@ -1529,12 +1645,15 @@ def classify_bngsim_route(
bngsim_has_nfsim=None,
bngl_actions=None,
has_protocol=None,
bngsim_has_rulemonkey=None,
):
"""Choose the conservative Stage 1 route for a simulation request."""
if bngsim_available is None:
bngsim_available = BNGSIM_AVAILABLE
if bngsim_has_nfsim is None:
bngsim_has_nfsim = BNGSIM_HAS_NFSIM
if bngsim_has_rulemonkey is None:
bngsim_has_rulemonkey = BNGSIM_HAS_RULEMONKEY

if simulator not in {"auto", "bngsim", "subprocess"}:
raise ValueError(
Expand DownExpand Up@@ -1628,13 +1747,30 @@ def classify_bngsim_route(

if has_protocol is None:
has_protocol = _bngl_has_protocol_block(input_path)
parse_reason = None
if bngl_actions is None:
bngl_actions, parse_reason = _load_bngl_routing_actions(input_path)
if bngl_actions is None:
bngl_actions = _load_bngl_actions_for_routing(input_path)
# Action inspection failed: the Python parser rejects this BNGL even
# though BNG2.pl may tolerate it (e.g. a typo'd or unknown ``simulate``
# argument). A strict ``simulator='bngsim'`` request must not silently
# downgrade to legacy BNG2.pl — surface why instead (issue #109). For
# ``auto`` the subprocess fallback stays, with a one-time warning.
detail = parse_reason or "the BNGL actions could not be parsed"
if simulator == "bngsim":
return BngsimRouteDecision(
ROUTE_ERROR,
"simulator='bngsim' was requested but the BNGL actions could "
f"not be inspected for BNGsim routing: {detail}",
)
_warn_routing_inspection_fallback_once(input_path, detail)
return _classify_bngl_actions_for_bngsim(
bngl_actions,
method=method,
has_protocol=has_protocol,
bngsim_has_nfsim=bngsim_has_nfsim,
bngsim_has_rulemonkey=bngsim_has_rulemonkey,
simulator=simulator,
)


Expand Down
13 changes: 12 additions & 1 deletion bionetgen/core/utils/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,7 +576,18 @@ def define_parser(self):
arg_type_expr = pp.Word(
pp.nums + "." + "+" + "-" + "e" + "E" + "(" + ")" + "/" + "*" + "^"
)
arg_type_list = "[" + pp.delimitedList((quote_word ^ arg_type_float)) + "]"
# Match BNG2.pl/Perl list syntax: elements may be quoted strings or
# numeric expressions including scientific notation (arg_type_expr
# covers e/E and +/-), an empty list `[]` is allowed, and a single
# trailing comma `[1,2,]` is tolerated. arg_type_float only spans
# digits and '.', so it rejected `2.3e-10`; delimitedList rejected the
# trailing comma — both are valid Perl that BNG2.pl runs (issue #110).
arg_type_list = (
"["
+ pp.Optional(pp.delimitedList(quote_word ^ arg_type_expr))
+ pp.Optional(",")
+ "]"
)
arg_type_string = quote_word
#
# BNGL/Perl `=>` auto-quotes its left operand, so dict keys
Expand Down
Loading
Loading