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/1994.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- **A `folded_at_load=` comment written by hand in a `.bngl` could freeze the wrong parameter, or none.** `Model.from_bngl` read each line of the parameters block as one declaration, and the first blank-separated word as its name. BNG2.pl joins a line that ends in `\` with the next, so `f \` then `k # folded_at_load=...` declares `f = k`: the comment froze `k`, which the file says nothing about, and `f` took `set_param`. With a number on the second line, nothing was frozen. BNG2.pl also takes the name as the identifier a declaration starts with, so `f(2.0)`, `f(k+1)` and `f-2.0` declare `f`, and on those the comment froze nothing. A comment in a block opened `beginparameters`, which BNG2.pl reads as `begin parameters`, was not read at all. The comment is now read off the declaration BNG2.pl reads, and freezes the parameter it declares. A `.net`, which bngsim's loader reads one line to a declaration, and every file `sbml_to_net` and `sbml_to_bngl` write, are read as before.
4 changes: 3 additions & 1 deletion python/bngsim/_bngl_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -1221,7 +1221,9 @@ def load_bngl(
)
# Issue #1792: a parameter folded when an SBML model was loaded is marked in
# a comment on its line, which BNG2.pl does not carry into its network.
model._frozen_params.update(_folded_at_load(_folded_at_load_in(_file_text(path)), model._core))
model._frozen_params.update(
_folded_at_load(_folded_at_load_in(_file_text(path), bngl=True), model._core)
)
# Issue #1705: the model came from the .bngl, by way of the network BNG2.pl wrote.
_record_source(model, "bngl", path=path, network=os.path.abspath(os.fspath(net)))
return model
156 changes: 123 additions & 33 deletions python/bngsim/_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -2141,7 +2141,11 @@ def frozen_params(self) -> list[str]:
in the model loaded from the file. (One that nothing in the network
reads is left out of the file.) The comment may be written by hand
on a parameter line of either format, to the same effect; one on a
line that declares no parameter of the model says nothing.
line that declares no parameter of the model says nothing. In a
``.bngl`` it is read off the declaration as BNG2.pl reads it: a line
continued with ``\\`` and the next are one declaration, and a comment
on either is its; and the name is the identifier the declaration
starts with, so ``f(2.0)`` and ``f-2.0`` declare ``f``.

Empty for most models.

Expand Down Expand Up @@ -4823,48 +4827,134 @@ def _file_text(path: str | Path) -> str:
return ""


def _folded_at_load_in(text: str) -> list[tuple[str, str]]:
def _folded_at_load_in(text: str, *, bngl: bool = False) -> list[tuple[str, str]]:
"""``(parameter, what it was folded into)`` for each ``folded_at_load=``
comment on a line of the parameters block of a ``.net`` or ``.bngl`` text
(issue #1792; :mod:`bngsim.convert._frozen` writes them).

The block is found as :func:`_unit_conversions_in` finds the reactions:
by the first two words of a line with its comment taken off. A parameter
line is ``<index> <name> <value>`` in a ``.net``. In a ``.bngl`` it may
also have no index, an ``=`` between the name and the value, and a label
before the name (``f 2``, ``f = 2``, ``3 f=2``, ``label: f 2``,
``label : f 2``, ``3 label: f 2``), each of which BNG2.pl reads.
comment on a declaration of the parameters block of a ``.net`` text, or of
a ``.bngl`` text with *bngl* (issue #1792; :mod:`bngsim.convert._frozen`
writes them).

In a ``.net`` the block is found as :func:`_unit_conversions_in` finds
the reactions, by the first two words of a line with its comment taken
off, and a parameter line is ``[<index>] <name> <value>``, one to a line,
as the loader reads it. A ``.bngl`` is read as BNG2.pl reads it (issue
#1994): a line that ends in ``\\`` once its comment is taken off is
joined with the next, so the declaration is the two lines', and a comment
on either is the declaration's; the block opens on ``begin`` and its name,
with or without a blank between them, and closes on ``end`` and a blank;
and :func:`_bngl_parameter_name` gives the name.
"""
if "folded_at_load" not in text:
return []
found: list[tuple[str, str]] = []
inside = False
for line in text.split("\n"):
code, _, comment = line.partition("#")
words = code.split()
if not words:
continue
if words[0] in ("begin", "end"):
inside = words[:2] == ["begin", "parameters"]
continue
if not inside:
for code, comments in _bngl_text_lines(text) if bngl else _net_text_lines(text):
if bngl:
# BNG2.pl's readFile and read_block_array: a block opens on
# `begin` and its name, blanks between them or not, and closes on
# `end` and a blank.
opened = _BNGL_BEGIN.match(code)
if opened or (inside and _BNGL_END.match(code)):
inside = opened is not None and opened.group(1).split() == ["parameters"]
continue
if not inside or not code.strip(_ASCII_BLANKS):
continue
else:
words = code.split()
if not words:
continue
if words[0] in ("begin", "end"):
inside = words[:2] == ["begin", "parameters"]
continue
if not inside:
continue
said = next(
(m.group(1) for m in map(_FOLDED_AT_LOAD.search, comments) if m and m.group(1)),
None,
)
if said is None:
continue
said = _FOLDED_AT_LOAD.search(comment)
if said and said.group(1):
words = code.replace("=", " ").split()
if len(words) >= 3 and words[0].isdigit():
words = words[1:] # the index
if words[:1] == [":"]:
continue # a colon and no label before it
if words and words[0].endswith(":"):
words = words[1:] # a label, its colon with it
elif words[1:2] == [":"]:
words = words[2:] # a label, a blank, its colon
if words:
found.append((words[0], said.group(1)))
name = _bngl_parameter_name(code) if bngl else _net_parameter_name(code)
if name:
found.append((name, said))
return found


