Repository: sympy/sympy

Issue:
make TR4 do something
If an expression is unevaluated, then TR4 of the fu.py will not do anything -- it is assuming that SymPy has already taken care of it. But if we are working with an unevaluated expression in the classroom setting, then we need it to do something. So maybe it could be:
```python
def TR4(expr):
    return expr.replace(lambda x: isinstance(x, TrigonometricFunction) and (r:=x.args[0]/pi).is_Rational and r.q in (1,2, 3, 4, 6),
           lambda x: x.func(x.args[0].func(*x.args[0].args)))
```
```
>>> with evaluate(False):
...     eq = cos(11*pi/6)
...
>>> TR4(eq)
sqrt(3)/2
```

Discussion:
sympy-bot: :white_check_mark:

Hi, I am the [SymPy bot](https://github.com/sympy/sympy-bot). I'm here to help you write a release notes entry. Please read the [guide on how to write release notes](https://github.com/sympy/sympy/wiki/Writing-Release-Notes).



Your release notes are in good order.

Here is what the release notes will look like:
* simplify
  * TR3 and TR4 of fu will now work with unevaluated numbers in trig functions; previously such numbers were unchanged ([#26390](https://github.com/sympy/sympy/pull/26390) by [@smichr](https://github.com/smichr))

This will be added to https://github.com/sympy/sympy/wiki/Release-Notes-for-1.13.

<details><summary>Click here to see the pull request description that was parsed.</summary>

    <!-- Your title above should be a short description of what
    was changed. Do not include the issue number in the title. -->

    #### References to other Issues or PRs
    <!-- If this pull request fixes an issue, write "Fixes #NNNN" in that exact
    format, e.g. "Fixes #1234" (see
    https://tinyurl.com/auto-closing for more information). Also, please
    write a comment on that issue linking back to this pull request once it is
    open. -->

    fixes #26388 

    #### Brief description of what is fixed or changed

    TR3 and TR4 now touch numbers in all trig functions of an expressions to make sure they are evaluated so unevaluated expressions will be processed properly.

    #### Other comments

    ```
    >>> with evaluate(False):
    ...  eq = cos(31*pi/22)
    ...
    >>> cos(31*pi/22)
    -cos(9*pi/22)
    >>> TR3(_)
    -sin(pi/11)
    >>> eq
    cos((31*pi)/22)
    >>> TR3(eq) <--- makes no change in master, but now gives the right answer
    -sin(pi/11)
    ```

    #### Release Notes

    <!-- Write the release notes for this release below between the BEGIN and END
    statements. The basic format is a bulleted list with the name of the subpackage
    and the release note for this PR. For example:

    * solvers
      * Added a new solver for logarithmic equations.

    * functions
      * Fixed a bug with log of integers. Formerly, `log(-x)` incorrectly gave `-log(x)`.

    * physics.units
      * Corrected a semantical error in the conversion between volt and statvolt which
        reported the volt as being larger than the statvolt.

    or if no release note(s) should be included use:

    NO ENTRY

    See https://github.com/sympy/sympy/wiki/Writing-Release-Notes for more
    information on how to write release notes. The bot will check your release
    notes automatically to see if they are formatted correctly. -->

    <!-- BEGIN RELEASE NOTES -->
    * simplify
      * TR3 and TR4 of fu will now work with unevaluated numbers in trig functions; previously such numbers were unchanged
    <!-- END RELEASE NOTES -->


</details><p>

github-actions[bot]: Benchmark results from GitHub Actions

Lower numbers are good, higher numbers are bad. A ratio less than 1
means a speed up and greater than 1 means a slowdown. Green lines
beginning with `+` are slowdowns (the PR is slower then master or
master is slower than the previous release). Red lines beginning
with `-` are speedups.

Significantly changed benchmark results (PR vs master)
```diff

```
Significantly changed benchmark results (master vs previous release)
```diff
| Change   | Before [a00718ba]    | After [cba1e7c6]    |   Ratio | Benchmark (Parameter)                                                |
|----------|----------------------|---------------------|---------|----------------------------------------------------------------------|
| -        | 69.6±0.3ms           | 44.2±0.4ms          |    0.63 | integrate.TimeIntegrationRisch02.time_doit(10)                       |
| -        | 67.1±0.7ms           | 42.9±0.1ms          |    0.64 | integrate.TimeIntegrationRisch02.time_doit_risch(10)                 |
| +        | 18.7±0.2μs           | 29.6±0.3μs          |    1.58 | integrate.TimeIntegrationRisch03.time_doit(1)                        |
| -        | 5.22±0.02ms          | 2.85±0.02ms         |    0.55 | logic.LogicSuite.time_load_file                                      |
| -        | 73.6±0.3ms           | 28.5±0.2ms          |    0.39 | polys.TimeGCD_GaussInt.time_op(1, 'dense')                           |
| -        | 25.8±0.08ms          | 17.1±0.2ms          |    0.66 | polys.TimeGCD_GaussInt.time_op(1, 'expr')                            |
| -        | 74.3±0.3ms           | 28.6±0.1ms          |    0.39 | polys.TimeGCD_GaussInt.time_op(1, 'sparse')                          |
| -        | 256±3ms              | 124±0.5ms           |    0.48 | polys.TimeGCD_GaussInt.time_op(2, 'dense')                           |
| -        | 258±2ms              | 125±0.7ms           |    0.48 | polys.TimeGCD_GaussInt.time_op(2, 'sparse')                          |
| -        | 658±4ms              | 372±3ms             |    0.56 | polys.TimeGCD_GaussInt.time_op(3, 'dense')                           |
| -        | 659±4ms              | 369±2ms             |    0.56 | polys.TimeGCD_GaussInt.time_op(3, 'sparse')                          |
| -        | 506±10μs             | 287±1μs             |    0.57 | polys.TimeGCD_LinearDenseQuadraticGCD.time_op(1, 'dense')            |
| -        | 1.81±0.01ms          | 1.05±0.01ms         |    0.58 | polys.TimeGCD_LinearDenseQuadraticGCD.time_op(2, 'dense')            |
| -        | 5.84±0.04ms          | 3.05±0ms            |    0.52 | polys.TimeGCD_LinearDenseQuadraticGCD.time_op(3, 'dense')            |
| -        | 447±2μs              | 231±3μs             |    0.52 | polys.TimeGCD_QuadraticNonMonicGCD.time_op(1, 'dense')               |
| -        | 1.48±0.01ms          | 676±5μs             |    0.46 | polys.TimeGCD_QuadraticNonMonicGCD.time_op(2, 'dense')               |
| -        | 4.95±0.04ms          | 1.63±0.01ms         |    0.33 | polys.TimeGCD_QuadraticNonMonicGCD.time_op(3, 'dense')               |
| -        | 380±4μs              | 208±0.8μs           |    0.55 | polys.TimeGCD_SparseGCDHighDegree.time_op(1, 'dense')                |
| -        | 2.51±0.01ms          | 1.22±0.01ms         |    0.49 | polys.TimeGCD_SparseGCDHighDegree.time_op(3, 'dense')                |
| -        | 10.2±0.1ms           | 4.38±0.03ms         |    0.43 | polys.TimeGCD_SparseGCDHighDegree.time_op(5, 'dense')                |
| -        | 362±0.9μs            | 169±1μs             |    0.47 | polys.TimeGCD_SparseNonMonicQuadratic.time_op(1, 'dense')            |
| -        | 2.60±0.02ms          | 899±7μs             |    0.35 | polys.TimeGCD_SparseNonMonicQuadratic.time_op(3, 'dense')            |
| -        | 9.75±0.09ms          | 2.62±0.04ms         |    0.27 | polys.TimeGCD_SparseNonMonicQuadratic.time_op(5, 'dense')            |
| -        | 1.04±0.01ms          | 433±2μs             |    0.42 | polys.TimePREM_LinearDenseQuadraticGCD.time_op(3, 'dense')           |
| -        | 1.73±0.01ms          | 504±0.8μs           |    0.29 | polys.TimePREM_LinearDenseQuadraticGCD.time_op(3, 'sparse')          |
| -        | 5.95±0.03ms          | 1.78±0.01ms         |    0.3  | polys.TimePREM_LinearDenseQuadraticGCD.time_op(5, 'dense')           |
| -        | 8.56±0.05ms          | 1.49±0.01ms         |    0.17 | polys.TimePREM_LinearDenseQuadraticGCD.time_op(5, 'sparse')          |
| -        | 282±0.6μs            | 64.0±0.4μs          |    0.23 | polys.TimePREM_QuadraticNonMonicGCD.time_op(1, 'sparse')             |
| -        | 3.46±0.02ms          | 392±3μs             |    0.11 | polys.TimePREM_QuadraticNonMonicGCD.time_op(3, 'dense')              |
| -        | 4.06±0.02ms          | 279±1μs             |    0.07 | polys.TimePREM_QuadraticNonMonicGCD.time_op(3, 'sparse')             |
| -        | 7.02±0.09ms          | 1.27±0.01ms         |    0.18 | polys.TimePREM_QuadraticNonMonicGCD.time_op(5, 'dense')              |
| -        | 8.75±0.03ms          | 834±2μs             |    0.1  | polys.TimePREM_QuadraticNonMonicGCD.time_op(5, 'sparse')             |
| -        | 5.02±0.02ms          | 2.97±0.01ms         |    0.59 | polys.TimeSUBRESULTANTS_LinearDenseQuadraticGCD.time_op(2, 'sparse') |
| -        | 12.2±0.1ms           | 6.46±0.04ms         |    0.53 | polys.TimeSUBRESULTANTS_LinearDenseQuadraticGCD.time_op(3, 'dense')  |
| -        | 22.2±0.1ms           | 8.96±0.02ms         |    0.4  | polys.TimeSUBRESULTANTS_LinearDenseQuadraticGCD.time_op(3, 'sparse') |
| -        | 5.20±0.02ms          | 865±5μs             |    0.17 | polys.TimeSUBRESULTANTS_QuadraticNonMonicGCD.time_op(1, 'sparse')    |
| -        | 12.5±0.07ms          | 6.96±0.03ms         |    0.56 | polys.TimeSUBRESULTANTS_QuadraticNonMonicGCD.time_op(2, 'sparse')    |
| -        | 103±0.4ms            | 25.5±0.1ms          |    0.25 | polys.TimeSUBRESULTANTS_QuadraticNonMonicGCD.time_op(3, 'dense')     |
| -        | 169±0.6ms            | 53.8±0.3ms          |    0.32 | polys.TimeSUBRESULTANTS_QuadraticNonMonicGCD.time_op(3, 'sparse')    |
| -        | 174±0.6μs            | 111±0.6μs           |    0.64 | polys.TimeSUBRESULTANTS_SparseGCDHighDegree.time_op(1, 'dense')      |
| -        | 357±5μs              | 214±2μs             |    0.6  | polys.TimeSUBRESULTANTS_SparseGCDHighDegree.time_op(1, 'sparse')     |
| -        | 4.34±0.03ms          | 840±5μs             |    0.19 | polys.TimeSUBRESULTANTS_SparseGCDHighDegree.time_op(3, 'dense')      |
| -        | 5.39±0.03ms          | 377±1μs             |    0.07 | polys.TimeSUBRESULTANTS_SparseGCDHighDegree.time_op(3, 'sparse')     |
| -        | 19.8±0.1ms           | 2.78±0.01ms         |    0.14 | polys.TimeSUBRESULTANTS_SparseGCDHighDegree.time_op(5, 'dense')      |
| -        | 23.1±0.1ms           | 619±2μs             |    0.03 | polys.TimeSUBRESULTANTS_SparseGCDHighDegree.time_op(5, 'sparse')     |
| -        | 479±3μs              | 134±0.8μs           |    0.28 | polys.TimeSUBRESULTANTS_SparseNonMonicQuadratic.time_op(1, 'sparse') |
| -        | 4.83±0.05ms          | 609±5μs             |    0.13 | polys.TimeSUBRESULTANTS_SparseNonMonicQuadratic.time_op(3, 'dense')  |
| -        | 5.31±0.06ms          | 138±0.7μs           |    0.03 | polys.TimeSUBRESULTANTS_SparseNonMonicQuadratic.time_op(3, 'sparse') |
| -        | 13.2±0.09ms          | 1.29±0.01ms         |    0.1  | polys.TimeSUBRESULTANTS_SparseNonMonicQuadratic.time_op(5, 'dense')  |
| -        | 14.4±0.05ms          | 140±0.8μs           |    0.01 | polys.TimeSUBRESULTANTS_SparseNonMonicQuadratic.time_op(5, 'sparse') |
| -        | 134±1μs              | 74.8±0.4μs          |    0.56 | solve.TimeMatrixOperations.time_rref(3, 0)                           |
| -        | 248±1μs              | 86.0±2μs            |    0.35 | solve.TimeMatrixOperations.time_rref(4, 0)                           |
| -        | 24.0±0.05ms          | 10.1±0.02ms         |    0.42 | solve.TimeSolveLinSys189x49.time_solve_lin_sys                       |
| -        | 28.2±0.3ms           | 15.4±0.1ms          |    0.55 | solve.TimeSparseSystem.time_linsolve_Aaug(20)                        |
| -        | 54.6±1ms             | 24.9±0.06ms         |    0.46 | solve.TimeSparseSystem.time_linsolve_Aaug(30)                        |
| -        | 28.5±0.3ms           | 15.1±0.08ms         |    0.53 | solve.TimeSparseSystem.time_linsolve_Ab(20)                          |
| -        | 54.6±0.2ms           | 24.7±0.2ms          |    0.45 | solve.TimeSparseSystem.time_linsolve_Ab(30)                          |

```
Full benchmark results can be found as artifacts in GitHub Actions
(click on checks at the top of the PR).

Patch:
diff --git a/doc/src/modules/simplify/fu.rst b/doc/src/modules/simplify/fu.rst
index bb742127d1..7d3a2dfc7d 100644
--- a/doc/src/modules/simplify/fu.rst
+++ b/doc/src/modules/simplify/fu.rst
@@ -112,7 +112,7 @@ In the expanded state, there are nearly 1000 trig functions:
     >>> L(expr)
     932
 
-If the expression where factored first, this would take time but the
+If the expression were factored first, this would take time but the
 resulting expression would be transformed very quickly:
 
     >>> def clock(f, n=2):
diff --git a/sympy/parsing/sympy_parser.py b/sympy/parsing/sympy_parser.py
index f32dcc4f2c..c9fba7634b 100644
--- a/sympy/parsing/sympy_parser.py
+++ b/sympy/parsing/sympy_parser.py
@@ -1138,7 +1138,9 @@ def visit_Compare(self, node):
             new_node = ast.Call(
                 func=ast.Name(id=sympy_class, ctx=ast.Load()),
                 args=[left, right],
-                keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
+                keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False, ctx=ast.Load()))],
+                starargs=None,
+                kwargs=None
             )
             return new_node
         return node
@@ -1169,7 +1171,9 @@ def visit_BinOp(self, node):
                 right = ast.Call(
                     func=ast.Name(id='Mul', ctx=ast.Load()),
                     args=[ast.UnaryOp(op=ast.USub(), operand=ast.Constant(1)), right],
-                    keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
+                    keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False, ctx=ast.Load()))],
+                    starargs=None,
+                    kwargs=None
                 )
             elif isinstance(node.op, ast.Div):
                 if isinstance(node.left, ast.UnaryOp):
