\documentclass[12pt]{article}
\usepackage{times}
\setlength{\oddsidemargin}{-0.25in}
\setlength{\evensidemargin}{-0.25in}
\setlength{\topmargin}{-0.5in}
\setlength{\textheight}{9.0in}
\setlength{\textwidth}{7.0in}

\begin{document}

\title{Scientific computing tools in the UNI Physics Department: \\ a tutorial}
\author{John Deisz}
\date{August 28, 2001}
\maketitle



\section{Introduction}

The following is an aide to using
some of the scientific computing resources
in 
Rooms 308 and 300 in the Physics Building.
We focus on the 13 Pentium III computers in Room 308 and
3 Pentium III computers in Room 300.  
These computers are purchased with student computer fee
funds and are maintained by CNS support staff in collaboration
with the Physics Department computer committee.
All 16 computers are intended to have an identical configuration
so the instructions below apply to all systems.  It should
be possible to move easily between computers.  Since your
files are saved on a network server, a file generated
on one computer will be available on another computer
the next time you log in.

Sometime this semester
all 16 computers will be replaced by newer computers
with enhanced capabilities.  Hopefully, this will
not disrupt any class activities.  However, if problems
arise with system or an individual computer at any time,
then notify your instructor and he/she will work with CNS
support staff to resolve the problem as quickly as is practical.

Computers are dual boot Linux/Windows NT systems.  The standard
mathematics program in the Physics Department,
Matlab, is available
under both operating systems.  You are free to choose the operating system
you are most comfortable with.  However, in the past we have found that
Matlab crashes more frequently when running Windows NT.  Thus,
if you are having crashes you should consider running your
program under Linux to see if this rectifies the problem.
Note that Linux and NT share the same network file system; files
saved under Linux should be available when you run NT and vice versa.

In the following, we provide a brief introduction/tutorial to using
some of the available computational tools.  
More detailed references are available in library.
In some cases
(Matlab, xmgrace) there is an extensive collection of electronic
help materials that are easily accessed from within the application.
In any case, the following is only meant to serve as a starting
point for using these applications.

\section{Matlab, ver. 6 (Linux and NT)}

\subsection{Basics}

To start Matlab under Linux open a terminal window and
type ``matlab.''
When Matlab is started you are presented
with an interactive shell.  To begin type some simple
commands that allow you to use the interactive Matlab
shell as a calculator:
\begin{verbatim}
>> exp(5.2)

>> cos(3.3)

>> cos(pi)

>> pi

>> 1/0

>> 4.0 * atan(1.0)
\end{verbatim}
In addition to elementary functions, Matlab
includes an extensive library of less familiar, though
useful functions.  One example is the Bessel function
of the first kind.  Use the Matlab search tool to
find the command for evaluating the Bessel function
of the first kind having an order of zero and an argument
of 1.1; in standard notation this is written as $J_{0}(1.1)$.  
Once you have identified the function call
and typed in the command, the result you obtain 
should be (approximately) .7196.

You can define and manipulate variables:
\begin{verbatim}
>> x = 1.5

>> y = 2.3

>> z = x * y

>> z
\end{verbatim}

If you ask for the value of an undefined variable, then
you get an error message.  To obtain a list of
defined variables type ``who'' or ``whos''
in the interactive shell.

There are special variables that you are not
allowed to use.  These include: pi, ans (previous result), eps (the
smallest representable number in Matlab), inf, i ($\sqrt{-1}$),
NaN, and nan.

Matlab handles complex numbers easily, for
example to assign the complex value $3 + 2i$ to the variable
``a'' and then determine the square of a, type
\begin{verbatim}
>> a = 3 + 2i

>> a*a
\end{verbatim}
Most functions generalize to handle complex arguments, plus
there are special functions related to complex variables.
For example, the complex conjugate of ``a'' is determined
by typing
\begin{verbatim}
>> conj(a)
\end{verbatim}

\subsection{Arrays}

The fundamental laws of physics are expressed in forms
where time, space and other quantities are 
assumed to be continuous.  However,
on a computer we can only represent finite collections
of quantities.   
Matlab represents these finite collections as arrays
and so we will need to be able to use these arrays in Matlab.

A grid of points along the x-axis at 0, $0.1\pi$, $0.2\pi$
can be (laboriously) defined in Matlab as follows:
\begin{verbatim}
>> x(1) = 0; x(2) = 0.1*pi; x(3) = 0.2*pi  ...  x(11) = pi
\end{verbatim}
You can print the array by typing ``x''.  
A simpler method for creating an array of regularly spaced points
is given by 
\begin{verbatim}
>> x = (0: 0.1*pi: pi)
\end{verbatim}
This creates a regularly spaced array from 0 to $\pi$
with steps of $0.1\pi$.  If you type ``x(3)'', then the third
element of the array ($0.2\pi$) is printed.

