Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix latex rendering of variables with underscore in name #7501

Merged
merged 4 commits into from
Sep 16, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
25 changes: 25 additions & 0 deletions pymc/printing.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ def str_for_dist(
if "latex" in formatting:
if print_name is not None:
print_name = r"\text{" + _latex_escape(print_name.strip("$")) + "}"
print_name = _format_underscore(print_name)

op_name = (
dist.owner.op._print_name[1]
Expand Down Expand Up @@ -114,6 +115,7 @@ def str_for_model(model: Model, formatting: str = "plain", include_params: bool
if not var_reprs:
return ""
if "latex" in formatting:
var_reprs = [_format_underscore(x) for x in var_reprs]
var_reprs = [
var_repr.replace(r"\sim", r"&\sim &").strip("$")
for var_repr in var_reprs
Expand Down Expand Up @@ -295,3 +297,26 @@ def _default_repr_pretty(obj: TensorVariable | Model, p, cycle):
except (ModuleNotFoundError, AttributeError):
# no ipython shell
pass


def _format_underscore(variable: str) -> str:
twiecki marked this conversation as resolved.
Show resolved Hide resolved
"""
formats variables with underscores in its name by prefixing underscores by '\\'
---
Params:
variable: The string representation of the variable in the model
"""
if "_" not in variable:
return variable

inds = [i for i, ltr in enumerate(variable) if ltr == "_"]
var_len_original = len(variable)
var_len = None
for ind in inds:
if var_len:
if var_len != var_len_original:
ind = ind + (var_len - var_len_original)
if variable[ind - 1 : ind] != "\\":
variable = variable[:ind] + "\\" + variable[ind:]
var_len = len(variable)
return variable
38 changes: 31 additions & 7 deletions tests/test_printing.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re

import numpy as np

from pytensor.tensor.random import normal
Expand Down Expand Up @@ -171,15 +173,15 @@ def setup_class(self):
r"$\text{mu} \sim \operatorname{Deterministic}(f(\text{beta},~\text{alpha}))$",
r"$\text{beta} \sim \operatorname{Normal}(0,~10)$",
r"$\text{Z} \sim \operatorname{MultivariateNormal}(f(),~f())$",
r"$\text{nb_with_p_n} \sim \operatorname{NegativeBinomial}(10,~\text{nbp})$",
r"$\text{nb\_with\_p\_n} \sim \operatorname{NegativeBinomial}(10,~\text{nbp})$",
r"$\text{zip} \sim \operatorname{MarginalMixture}(f(),~\operatorname{DiracDelta}(0),~\operatorname{Poisson}(5))$",
r"$\text{w} \sim \operatorname{Dirichlet}(\text{<constant>})$",
(
r"$\text{nested_mix} \sim \operatorname{MarginalMixture}(\text{w},"
r"$\text{nested\_mix} \sim \operatorname{MarginalMixture}(\text{w},"
r"~\operatorname{MarginalMixture}(f(),~\operatorname{DiracDelta}(0),~\operatorname{Poisson}(5)),"
r"~\operatorname{Censored}(\operatorname{Bernoulli}(0.5),~-1,~1))$"
),
r"$\text{Y_obs} \sim \operatorname{Normal}(\text{mu},~\text{sigma})$",
r"$\text{Y\_obs} \sim \operatorname{Normal}(\text{mu},~\text{sigma})$",
r"$\text{pot} \sim \operatorname{Potential}(f(\text{beta},~\text{alpha}))$",
r"$\text{pred} \sim \operatorname{Deterministic}(f(\text{<normal>}))",
],
Expand All @@ -189,11 +191,11 @@ def setup_class(self):
r"$\text{mu} \sim \operatorname{Deterministic}$",
r"$\text{beta} \sim \operatorname{Normal}$",
r"$\text{Z} \sim \operatorname{MultivariateNormal}$",
r"$\text{nb_with_p_n} \sim \operatorname{NegativeBinomial}$",
r"$\text{nb\_with\_p\_n} \sim \operatorname{NegativeBinomial}$",
r"$\text{zip} \sim \operatorname{MarginalMixture}$",
r"$\text{w} \sim \operatorname{Dirichlet}$",
r"$\text{nested_mix} \sim \operatorname{MarginalMixture}$",
r"$\text{Y_obs} \sim \operatorname{Normal}$",
r"$\text{nested\_mix} \sim \operatorname{MarginalMixture}$",
r"$\text{Y\_obs} \sim \operatorname{Normal}$",
r"$\text{pot} \sim \operatorname{Potential}$",
r"$\text{pred} \sim \operatorname{Deterministic}",
],
Expand Down Expand Up @@ -256,7 +258,7 @@ def test_model_latex_repr_three_levels_model():
"$$",
"\\begin{array}{rcl}",
"\\text{mu} &\\sim & \\operatorname{Normal}(0,~5)\\\\\\text{sigma} &\\sim & "
"\\operatorname{HalfCauchy}(0,~2.5)\\\\\\text{censored_normal} &\\sim & "
"\\operatorname{HalfCauchy}(0,~2.5)\\\\\\text{censored\\_normal} &\\sim & "
"\\operatorname{Censored}(\\operatorname{Normal}(\\text{mu},~\\text{sigma}),~-2,~2)",
"\\end{array}",
"$$",
Expand Down Expand Up @@ -316,3 +318,25 @@ def random(rng, mu, size):

str_repr = model.str_repr(include_params=False)
assert str_repr == "\n".join(["x ~ CustomDistNormal", "y ~ CustomRandomNormal"])


class TestLatexRepr:
@staticmethod
def simple_model() -> Model:
with Model() as simple_model:
error = HalfNormal("error", 0.5)
alpha_a = Normal("alpha_a", 0, 1)
Normal("y", alpha_a, error)
return simple_model

def test_latex_escaped_underscore(self):
twiecki marked this conversation as resolved.
Show resolved Hide resolved
"""
Ensures that all underscores in model variable names are properly escaped for LaTeX representation
"""
model = self.simple_model()
model_str = model.str_repr(formatting="latex")
underscores = re.finditer(r"_", model_str)
for match in underscores:
if match:
start = match.span(0)[0] - 1
assert model_str[start : start + 1] == "\\"
Loading