@@ -1178,13 +1182,17 @@ def visit_BinOp(self, node):
                     left = ast.Call(
                     func=ast.Name(id='Pow', ctx=ast.Load()),
                     args=[left, ast.UnaryOp(op=ast.USub(), operand=ast.Constant(1))],
-                    keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
+                    keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False, ctx=ast.Load()))],
+                    starargs=None,
+                    kwargs=None
                 )
                 else:
                     right = ast.Call(
                     func=ast.Name(id='Pow', ctx=ast.Load()),
                     args=[right, ast.UnaryOp(op=ast.USub(), operand=ast.Constant(1))],
-                    keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
+                    keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False, ctx=ast.Load()))],
+                    starargs=None,
+                    kwargs=None
                 )
 
             if rev:  # undo reversal
@@ -1192,7 +1200,9 @@ def visit_BinOp(self, node):
             new_node = ast.Call(
                 func=ast.Name(id=sympy_class, ctx=ast.Load()),
                 args=[left, right],
-                keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
+                keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False, ctx=ast.Load()))],
+                starargs=None,
+                kwargs=None
             )
 
             if sympy_class in ('Add', 'Mul'):
@@ -1205,7 +1215,7 @@ def visit_BinOp(self, node):
     def visit_Call(self, node):
         new_node = self.generic_visit(node)
         if isinstance(node.func, ast.Name) and node.func.id in self.functions:
