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

Added remaining Numpy NDArray single function expressions #183

Merged
merged 4 commits into from
Nov 17, 2023
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
137 changes: 135 additions & 2 deletions src/latexify/codegen/expression_codegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ def __init__(
"""Initializer.

Args:
use_math_symbols: Whether to convert identifiers with a math symbol surface
(e.g., "alpha") to the LaTeX symbol (e.g., "\\alpha").
use_math_symbols: Whether to convert identifiers with a math symbol
surface (e.g., "alpha") to the LaTeX symbol (e.g., "\\alpha").
use_set_symbols: Whether to use set symbols or not.
"""
self._identifier_converter = identifier_converter.IdentifierConverter(
Expand Down Expand Up @@ -240,6 +240,129 @@ def _generate_transpose(self, node: ast.Call) -> str | None:
else:
return None

def _generate_determinant(self, node: ast.Call) -> str | None:
"""Generates LaTeX for numpy.linalg.det.
Args:
node: ast.Call node containing the appropriate method invocation.
Returns:
Generated LaTeX, or None if the node has unsupported syntax.
Raises:
LatexifyError: Unsupported argument type given.
"""
name = ast_utils.extract_function_name_or_none(node)
assert name == "det"

if len(node.args) != 1:
return None

func_arg = node.args[0]
if isinstance(func_arg, ast.Name):
return rf"\det \left( \mathbf{{{func_arg.id}}} \right)"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks some generation rules don't follow the convention of the library: \mathopen{}\left* and \mathclose{}\right*

elif isinstance(func_arg, ast.List):
return rf"\det \left( {self._generate_matrix(node)} \right)"

return None

def _generate_matrix_rank(self, node: ast.Call) -> str | None:
"""Generates LaTeX for numpy.linalg.matrix_rank.
Args:
node: ast.Call node containing the appropriate method invocation.
Returns:
Generated LaTeX, or None if the node has unsupported syntax.
Raises:
LatexifyError: Unsupported argument type given.
"""
name = ast_utils.extract_function_name_or_none(node)
assert name == "matrix_rank"

if len(node.args) != 1:
return None

func_arg = node.args[0]
if isinstance(func_arg, ast.Name):
return rf"\mathrm{{rank}} \left( \mathbf{{{func_arg.id}}} \right)"
elif isinstance(func_arg, ast.List):
return rf"\mathrm{{rank}} \left( {self._generate_matrix(node)} \right)"

return None

def _generate_matrix_power(self, node: ast.Call) -> str | None:
"""Generates LaTeX for numpy.linalg.matrix_power.
Args:
node: ast.Call node containing the appropriate method invocation.
Returns:
Generated LaTeX, or None if the node has unsupported syntax.
Raises:
LatexifyError: Unsupported argument type given.
"""
name = ast_utils.extract_function_name_or_none(node)
assert name == "matrix_power"

if len(node.args) != 2:
return None

func_arg = node.args[0]
power_arg = node.args[1]
if isinstance(power_arg, ast.Num):
if isinstance(func_arg, ast.Name):
return rf"\mathbf{{{func_arg.id}}}^{{{power_arg.n}}}"
elif isinstance(func_arg, ast.List):
matrix = self._generate_matrix(node)
if matrix is not None:
return rf"{matrix}^{{{power_arg.n}}}"
return None

def _generate_qr_and_svd(self, node: ast.Call) -> str | None:
"""Generates LaTeX for numpy.linalg.qr and numpy.linalg.svd.
Args:
node: ast.Call node containing the appropriate method invocation.
Returns:
Generated LaTeX, or None if the node has unsupported syntax.
Raises:
LatexifyError: Unsupported argument type given.
"""
name = ast_utils.extract_function_name_or_none(node)
assert name == "QR" or name == "SVD"

if len(node.args) != 1:
return None

func_arg = node.args[0]
if isinstance(func_arg, ast.Name):
func_arg_str = rf"\mathbf{{{func_arg.id}}}"
return rf"\mathrm{{{name.upper()}}} \left( {func_arg_str} \right)"

elif isinstance(func_arg, ast.List):
matrix_str = self._generate_matrix(node)
return rf"\mathrm{{{name.upper()}}} \left( {matrix_str} \right)"
return None
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function can be removed. The current implementation converts QR(A) to $\mathrm{QR}(A)$ and SVD(A) to $\mathrm{SVD}(A)$


def _generate_inverses(self, node: ast.Call) -> str | None:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks there is no reason to combine inv and pinv into the same function.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To clarify, would you rather I separate them into two different functions?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah that would be reasonable I think.

"""Generates LaTeX for numpy.linalg.inv.
Args:
node: ast.Call node containing the appropriate method invocation.
Returns:
Generated LaTeX, or None if the node has unsupported syntax.
Raises:
LatexifyError: Unsupported argument type given.
"""
name = ast_utils.extract_function_name_or_none(node)
assert name == "inv" or name == "pinv"

if len(node.args) != 1:
return None

func_arg = node.args[0]
if isinstance(func_arg, ast.Name):
if name == "inv":
return rf"\mathbf{{{func_arg.id}}}^{{-1}}"
return rf"\mathbf{{{func_arg.id}}}^{{+}}"
elif isinstance(func_arg, ast.List):
if name == "inv":
return rf"{self._generate_matrix(node)}^{{-1}}"
return rf"{self._generate_matrix(node)}^{{+}}"
return None

def visit_Call(self, node: ast.Call) -> str:
"""Visit a Call node."""
func_name = ast_utils.extract_function_name_or_none(node)
Expand All @@ -256,6 +379,16 @@ def visit_Call(self, node: ast.Call) -> str:
special_latex = self._generate_identity(node)
elif func_name == "transpose":
special_latex = self._generate_transpose(node)
elif func_name == "det":
special_latex = self._generate_determinant(node)
elif func_name == "matrix_rank":
special_latex = self._generate_matrix_rank(node)
elif func_name == "matrix_power":
special_latex = self._generate_matrix_power(node)
elif func_name in ("QR", "SVD"):
special_latex = self._generate_qr_and_svd(node)
elif func_name in ("inv", "pinv"):
special_latex = self._generate_inverses(node)
else:
special_latex = None

Expand Down
197 changes: 197 additions & 0 deletions src/latexify/codegen/expression_codegen_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -993,6 +993,203 @@ def test_transpose(code: str, latex: str) -> None:
assert expression_codegen.ExpressionCodegen().visit(tree) == latex


@pytest.mark.parametrize(
"code,latex",
[
("det(A)", r"\det \left( \mathbf{A} \right)"),
("det(b)", r"\det \left( \mathbf{b} \right)"),
(
"det([[1, 2], [3, 4]])",
r"\det \left( \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} \right)",
),
(
"det([[1, 2, 3], [4, 5, 6], [7, 8, 9]])",
r"\det \left( \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\"
r" 7 & 8 & 9 \end{bmatrix} \right)",
),
# Unsupported
("det()", r"\mathrm{det} \mathopen{}\left( \mathclose{}\right)"),
("det(2)", r"\mathrm{det} \mathopen{}\left( 2 \mathclose{}\right)"),
(
"det(a, (1, 0))",
r"\mathrm{det} \mathopen{}\left( a, "
r"\mathopen{}\left( 1, 0 \mathclose{}\right) \mathclose{}\right)",
),
],
)
def test_determinant(code: str, latex: str) -> None:
tree = ast_utils.parse_expr(code)
assert isinstance(tree, ast.Call)
assert expression_codegen.ExpressionCodegen().visit(tree) == latex


@pytest.mark.parametrize(
"code,latex",
[
("matrix_rank(A)", r"\mathrm{rank} \left( \mathbf{A} \right)"),
("matrix_rank(b)", r"\mathrm{rank} \left( \mathbf{b} \right)"),
(
"matrix_rank([[1, 2], [3, 4]])",
r"\mathrm{rank} \left( \begin{bmatrix} 1 & 2 \\"
r" 3 & 4 \end{bmatrix} \right)",
),
(
"matrix_rank([[1, 2, 3], [4, 5, 6], [7, 8, 9]])",
r"\mathrm{rank} \left( \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\"
r" 7 & 8 & 9 \end{bmatrix} \right)",
),
# Unsupported
(
"matrix_rank()",
r"\mathrm{matrix\_rank} \mathopen{}\left( \mathclose{}\right)",
),
(
"matrix_rank(2)",
r"\mathrm{matrix\_rank} \mathopen{}\left( 2 \mathclose{}\right)",
),
(
"matrix_rank(a, (1, 0))",
r"\mathrm{matrix\_rank} \mathopen{}\left( a, "
r"\mathopen{}\left( 1, 0 \mathclose{}\right) \mathclose{}\right)",
),
],
)
def test_matrix_rank(code: str, latex: str) -> None:
tree = ast_utils.parse_expr(code)
assert isinstance(tree, ast.Call)
assert expression_codegen.ExpressionCodegen().visit(tree) == latex


@pytest.mark.parametrize(
"code,latex",
[
("matrix_power(A, 2)", r"\mathbf{A}^{2}"),
("matrix_power(b, 2)", r"\mathbf{b}^{2}"),
(
"matrix_power([[1, 2], [3, 4]], 2)",
r"\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}^{2}",
),
(
"matrix_power([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 42)",
r"\begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{bmatrix}^{42}",
),
# Unsupported
(
"matrix_power()",
r"\mathrm{matrix\_power} \mathopen{}\left( \mathclose{}\right)",
),
(
"matrix_power(2)",
r"\mathrm{matrix\_power} \mathopen{}\left( 2 \mathclose{}\right)",
),
(
"matrix_power(a, (1, 0))",
r"\mathrm{matrix\_power} \mathopen{}\left( a, "
r"\mathopen{}\left( 1, 0 \mathclose{}\right) \mathclose{}\right)",
),
],
)
def test_matrix_power(code: str, latex: str) -> None:
tree = ast_utils.parse_expr(code)
assert isinstance(tree, ast.Call)
assert expression_codegen.ExpressionCodegen().visit(tree) == latex


@pytest.mark.parametrize(
"code,latex",
[
# Test QR
("QR(A)", r"\mathrm{QR} \left( \mathbf{A} \right)"),
("QR(b)", r"\mathrm{QR} \left( \mathbf{b} \right)"),
(
"QR([[1, 2], [3, 4]])",
r"\mathrm{QR} \left( \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} \right)",
),
(
"QR([[1, 2, 3], [4, 5, 6], [7, 8, 9]])",
r"\mathrm{QR} \left( \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\"
r" 7 & 8 & 9 \end{bmatrix} \right)",
),
# Unsupported
("QR()", r"\mathrm{QR} \mathopen{}\left( \mathclose{}\right)"),
("QR(2)", r"\mathrm{QR} \mathopen{}\left( 2 \mathclose{}\right)"),
(
"QR(a, (1, 0))",
r"\mathrm{QR} \mathopen{}\left( a, "
r"\mathopen{}\left( 1, 0 \mathclose{}\right) \mathclose{}\right)",
),
# Test SVD
("SVD(A)", r"\mathrm{SVD} \left( \mathbf{A} \right)"),
("SVD(b)", r"\mathrm{SVD} \left( \mathbf{b} \right)"),
(
"SVD([[1, 2], [3, 4]])",
r"\mathrm{SVD} \left( \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} \right)",
),
(
"SVD([[1, 2, 3], [4, 5, 6], [7, 8, 9]])",
r"\mathrm{SVD} \left( \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\"
r" 7 & 8 & 9 \end{bmatrix} \right)",
),
# Unsupported
("SVD()", r"\mathrm{SVD} \mathopen{}\left( \mathclose{}\right)"),
("SVD(2)", r"\mathrm{SVD} \mathopen{}\left( 2 \mathclose{}\right)"),
(
"SVD(a, (1, 0))",
r"\mathrm{SVD} \mathopen{}\left( a, "
r"\mathopen{}\left( 1, 0 \mathclose{}\right) \mathclose{}\right)",
),
],
)
def test_qr_and_svd(code: str, latex: str) -> None:
tree = ast_utils.parse_expr(code)
assert isinstance(tree, ast.Call)
assert expression_codegen.ExpressionCodegen().visit(tree) == latex


# tests for inv and pinv
@pytest.mark.parametrize(
"code,latex",
[
# Test inv
("inv(A)", r"\mathbf{A}^{-1}"),
("inv(b)", r"\mathbf{b}^{-1}"),
("inv([[1, 2], [3, 4]])", r"\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}^{-1}"),
(
"inv([[1, 2, 3], [4, 5, 6], [7, 8, 9]])",
r"\begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{bmatrix}^{-1}",
),
# Unsupported
("inv()", r"\mathrm{inv} \mathopen{}\left( \mathclose{}\right)"),
("inv(2)", r"\mathrm{inv} \mathopen{}\left( 2 \mathclose{}\right)"),
(
"inv(a, (1, 0))",
r"\mathrm{inv} \mathopen{}\left( a, "
r"\mathopen{}\left( 1, 0 \mathclose{}\right) \mathclose{}\right)",
),
# Test pinv
("pinv(A)", r"\mathbf{A}^{+}"),
("pinv(b)", r"\mathbf{b}^{+}"),
("pinv([[1, 2], [3, 4]])", r"\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}^{+}"),
(
"pinv([[1, 2, 3], [4, 5, 6], [7, 8, 9]])",
r"\begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{bmatrix}^{+}",
),
# Unsupported
("pinv()", r"\mathrm{pinv} \mathopen{}\left( \mathclose{}\right)"),
("pinv(2)", r"\mathrm{pinv} \mathopen{}\left( 2 \mathclose{}\right)"),
(
"pinv(a, (1, 0))",
r"\mathrm{pinv} \mathopen{}\left( a, "
r"\mathopen{}\left( 1, 0 \mathclose{}\right) \mathclose{}\right)",
),
],
)
def test_inv_and_pinv(code: str, latex: str) -> None:
tree = ast_utils.parse_expr(code)
assert isinstance(tree, ast.Call)
assert expression_codegen.ExpressionCodegen().visit(tree) == latex


# Check list for #89.
# https://github.com/google/latexify_py/issues/89#issuecomment-1344967636
@pytest.mark.parametrize(
Expand Down
Loading