ILNumerics for Scientists – How did you do the Visualization?

Reactions

I got a lot of emails after the last two posts (first, second) of people that liked the post and are interested in learning more. Most emails asked me to go into more details about how I did all that. Obviously, not too many people are interested in implementing the particle in a box, so the “what” is not as interesting as the “how”.

In this post I want to focus on the visualization part of the previous two examples and how ILNumerics helped me. As many of our users are scientists and engineers they are typically experts in the computation part but appreciate a little help in the visualization. If you’re interested in the computation part, please be patient until the next post.

The Form

I started by creating a new project in Visual Studio and chose Windows Forms Application. This gives me a vanilla Form1.cs. That’s the basis of all the visualization and helps me – being a scientist and not a coder – a lot, because I couldn’t do all that without the help of Visual Studio in the background.

On the left-hand side in the Toolbox panel I picked TableLayoutPanel under Containers and dragged it into Form1.cs.

firstimage

I adjusted the table to have three rows and a single column. In the Properties section under Dock I chose Fill so that everything scales when scaling the window later on.

secondimage

A right click on Table -> Edit Rows and Columns allows you to change the behavior of the three rows. I wanted the first and last row not to scale when changing the window. This is what I chose here.

thirdimage

In the middle row we would like to see two ILNumerics panels. So I dragged another TableLayoutPanel in the middle row and chose two columns and one row. Choosing Dock = Fill for the new table and dragging two ILPanels into the respective columns (again with Dock = Fill) gives us the layout for our final Windows Form.

fourthimage

In the header (the first row) I inserted a FlowLayoutPanel that makes sure that everything in there will be displayed rather neatly. Then I added the labels and the NumericUpDown according to my needs. Please make sure that you go through the properties of every item and choose the values according to your needs. In my case, for instance, the minimum value for the state is 1, since 0 would mean that there is no particle present. Here is the final picture of the form for the 1D particle in a box:

fifthimage

The Wiring

After having the layout ready the interactivity needs to be implemented. In this case there is only one point of user interaction. The user can choose which eigenvector to display. Double-clicking on the NumericUpDown control opens a new tab with a predefined class and a function handling the event when a user changes the value of the eigenvector.

sixthimage

All that’s needed now is to implement the function numericUpDown1_ValueChanged. This is particularly simple in our case. We just call the Update function (still to be implemented) with the new value for the eigenvector.

In the case of the 2D particle in a box we have, in fact, four events that should trigger the Update function. This is easily done by introducing these lines of code in the public function Form1():

     numericUpDown1.ValueChanged += Update;
     numericUpDown2.ValueChanged += Update;
     numericUpDown3.ValueChanged += Update;
     textBox1.TextChanged += Update;

The Implementation

Now, all we need to do is to implement the Update function and the initialization. The initialization makes sure that all the plotting objects are created when starting the program.

     public Form1()
     {
        InitializeComponent();

        var EVID = 1;
        var MeshSize = 1000;

        InitializePanel1(EVID, MeshSize);
        InitializePanel2(EVID, MeshSize);

        label2.Text = string.Format("In appropriate units the energy is {0}", EVID * EVID);
     }

     private void InitializePanel1(int EVID, int MeshSize)
     {
        ILArray<float> XY = ILMath.tosingle(Computing_Module1.CalcWF(EVID, MeshSize));
        var color = Color.Black;
        ilPanel1.Scene =
          new ILScene {
            new ILPlotCube {
              new ILLinePlot (XY, lineColor : color)
            }
          };
     }

The call to Computing_Module1.CalcWF will be explained in the next post. The piece of code above initializes the wave function plot and the density plot in their respective panels with the first eigenvector and a mesh size of 1000.

