cdb.core.trigrat
Canonical simplification of expressions in sines and cosines
This package simplifies expressions which are rational functions of sines and
cosines (and of tan, cot, sec and csc), of any number of angles. Such
expressions appear for instance in the components of metrics in polar or
spheroidal coordinates. Unlike Sympy's generic simplify or
trigsimp, it brings expressions into a canonical form: expressions
which are equal because of identities such as $\sin^2 x + \cos^2 x = 1$ or the
addition formulas are mapped to identical results, and an expression which
vanishes is always recognised as zero. It is also much faster on large
expressions.
Use it with from cdb.core.trigrat import trigrat. Importing the package
also makes the function available under the name "trigrat" to
map_sympy, and to evaluate through its simplify argument.trigrat(ex: Ex) -> Ex
Bring sines and cosines into canonical form.
Acts on all scalar parts of
ex, including the values of tensor
components produced by evaluate. Components which simplify to zero are
removed; if no components remain, the components node is replaced by zero. The
expression is modified in place and returned. Given a Sympy expression instead
of a Cadabra expression, it returns the result of trigrat_sympy.trigrat($\sin(x)**2 + \cos(x)**2$);
\(\displaystyle{}1\)
trigrat($\sin(x+y) - \sin(x) \cos(y)$);
\(\displaystyle{}\sin{y} \cos{x}\)
trigrat($\sin(x) - 2 \sin(x/2) \cos(x/2)$);
\(\displaystyle{}0\,\)
trigrat($\tan(x) + 1/\tan(x)$);
\(\displaystyle{}{\left(\sin{x} \cos{x}\right)}^{-\,1}\)
Denominators are made free of sines, so the following is rewritten:
trigrat($1/(1+\sin(x))$);
\(\displaystyle{}\left(1 -\,\sin{x}\right) {\left(\cos{x}\right)}^{-2\,}\)
A typical use is the simplification of tensor components. Below are the
Christoffel symbols of a sphere of radius $R$. Switching off the built-in
simplification of
evaluate and calling trigrat afterwards is
often much faster than the default simplification.{\theta,\phi}::Coordinate;
{a,b,c,d}::Indices(values={\theta,\phi}, position=fixed);
\partial{#}::PartialDerivative;
g_{a b}::Metric.
g^{a b}::InverseMetric.
\(\displaystyle{}\text{Property Coordinate attached to }\left[\theta, \phi\right].\)
\(\displaystyle{}\text{Property Indices(position=fixed, values=\{{\theta}
, {\phi}
\}) attached to }\left[a, b, c, d\right].\)
\(\displaystyle{}\text{Property PartialDerivative attached to }\backslash\texttt{partial}\{\#\}.\)
sph:= { g_{\theta\theta} = R**2, g_{\phi\phi} = R**2 \sin(\theta)**2 }.
complete(sph, $g^{a b}$);
\(\displaystyle{}\left[g_{\theta \theta} = {R}^{2\,}, g_{\phi \phi} = {R}^{2\,} {\left(\sin{\theta}\right)}^{2\,}, g^{\theta \theta} = {R}^{-2\,}, g^{\phi \phi} = {\left({R}^{2\,} {\left(\sin{\theta}\right)}^{2\,}\right)}^{-\,1}\right]\)
ch:= \Gamma^{a}_{b c} = 1/2 g^{a d} ( \partial_{c}{g_{b d}}
+\partial_{b}{g_{c d}}
-\partial_{d}{g_{b c}} ):
evaluate(ch, sph, rhsonly=True, simplify=False)
trigrat(ch);
\(\displaystyle{}\Gamma^{a}\,_{b c} = \frac{1}{2}\,g^{a d} \left(\partial_{c}{g_{b d}} +\partial_{b}{g_{c d}} -\,\partial_{d}{g_{b c}}\right)\)
\(\displaystyle{}\Gamma^{a}\,_{b c} = \square{}_{b}{}_{c}{}^{a}\left\{\begin{aligned}\square{}_{\phi}{}_{\theta}{}^{\phi}& = \square{}_{\theta}{}_{\phi}{}^{\phi} = \cos{\theta} {\left(\sin{\theta}\right)}^{-\,1}\\[-.5ex]
\square{}_{\phi}{}_{\phi}{}^{\theta}& = -\,\sin{\theta} \cos{\theta}\\[-.5ex]
\end{aligned}\right\}
\)
Alternatively,
trigrat can be used for the simplification steps
inside evaluate:ch2:= \Gamma^{a}_{b c} = 1/2 g^{a d} ( \partial_{c}{g_{b d}}
+\partial_{b}{g_{c d}}
-\partial_{d}{g_{b c}} ):
evaluate(ch2, sph, rhsonly=True, simplify="trigrat");
\(\displaystyle{}\Gamma^{a}\,_{b c} = \frac{1}{2}\,g^{a d} \left(\partial_{c}{g_{b d}} +\partial_{b}{g_{c d}} -\,\partial_{d}{g_{b c}}\right)\)
\(\displaystyle{}\Gamma^{a}\,_{b c} = \square{}_{b}{}_{c}{}^{a}\left\{\begin{aligned}\square{}_{\phi}{}_{\theta}{}^{\phi}& = \square{}_{\theta}{}_{\phi}{}^{\phi} = \cos{\theta} {\left(\sin{\theta}\right)}^{-\,1}\\[-.5ex]
\square{}_{\phi}{}_{\phi}{}^{\theta}& = -\,\sin{\theta} \cos{\theta}\\[-.5ex]
\end{aligned}\right\}
\)
trigrat_sympy(expr) -> sympy expression
Canonical form of a Sympy expression in sines and cosines.
import sympy
_RECIPROCAL = {
sympy.tan: lambda u: sympy.sin(u)/sympy.cos(u),
sympy.cot: lambda u: sympy.cos(u)/sympy.sin(u),
sympy.sec: lambda u: 1/sympy.cos(u),
sympy.csc: lambda u: 1/sympy.sin(u),
}
def _to_sin_cos(e):
for f, rep in _RECIPROCAL.items():
e = e.replace(f, rep)
return e
def _hide_opaque(e, table):
# Subexpressions which are not rational in sin and cos (other
# functions, non-integer powers) are treated as opaque symbols, after
# bringing their arguments into canonical form.
if e.is_Atom or isinstance(e, (sympy.sin, sympy.cos)):
return e
if isinstance(e, (sympy.Add, sympy.Mul)):
return e.func(*[_hide_opaque(a, table) for a in e.args])
if isinstance(e, sympy.Pow) and e.exp.is_Integer:
return sympy.Pow(_hide_opaque(e.base, table), e.exp)
inner = e.func(*[trigrat_sympy(a) for a in e.args])
if inner.is_number or inner.is_Atom or not inner.has(sympy.sin, sympy.cos):
return inner
table[inner] = None
return inner
def _angle_groups(angles):
# Angles q*t with rational q are grouped by t; within a group all
# angles are integer multiples of the base angle t/L.
groups = {}
for a in angles:
q, t = a.as_coeff_Mul()
if not q.is_Rational:
q, t = sympy.Integer(1), a
groups.setdefault(t, set()).add(q)
out = []
for t in sorted(groups, key=sympy.default_sort_key):
L = 1
for q in groups[t]:
L = sympy.ilcm(L, q.q)
out.append((t, sympy.Integer(L), groups[t]))
return out
def _reduce(p, svars, cvars):
# Reduce a polynomial modulo s_k**2 + c_k**2 - 1, leaving it of
# degree at most one in each s_k.
p = sympy.expand(p)
if not svars or p == 0:
return p
out = []
for mon, coeff in sympy.Poly(p, *svars).terms():
term = coeff
for e, s, c in zip(mon, svars, cvars):
term *= (1 - c**2)**(e // 2) * s**(e % 2)
out.append(term)
return sympy.expand(sympy.Add(*out))
def _pretty(p, svars, cvars):
# Factor p, writing factors c_k**2 - 1 as -s_k**2. This is a fixed
# function of p, so the result stays unique.
pre = sympy.Integer(1)
for s, c in zip(svars, cvars):
if not p.has(c):
continue
rel = sympy.Poly(c**2 - 1, c)
while True:
q, r = sympy.div(sympy.Poly(p, c), rel)
if not r.is_zero:
break
p = q.as_expr()
pre *= -s**2
return pre * sympy.factor(p)
def trigrat_sympy(expr):
"""Canonical form of a rational function of sines and cosines (and
tan, cot, sec, csc) of any number of angles."""
e = _to_sin_cos(sympy.sympify(expr))
if not e.has(sympy.sin, sympy.cos):
return sympy.factor(sympy.cancel(e))
table = {}
e = _hide_opaque(e, table)
hidden = sorted(table, key=sympy.default_sort_key)
hsyms = [sympy.Symbol('_trigrat_h%d' % i) for i in range(len(hidden))]
e = e.xreplace(dict(zip(hidden, hsyms)))
e = sympy.expand_trig(e)
angles = {f.args[0] for f in e.atoms(sympy.sin, sympy.cos)}
groups = _angle_groups(angles)
svars = [sympy.Symbol('_trigrat_s%d' % k) for k in range(len(groups))]
cvars = [sympy.Symbol('_trigrat_c%d' % k) for k in range(len(groups))]
u = sympy.Dummy('u')
rep, bases = {}, []
for (t, L, qs), s, c in zip(groups, svars, cvars):
bases.append(t / L)
for q in qs:
for f in (sympy.sin, sympy.cos):
rep[f(q * t)] = sympy.expand_trig(f(q * L * u)).xreplace(
{sympy.sin(u): s, sympy.cos(u): c})
e = e.xreplace(rep)
n, d = sympy.fraction(sympy.together(e))
n, d = _reduce(n, svars, cvars), _reduce(d, svars, cvars)
for s, c in zip(svars, cvars):
d0, d1 = d.coeff(s, 0), d.coeff(s, 1)
if d1 != 0:
n = _reduce(n * (d0 - d1 * s), svars, cvars)
d = _reduce(d0**2 - d1**2 * (1 - c**2), svars, cvars)
if n == 0:
return sympy.Integer(0)
terms = sympy.Poly(n, *svars).terms() if svars else [((), n)]
coeffs = [cf for _, cf in terms]
g = sympy.gcd_list(coeffs + [d])
coeffs = [sympy.cancel(cf / g) for cf in coeffs]
d = sympy.cancel(d / g)
gens = sorted(d.free_symbols, key=sympy.default_sort_key)
# Fix the overall sign: denominator with more positive than negative
# coefficients, or a positive leading coefficient in case of a tie.
dc = sympy.Poly(d, *gens).coeffs() if gens else [d]
neg = sum(1 for k in dc if k < 0)
if 2 * neg > len(dc) or (2 * neg == len(dc) and dc[0] < 0):
coeffs, d = [-cf for cf in coeffs], -d
num = sympy.Add(*[_pretty(cf, svars, cvars)
* sympy.Mul(*[s**k for s, k in zip(svars, mon)])
for (mon, _), cf in zip(terms, coeffs)])
res = num / _pretty(d, svars, cvars)
back = dict(zip(hsyms, hidden))
for s, c, b in zip(svars, cvars, bases):
back[s], back[c] = sympy.sin(b), sympy.cos(b)
return res.xreplace(back)
# Make the function available by name to map_sympy and evaluate.
sympy.trigrat = trigrat_sympy
if 'trigrat' not in sympy.__all__:
sympy.__all__.append('trigrat')
__all__ = ['trigrat', 'trigrat_sympy']
The function behind
trigrat, acting on a Sympy expression.\(\displaystyle{}\cos^{2}{\left(x \right)}\)
Method
Sums and integer multiples of angles are first expanded, and angles which are rational multiples of each other ($x$ and $x/2$, say) are written as integer multiples of a common base angle. After that, every sine and cosine is $s_k=\sin\theta_k$ or $c_k=\cos\theta_k$ of an independent base angle $\theta_k$, and the expression is a rational function of the $s_k$, $c_k$ and the remaining symbols, taken modulo the relations $s_k^2+c_k^2=1$. Numerator and denominator are reduced to degree at most one in each $s_k$, and the denominator is made independent of all $s_k$ by multiplying numerator and denominator with its conjugate in each $s_k$ in turn. The result \begin{equation*} \frac{\sum_S A_S(c)\,\prod_{k\in S} s_k}{D(c)}\,, \end{equation*} with common factors of the $A_S$ and $D$ removed and a fixed overall sign, is unique. For display, factors $c_k^2-1$ in the factorised $A_S$ and $D$ are written as $-\sin^2\theta_k$. Other functions (square roots, exponentials, ...) are treated as opaque symbols, after their arguments have themselves been brought into canonical form. The form is canonical with respect to the angles which occur in the expression: $\sin x - 2 \sin(x/2)\cos(x/2)$ simplifies to zero, buttrigrat applied separately to $\sin x$ and to
$2\sin(x/2)\cos(x/2)$ gives two different (equivalent) forms. Hyperbolic
functions are not handled.
Maxima has a function of the same name and purpose (by D. Lazard), which uses
a different normal form: it linearises products into sines and cosines of
sums of angles. The form used here keeps powers of $\cos\theta_k$, which is
closer to how, for instance, metrics are usually written.