matlab – Elektromagnetisme http://elektromagnetisme.no The home of FYS1120 Mon, 20 Oct 2014 11:23:54 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.3 28429679 Animating plots and waves in Python using matplotlib http://elektromagnetisme.no/2011/04/03/animating-plots-and-waves-in-python-using-matplotlib/ http://elektromagnetisme.no/2011/04/03/animating-plots-and-waves-in-python-using-matplotlib/#comments Sun, 03 Apr 2011 16:34:14 +0000 http://mindseye.no/?p=393 Continue reading ]]> matplotlib is an amazing framework to do visual plots in Python. It compares well with GnuPlot and beats Matlab’s plotting abilities by having more features. Although it does lack some 3D support, you may simply choose a different framework for 3D plots thanks to Python’s flexibility . In which case I would recommend Mayavi as a superb 3D plotting engine which I have written about before.

But now, let’s have a look at matplotlib’s animation capabilities. The script below shows a very easy approach to animation in matplotlib. This results in an animation of the standing wave shown here:

The script is as follows:

from matplotlib.pylab import *  # pylab is the easiest approach to any plotting
import time                     # we'll do this rendering i real time

ion()                           # interaction mode needs to be turned off

x = arange(0,2*pi,0.01)         # we'll create an x-axis from 0 to 2 pi
line, = plot(x,x)               # this is our initial plot, and does nothing
line.axes.set_ylim(-3,3)        # set the range for our plot

starttime = time.time()         # this is our start time
t = 0                           # this is our relative start time

while(t < 5.0):                 # we'll limit ourselves to 5 seconds.
                                # set this to while(True) if you want to loop forever
    t = time.time() - starttime # find out how long the script has been running
    y = -2*sin(x)*sin(t)        # just a function for a standing wave
                                # replace this with any function you want to animate
                                # for instance, y = sin(x-t)

    line.set_ydata(y)           # update the plot data
    draw()                      # redraw the canvas

I’ve commented each line, since the script is fairly small, but let’s outline a few important things.

First of all, you need to disable interactive mode with

ion()

This makes it possible to animate, but disables all the button controls in matplotlib’s figure window.

Furthermore, we need to assign our plot to a variable (or pointer if you like), named line. This is done by plotting some dummy data:

line, = plot(x,x)

Note the comma after “line”. This is placed here because plot returns a list of lines that are drawn. Since we draw only one line we unpack only this by placing a comma and nothing else after “line”. If you plot multiple lines at once you may unpack them together by issuing a command like this:

line_a,line_b,line_c = plot(...

This plotting makes our axes aligned to the dummy data (in this case y = x). To make sure we have enough room, we manually set the limits of our y axis:

line.axes.set_ylim(-3,3)

Finally, we do our calculations and eventually change the y-data for each time step. After this, we draw everything back onto the canvas. This is done through the following two lines:

    line.set_ydata(y)           # update the plot data
    draw()                      # redraw the canvas

That’s it. Your animation should now look like the one above.

Saving the animation to a  file

Saving everything to file is fairly simple with the savefig command. You can save all the frames as images and then convert them to video using your favorite video editor. I recommend using ffmpeg from command line or Blender (which also does 3D). There are surely easier tools out there, but I find the work flow using ffmpeg and Blender quite quick, and they are also useful tools for many other tasks.

I’ve made the script animation ready below, and there’s really just one important thing to note: Earlier we showed the animation in real time. Saving all the images in real time lags badly and many frames are dropped. Because of this, we now set a delta time between each frame and iterates over each and every frame to make sure we have enough data for a smooth video.

Feel free to use the script below as it suits you:

from matplotlib.pylab import *  # pylab is the easiest approach to any plotting

ion()                           # interaction mode needs to be turned off

fig = figure(figsize=(16,9),dpi=80)     # create a figure in 1280 x 720 pixels
                                # this is not as simple as it could be, but
                                # it is like this because matplotlib is focused
                                # on print, not screen

x = arange(0,2*pi,0.01)         # we'll create an x-axis from 0 to 2 pi
line, = plot(x,x)               # this is our initial plot, and does nothing
line.axes.set_ylim(-3,3)        # set the range for our plot

t = 0                           # this is our relative start time
dt = 0.04
i = 0
while(t < 5.0):                 # we'll limit ourselves to 5 seconds.
                                # set this to while(True) if you want to loop forever
    y = -2*sin(x)*sin(t)        # just a function for a standing wave
                                # replace this with any function you want to animate
                                # for instance, y = sin(x-t)

    line.set_ydata(y)           # update the plot data
    draw()                      # redraw the canvas

    t = t + dt                  # increase the time
    i = i + 1                   # increase our counter

    # save the figure with a 4-digit number
    savefig("outdata/blah" + '%04d' % i + ".png")
]]>
http://elektromagnetisme.no/2011/04/03/animating-plots-and-waves-in-python-using-matplotlib/feed/ 6 393
Using Mayavi to visualize electric fields http://elektromagnetisme.no/2010/09/25/using-mayavi-to-visualize-electric-fields/ http://elektromagnetisme.no/2010/09/25/using-mayavi-to-visualize-electric-fields/#comments Fri, 24 Sep 2010 22:53:47 +0000 http://mindseye.no/?p=141 Continue reading ]]>