Finally, the Update function is implemented.

     private void Update(int EVID, int MeshSize = 1000)
     {
       ILArray<float> XY = ILMath.tosingle(Computing_Module1.CalcWF(EVID, MeshSize));
       ilPanel1.Scene.First<ILLinePlot>().Update(XY);
       ilPanel1.Scene.First<ILPlotCube>().Reset();
       ilPanel1.Refresh();

       ILArray<float> XD = ILMath.tosingle(Computing_Module1.CalcDensity(EVID, MeshSize));
       ilPanel2.Scene.First<ILLinePlot>().Update(XD);
       ilPanel2.Scene.First<ILPlotCube>().Reset();
       ilPanel2.Refresh();
       label2.Text = string.Format("In appropriate units the energy is {0}", EVID * EVID);
     }

Again, the CalcWF and CalcDensity calls will be explained in the next post. The Reset() function rescales the axes and the Refresh() function finally puts the new plot on screen.

ILNumerics for Scientists – Going 3D

Recap

Last time I started with one of the easiest problems in quantum mechanics: the particle in a box. This time I’ll add 1 dimension and we’ll see a particle in a 2D box. To visualize its wave function and density we need 3D surface plots.

2D Box

This time we have a particle that is confined in a 2D box. The potential within the box is zero and outside the box infinity. Again the solution is well-known and can be found on Wikipedia. This time the state of the wave function is determined by two numbers. These are typically called quantum numbers and refer to the X and the Y direction, respectively.

The absolute size of the box doesn’t really matter and we didn’t worry about it in the 1D case. However, the relative size of the length and the width make a difference. The solution to our problem reads

$\Psi_{n,k}(x,y) = \sqrt{\frac{4}{L_x L_y}} \cdot \sin(n \cdot \pi \cdot x / L_x) \cdot \sin(k \cdot \pi \cdot y / L_y)$

The Math

Very similar to the 1D case I quickly coded the wave function and the density for further plotting. I had to make sure that the arrays are fit for 3D plotting, so the code looks a little bit different compared to last post’s

     public static ILArray<double> CalcWF(int EVXID, int EVYID, double LX, double LY, int MeshSize)
     {
        ILArray<double> X = linspace<double>(0, LX, MeshSize);
        ILArray<double> Y = linspace<double>(0, LY, MeshSize);

        ILArray<double> Y2d = 1;
        ILArray<double> X2d = meshgrid(X, Y, Y2d);

        ILArray<double> Z = sqrt(4.0 / LX / LY) * sin(EVXID * pi * X2d / LX) * sin(EVYID * pi * Y2d / LY);

        return Z.Concat(X2d,2).Concat(Y2d,2);
     }

Again, this took me like 10 minutes and I was done.

The Visualization

This time the user can choose the quantum numbers for X and Y direction, the ratio between the length and the width of the box and also the number of mesh points along each axis for plotting. This makes the visualization panel a little bit more involved. Nevertheless, it’s still rather simple and easy to use. This time it took me only 45 minutes – I guess I learned a lot from last time.

The result

Here is the result of my little program. You can click and play with it. If you’re interested, you can download the Particle2DBox source code. Have fun!

Particle2DBoxThis is a screenshot of the application. I chose the second quantum number along the x axis and the fourth quantum number along the y axis. The box is twice as long in y direction as it is in x direction. The mesh size is 100 in each direction. On the left hand side you see the wave function and on the right hand side the probability density.

Rosenbrock2D

Directions to the ILNumerics Optimization Toolbox

As of yesterday the ILNumerics Optimization Toolbox is out and online! It’s been quite a challenge to bring everything together: some of the best algorithms, the convenience you as an user of ILNumerics expect and deserve, and the high performance requirements ILNumerics sets the scale on for. We believe that all these goals could be achieved quite greatly.

Continue reading Directions to the ILNumerics Optimization Toolbox

ILNumerics for Scientists – An easy start

Motivation

I’ve been working as a scientist at universities for 10 years before deciding to go into industry. The one thing I hated most was coding. At the end of the day coding for scientists is like running for a football player. Obviously, you need it but it’s not what you’re here for.

I really dreaded the coding and the debugging. So much precious time for something that was so clear on paper and I just wanted the solution of my equations to see whether my idea made sense or not. More often than not scientists find that their idea was not so great and now they had spent so much time coding just to find out that the idea didn’t work. Continue reading ILNumerics for Scientists – An easy start