You can create an array of the same size by typing:
\begin{verbatim}
>> y = sin(x)
\end{verbatim}
The array ``y'' has 11 elements with each element
corresponding the sine of a certain ``x'' value as given
by the array ``x.''

Now that you have an array of $x$ and $y$ values of the
same size, you can make an $x-y$ plot.  Do this by typing:
\begin{verbatim}
>> plot(x,y)
\end{verbatim}

\subsection{M-files}

The interactive shell is inadequate for calculations
involving a long sequence of steps or for calculations
that are repeated many times for different sets of
parameters.  Matlab M-files are essentially small programs
that are created using a text editor, saved as a file, and 
then interpreted using Matlab.  By convention, these files
use a ``.m'' extension that you should remember to use when
naming these files.

We are going to develop an M-file that computes the
hypotenuse of a triangle when the values of the sides
are provided as input.  Invoke the editor under matlab by choosing
the ``new'' command under ``file''.  Name the file ``hypotenuse.m''.
The only command in hypotenuse should be
\texttt{
\\
\\
c = sqrt(a*a + b*b)
\\
\\
}
Once you have saved this file, go back to the interactive
shell.  Next, define a and b:
\texttt{
\\
\\
>> a = 3
\\
>> b = 4
\\
\\
}
Now determine the sides by typing
\texttt{
\\
\\
>> run hypotenuse
\\
\\
}
This command should load and run the file ``hypotenuse.m'' and
print the value for the hypotenuse.  Next, give new values
for a and b by typing these in the shell.  Find the new hypotenuse
by running ``hypotenuse'' again.  A new value should be produced.

You receive an error message if you run ``hypotenuse.m'' before
variables a and b are defined.  To avoid this error, you can modify
the M-file to prompt for these values each time the 
M-file is executed.  Go back to the M-file and add these
lines to the beginning
\begin{verbatim}
a = input('Enter side a > '); 
b = input('Enter side b > '); 
\end{verbatim}

\subsection{Logical operations}

Matlab supports standard operations 
with the logical values of ``true'' and ``false''
represented by the numbers 1 and 0 respectively.
Thus, if you type
\begin{verbatim}
>> x = 3; y = 2; z = 1;

>> x > y
\end{verbatim}
The final statement should return a ``1'' since it
is true.  The logical operators ``and'' and ``or'' are
represented by ``\&'' and ``$|$'' respectively (following C conventions).
The following statement represents the
expression ``$x$ is greater than $y$ \textbf{and} $z$ is greater than
$y$,''
\begin{verbatim}
(x > y) & (z > y)
\end{verbatim}
with the values we have defined, the statement is false and
Matlab should return a ``0''.

\subsection{Control flow}

``For loops'' are used to perform a set of equivalent
operations several different times.  Such loops are more
likely to be used in M-files than from the shell, but nonetheless
can used in the shell.  Here is a simple for loop
that generates an array of $x$-values:
\begin{verbatim}
for n = 1:11 
  x(n) = (n - 1)*pi/10.0; 
end
\end{verbatim}
Gauss did not need Matlab to do this, but here is a for loop
for adding the integers from 1 to 100 and then printing the result:
\begin{verbatim}
sum = 0.0; 
for n = 1:100 
  sum = sum + n; 
end 

sum
\end{verbatim}

``While loops'' can be used to execute a statement 
as long as a control expression is true (equal to 1).
For example
\begin{verbatim}
sum = 0; 
n = 1; 
while (n < 101) 
  sum = sum + n; 
  n = n+1; 
end
\end{verbatim}
also adds all integers between 1 and 100.

