Sympy extract Fourier Series coefficients
<p>I am using <code>sympy</code> to carry on some symbolic math manipulations.</p>
<p>Start by creating a Fourier series representation of a rectangular pulse train (duty cycle &lt; 50%), then try to access the multiplying factors, i.e. <code>a_n</code> and <code>b_n</code> of the standard Fourier series.</p>
<p>In a nutshell:</p>
<pre><code>import sympy as sy
from sympy import fourier_series, pi, cos, sin
from sympy.abc import t
from sympy.functions.special.delta_functions import Heaviside
T = sy.symbols('T')
s = fourier_series(Heaviside(t) - Heaviside(t-1/4), (t, 0, 1))
s.truncate(3)

1/π*sin(2πt)+1/π*sin(4πt)+1/π*cos(2πt)+0.25
</code></pre>
<p>I would then like to access the coefficients of the base functions. To this extent, I thought I should use <code>as_coefficient(expr)</code>.</p>
<p>This produces the expected results in a simpler case:</p>
<pre><code>g = 1/(pi*T)*sin(2*pi*t)
g.as_coefficient(sin(2*pi*t))

1/πT
</code></pre>
<p>However, with the object returned by <code>fourier_series</code>, this does not seem to work:</p>
<pre><code>a = s.truncate(3)
a.as_coefficient(sin(2*pi*t))
</code></pre>
<p>returns nothing (not even a warning or message).</p>
<p>Other methods like <code>s.as_Add()</code> or <code>s.as_Mul()</code> return both a full expression where the <code>a_n</code> is tied to its <code>sin(2*pi*n*t)</code> term (or <code>b_n</code> to its dual).</p>