Skip to content

Commit

Permalink
added symbol replacement for latext formula
Browse files Browse the repository at this point in the history
  • Loading branch information
RickDGO committed Oct 16, 2024
1 parent 12e26b6 commit cdd3b71
Show file tree
Hide file tree
Showing 4 changed files with 135 additions and 2 deletions.
64 changes: 63 additions & 1 deletion blueprints/codes/latex_formula.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ def latex_fraction(numerator: str | float, denominator: str | float) -> str:
"""
return f"\\frac{{{numerator}}}{{{denominator}}}"


def latex_min_curly_brackets(*args: str | float) -> str:
r"""Return a string which will output: min{arg_1; arg_2; ...; arg_N} in latex and it will also automatically ensure floats are converted to latex
text.
Expand Down Expand Up @@ -132,3 +131,66 @@ def latex_max_curly_brackets(*args: str | float) -> str:
"""
arguments = [str(arg) for arg in args]
return f"\\max \\left\\{{{'; '.join(arguments)}\\right\\}}"


def latex_replace_symbols(
template: str,
replacements: dict[str, str],
unique_symbol_check: bool = True
) -> str:
r"""
Replace symbols in a LaTeX template string based on the provided dictionary.
This function searches the template for symbols specified in the
replacements and replaces them with their corresponding
values. It also checks for the occurrence of symbols based on the
unique_symbol_check parameter, raising an error if necessary.
Examples
--------
>>> latex_template = r"\frac{K_{MOD}}{B}"
>>> replacements = {'K_{MOD}': '1.0', 'B': 'y'}
>>> latex_replace_symbols(latex_template, replacements)
'\frac{1.0}{y}
Parameters
----------
template: str
The original LaTeX string containing symbols to replace.
replacements: dict[str, str]
A dictionary where keys are symbols to be replaced and values
are their replacements.
unique_symbol_check: bool, optional
If True (default), raises an error if a symbol appears more
than once in the template. If False, multiple occurrences
will be replaced without error.
Returns
-------
str
The modified LaTeX string with symbols replaced.
Raises
------
ValueError
If a symbol in the dictionary is not found in the template,
or if a symbol appears more than once when single_symbol_search is True.
"""
_filled_latex_string: str = template
for symbol, replacement in replacements.items():
occurrences = _filled_latex_string.count(symbol)

# Check for the presence of the symbol in the template
if occurrences == 0:
raise ValueError(f"Symbol '{symbol}' not found in the template.")

# If single_symbol_search is True, check for multiple occurrences
if unique_symbol_check and occurrences > 1:
raise ValueError(f"Symbol '{symbol}' found multiple times in the template.")

# Replace the symbol with its replacement
_filled_latex_string = _filled_latex_string.replace(symbol, replacement)

return _filled_latex_string
Empty file.
37 changes: 37 additions & 0 deletions tests/codes/latex_formula/test_latext_replace_symbols.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import pytest

from blueprints.codes.latex_formula import latex_replace_symbols


# Success tests using pytest
@pytest.mark.parametrize("latex_template, replacements, unique_check, expected", [
(r"\frac{A}{B}", {'A': 'x', 'B': 'y'}, True, r"\frac{x}{y}"),
(r"\frac{A}{B}", {'A': 'x', 'B': 'y'}, False, r"\frac{x}{y}"),
(r"\frac{A}{B}", {'A': 'x', 'B': 'y'}, False, r"\frac{x}{y}"),
(r"\frac{A}{B}", {'A': 'x', 'B': 'y'}, False, r"\frac{x}{y}"),
(
r"\frac{k_{mod}}{\gamma_{R}}",
{'k_{mod}': '0.9', r'\gamma_{R}': '1.2'},
False,
r"\frac{0.9}{1.2}",
),
])
def test_latex_replace_symbols_success(latex_template, replacements, unique_check, expected):
"""Test successful symbol replacements in LaTeX strings."""
result = latex_replace_symbols(latex_template, replacements, unique_check)
assert result == expected

# Error tests using pytest
@pytest.mark.parametrize("latex_template, replacements, unique_check, expected_exception", [
(r"\frac{A}{B}", {'C': 'x'}, True, "Symbol 'C' not found in the template."),
(r"\frac{A}{A}", {'A': 'x'}, True, "Symbol 'A' found multiple times in the template."),
])
def test_latex_replace_symbols_error(
latex_template,
replacements,
unique_check,
expected_exception
):
"""Test error conditions when replacing symbols in LaTeX strings."""
with pytest.raises(ValueError, match=expected_exception):
latex_replace_symbols(latex_template, replacements, unique_check)
36 changes: 35 additions & 1 deletion tests/codes/test_latex_formula.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import pytest

from blueprints.codes.latex_formula import LatexFormula, latex_fraction, latex_max_curly_brackets, latex_min_curly_brackets
from blueprints.codes.latex_formula import LatexFormula, latex_fraction, latex_max_curly_brackets, latex_min_curly_brackets, latex_replace_symbols


@pytest.fixture
Expand Down Expand Up @@ -62,3 +62,37 @@ def test_latex_min_curly_brackets() -> None:
"""Test the latex_max_curly_brackets function."""
result = latex_min_curly_brackets(r"a+b", r"500", r"c-d")
assert result == r"\min \left\{a+b; 500; c-d\right\}"


# Success tests using pytest
@pytest.mark.parametrize("latex_template, replacements, unique_check, expected", [
(r"\frac{A}{B}", {'A': 'x', 'B': 'y'}, True, r"\frac{x}{y}"),
(r"\frac{A}{B}", {'A': 'x', 'B': 'y'}, False, r"\frac{x}{y}"),
(r"\frac{A}{B}", {'A': 'x', 'B': 'y'}, False, r"\frac{x}{y}"),
(r"\frac{A}{B}", {'A': 'x', 'B': 'y'}, False, r"\frac{x}{y}"),
(
r"\frac{k_{mod}}{\gamma_{R}}",
{'k_{mod}': '0.9', r'\gamma_{R}': '1.2'},
False,
r"\frac{0.9}{1.2}",
),
])
def test_latex_replace_symbols_success(latex_template, replacements, unique_check, expected):
"""Test successful symbol replacements in LaTeX strings."""
result = latex_replace_symbols(latex_template, replacements, unique_check)
assert result == expected

# Error tests using pytest
@pytest.mark.parametrize("latex_template, replacements, unique_check, expected_exception", [
(r"\frac{A}{B}", {'C': 'x'}, True, "Symbol 'C' not found in the template."),
(r"\frac{A}{A}", {'A': 'x'}, True, "Symbol 'A' found multiple times in the template."),
])
def test_latex_replace_symbols_error(
latex_template,
replacements,
unique_check,
expected_exception
):
"""Test error conditions when replacing symbols in LaTeX strings."""
with pytest.raises(ValueError, match=expected_exception):
latex_replace_symbols(latex_template, replacements, unique_check)

0 comments on commit cdd3b71

Please sign in to comment.