Sunday, February 12, 2012

Streamlines with Matplotlib

This is a translation into English of an old post in Spanish.

As an assignment for the Numerical Methods for Dissipative Systems course I had to solve the 2D Laplace equation in a rectangle with some given boundary conditions.
I wrote a program to solve it in C, but to do the streamline graphics I used MatPlotLib.
This is the Python script that generated the streamlines:
# -*- coding: iso-8859-15
import sys
from numpy import * 
from pylab import load  
import matplotlib.pyplot as plt
if len(sys.argv) >= 1:
    psi = load(sys.argv[1])
    cs = plt.contour(psi,20)
    plt.clabel(cs)
    plt.xlabel("y/h")
    plt.ylabel("x/h")
    plt.show()
else:
    print "This program needs the path to the file that contains the psi matrix"

To generate the streamlines we should execute the script passing to it the path of the file where the solution matrix is. In this case the entries of the matrix must be separated by white spaces. Reading the help of the load function, you can learn how to modify it to use different delimiters.

I run the script from iPython:
$ ipython
Python 2.5.2 (r252:60911, Dic 20 2009, 23:16:55) 
Type "copyright", "credits" or "license" for more information.

IPython 0.8.4 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object'. ?object also works, ?? prints more.

In [1]: run ~/grafico.py 'pathToFileWithSolutionMatrix'
and this was the result:

To be able to run it, besides python, you'll need to install the following modules: numpy, pylab and matPlotLib (you can find them all in the Ubuntu repositories).

2 comments:

  1. Hi, your blogs are helpful!

    Any ideas to plot streamlines(not contour) using matplotlib?

    Matrix U in U.dat, Matrix V in V.dat, then plot the streamline of vector field(U, V)?

    Regards!

    ReplyDelete
  2. Thanks!

    Take a look here: http://stackoverflow.com/questions/8296617/how-to-plot-a-streamlines-when-i-know-u-and-v-components-of-velocitynumpy-2d

    Regards,
    M

    ReplyDelete