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])
numSpecies = 10
n = symbols('n0:%d'%numSpecies)
k = symbols('k',integer=True)
ntot = summation(n[k],[k,0,numSpecies])
With SymPy's development version, your example works.
To install SymPy's development version, just pull it down with
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 : numSpecies = 10 In : n = IndexedBase('n') In : i = symbols("i",cls=Idx) In : nges = summation(n[i],[i,1,numSpecies]) In : nges Out: n + n + n + n + n + n + n + n + n + n In : diff(nges,n) Out: 1
You could also use the contracted form of summation:
In : nges_uneval = Sum(n[i], [i,1,numSpecies]) In : nges_uneval Out: 10 ___ ╲ ╲ n[i] ╱ ╱ ‾‾‾ i = 1 In : diff(nges_uneval, n) Out: 10 ___ ╲ ╲ δ ╱ 5,i ╱ ‾‾‾ i = 1 In : diff(nges_uneval, n).doit() Out: 1
Also notice that in the next SymPy version you will be able to derive symbols with symbolic indices:
In : j = symbols("j") In : diff(n[i], n[j]) Out: δ 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