Mayavi renders great field line plots.

While searching for a good Python module to visualize electric fields, I found Mayavi. Developed by Enthought, Mayavi is a very good module for visualizing a huge range of different scientific data sets. Everything from surfaces, flows and streamlines to bar charts, 3D plots and contour surfs are beautifully drawn on screen and exported to several file formats, such as PDF, PNG, EPS and more.

What I needed it for, however, was to visualize electric field lines in the course FYS1120 at the University of Oslo. We were told to use Matlab with the streamline and quiver functions, but even so, I wanted to use Python and decided to do a search and see if something similar was possible with Python. It took me some time to figure out how to use the scitools package to do streamline plots, but eventually I made it. However, these were a bit tedious to get working correctly and looked only about as good as the Matlab plots.

I continued my search and found Mayavi as an alternative. It seemed like it was a bit out of the scope of my quest, but I decided to give it a serious try in any case.

I’m glad I did. The quality of the plots in Mayavi are amazing compared to Matlab’s. Let’s take the following field line plot done in Matlab as an example:

The field line plot in Matlab.

This is done with the streamline function, and if you have been working with field lines in electromagnetism, you’ll notice that the plot doesn’t really follow the definition of field lines.

In the field line definition, the tangent of any point on the field line is the same as the electric field in that point. At the same time, the density of field lines should represent the strength of the field. That is, the electric field in a specified area is proportional to the number of field lines in the same area.

This is where this Matlab approach with the streamline function doesn’t work well. Actually, it misses completely. As you see, the density of the field lines is bigger in the edges, further away from the charge, while it should be bigger in the middle, close to the charge.

Methodically, the streamline function allows us to select from which points we want to draw field lines, and we could of course generate the streamlines in a circle around the charge instead of in a grid like now. However, the plot will still be a bit “rough” in the edges and doing this for every point requires some extra amount of logic for the programmer.

Giving Mayavi a try at the job shows us how much prettier and more correct the representation in Mayavi is:

The same field line plot in MayaVi.

Now that’s what I call a field line plot! Giving our lonely charge a few positive and negative friends to play with yields another pretty picture:

A field line plot using Python with MayaVi, showing four charges

You might notice that this plot is also not perfect in terms of the field line definition, but it is very close and a lot better than what we would have gotten from Matlab’s equivalent plot.

How to do it

Below you see the full source code for this script. I’ve included comments on each line instead of describing the script in detail here. However, I do want you to notice one important thing:

Mayavi is very good at visualizing things in 3D space, but it does not seem to be intended for 2D use. Therefore, we need to do some hacks to simulate a 2D space. It works flawlessly when you know how to do this, but it makes everything seem a bit harder than necessary. The payoff, on the other hand, is humongous, and it is one-time thing to learn how to do.

As well, it makes it easily possible to scale our plot up to a 3D-plot instead, which I will show you in the next post about Mayavi.

Enjoy!

from numpy import *
from enthought.mayavi.mlab import *

N = 100 # the bigger the number, the more calculations your script has to make, but you save MayaVi's Runge Kutta method a lot of trouble and the total plot time is lowered
a = 0. # the lowest coordinate
b = 1. # the highest coordinate
dt = b / N; # the step we need to make to get to each position on our grid

q = [1., -1., 1., -1.] # the values of our four charges
qpos = [[0.56, 0.56, 0.50], # and their positions
        [0.26, 0.76, 0.50],
        [0.66, 0.16, 0.50],
        [0.66, 0.86, 0.50]]

x,y,z = mgrid[a:b:dt, a:b:dt, 0.:1.:0.5] # here is the trick - we want a 2d plot, but MayaVi works best in 3D space. Let's just keep the z-axis to a minimum (two steps)
Ex, Ey, Ez = mgrid[a:b:dt, a:b:dt, 0.:1.:0.5] # create a few arrays to store the vector field in, using meshgrid

for i in range(N): # iterate over all rows
    for j in range(N): # and all columns
        Ex[i,j] = 0.0 # set the value of each point to 0, initially
        Ey[i,j] = 0.0
        for num in range(len(q)): # for each charge, calculate the electric field it provides
            rs = ((x[i,j] - qpos[num][0])**2 + (y[i,j] - qpos[num][1])**2) # the distance from the point to the charge, squared
            r = sqrt(rs)
            q1x = q[num] * (x[i,j] - qpos[num][0]) / (r * rs) # the x-component of the field
            q1y = q[num] * (y[i,j] - qpos[num][1]) / (r * rs) # and the y-component
            # this is $\frac{q}{r^2} \hat{\mathbf r}$ on component form
            Ex[i,j] = q1x + Ex[i,j] # now, add this to the electric field in this point, together with the contribution from the other charges
            Ey[i,j] = q1y + Ey[i,j]