def _net_text_lines(text: str):
"""``(code, [comment])`` for each line of a ``.net`` text: the loader reads
no line continuation."""
for line in text.split("\n"):
code, _, comment = line.partition("#")
yield code, [comment]


def _bngl_text_lines(text: str):
"""``(code, comments)`` for each line of a ``.bngl`` text as BNG2.pl reads
it (``get_line`` in ``BNGModel.pm``): a comment runs from the first ``#``;
a line whose code ends in ``\\`` and blanks has those taken off and the
next line's code appended, with nothing between, whatever that line holds.
The comments are each joined line's, in order."""
lines = text.split("\n")
i = 0
while i < len(lines):
code, _, comment = lines[i].partition("#")
comments = [comment]
i += 1
while (cut := _CONTINUED.search(code)) is not None and i < len(lines):
more, _, comment = lines[i].partition("#")
code = code[: cut.start()] + more
comments.append(comment)
i += 1
yield code, comments


# A .bngl line's continuation: a backslash and blanks at the end of its code.
# Blanks and words as Perl reads them in BNG2.pl, which reads bytes: ASCII.
_CONTINUED = re.compile(r"\\\s*$", re.ASCII)
_ASCII_BLANKS = " \t\n\r\f\v"
_BNGL_BEGIN = re.compile(r"\s*begin\s*(.*)$", re.ASCII)
_BNGL_END = re.compile(r"\s*end\s", re.ASCII)


def _net_parameter_name(code: str) -> str | None:
"""The name a ``.net`` parameter line declares, as #1988 read it: the
first word after an index and a label, with ``=`` taken for a blank."""
words = code.replace("=", " ").split()
if len(words) >= 3 and words[0].isdigit():
words = words[1:] # the index
if words[:1] == [":"]:
return None # a colon and no label before it
if words and words[0].endswith(":"):
words = words[1:] # a label, its colon with it
elif words[1:2] == [":"]:
words = words[2:] # a label, a blank, its colon
return words[0] if words else None


def _bngl_parameter_name(code: str) -> str | None:
"""The name a ``.bngl`` parameter declaration declares, as
``ParamList::readString`` reads it in BNG2.pl 2.5.1 and 2.9.3: blanks, an
index (digits and a blank) and a label (a word, a colon and a blank) are
taken off the front, and the name is the identifier that starts what is
left, whatever follows it (``f 2``, ``f=2``, ``f(2.0)``, ``f-2.0``,
``lbl: f 2``, ``3 lbl : f 2``). ``None`` where no identifier starts it
or the label starts with a digit, which BNG2.pl refuses. (Some other
declarations BNG2.pl refuses, ``lbl:f 2`` among them, give a name: the
file fails to load before the name is read.)"""
rest = _BNGL_INDEX.sub("", code.lstrip(_ASCII_BLANKS), count=1)
labelled = _BNGL_LABEL.match(rest)
if labelled and labelled.group(1)[0].isdigit():
return None # "label begins with a number"
rest = rest[labelled.end() :] if labelled else rest
name = _BNGL_NAME.match(rest)
return name.group(0) if name else None


# ParamList::readString's three steps, \w as Perl reads it in BNG2.pl (ASCII).
_BNGL_INDEX = re.compile(r"^\d+\s+", re.ASCII)
_BNGL_LABEL = re.compile(r"^(\w+)\s*:\s+", re.ASCII)
_BNGL_NAME = re.compile(r"[A-Za-z_]\w*", re.ASCII)