2014-12-29 12_57_16-WindowsFormsApplication4 (Debugging) - Microsoft Visual Studio

Getting to know your Scene Graph

Did you ever miss a certain feature in your ILNumerics scene graph? You probably did. But did you know, that most of the missing “features” mean nothing more than a missing “property”? Often enough, there is only a convenient access to a certain scene graph object needed in order to finalize a required configuration.

Recently, a user asked how to turn the background of a legend object in ILNumerics plots transparent. There doesn’t seem to be a straight forward way to that. One might expect code like the following to work:

var legend = new ILLegend("Line 1", "Line 2");
legend.Background.Color = Color.FromArgb(200, Color.White);

Continue reading Getting to know your Scene Graph

Fun with HDF5, ILNumerics and Excel

It is amazing how many complex business processes in major industries today are supported by a tool that shines by its simplicity: Microsoft Excel. ‘Recently’ (with Visual Studio 2010) Microsoft managed to polish the development tools for all Office applications significantly. The whole Office product line is now ready to serve as a convenient, flexible base framework for stunning custom business logic, custom computations and visualizations – with just a little help of tools like ILNumerics.

ExcelWorkbook1In this blog post I am going to show how easy it is to extend the common functionality of Excel. We will enable an Excel Workbook to load arbitrary HDF5 data files, inspect the content of such files and show the data as interactive 2D or 3D plots. Continue reading Fun with HDF5, ILNumerics and Excel

Performance on ILArray

Having a convenient data structure like ILArray<T> brings many advantages when handling numerical data in your algorithms. On the convenience side, there are flexible options for creating subarrays, altering existing data (i.e. lengthening or shortening individual dimensions on the run), keeping dimensionality information together with the data, and last but not least: being able to formulate an algorithm by concentrating on the math rather than on loops and the like.

Convenience and Speed

Another advantage is performance: by writing C = A + B, with A and B being large arrays, the inner implementation is able to choose the most efficient way of evaluating this expression. Here is, what ILNumerics internally does: Continue reading Performance on ILArray

Uncommon data conversion with ILArray

ILNumerics Computing Engine supports the most common numeric data types out of the box: double, float, complex, fcomplex, byte, short, int, long, ulong

If you need to convert from, let’s say ushort to float, you will not find any prepared conversion function in ILMath. Luckily, it is very easy to write your own:

Here comes a method which implements the conversion from ushort -> float. A straight forward version first:

        /// <summary>
        /// Convert ushort data to ILArray&lt;float>
        /// </summary>
        /// <param name="A">Input Array</param>
        /// <returns>Array of the same size as A, single precision float elements</returns>
        public static ILRetArray<float> UShort2Single(ILInArray<ushort> A) {
            using (ILScope.Enter(A)) {
                ILArray<float> ret = ILMath.zeros<float>(A.S);
                var retArr = ret.GetArrayForWrite();
                var AArr = A.GetArrayForRead();
                int c = 0;
                foreach (ushort a in A) {
                    retArr[c++] = a;
                }
                return ret;
            }
        }

Continue reading Uncommon data conversion with ILArray

Plotting Fun with ILNumerics and IronPython

Since the early days of IronPython, I keep shifting one bullet point down on my ToDo list:

* Evaluate options to use ILNumerics from IronPython

Several years ago there has been some attempts from ILNumerics users who successfully utilized ILNumerics from within IronPython. But despite our fascination for these attempts, we were not able to catch up and deeply evaluate all options for joining both projects. Years went by and Microsoft has dropped support for IronPython in the meantime. Nevertheless, a considerably large community seems to be active on IronPython. Finally, today is the day I am going to give this a first quick shot.

Continue reading Plotting Fun with ILNumerics and IronPython

Dark color schemes with ILPanel

I recently got a request for help in building an application, where ILPanel was supposed to create some plots with a dark background area. Dark color schemes are very popular in some industrial domains and ILNumerics’ ILPanel gives the full flexibility for supporting dark colors. Here comes a simple example:

Continue reading Dark color schemes with ILPanel