Introduction to the Maths Lab - Part 1

The METRIC Project

Introduction

By their very nature chemical systems are normally so complex that it is impossible to compute their physical properties by hand. Chemists have therefore made extensive use of computers in chemical calculations. Over the past two decades as hardware and software have become more powerful and more widely available, the main thing that has changed is what we mean by "calculations". Once computers were reserved for processing large amounts of numerical data or "number-crunching". While that is still one of the things they are good at (especially for quatum mechanical calculations), the story doesn't end there any more.

Mathematica is just one of the mathematical software tools available to the modern, professional chemist: one of the more powerful and flexible ones as it happens. It is described by its manufacturers as "A System for Doing Mathematics by Computer". In this and the next introductory session we hope to give you a flavour of what that means in practice.

The price you pay for all this power and flexibility is that Mathematica takes some learning. Unlike some word processing packages, or even some of the more restricted mathematical software, its use is not self explanatory. It has a syntax all its own, and it is in general very pedantic about errors in syntax. It is important that you become used to Mathematica's way of doing things so for the first few sessions you will be expected to type all the input yourself. In the beginning this can be very frustrating, but just remember as you get ready to destroy the computer, it is worth it in the end!

1. Arithmetical Calculations

To start with, it may be helpful to think of Mathematica as a kind of calculator. For example, try typing

2 + 2

To get Mathematica to perform this calculation, hold down the "shift" key and press "return" ("return" without "shift" just gives you a line break.) With any luck, you should get the   output

We say that the expression 2 + 2 has been "evaluated".

This calculation may have taken a long time. That's not because Mathematica finds it difficult, but because the part of the program that actually  does the calculating doesn't get loaded until the first time it's needed;  it's this loading process that takes the time. All subsequent calculations  should be much quicker, some very fast indeed. Here are a few:

6 + 2

6 - 2

6*2

6 2

6/2

6^2

100!

1000!

Sin[Pi/3]

Sqrt[9]

Sqrt[50]

2^(1 + 4)

Notice the use of the symbols *, / and ^. Notice, too, the way Mathematica interprets the space between the 6 and the 2 in the fourth line.

Exercises and Explorations 1

1: Brackets

The last few examples all involve the use of brackets of some kind. But sometimes square brackets have been used, and sometimes  round ones (parentheses). Does this matter? What are the rules governing what kind of brackets to   use when?

2: Some syntax

Would it have mattered if we'd typed

sin[pi/3]

instead? What are Mathematica's rules about capital and lower-case letters?

3: Output

Was the output from

Sqrt[50]

what you'd expected? What's happening here? What other examples can you find?

1.1 The Basic Input Palette

If you look to the right-hand side of the screen, you may see a tall  rectangular window, the top portion of which looks like this:

If not, you can open this window (which is known as the "Basic Input"  palette) by finding Palettes in the File menu and selecting BasicInput.

This facility allows you to create Mathematica commands that look like typeset mathematics. Try, for example:

(6^2)

Sin[(π/3)]

(Sqrt[50])

Exercises and Explorations 2

1: Shortcuts

What happens if you type 6, followed by "ctrl-6" (hold down the "Ctrl" key and hit 6), followed by 2? What does "ctrl-6" do? How about "ctrl-/"?

Try typing "esc, p, i, esc" (hit the escape key, then p, then i, then escape again). What happens? What if you leave out the "i"? What other symbols can you create in this way?

1.2 Exact or Approximate?

All the commands above are examples of exact arithmetic: calculations with whole numbers, surds, fractions and named constants  such as π. This is something a calculator doesn't do: it works with numbers in the form of decimals, or in standard  scientific form. Mathematica can also do this type of arithmetic. Try the following pairs of commands,   taking note of any differences in the output:

(2/6)(2.0/6.0)

Cos[(π/6)]Cos[(3.1415927/6)]

Sin[2]Sin[2.0]

(Sqrt[50])(Sqrt[50.0])

Exercises and Explorations 3

1: What does N do?

Experiment with the Mathematica command N, as in

N[π]

N[π, 100]

N[(2/6)]

How would you describe what this command does? How could you see it being used?

2: Manipulating numerical evaluation