-            new_node.keywords.append(ast.keyword(arg='evaluate', value=ast.Constant(value=False)))
+            new_node.keywords.append(ast.keyword(arg='evaluate', value=ast.Constant(value=False, ctx=ast.Load())))
         return new_node
 
 
diff --git a/sympy/printing/c.py b/sympy/printing/c.py
index 21d015bde1..5a1e677496 100644
--- a/sympy/printing/c.py
+++ b/sympy/printing/c.py
@@ -13,7 +13,6 @@
 
 from __future__ import annotations
 from typing import Any
-import re
 
 from functools import wraps
 from itertools import chain
@@ -89,7 +88,6 @@
 
 reserved_words_c99 = ['inline', 'restrict']
 
-
 def get_math_macros():
     """ Returns a dictionary with math-related macros from math.h/cmath
 
@@ -269,13 +267,6 @@ def _traverse_matrix_indices(self, mat):
         rows, cols = mat.shape
         return ((i, j) for i in range(rows) for j in range(cols))
 
-    @staticmethod
-    def _check_valid_c_variable_name(var_name):
-        pattern = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]{0,30}$")
-        msg = 'SymPy symbol {} not printable in C.'
-        if not pattern.search(var_name):
-            raise ValueError(msg.format(var_name))
-
     @_as_macro_if_defined
     def _print_Mul(self, expr, **kwargs):
         return super()._print_Mul(expr, **kwargs)
@@ -396,8 +387,6 @@ def _print_MatrixElement(self, expr):
 
     def _print_Symbol(self, expr):
         name = super()._print_Symbol(expr)
-        # if name is an indexed, e.g. a[0], only check the variable name
-        self._check_valid_c_variable_name(name.split('[')[0])
         if expr in self._settings['dereference']:
             return '(*{})'.format(name)
         else:
diff --git a/sympy/simplify/fu.py b/sympy/simplify/fu.py
index 8cd518b3d4..bd66c2c161 100644
--- a/sympy/simplify/fu.py
+++ b/sympy/simplify/fu.py
@@ -246,6 +246,13 @@ def f(rv):
             rv = fmap[type(rv)](S.Pi/2 - rv.args[0])
         return rv
 
+    # touch numbers iside of trig functions to let them automatically update
+    rv = rv.replace(
+        lambda x: isinstance(x, TrigonometricFunction),
+        lambda x: x.replace(
+            lambda n: n.is_number and n.is_Mul,
+            lambda n: n.func(*n.args)))
+
     return bottom_up(rv, f)
 
 
@@ -273,7 +280,12 @@ def TR4(rv):
     0 1 zoo 0
     """
     # special values at 0, pi/6, pi/4, pi/3, pi/2 already handled