fig = figure(fgcolor=(0,0,0), bgcolor=(1,1,1)) # set the background and foreground of our figure
#obj = quiver3d(x, y, z, Ex, Ey, Ez, line_width=1) # uncomment this if you want a quiver plot
streams = list() # create a list to hold all our streamlines (or flows if you speak MayaVi)

for s in range(len(q)): # for each charge, create a streamline seed
    stream = flow(x,y,z,Ex, Ey, Ez, seed_scale=0.5, seed_resolution=1, seedtype='sphere') # the seed resolution is set to a minimum initially to avoid extra calculations
    stream.stream_tracer.initial_integration_step = 0.01 # the integration step for the runge kutta method
    stream.stream_tracer.maximum_propagation = 20.0 # the maximum length each step should reach - lowered to avoid messy output
    stream.stream_tracer.integration_direction = 'both' # integrate in both directions
    stream.seed.widget.center = qpos[s] # set the stream widget to the same position as the charge
    stream.seed.widget.radius = dt * 2 # and its radius a bit bigger than the grid size
    stream.seed.widget.theta_resolution = 30 # make the resolution high enough to give a fair number of lines
    stream.seed.widget.phi_resolution = 1 # but we are looking at a plane for now, so let's not have any resolution in the z-direction
    stream.seed.widget.enabled = False # hide the widget itself
    streams.append(stream) # and eventually, add the stream to our list for convenience

xlab = xlabel("x") # set the labels
ylab = ylabel("y")
showm = show() # show everything
axesm = axes() # add some axes
axesm.axes.y_axis_visibility = False # remove the z-axis (named y for some MayaVi reason)
fig.scene.z_plus_view() # let's look at it from the top!
fig.scene.parallel_projection = True # and we don't need any projection when looking at it in 2D
print "Done."
]]>
http://elektromagnetisme.no/2010/09/25/using-mayavi-to-visualize-electric-fields/feed/ 13 141
Using Python in the first MAT1120 oblig http://elektromagnetisme.no/2010/09/13/using-python-in-the-first-mat1120-oblig/ http://elektromagnetisme.no/2010/09/13/using-python-in-the-first-mat1120-oblig/#respond Mon, 13 Sep 2010 13:00:04 +0000 http://mindseye.no/?p=84 Continue reading ]]> The first “oblig” (mandatory exercise) in the subject MAT1120 is now available. I am trying to do as much work as possible in Python instead of Matlab, but as always this creates some extra effort when the subject is oriented around the latter.

Already in the first exercise there is a minor challenge, since the data file is not stored as a simple array, but as Matlab code. This means we need to rewrite this file to Python code or run it in Matlab and export it as data instead. As I am currently using a computer without Matlab installed and being to lazy to connect to a server with Matlab via remote desktop, I decided to do the latter. (I might add that I also wanted to see if I could do this without Matlab at all).

First of all, I figured the data was stored in the following manner:

n=28;
B=zeros(n);

B(1,1)=0.3;
B(1,2)=0.3;
B(1,3)=0.2;

This is quite similar to Python code, but the parentheses should be square brackets and the zeros function requires NumPy. Thus, we need a way to replace these. Using regular expressions was the most probable useful way to do this. Thanks to the Gedit Regex Plugin I managed to do this without even opening a terminal. The needed Regex code was as follows:

Search for: B\((.*?)\)
Replace with: B[\1]

This will match any line with a “B” and replace the round brackets with square ones.  Notice that we don’t need any more fancy regex in this example as there are no other B’s with round brackets getting caught by our search.

The last challenge is to match the dimensions of the array. Matlab stores all n \times n matrices with indexes running from 1 \to n, while Python uses indexes from 0 \to n - 1.

First of all, we need to make the dimensions of the array n+1 to make sure the indexes used to insert the variables are not out of bounds, and in the end we need to delete the first row and column.

Luckily, this is easy to achieve by adding +1 to the zeros function:

B=zeros((n+1,n+1));

And by using the delete function from NumPy:

B=delete(B,1,1) # removes the first and row and column
B=delete(B,1,0)

You may download the finished Python version of the file here.

Note that when you are continuing to do these exercises you should convert B to a matrix whenever you need to do matrix multiplication. You might also use the B.dot(B) function, but there is no such equivalent for exponentials (powers). Check out this page for more info about differences between matrices and arrays in NumPy.

]]>
http://elektromagnetisme.no/2010/09/13/using-python-in-the-first-mat1120-oblig/feed/ 0 84