Pages

Showing posts with label math. Show all posts
Showing posts with label math. Show all posts

Tuesday, November 13, 2012

Adaptive Time Step Integrators in SciPy

For one of my projects at school I have to numericaly integrate a bunch of ODEs, something I would normally do using ode45 in Matlab or NDSolve in Mathematica. However, since the rest of my code is written in Python, and I really don't want to install the bloatware that is Matlab on my clean linux machine, I've decided I was going to try out the ODE libraries that come with numpy and scipy. As it turns out, they're not too bad, but their documentation is. So, it took me a while to figure out how to do this, and I'm guessing someone else will probably benefit from this post (I know it would have saved me about a day's work, at least).

So, it turns out that scipy doesn't really implement its own ode solver, but instead wraps a bunch of FORTRAN code, and just silently drops like 80% of the functionality of that code without documenting much of what it kept and what it ignored. Anyway, after sifting through a bunch of forums and a whole bunch of source code, I came to the conclusion that the only function that can actually do adaptive time stepping and supply dense output is the wrapper around the vode integrator. The other thing that I needed was to detect when my trajectory crosses a certain boundary defined by $\phi(y) = 0$ and trigger an event at that point. In my case I simply needed to restart integration after adding the crossing point to the solution array. The following code does what I needed:
def f(t, y):
    # define your \dot{y}=f(y,t) here

def phi(y):
    # this function defines the boundary that is crossed


from scipy.integrate import ode 

# set up the solver, with a maximum time step of 1e-1
# an initial condition of y0 = init and t0 = 0
solver = ode(f)
solver.set_integrator('vode', max_step=1e-1)
solver.set_initial_value(init, 0)
tfinal = 30  # run this for 30 seconds
t = [0] 
y = [init]

# call the solver iteratively with the 'step' option
# what this does is it returns the result of the integration
# after the next (variable) time step, and the length of that step
while solver.successful() and solver.t < tfinal :
    solver.integrate(tfinal, step=True)
    y.append(solver.y);
    t.append(solver.t);

    # check for zero crossing
    gg1 = phi(y[-1])
    gg0 = phi(y[-2]) 
    if gg0*gg1 < 0 : 
        # find zero crossing
        # simple linear interpolation will do for now
        tcross = t[-2] - gg0*(t[-1]-t[-2])/(gg1-gg0)
        ycross = y[-2] - gg0*(y[-1]-y[-2])/(gg1-gg0)
        
        # replace wrong y and t
        y[-1] = ycross
        t[-1] = tcross

        # reset integration and start again
        solver.set_initial_value(ycross, tcross)
        print("crossed the boundary at time ", tcross)

Wednesday, October 17, 2012

Chain Rule under Einstein Notation

OK, so the other day I was trying to do all this symbolic math in order to get expressions for the derivatives of certain mappings from one vector space into another. Ultimately, all this would go into a Python function. When dealing with the first derivative things are pretty easy, because all you have is matrix-vector multiplication, and you can easily do that using NumPy's dot() function. The problem was that second and higher derivatives started showing in my formulas. These are higher dimensional tensors, and all of a sudden it is not clear what row multiplies what column when (for example, there are two ways to right multiply a 3-tensor to a vector) and what dimensions get added where when derivatives are taken. In particular, I was having a lot of trouble with applying chain rule. After reading the wikipedia article on Ricci calculus I wrote down a simple little rule for chain rule in index notation. Here it is:

Suppose we have a vector valued mapping $A^i(\mathbf{x})=B^i\left(\mathbf{C}\left(\mathbf{x}\right)\right)$ and we want to find its derivative with respect to $x^i$. We do this by applying chain rule, but first a little bit about the notation. The superscript denotes that $\mathbf{A}$ is a column vector, and the little equality above simply says that the $i$th element of $\mathbf{A}$ is equal to the $i$th element of $\mathbf{B}$. Now, we want to take the derivative with respect to $x$, which is also a column vector. The standard notation for this is
\[ \partial_{x^j}A^i(\mathbf{x}) = A^i_{,\,j}. \]
Now, on to chain rule. We drop the arguments of the functions, since they are unambiguous. Then, we write:
\[ A^i_{,\,j} = B^i_{,\,k}C^k_{,\,l}x^l_{,\,j} = B^i_{,\,k}C^k_{,\,l}\delta^l_j = B^i_{,\,k}C^k_{,\,j} .\]
And that's it! Now you know how to do chain rule, so taking derivatives and calculating them in [insert favorite programming language here] should be a piece of cake!

p.s. I might have been a little bit sloppy in my terminology and notation, but I am open to suggestions.
p.p.s. I have enabled $\LaTeX$ in my posts and comments. Feel free to give it a try!