-    return rv
+    return rv.replace(
+        lambda x:
+            isinstance(x, TrigonometricFunction) and
+            (r:=x.args[0]/pi).is_Rational and r.q in (1, 2, 3, 4, 6),
+        lambda x:
+            x.func(x.args[0].func(*x.args[0].args)))
 
 
 def _TR56(rv, f, g, h, max, pow):


Test patch:
diff --git a/sympy/printing/tests/test_c.py b/sympy/printing/tests/test_c.py
index 7ba03cb7a2..11836539f0 100644
--- a/sympy/printing/tests/test_c.py
+++ b/sympy/printing/tests/test_c.py
@@ -30,19 +30,6 @@
 x, y, z = symbols('x,y,z')
 
 
-def test_invalid_variable_names():
-    long_var = 'w'*32
-    syms = symbols(r'a_{\delta}[0], I_{x}, a*, 9t, bus#, %s' % long_var)
-    for s in syms:
-        with raises(ValueError):
-            ccode(s)
-    # these should not raise
-    short_var = 'w'*31
-    syms = symbols('funny_var[5], b[1][2], a[idx], out[i*N+j], %s' % short_var)
-    for s in syms:
-        ccode(s)
-
-
 def test_printmethod():
     class fabs(Abs):
         def _ccode(self, printer):