Investigate the Mathematica commands Floor, Ceiling and Round, as in

Floor[3.77]

Round[25]

1.3 A Warning to the Wise

You should always keep a record of your work in the Maths Lab. We suggest that after you complete each section you first of all print what you have done. To do this, highlight the cells you wish to print and then go to the File menu and select Print Selection. It should show that you are printing to the local printer. If you have problems with any of this ask a supervisor.

 Once you have a printout you should save your work to your floppy disk.
 
 At this point we issue a warning. The current version of Mathematica has a nasty, but fortunately quite rare habit of corrupting notebook documents into an unreadable form which can be beyond recovery. We recommend several ways to avoid the corruption problem:
 
 (1) Clear all of the output you have produced before you save a notebook. Do this by going to the Kernel pull down menu and selecting Delete All Output. To reproduce your work later all you have to do is re-execute your input statements. Saving without output also saves a lot of disk space, particularly when graphics are involved.

(2) Keep your notebooks small - start a fresh notebook at least every Maths Lab session and preferably more often.

(3) Save your notebooks every few minutes whilst you are working. Do not save to the floppy disk directly - make a copy on the hard disk whilst you are working, then copy the final version to the floppy when you have finished.

(4) Keep backups on separate floppy disks - the technology is far from 100% reliable and you will not regret spending a fiver on a box of 10 disks.

2. Symbolic Calculation

Where Mathematica starts to differ from most calculators is in its ability to perform symbolic calculations, for example:

Expand[(((x + y))^3)]

Factor[(x^3) + 3  (x^2)*y + 3  x*(y^2) + (y^3)]

Apart[(x/((1 + x) (1 + (x^2))))]

Together[%]

(Notice the use of the percent sign, %, to mean "last output". Put the number of the output line after % to refer to that output rather than the "last output".)

D[(x^3), x]

∫3  (x^2) \[DifferentialD]x

Exercises and Explorations 4

1: Some algebra

What do Apart and Together do? How about Cancel and Simplify?

2: Some more algebra

Open up the Algebraic Manipulation palette (under Palettes in the File menu). This palette, unlike Basic Input, has the setting "Evaluate in  Place". To find out what this means, first type, without evaluating,

∫((2 + 3  x + (x^2))/(2 + 2  x + (x^2))) 
        \[DifferentialD]x

Then select the fraction inside the integral, and click on the Apart[■] button. With the same area selected, click on Together[■]. Try using Expand[■] on the numerator, and so on.

3: Summations

Using the Basic Input palette, type

(∑_(r = 1)^6)((1/(r^2)))

