Derivative of summations
<p>I am using sympy from time to time, but am not very good at it. At the moment I am stuck with defining a list of indexed variables, i.e. n1 to nmax and performing a summation on it. Then I want to be able to take the derivative:</p>

<p>So far I tried the following:</p>

<pre><code>numSpecies = 10
n = IndexedBase('n')
i = symbols("i",cls=Idx)
nges = summation(n[i],[i,1,numSpecies])
</code></pre>

<p>However, if i try to take the derivative with respect to one variable, this fails:</p>

<pre><code>diff(nges,n[5])
</code></pre>

<p>I also tried to avoid working with <a href="http://docs.sympy.org/latest/modules/tensor/indexed.html" rel="nofollow"><code>IndexedBase</code></a>.</p>

<pre><code>numSpecies = 10
n = symbols('n0:%d'%numSpecies)
k = symbols('k',integer=True)
ntot = summation(n[k],[k,0,numSpecies])
</code></pre>

<p>However, here already the summation fails because mixing python tuples and the sympy summation.</p>

<p>How I can perform indexedbase derivatives or some kind of workaround?</p>

<p>With SymPy's development version, your example works.</p>

<p>To install SymPy's development version, just pull it down with <code>git</code>:</p>

<pre><code>git clone git://github.com/sympy/sympy.git
cd sympy
</code></pre>

<p>Then run python from that path or set the <code>PYTHONPATH</code> to include that directory before Python's default installation.</p>

<p>Your example on the development version:</p>

<pre><code>In [3]: numSpecies = 10

In [4]: n = IndexedBase('n')

In [5]: i = symbols("i",cls=Idx)

In [6]: nges = summation(n[i],[i,1,numSpecies])

In [7]: nges
Out[7]: n[10] + n[1] + n[2] + n[3] + n[4] + n[5] + n[6] + n[7] + n[8] + n[9]

In [8]: diff(nges,n[5])
Out[8]: 1
</code></pre>

<p>You could also use the contracted form of summation:</p>

<pre><code>In [9]: nges_uneval = Sum(n[i], [i,1,numSpecies])

In [10]: nges_uneval
Out[10]: 
  10      
 ___      
 â²        
  â²   n[i]
  â±       
 â±        
 â¾â¾â¾      
i = 1     

In [11]: diff(nges_uneval, n[5])
Out[11]: 
  10      
 ___      
 â²        
  â²   Î´   
  â±    5,i
 â±        
 â¾â¾â¾      
i = 1     

In [12]: diff(nges_uneval, n[5]).doit()
Out[12]: 1
</code></pre>

<p>Also notice that in the next SymPy version you will be able to derive symbols with symbolic indices:</p>

<pre><code>In [13]: j = symbols("j")

In [13]: diff(n[i], n[j])
Out[13]: 
Î´   
 j,i
</code></pre>

<p>Where you get the <a href="https://en.wikipedia.org/wiki/Kronecker_delta" rel="nofollow">Kronecker delta</a>.</p>

<p>If you don't feel like installing the SymPy development version, just wait for the next full version (probably coming out this autumn), it will support derivatives of <code>IndexedBase</code>.</p>

python sympy derivative