python – 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 Adjusting to the new version of Pylab and Mayavi on Ubuntu 12.04 Mon, 14 May 2012 22:32:27 +0000 http://dragly.org/?p=754 Continue reading ]]> It seems the IPython and Pylab packages has also been updated in 12.04 and thus removing the old ipython -wthread flag that would ensure Mayavi plots to be run in a separate thread. Running with the flag causes this error to show up:

[TerminalIPythonApp] Unrecognized flag: '-wthread'

Without this flag, the Mayavi plots lock up the UI and hangs. If you want to get the possibility back to rotate and play around with the plots, just start IPython the following way from now on:

ipython --pylab=qt

This will launch IPython with the Qt backend and threading. Using only –pylab does not include threading. For easy and quick access, add the following to a file named .bashrc in your home folder:

alias pylab='ipython --pylab=qt'

From now on you can launch IPython just by typing

pylab

in a terminal.

]]>
1125
Using the same script on installs with different EPD versions Mon, 14 May 2012 22:20:51 +0000 http://dragly.org/?p=751 Continue reading ]]> In the newest version of Enthought’s Python Distribution (EPD) on Ubuntu, the plotting package has been moved from enthought.mayavi.mlab to the shorter and more general mayavi.mlab. This does however mean that if you, like me, need to work with different versions of EPD on multiple systems, will experience the following error from time to time:

ImportError: No module named enthought.mayavi.mlab

Now, to avoid switching the import statement every time you switch systems, you can make Python check if one of the versions is installed during import. If it is not, we’ll tell it to try the other. This is done in this simple command:

try:
    from enthought.mayavi.mlab import *
except ImportError:
    from mayavi.mlab import *

Just replace any other similar import statements the same way and your code should once again be working across all your installations.

]]>
1126
The beauty of Mayavi http://elektromagnetisme.no/2010/10/07/the-beauty-of-mayavi/ http://elektromagnetisme.no/2010/10/07/the-beauty-of-mayavi/#comments Thu, 07 Oct 2010 07:07:53 +0000 http://mindseye.no/?p=214 Continue reading ]]>

Four charges with different magnitude plotted in 3D using Mayavi

In one of my earlier posts about Mayavi, I wrote about how you could visualize 2D field line plots using the flow function. At the end of that post I added that Mayavi is actually best at 3D plotting, and to follow up on that I’ll show you some of these plots with a few example Python scripts you might try out on your own.

First of all, you might want to know how to install Mayavi. For those lucky ones of you who have freed yourself and jumped on the Linux bandwagon, installing Mayavi should be quite easy. If you are using Ubuntu in particular, you may just install the package mayavi2 using either Synaptic or apt-get. If you are on Windows or Mac, you may either install Enthought’s own Python distribution (EPD) or give a shot at compiling on your own. Just note that EPD is quite expensive, even though all its components are open source, but if you are a student or academic user you could go ahead and download the academic version for free. It is basically the same as the commercial one, but with an academic license. (Kudos to Enthought for both making Mayavi open source, building an business model around it and still providing a great solution for students!)

Now, Enter 3D!

The way you do your plots in Mayavi depends on what you want to express. Most likely, you would prefer to show some simple plots giving just the necessary amount of information to tell you how the electric field behaves around your charges. A simple example of this is shown below:

Four charges in a Mayavi plot

The simple plots often give you a great perspective about what happens in the electric field

On the other hand, you might want to give a strong visualization to show off the density and beauty of an electric field. In such a case, increasing the resolution of the flow/streamline seeds gives you a greater amount of field lines, which could result in plots like this:

An highger seed resolution gives a more dense plot.

Note that the plot shows the same four charges as above, but from a different angle and, of course, with more field lines.

The greatest part of using Mayavi to visualize these plots, however, comes from the fact that you may rotate the plot in real time in the Mayavi scene view. This gives you great control and insight of what you are plotting as you may rotate it as if it was a physical object in front of you. To show how interesting this may be, I’ve created a short video rotating around the same plot as above, recorded using Mayavi’s animation features:

You may even animate the charges individually, showing you what happens when a charge moves through space.

Note that the video below shows some artifacts around the charges. I believe I could have tweaked the settings a bit more to avoid these, but I decided it was good enough for the purpose of showing Mayavi’s capabilities.

If you would like to test out these plots on your own, you can download the source code here:

And if you couldn’t get enough of those field line plots, here are all the above and a some more, stacked in one set:

Four charges in a Mayavi plot High resolution plot of four charges in a square Low resultion plot of four charges perfectly aligned in a square Using planes and spheres together as seeds yields more interesting results. A medium resolution dipole plot with spheres as seeds. Using a plane as a flow/streamline seed between the two charges in a dipole ]]>
http://elektromagnetisme.no/2010/10/07/the-beauty-of-mayavi/feed/ 7 214
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