Express this sum as a decimal. Try summing from 1 to n, and from 1 to ∞ (you'll find the infinity symbol on the   palette).

4: Differentiation

You may not be familiar with the notation used by the (∂_□) ■ button, but see if you can work out what it does. You might start by trying (∂_x) Sin[x].

3. Graphics

Mathematica incorporates a wide range of two- and three-dimensional graphics  functions. The simplest is Plot, which generates ordinary two-dimensional graphs, as in

Plot[Sin[x], {x, -π, π}]

Plot[{Sin[x],  Cos[x]}, {x, -π, π}]

(Notice here the use, for the first time, of curly brackets or braces, to enclose the elements of the x-range or to group collections of functions.)

You can take control of some of the characteristics of the plot by means  of what are called option settings, for example:

Plot[Sin[x], {x, -π, π}, PlotRange -> {-1.5, 1.5}]

Plot[Sin[x], {x, -π, π}, 
      PlotRange -> {{-2 π, 2  π}, {-1.5, 1.5}}]

Plot[Sin[x], {x, -π, π}, AspectRatio -> 1]

Plot[Sin[x], {x, -π, π}, AspectRatio -> Automatic]

Plot[{Sin[x], Cos[x]}, {x, -π, π}, 
      PlotStyle -> {RGBColor[1, 0, 0], RGBColor[0, 0, 1]}]

More than one option can be set in this way, for example:

Plot[(4 - x) x (E^(-(x/2))), {x, 0, 20}, 
      Background -> Hue[0.5], PlotLabel -> " The 3p radial wavefunction"]

For a complete list of options for Plot, together with their default settings (what Mathematica assumes the setting to be if you don't set the option explicitly), type

Options[Plot]

Exercises and Explorations 5

1: Labelling a graph

If you have not done so already, look up the entry for Plot in the Help system: choose Help from the Help menu, and type "Plot" in the search box. Find out how the AxesLabel option works, and produce a graph of the (2p) radial wavefunction of hydrogen (x (e^(-x/2))) where the x-axis is labelled "x" and the y-axis "(Subscript[R, 2, 1])".

2: Plotting things together

Produce a plot showing the relationship between the graphs of y = (x^2) and y = (Sqrt[x]). Your graphs should be in different colours and the scales should be the  same on both axes.

3.1 Other Graphical Functions

Plot is the simplest graphical function in Mathematica, and one of the most useful, but there are many others. For example, this command plots the associated Legendre function for one of the hydrogenic molecular orbitals. You will revisit this next week.

\(ParametricPlot[{Sin[θ]^2\ Cos[θ], 
        Sin[θ]^2\ Sin[θ]}, {θ, 0, 2  π}, 

      AspectRatio -> Automatic]\)

This plots the potential surface for a dipolar molecule.

Plot3D[(1/(Sqrt[(y^2) + (((-1 + z))^2)]))-(1/(Sqrt[(y^2)+(((1+z))^2)])),{y, -2, 2 },{z, -2, 2},PlotPoints -> 30,
BoxRatios -> {1, 1, 1},PlotRange -> All]

And this plots the potential surface as a contour map.

ContourPlot[(1/(Sqrt[(y^2) + (((-1 + z))^2)]))-(1/(Sqrt[(y^2)+(((1+z))^2)])),{y, -2, 2},{z, -2, 2},PlotPoints -> 35,
	ContourSmoothing -> True]

This plots the real part of one of the quantum mechanical wavefunctions for a particle on a ring. This turns out to be a good model for the π-electrons on a benzene ring.

\(ParametricPlot3D[{{Cos[θ], Sin[θ], Cos[3\ θ]}, 

        	{Cos[θ], Sin[θ], 0}}, {θ, 0, 2  π}]\)

And here is a three-dimensional representation of the hydrogen s orbital! We will look at more complex orbitals next week.

ParametricPlot3D[{Cos[θ] Sin[ϕ], Sin[θ] Sin[ϕ], 
        Cos[ϕ]}, {θ, 0, π}, {ϕ, 0, 2  π}]

Exercises and Explorations 6

1: Reading a 3D plot

By studying the output from a plot of z = ((x^2) - (y^2)) (e^(-(x^2) - (y^2))), and by further investigation if  necessary, find out how (i) a maximum (that is, a hill), (ii) a minimum (that is, a depression) and (iii) a saddle (that is, a high "pass" between two hills) show up on a contour plot.

Estimate the coordinates of any maxima, minima and saddles of the  function .

2: Making shapes

Produce 3D parametric plots of a helix that spirals outwards as it  rises, and of a prolate spheroid (that's a rugby ball shape).

4. Animations

In Section 3,  you saw some of Mathematica's capabilities for generating mathematical graphics: the functions Plot, ParametricPlot, Plot3D and so on. These functions can, of course, be used to generate single, static diagrams - but Mathematica also has the capability to generate and display moving, animated graphics. These are called "movies", and indeed they work on the same principle as the cinema: the user creates a series of still pictures (frames) and uses Mathematica to display them in rapid succession, creating the illusion of motion.

As a simple example of this, we are going to show you  how to program a movie for the oscillations of a homonuclear diatomic molecule undergoing simple harmonic motion. The motion of each atom undergoing simple harmonic motion, x(t), around its equilibrium position, (Subscript[x, 0]), is given by

x(t) = (Subscript[x, 0]) + A sin ωt.

where A is the amplitude of the oscillation and ω is the circular frequency.

Mathematica has a set of special functions that are called "graphical primitives" to create lines, circles, rectangles etc. We'll use these to construct our model molecule. The atoms will be represented by circles of radius 1/2 whose centres are going to move - so they must be a function of the position variable x.

atom[x_] := Circle[{x, 0}, 1/2]

The underscore, "_", and the ":=" are required for defining functions. Functions are extremely useful and you will be using them a lot in later sessions.

Just for simplicity, we'll draw the bond as a straight line joining the atoms. Again it must be a function of position, but we have to remember that the bond must stretch from atom 1 to atom 2, so we make it a function of (Subscript[x, 1])and (Subscript[x, 2]), the respective positions of the atoms:

bond[x1_, x2_] := Line[{{x1 - 1/2, 0}, {x2 + 1/2, 0}}]

Now we draw a frame, using the special plotting construction Show[Graphics[{...}]]:

Show[Graphics[{atom[3.0], atom[-3.0], bond[3.0, -3.0]}], 
      AspectRatio -> Automatic]

Note: If you want an x-axis to show, you can use the option Axes->{True,False}.

Now for the movie. In the procedure below, we assign values to (Subscript[x, 0]), A and ω, and then use the command Table to create a sequence of frames, with the time step set at π/16. (Note that by putting semi-colons after a line of code we can type as many lines as we like into a single input box. Furthermore it prevents the input of parameter values being output.)

\(x0 = 1; 
A =  .2; 
ω = 5; 

    Table[\((
		x1 = x0 + A\ Sin[ω\ t]; 
			
        x2 = \(-x0\) - A\ Sin[ω\ t]; 
		
        Show[Graphics[{atom[x2], atom[x1], bond[x1, x2]}], 
          AspectRatio -> Automatic, PlotRange -> {{\(-5\), 5}, {\(-1\), 1}}])
        \), 
	{t, 0, 2  π - π/16, π/16}]\)

To animate these frames, the first thing you have to do is double-click on the cell bracket that contains them all (on the right-hand edge of the Mathematica window). They should all disappear apart from the first frame in the sequence (consult a supervisor if this isn't working for you). Then, select Animate Selected Graphics from the Cell menu.

You can change the speed or direction of the movie using the buttons at the bottom left of the screen. To stop, click the mouse button anywhere in the notebook. If you want to resize the frames in the animation, resize the first frame and then reevaluate the code for the animation.

Exercises and Explorations 7

1: Manipulating code

Run the movie procedure for values of ω = 2, 1, (1/2), (1/4). Modify the procedure so that it automatically generates a sequence for a full period of the oscillation, whatever the value of ω.

2: Display effects

Find out what happens when you do not have the AspectRatio option and when you do not have the PlotRange option in the procedure.

3: A new bond

If you have the time and feel up to the challenge design a function to put a spring between the atoms which compresses and expands during the oscillations.

5. Writing Documents with Mathematica

This document was produced with Mathematica. You will be expected to produce well presented documents of your assigments using Mathematica, and to do this the main thing you need to know about is how to format cell styles. Ordinarily, when you type into Mathematica,

the text looks like this .

To get it to look the text in this cell (i.e. a regular Times font), simply click on the cell bracket on the right, then go to the Style submenu of the Format menu and select Text. You can also set up titles, sections and subsection headings in the same way. (You can also make style changes using the keyboard shortcuts indicated on the right-hand side of the Style submenu.)

Besides making your text look like word-processor text, the style change has another important effect of making the cell "inactive", so nothing happens when you evaluate it. Compare what happens when you evaluate the following two cells (the first is in Input style, the second in Text):

Besides making your text look like word - processor text ...

Besides making your text look like word-processor text...

Using the right cell styles, you can then safely select collections of cells and "shift-return" will evaluate only those that are inputs.

Typesetting can be used for preparing text as well as writing Mathematica inputs. Using palettes, it's possible to embed fairly complicated mathematical expressions such as \(TraditionalForm
      \`∫\_0\%∞\( x\^2\) dx\) in the middle of ordinary text. Take some time to explore what the various typesetting palettes will do - access them via Palettes in the File menu.

You will find more information on preparing documents, mathematical typesetting, using the help files and various keyboard shortcuts in the Maths Lab Reference Guide.

Exercises and Explorations 8

Go over the notebooks you have created making text-style annotations of the Mathematica inputs you have used, your answers to the exercises, etc. 

Try out using the Title, Section and Subsection cell styles to organise your notebooks. What do these cell styles do to the grouping of cells?