diff --git a/sympy/simplify/tests/test_fu.py b/sympy/simplify/tests/test_fu.py
index 29f614d7ad..2de2126b73 100644
--- a/sympy/simplify/tests/test_fu.py
+++ b/sympy/simplify/tests/test_fu.py
@@ -1,6 +1,7 @@
 from sympy.core.add import Add
 from sympy.core.mul import Mul
 from sympy.core.numbers import (I, Rational, pi)
+from sympy.core.parameters import evaluate
 from sympy.core.singleton import S
 from sympy.core.symbol import (Dummy, Symbol, symbols)
 from sympy.functions.elementary.hyperbolic import (cosh, coth, csch, sech, sinh, tanh)
@@ -9,7 +10,7 @@
 from sympy.simplify.powsimp import powsimp
 from sympy.simplify.fu import (
     L, TR1, TR10, TR10i, TR11, _TR11, TR12, TR12i, TR13, TR14, TR15, TR16,
-    TR111, TR2, TR2i, TR3, TR5, TR6, TR7, TR8, TR9, TRmorrie, _TR56 as T,
+    TR111, TR2, TR2i, TR3, TR4, TR5, TR6, TR7, TR8, TR9, TRmorrie, _TR56 as T,
     TRpower, hyper_as_trig, fu, process_common_addends, trig_split,
     as_f_sign_1)
 from sympy.core.random import verify_numerically
@@ -72,6 +73,17 @@ def test_TR3():
         j = TR3(i)
         assert verify_numerically(i, j) and i.func != j.func
 
+    with evaluate(False):
+        eq = cos(9*pi/22)
+    assert eq.has(9*pi) and TR3(eq) == sin(pi/11)
+
+
+def test_TR4():
+    for i in [0, pi/6, pi/4, pi/3, pi/2]:
+        with evaluate(False):
+            eq = cos(i)
+        assert isinstance(eq, cos) and TR4(eq) == cos(i)
+
 
 def test__TR56():
     h = lambda x: 1 - x