Download the M-file at 
\\ \hspace*{0.5in}
\texttt{http://www.physics.uni.edu/\~{}deisz/phys-150/intro/sine\_zero.m} 
\\
The downloaded file contains the following.
\begin{verbatim}
x = input(' input starting x-value > '); 
dx = input(' input x-value increment > '); 

while ( sin(x)*sin(x+dx) > 0 ) 
  x = x + dx; 
end 

x
\end{verbatim}
What this program does is take a starting value for $x$
and determines $\sin(x) \times \sin(x+dx)$ where $dx$ is
small.  If this product is positive, then (assuming $dx$
is sufficiently small) the sine function does not
change value between $x$ and $x+dx$.  However,
if the product is negative, then the sine function
changes sign between $x$ and $x+dx$ and thus there
must be a zero of the sine function in that range.
The program stops at that point and prints the value of
$x$.
Download the file and run it from Matlab.

Matlab also provides if-else and if-elseif-else conditionals
No examples are provided in this tutorial.

\subsection{Import and export of ASCII data files}

Matlab VI has a convenient utility for importing 
ASCII data from a text file.  Export is somewhat more
difficult, but is useful for analyzing data generated by
Matlab using some other utility.  In this
example, we create two arrays, $x$ and $y$, and then
export the data to a text file.
\begin{verbatim}
>> x = (0: 0.1*pi: pi); 

>> y = sin(x);

>> xydata = [x', y'];

>> save my_data.dat xydata -ASCII
\end{verbatim}
One-dimensional arrays are normally stored as row vectors so 
we have used the transpose operator (single right quote) to put $xydata$ in 
the standard form of two columns for $x$ and $y$.

\section{Xmgrace (Linux)}

\subsection{Plot creation and manipulation}

Xmgrace is a sophisticated, easy to use two-dimensional plotting
utility.  It is available under Linux in the physics lab
(by typing ``xmgrace'' in an xterm window), but can be
downloaded for free and used under Windows and Linux.

Most likely you will find Xmgrace much more convenient and powerful
than Matlab for producing two-dimensional plots.  Among the
capabilities Xmgrace provides are multiple graphs in
a single plot display, statistical and other data analysis
tools and extensive color graphics.

To test run Xmgrace, start the program, go to the ``data''
menu and then import an $x$-$y$ data file created
with some other application or a text editor.
Once the data displays, go to the ``plot'' menu and
then select ``graph appearance.'' Within the dialog box,
choose the ``Frame'' tab and then make the
appropriate choices to fill the frame with the color yellow.
Also, it might be useful to make the graphics output
smaller to easily embed the graphics output 
in a document.  Under the ``plot'' menu
choose ``Graph Appearance.''  Under the ``main'' tab, reduce
the $x$ and $y$ dimensions of the view port.  After
applying the changes, the graphics output dimensions
should be reduced.

\subsection{Exporting graphics and saving your work}

You can send your output directly to the printer,
but it is also useful to save the output to an
encapsulated postscript file (this can be done with
Matlab graphics as well) which can be embedded in
other documents.  
To do this, go to the ``file'' menu
and choose ``Print setup.''  For device output
select ``EPS,'' choose a convenient filename (
preferably with a .eps filename
extension)
and then for orientation choose ``portrait.''
Apply the changes.  Next time you select ``Print'' from
the file menu, the output is sent to the file.

Note that any point you can save your work by selecting
``save'' or ``save as'' under the ``file'' menu.  This is
handy if you have made many stylistic changes to a plot
that you would like to have available when you reload
the file that is saved.  

An example ``agr'' file is located at
\\
\hspace*{0.5in}
\texttt{http://www.physics.uni.edu/\~{}deisz/phys-150/intro/example.agr} 
\\
Download this file and open it under xmgrace to see how easy it
is to work with saved agr files.

\section{Latex}

Latex is a word processing tool that is heavily used
by scientists and mathematicians.  It is especially convenient
for producing beautifully formatted equations.  
The disadvantage of Latex is that you need to learn
the text formatting commands.  Once you learn a few
basic commands and have access to a Latex reference,
producing a document with Latex is not especially difficult.
For people who are used to using Latex, it is difficult
to use any other tool (such as Microsoft Word) since this
means giving up power and flexibility that is only found
in Latex.  

The following is a sample latex file that can be downloaded
from \\
\hspace*{0.5in}
\texttt{http://www.physics.uni.edu/\~{}deisz/phys-150/intro/latex-example.tex}
\begin{verbatim}
\documentclass[12pt]{article}
\begin{document}

\title{Sample Latex document}
\author{John Deisz}
\date{August 28, 2001}
\maketitle
\newpage
\section{Introduction}

This is the introduction.

\section{Relevant equations}

\begin{equation}
x = \frac{1}{2} + y^{2}
\end{equation}

\end{document}
\end{verbatim}

To create an intermediate ``dvi'' file, type the following from an xterm
\begin{verbatim}
latex latex-example.tex 
\end{verbatim}
If there are errors, the error messages should point you
to a line number that should be close to where the error is located.
Sometimes the error messages are informative and
it is easy to fix any mistakes.  However, it is often the
case that the error messages are uninformative and
the search for the mistake is painful.  With experience, though,
correcting errors in Latex files becomes fairly easy.

If there were no errors a file ``latex-examples.dvi'' should
have been created.  This can be sent to a printer, but it
is best to view the formatted output first on a terminal as you may wish to
make additional changes before obtaining a final printed copy.
To view the dvi file, type
\begin{verbatim}
xdvi latex-example.dvi
\end{verbatim}

Finally, if the output is acceptable, you can send the output
to the default printer.  This is done with
\begin{verbatim}
dvips latex-example.dvi 
\end{verbatim}

Lets make a change to this Latex file so that an encapsulated
postscript file you have created is embedded into the Latex 
file.  This requires two additional lines.  Somewhere
after \\``$\backslash$documentclass[12pt]\{article\}'' but
before ``$\backslash$begin\{document\}'' type
\begin{verbatim}
\usepackage{epsfig} 
\end{verbatim}
This gives Latex the ability to embed eps files.  To include
a specific file somewhere in the document, type
\begin{verbatim}
\epsfig{file=example.eps}
\end{verbatim}
where ``example.eps'' is assumed to be the name of the
eps file.  After the file is reprocessed you should find
that the figure has been embedded into the document.

\section{C++ compiler}

\subsection{Introduction}

Matlab is a convenient, integrated environment for
programming, calculations, graphing, etc.  For the most intensive
numerical tasks, where a single computer takes more than
several hours to complete a calculation, compiled languages
such as C, C++, and FORTRAN are most frequently used.
There are several reasons for this.  First, Matlab code
runs slower than equivalent code in a compiled language.
Now, Matlab code can be compiled to make up the performance
gap, but we have found compiled Matlab code to still be
significantly slower (at least in some test cases) than
equivalent codes written in C.
Second, Matlab is not a de facto standard
so your ability to collaborate or to use your
code on a new machine (such as at a national supercomputer center)
is limited if you insist on writing all programs in Matlab.
It is true that Matlab can link to compile C codes and C libraries
to improve the performance of calculations done within the
Matlab environment.  However, the use of Matlab in 
this mixed calculation mode could be more of a hindrance than
an aid.

Unless you are a professional computational scientist, Matlab
will most likely be adequate for most of your needs.  Nonetheless,
the types of programs that can be written in Matlab are
relatively painless to convert into other languages.  Here
is a sample C++ code as well as instructions for compiling
and running the code on a Linux-based system.

\subsection{Example code}

A simple code might look like the following, which
can be downloaded from\\
\hspace*{0.5in}
 \texttt{http://www.physics.uni.edu/\~{}deisz/phys-150/intro/cpp-example.cpp}
\begin{verbatim}
#include <iostream> 
#include <complex> 
  
int main() 
{ 
  float x[11], y[11]; 
  int n; 
  float pi; 

  pi = 4.0 * atan(1.0); 

  n = 0; 

  while ( n < 11 ) { 
  
    x[n] = n * pi / 10.0; 
    y[n] = sin(x[n]); 

    cout << x[n] << " " << y[n] << "\n"; 

    n = n + 1; 

  }


 return(0); 
}
\end{verbatim}

Unlike Matlab, all variables and their type (float, int, complex$<$float$>$)
must be declared before being used.  ``pi'' does not have a
predefined value and needs to be calculated.

\subsection{Compiling}

C++ code must be compiled before it is run.  To compile
this code type the following from a Linux xterm:
\begin{verbatim}
g++ example.cpp
\end{verbatim}
Assuming no errors were found, the compiled file ``a.out''
has been created.  To execute the compiled file, type
\begin{verbatim}
./a.out
\end{verbatim}
You should have 11 $x-y$ pairs dumped to the terminal screen.
To capture these in a file modify the above command 
to this:
\begin{verbatim}
./a.out > data_file.dat
\end{verbatim}
It should now be possible to use Xmgrace or Matlab to read
and plot this data file.

\section{Other tools}

Other available tools that are not discussed in detail here
include the following:
\begin{itemize}
\item Octave - This is a Matlab-like tool with less polish, but
is available for free.  Installed under Linux.
\item Stella - This is a graphical programming tool that is
particularly useful for building models of complex systems.
Available under Windows NT.
\item C, Fortran, and Java compilers - Available under Linux.
\item MPI libraries - These libraries enable communication
between several computers, thus allowing C, C++, and FORTRAN
codes to access the computing power of more than one machine
at a time.  This parallel programming tool is especially useful
for demanding computational tasks that require either many
mathematical operations or the storage of very large arrays.
\item Gnuplot - Another plotting tool under Linux with some
3D capabilities.
\end{itemize}

\section{Document status}

This document was last updated 
on 
August 28, 2001.  

\end{document}
