Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/1937.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- **A forward sensitivity through one of ExprTk's implicit products was exact zeros, with no warning, and a plain run stepped over a pulse centred on one (issue #1937).** The engine reads `2j`, `2 j`, `(1+1)j`, `(j)2` and `j(2)` as `2*j`. The Python readers scanned the text for the word `j`, found none, and took the expression to name no parameter: with `A0 = 2j`, dA/dj came back [0, 0, 0] for 2·e^(-t/2); a rate law `k*2j` failed its build on Python's imaginary `I`; and `1000*exp(-((time() - c)/0.0005)^2)` with `c = 2j` gave A(10) = 0 for 0.886. The products are now written out, by the pass the C emitter already uses, before a derived parameter's expression is scanned or parsed (seeds, the chain rule, the kink check, pulse stops), and a rate law's lexer-level ones before its parse. A law with ExprTk's square or curly brackets (`j[2]`), or with a name against a bracket beside another product (`0.5Atot(2)`), declines as before. Also: a reserved word in another case is a name, as it is to the engine (`2In` was zeros too), and a derived parameter that is a logical operation (`j and k`) has a zero column, not 1.
5 changes: 5 additions & 0 deletions docs/development/sensitivity-terms.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ s' = f_x·s + f_p, f_p = ∂f/∂p + Σ_d (∂f/∂d)·(∂d/∂p) over d
- A `%` in a rate law is read as the engine's `fmod`, its `mod()`, and not
as sympy's floored `Mod` (#1815). Oracle: `rate-law-mod-of-literals`,
`rate-law-mod-of-integer-literals`, `rate-law-mod-negative-divisor`.
- The products ExprTk reads between operands written side by side (`2j`,
`(1+1)j`, `j(2)`) are written out before a derived expression is scanned
for names or parsed, and a rate law's lexer-level ones before its parse
(#1937). Oracle: `ic-seed-derived-implicit-product`,
`rhs-derived-chain-implicit-product`, `rate-law-implicit-product`.
- **Open:** a compiled sensitivity RHS that is already attached is reused
after `set_param` changes a derived parameter's attachment, so it keeps the
old chain rule (#708, `stale-artifact-after-override`).
Expand Down
92 changes: 84 additions & 8 deletions python/bngsim/_codegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -3181,6 +3181,49 @@ class _PreparedDerivedExpr(NamedTuple):
_HAS_NON_WORD_RE = re.compile(r"\W")


class _ScalarNames:
"""A set of names as the lookup :func:`_insert_implicit_products` takes,
each one a variable, without a dict built per expression."""

__slots__ = ("names",)

def __init__(self, names):
self.names = names

def __bool__(self) -> bool:
return bool(self.names)

def get(self, name: str):
return (name, True) if name in self.names else None


def _products_written_out(expr: str, scalars=None) -> str:
"""*expr* with the products ExprTk reads between operands written side by
side spelled with ``*`` (:func:`_insert_implicit_products`), for a reader
that scans it for names or hands it to sympy: ``2j`` holds no word ``j``,
and to Python it is an imaginary number. *scalars* are the names that are
variables (a set, or the emitter's lookup); with none, only the pairs the
lexer multiplies are written. A text the pass declines is returned as it
is, for the reader to decline in its own words."""
if not expr:
return expr
if isinstance(scalars, (set, frozenset)):
scalars = _ScalarNames(scalars)
if scalars and scalars.get("time") is not None and _NUMBER_GLUED_TO_TIME.search(expr):
return expr
try:
return _insert_implicit_products(expr, scalars)
except CodegenDeclined:
return expr


# A number written against the name `time`. The engine renames the clock at a
# word boundary before ExprTk splits the pair, so in a model with a scalar
# named `time`, `2time` is twice the clock and `2 time` twice the scalar.
# Written out, both would read as the scalar: such a text is left as it is.
_NUMBER_GLUED_TO_TIME = re.compile(r"[\d.]time\b")


def _names_referenced_in(text: str, names) -> list[str]:
"""Sorted members of ``names`` that occur in ``text`` as whole words.

Expand Down Expand Up @@ -3315,9 +3358,18 @@ def _prepare_derived_expr(
# the parse, it is read as fmod (issue #1800). The call is a private name,
# so a parameter named `mod` is not called, and only this parse sees it: the
# clock parser shares _preprocess_derived_expr and reads `%` as before.
diff_names = primary_names | set(derived_names)
# The products ExprTk reads between operands written side by side (`2j`,
# `(1+1)j`, `j(2)`), written out first, while the text is still the
# model's: the name scan below finds no `j` in `2j`, and the expression
# read as naming no parameter, a zero partial with nothing said.
if not ("time" in diff_names and _NUMBER_GLUED_TO_TIME.search(expr)):
try:
expr = _insert_implicit_products(expr, _ScalarNames(diff_names))
except CodegenDeclined as exc:
return None, str(exc)
s_pre = _spell_mod(_preprocess_derived_expr(expr), call=_ENGINE_ROUNDING_NAMES[1])

diff_names = primary_names | set(derived_names)
referenced = _names_referenced_in(s_pre, diff_names)
if not referenced and not allow_no_reference:
return None, None # names no parameter — a genuine zero, not a failure
Expand Down Expand Up @@ -3433,6 +3485,19 @@ def _prepare_derived_expr(
)


def _is_truth_value(sym_expr) -> bool:
"""Whether the whole expression is a logical operation (``j and k``,
``not(j)``). The engine's value is then 0 or 1, constant in every
parameter between its switches: a zero partial, where sympy's derivative
of the unevaluated ``And`` came back 1. A bare comparison is not one of
these: the switch-time scan hands its thresholds through the same parse."""
import sympy as sp

return isinstance(sym_expr, sp.logic.boolalg.BooleanFunction) and not isinstance(
sym_expr, sp.core.relational.Relational
)


def _derivative_is_unevaluated(deriv) -> bool:
"""Whether sympy left any part of ``deriv`` as an unevaluated ``Derivative``
(see :data:`_STEP_DERIVATIVE_REASON`)."""
Expand Down Expand Up @@ -3685,6 +3750,8 @@ def _direct_derived_partials(
prep, reason = _prepare_derived_expr(expr, primary_names, derived_names)
if prep is None:
return None, reason
if _is_truth_value(prep.sym_expr):
return None, None

# For round-tripping the ccode output: map each (possibly-aliased) sympy
# symbol name back to ``p[idx]`` using the ORIGINAL parameter's index.
Expand Down Expand Up @@ -3926,6 +3993,8 @@ def _direct_derived_partials_numeric(
prep, reason = _prepare_derived_expr(expr, primary_names, derived_names)
if prep is None:
return None, reason
if _is_truth_value(prep.sym_expr):
return None, None

subs = {
prep.sym_map[prep.sym_name_of[p]]: param_values[param_idx[p]]
Expand Down Expand Up @@ -4099,7 +4168,12 @@ def compute_ic_param_sens_seed(core) -> list[tuple[int, int, float]]:
values = [core.get_param(n) for n in names]
param_idx = {n: i for i, n in enumerate(names)}
primary_names = {names[i] for i in range(len(names)) if not is_expr[i]}
derived_exprs = {names[i]: exprs[i] for i in range(len(names)) if is_expr[i] and exprs[i]}
scalars = _ScalarNames(set(names))
derived_exprs = {
names[i]: _products_written_out(exprs[i], scalars)
for i in range(len(names))
if is_expr[i] and exprs[i]
}

seeds: list[tuple[int, int, float]] = []
for (species_idx0, param_idx0), divisor in zip(refs, ref_divisors, strict=True):
Expand Down Expand Up @@ -6707,7 +6781,9 @@ def _expr_to_c(
) # fmt: skip

# ExprTk's reserved words: never one side of an implicit product (its
# commutative_inserter ignores them; `reserved_words` in exprtk.hpp).
# commutative_inserter ignores them; `reserved_words` in exprtk.hpp). As
# written: the engine builds ExprTk with exprtk_disable_caseinsensitivity, so
# `In`, `Or` and `IF` are names, and `2In` is twice the parameter `In`.
_EXPRTK_RESERVED_WORDS = frozenset(
{
"assert", "break", "case", "continue", "const", "default", "false", "for",
Expand Down Expand Up @@ -6752,7 +6828,9 @@ def _expr_to_c(
_NAME_BEFORE_BRACKET_RE = re.compile("(" + _NAME + r")\s*[(\[{]")


def _insert_implicit_products(expr: str, lookup: dict[str, tuple[str, bool]] | None = None) -> str:
def _insert_implicit_products(
expr: str, lookup: dict[str, tuple[str, bool]] | _ScalarNames | None = None
) -> str:
"""Write out the ``*`` ExprTk reads between two operands written side by side.

ExprTk's lexer multiplies ``2x``, ``2(x + 1)``, ``(a)b`` and ``x y``, so
Expand Down Expand Up @@ -6800,7 +6878,7 @@ def variable(name: str) -> bool:
continue
if kind == "other":
kind = text
elif kind == "sym" and text.lower() in _EXPRTK_RESERVED_WORDS:
elif kind == "sym" and text in _EXPRTK_RESERVED_WORDS:
kind = "word"
if kind in _BRACKET_CLOSES:
if prev_call is not None:
Expand All @@ -6824,9 +6902,7 @@ def variable(name: str) -> bool:
elif prev_operand or (prev, kind) in _IMPLICIT_PRODUCT_PAIRS:
out.append("*")
opened.append(None)
elif prev == "sym" or (
prev == "word" and prev_text.lower() not in _EXPRTK_OPERATOR_WORDS
):
elif prev == "sym" or (prev == "word" and prev_text not in _EXPRTK_OPERATOR_WORDS):
opened.append(prev_text)
else:
opened.append(None)
Expand Down
19 changes: 18 additions & 1 deletion python/bngsim/_jacobian.py
Original file line number Diff line number Diff line change
Expand Up @@ -835,6 +835,15 @@ def _exprtk_to_sympy(expr: str, *, bends: bool = False, closed_forms: bool = Fal
except ImportError:
return None

# The products ExprTk's lexer reads between operands written side by side
# (`2j`, `(a)b`, `x y`), written out: Python reads `2j` as an imaginary
# number, and the build failed on its `I`. This parse is not told which
# names are the model's scalars, so `k(x)` stays the call it reads as.
from bngsim._codegen import _products_written_out

as_written = expr
expr = _products_written_out(expr)
wrote_products = expr != as_written
# ExprTk's `%` on doubles is fmod, its `mod()`. Left as written, Python's
# parser reads it as sympy's floored Mod, which folds two numbers at once
# (`-2.5 % 2` to 1.5 for the engine's -0.5: the law `k*((-2.5 % 2)+1)` was
Expand Down Expand Up @@ -879,9 +888,17 @@ def _exprtk_to_sympy(expr: str, *, bends: bool = False, closed_forms: bool = Fal
s = re.sub(rf"\b{re.escape(ident)}\b", alias_of[ident], s)

try:
return parse_expr(s, local_dict=local, evaluate=True)
parsed = parse_expr(s, local_dict=local, evaluate=True)
except Exception:
return None
# A law that also holds a name against a bracket (`0.5Atot(2)`, `j[2]`)
# did not parse before its other products, or its square brackets, were
# written, and declined. Parsed now, the `Atot(2)` in it is a call of an
# unknown function, a constant to every derivative, where the engine reads
# the product `Atot*2`: it declines still.
if wrote_products and parsed.atoms(sp.core.function.AppliedUndef):
return None
return parsed


# ─── Function inlining ─────────────────────────────────────────────────────
Expand Down
4 changes: 3 additions & 1 deletion python/bngsim/_parameter_kinks.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,15 +241,17 @@ def parameters_on_a_kink(
_PY_KEYWORD_PARAM_NAMES,
_alias_keyword_param,
_inline_derived_param_refs,
_products_written_out,
)
from bngsim._jacobian import has_condition_construct
from bngsim._switch_sensitivity import _BEND_CALL

all_names = list(core.param_names)
# The derived parameters as switch_condition_scope reads them, without its
# probe of the right-hand side for the clocks.
scalars = set(all_names)
derived = {
n: e
n: _products_written_out(e, scalars)
for n, is_e, e in zip(
all_names, core.param_is_expression, core.param_expressions, strict=True
)
Expand Down
9 changes: 7 additions & 2 deletions python/bngsim/_smooth_pulses.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ def _resolve(core, t_start: float, t_end: float) -> list[Any]:
_PY_KEYWORD_PARAM_NAMES,
_alias_keyword_param,
_inline_derived_param_refs,
_products_written_out,
)
from bngsim._jacobian import _TIME_SYM
from bngsim._switch_sensitivity import CrossingStop
Expand All @@ -293,8 +294,11 @@ def spelled(name: str) -> str:
return _alias_keyword_param(name) if name in _PY_KEYWORD_PARAM_NAMES else name

names = list(core.param_names)
# With the products ExprTk reads written out: `c = j(2)` inlined as it
# was written parsed as a call, and the pulse on it had no centre.
scalars = set(names)
derived = {
n: e
n: _products_written_out(e, scalars)
for n, is_expr, e in zip(
names, core.param_is_expression, core.param_expressions, strict=True
)
Expand All @@ -303,7 +307,8 @@ def spelled(name: str) -> str:
values = {spelled(n): float(core.get_param(n)) for n in names}
bumps: list[tuple[str, float, float, float]] = []
for text in texts:
expr = _parsed(_inline_derived_param_refs(text, derived))
# The law's own products too, with the names: `time() - j(2)`.
expr = _parsed(_inline_derived_param_refs(_products_written_out(text, scalars), derived))
if expr is None:
continue
subs = {s: values[s.name] for s in expr.free_symbols if s.name in values}
Expand Down
36 changes: 36 additions & 0 deletions python/tests/test_codegen_sens_fd_oracle.py
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,42 @@ def _chain_after_override(term: Term, method: str) -> np.ndarray:
param="k",
note="fmod gives 1.5, so c = 2.5; floored, c was 0.5 (#1815)",
),
Term(
"ic-seed-derived-implicit-product",
"net",
_fill(_IC_NET, "R0", Rt="3R0", B0="Rt"),
"R0",
"10",
10.0,
_T,
("B()",),
param="R0",
note="ExprTk's 3R0 is 3*R0; a scan for the word R0 found none, a zero seed (#1937)",
),
Term(
"rhs-derived-chain-implicit-product",
"net",
_fill(_DERIVED_RATE_NET, "k0", kd="(1+1)k0", body="1"),
"k0",
"0.5",
0.5,
_T,
("A()",),
param="k0",
note="a bracket against a name is a product too (#1937)",
),
Term(
"rate-law-implicit-product",
"net",
_fill(_DERIVED_RATE_NET, "k0", kd="2", body="0.5k0"),
"k0",
"0.5",
0.5,
_T,
("A()",),
param="k0",
note="in a law Python read 0.5k0 as a syntax error and 2j as imaginary (#1937)",
),
Term(
"ic-seed-param",
"net",
Expand Down
Loading
Loading