Johannes - 1 year ago 86

Python Question

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:

So far I tried the following:

`numSpecies = 10`

n = IndexedBase('n')

i = symbols("i",cls=Idx)

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

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

`diff(nges,n[5])`

I also tried to avoid working with

`IndexedBase`

`numSpecies = 10`

n = symbols('n0:%d'%numSpecies)

k = symbols('k',integer=True)

ntot = summation(n[k],[k,0,numSpecies])

However, here already the summation fails because mixing python tuples and the sympy summation.

How I can perform indexedbase derivatives or some kind of workaround?

Answer Source

With SymPy's development version, your example works.

To install SymPy's development version, just pull it down with `git`

:

```
git clone git://github.com/sympy/sympy.git
cd sympy
```

Then run python from that path or set the `PYTHONPATH`

to include that directory before Python's default installation.

Your example on the development version:

```
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
```

You could also use the contracted form of summation:

```
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
```

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

```
In [13]: j = symbols("j")
In [13]: diff(n[i], n[j])
Out[13]:
δ
j,i
```

Where you get the Kronecker delta.

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 `IndexedBase`

.