Repository: sympy/sympy
Pull request: Add LaTeX printing for matrix symbol trace
Fixes #15303. Adds a _print_Trace method and test. Also adds a _print_Basic method to handle unimplemented types.

<!-- BEGIN RELEASE NOTES -->
* printing
  * added a method to correctly LaTeX print the trace of a MatrixSymbol
  * fixed a bug in LaTeX.py where subexpressions of an unimplemented basic expression were not printed correctly
<!-- END RELEASE NOTES -->


Problem statement:
LaTeX printing for Matrix Expression
```py
>>> A = MatrixSymbol("A", n, n)
>>> latex(trace(A**2))
'Trace(A**2)'
```

The bad part is not only is Trace not recognized, but whatever printer is being used doesn't fallback to the LaTeX printer for the inner expression (it should be `A^2`).

Hints from issue discussion:
What is the correct way to print the trace? AFAIK there isn't one built in to Latex. One option is ```\mathrm{Tr}```. Or ```\operatorname{Tr}```.
What's the difference between the two. It looks like we use both in different parts of the latex printer. 
\operatorname puts a thin space after the operator.

Commit message: add test for printing trace

Patch to review:
diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index 00f844d9cb26..85ecb07999a4 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -1462,6 +1462,10 @@ def _print_Transpose(self, expr):
         else:
             return "%s^T" % self._print(mat)
 
+    def _print_Trace(self, expr):
+        mat = expr.arg
+        return r"\operatorname{Tr} %s" % self._print(mat)
+
     def _print_Adjoint(self, expr):
         mat = expr.arg
         from sympy.matrices import MatrixSymbol
diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index 46056321ab07..5adbe4fed06a 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -1845,3 +1845,11 @@ def test_latex_printer_tensor():
 
     expr = A(i) + 3*B(i)
     assert latex(expr) == "3B{}^{i} + A{}^{i}"
+
+
+def test_trace():
+    # Issue 15303
+    from sympy import trace
+    A = MatrixSymbol("A", 2, 2)
+    assert latex(trace(A)) == r"\operatorname{Tr} A"
+    assert latex(trace(A**2)) == r"\operatorname{Tr} A^{2}"


Code review comments:
diff_hunk: @@ -1462,6 +1462,10 @@ def _print_Transpose(self, expr):
         else:
             return "%s^T" % self._print(mat)
 
+    def _print_Trace(self, expr):
+        mat = expr.arg
+        return r"\operatorname{Tr} %s" % self._print(mat)
path: sympy/printing/latex.py
text: @user1:
I think it would be better to use `\mathrm{Tr}\left (%s \right )`. 

@user1:
Should it be `tr` with a lowercase `t`? That's what the pretty printer uses, and it's how Wikipedia renders it https://en.wikipedia.org/wiki/Trace_(linear_algebra) (Wikipedia also uses the parentheses everywhere). 

@author:
OK, that makes sense to me, for consistency. (http://mathworld.wolfram.com/MatrixTrace.html capitalizes, so it seems fairly arbitrary).