def _folded_at_load(found, core: Any) -> dict[str, str]:
"""``{name: what it was folded into}`` for the parameters of *core* among
*found*, which is what :func:`_folded_at_load_in` reads off a file. The
Expand Down
1 change: 1 addition & 0 deletions python/tests/test_convert_frozen_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -983,6 +983,7 @@ def test_the_comment_is_read_off_parameter_lines_only():
assert _folded_at_load_in(NET) == [("f", "a number"), ("j", "spaced out")]
assert _folded_at_load_in(NET.replace("folded_at_load", "folded")) == []
assert _folded_at_load_in(BNGL_FORMS) == [(name, f"reason {name}") for name in "fghjmnpst"]
assert _folded_at_load_in(BNGL_FORMS, bngl=True) == _folded_at_load_in(BNGL_FORMS)
# Lines that declare nothing name nothing.
nothing = (
"begin parameters\n = # folded_at_load=x\n : f 2 # folded_at_load=y\nend parameters\n"
Expand Down
169 changes: 169 additions & 0 deletions python/tests/test_folded_at_load_bngl_lines.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
"""A ``folded_at_load=`` comment in a ``.bngl`` is read off the declaration
BNG2.pl reads, not off the physical line (issue #1994).

``Model.from_bngl`` lists in ``frozen_params`` a parameter whose line carries a
``folded_at_load=`` comment (#1792). The reader took each line of the
parameters block for one declaration, and the first blank-separated word after
an index and a label for its name. BNG2.pl reads two kinds of line otherwise:

* a line whose code ends in ``\\`` is joined with the next (``get_line`` in
``BNGModel.pm``), so ``f \\`` then ``k # folded_at_load=...`` declares
``f = k``. The reader froze ``k``, which the file says nothing about, and
left ``f`` writable; with the comment on the second line and a number there,
it froze nothing;
* ``ParamList::readString`` takes the name as the identifier that starts the
declaration, so ``f(2.0)``, ``f(k+1)`` and ``f-2.0`` declare ``f``. The
reader froze nothing.

Oracle: the parameters of the network BNG2.pl generates from each form (the
same in 2.5.1 and 2.9.3; ``readString`` and ``get_line`` are the same text in
both), and which write the loaded model refuses.
"""

from __future__ import annotations

import shutil
import warnings
from pathlib import Path

import bngsim
import pytest
from bngsim import ParameterError
from bngsim._model import _folded_at_load_in
from bngsim.convert._bng2 import find_bng2

_FOUND = find_bng2()
HAS_BNG2 = bool(_FOUND) and Path(_FOUND).is_file() and bool(shutil.which("perl"))
needs_bng2 = pytest.mark.skipif(not HAS_BNG2, reason="BNG2.pl not found")

MARK = "# folded_at_load=by hand"

# (label, the declaration of f as written, BNG2.pl's f in the network it generates)
FORMS = [
("one line", f" f 2.0 {MARK}", "2.0"),
("continued, mark on the first line", f" f \\ {MARK}\n 2.0", "2.0"),
("continued, number and mark on the second", f" f \\\n 2.0 {MARK}", "2.0"),
("continued, a name and the mark on the second", f" f \\\n k {MARK}", "k"),
("continued, an expression and the mark on the second", f" f \\\n k * 2 {MARK}", "k*2"),
("no blank: f(2.0)", f" f(2.0) {MARK}", "2.0"),
("no blank: f(k+1)", f" f(k+1) {MARK}", "k+1"),
("no blank: f-2.0", f" f-2.0 {MARK}", "-2.0"),
("index, label, three lines", f" 3 lbl : \\\n f \\ # another\n 2.0 {MARK}", "2.0"),
]
# Nothing goes between two joined lines: `g\` then `2.0` declares g2 = .0.
JOINED = ("no blank before the backslash", f" g\\\n2.0 {MARK}\n f 1.0")

BNGL = """begin model
begin parameters
k 1.0
{line}
end parameters
begin molecule types
A()
B()
end molecule types
begin seed species
A() 1
end seed species
begin reaction rules
A() -> B() k*f
end reaction rules
end model
generate_network({{overwrite=>1}})
"""


def _block(line: str) -> str:
return f"begin parameters\n k 1.0\n{line}\nend parameters\n"


@pytest.mark.parametrize(("label", "line", "value"), FORMS, ids=[f[0] for f in FORMS])
def test_the_mark_is_read_for_the_parameter_the_declaration_declares(label, line, value):
assert _folded_at_load_in(_block(line), bngl=True) == [("f", "by hand")]


def test_a_continued_line_is_joined_as_bng2pl_joins_it():
# Nothing goes between the two lines: `f\` then `2.0` is `f2.0`, the
# parameter `f2` (= .0) to BNG2.pl.
assert _folded_at_load_in(_block(f" f\\\n2.0 {MARK}"), bngl=True) == [("f2", "by hand")]
# A carriage return before the newline is a blank after the backslash.
crlf = _block(f" f \\\r\n k {MARK}\r").replace("\n", "\r\n")
assert _folded_at_load_in(crlf, bngl=True) == [("f", "by hand")]
# The first mark among the joined lines is the declaration's.
two = _block(" f \\ # folded_at_load=first\n 2.0 # folded_at_load=second")
assert _folded_at_load_in(two, bngl=True) == [("f", "first")]
# A backslash in a comment continues nothing: it is the comment's, on a
# line with code before it or on a line that is all comment.
assert _folded_at_load_in(_block(f" f 2.0 {MARK} \\\n g 3.0"), bngl=True) == [
("f", "by hand \\")
]
assert _folded_at_load_in(_block(f" # \\\n f 2.0 {MARK}"), bngl=True) == [("f", "by hand")]


def test_a_mark_on_what_declares_no_parameter_names_none():
# What BNG2.pl refuses as a declaration: no name, a name that starts with
# a digit, a label and nothing after it, a colon with no label.
for line in (" = ", " 2f 1.0 ", " 3 4 1.0 ", " other: ", " : f 2 "):
assert _folded_at_load_in(_block(line + MARK), bngl=True) == [], line


def test_a_net_is_read_one_line_to_a_declaration_as_its_loader_reads_it():
# bngsim's .net loader joins no lines, so neither does the .net reading.
net = _block(f" 1 f \\\n 2 k 1.0 {MARK}")
assert _folded_at_load_in(net) == [("k", "by hand")]
assert _folded_at_load_in(net, bngl=True) == [("f", "by hand")]


@needs_bng2
@pytest.mark.parametrize(("label", "line", "value"), FORMS, ids=[f[0] for f in FORMS])
def test_from_bngl_freezes_the_parameter_bng2pl_declares(tmp_path, label, line, value):
bngl, net = tmp_path / "m.bngl", tmp_path / "m.net"
bngl.write_text(BNGL.format(line=line), encoding="utf-8")
with warnings.catch_warnings():
warnings.simplefilter("ignore")
model = bngsim.Model.from_bngl(str(bngl), cache=False, net_out=str(net))
block = net.read_text(encoding="utf-8").split("begin parameters")[1].split("end parameters")[0]
declared = {
words[1]: " ".join(words[2:])
for words in (row.split("#")[0].split() for row in block.splitlines())
if len(words) >= 3
}
assert declared["f"] == value and declared["k"] == "1.0"
assert model.frozen_params == ["f"]
with pytest.raises(ParameterError, match="by hand, as the file's folded_at_load comment"):
model.clone().set_param("f", 5.0)
taken = model.clone()
taken.set_param("k", 5.0)
assert taken.get_param("k") == 5.0


@needs_bng2
def test_from_bngl_joins_two_lines_with_nothing_between_as_bng2pl_does(tmp_path):
bngl, net = tmp_path / "m.bngl", tmp_path / "m.net"
bngl.write_text(BNGL.format(line=JOINED[1]), encoding="utf-8")
with warnings.catch_warnings():
warnings.simplefilter("ignore")
model = bngsim.Model.from_bngl(str(bngl), cache=False, net_out=str(net))
generated = net.read_text(encoding="utf-8")
assert " g2 " in generated and " g " not in generated
assert model.frozen_params == ["g2"]
with pytest.raises(ParameterError):
model.clone().set_param("g2", 5.0)


def test_the_block_is_found_as_bng2pl_finds_it():
# `begin` and the block's name need no blank between them; `end` needs one.
text = f"beginparameters\n f 2.0 {MARK}\nend parameters\n g 1.0 {MARK}\n"
assert _folded_at_load_in(text, bngl=True) == [("f", "by hand")]
# A block of another name is not read, whatever its spelling.
other = f"begin seed species\n f 2.0 {MARK}\nend seed species\n"
assert _folded_at_load_in(other, bngl=True) == []


def test_blanks_and_labels_are_read_as_perl_reads_them():
# A label that starts with a digit is refused by BNG2.pl, so names nothing.
assert _folded_at_load_in(_block(f" 3abc: f 2 {MARK}"), bngl=True) == []
# Perl's \s is ASCII in BNG2.pl: a no-break space after the backslash is no
# blank, so the line is not continued (and BNG2.pl refuses the file).
nbsp = _block(f" f \\ \n k {MARK}")
assert _folded_at_load_in(nbsp, bngl=True) == [("k", "by hand")]
Loading