Computational Physics: Software Notes

Leon Hostetler

July 14, 2018 Version 0.5

1 Contents

Contents 2

1 Preface 5

2 and Unix7 2.1 General Notes...... 7 2.2 Bash...... 8 2.3 Unix Networks ...... 18 2.4 Vim ...... 19 2.5 OpenLava...... 19 2.6 SLURM...... 19 2.7 System Monitoring and Performance...... 20

3 LaTeX 23 3.1 Installation ...... 23 3.2 Tables...... 23 3.3 Math...... 24 3.4 Images...... 28 3.5 Referencing...... 28 3.6 Tikz...... 29 3.7 PGFPlots...... 39

4 Inkscape 45 4.1 Installation ...... 45

5 Python 49 5.1 Installation ...... 49 5.2 General ...... 49 5.3 Style Guide...... 50 5.4 Plotting...... 50 5.5 File Cleaning ...... 56 5.6 Vectorization ...... 57

6 Fortran 63 6.1 Installation ...... 63 6.2 A Basic Program...... 63 6.3 Syntax...... 64 6.4 MPI...... 69

7 GnuPlot 71 7.1 Basic Command Line Plot...... 71 7.2 Plot Files ...... 72 7.3 Error Bars...... 73 7.4 Commands ...... 73 2 CONTENTS 3

7.5 Variable Attributes...... 73

8 MatLab 75 8.1 Installation ...... 75 8.2 Miscellaneous...... 75 8.3 Plotting...... 76 8.4 Vectors ...... 82 8.5 Linear Algebra ...... 83 8.6 Statistics ...... 86 8.7 Numerical Differentiation ...... 86 8.8 Integration ...... 87 8.9 Vector Differential Operators ...... 89 8.10 Differential Equations ...... 92 8.11 Quantum Mechanics...... 93

9 Mathematica 95 9.1 The Basics ...... 95 9.2 Quantum Mechanics...... 95

Chapter 1

Preface

About These Notes

These are simply the notes that I am using and occasionally adding to. Don’t expect too much from them.

Updates

Last Updated: July 14, 2018

Version 0.5: (Jul. 14, 2018) LaTeX chapter: Updated layout and added information on package dependencies.

Version —: (Dec. 12, 2017)

5

Chapter 2

Linux and Unix

2.1 General Notes

This book assumes that you are using Linux. This section contains general notes on using Linux.

To see the list of currently installed packages via the terminal, use the command apt list --installed

For example, the python subpackages are listed as python-subpackage.

To search for a package or see if it’s available, use apt-cache policy packagename

To see the version of the available package, use apt-cache policy packagename

To uninstall an installed package, use sudo apt-get remove packagename

To completely remove a package and all related stuff brought by the package, use “purge” instead of “remove”.

You will probably want to install the following packages via your terminal:

• sshpass (for automatically backing up to password-protected remote servers) • python-pip (to manage python packages) • python-tk (required for some of my plots) • texlive-full (the full LaTeX distribution) • python-visual • gfortran (Fortran compiler) • gnuplot (plotting) • emacs (general text editor) • cpufrequtils (CPU management) • lm-sensors (CPU temperature sensors) • scidavis (statistical plotting application) 7 8 CHAPTER 2. LINUX AND UNIX

• iotop (harddrive input/output) • wxmaxima (computer algebra system) • zotero (document/resources management utility)

To update Ubuntu, use sudo apt-get update followed by sudo apt-get upgrade

Enter “Y” to confirm the update. After these two commands, you should also run sudo apt-get dist-upgrade and enter “Y” to confirm.

2.2 Bash

Basic Usage Navigation To determine your current location in the directory structure, use the command

pwd

To list the files in the current directory, use the command

ls

The ls command has a lot of useful options. For example, the following command lists the contents, also the hidden files, the property information for the files, and one line per item.

ls -a -l -1

To list the files in another directory, use the command

ls [path][directory]

To list all directories, subdirectories, and files, use

find . -ls

To move to a new location, use the command

cd [path]

To return to your home directory, use the command 2.2. BASH 9

cd ∼

To see the help manual for a command

man [command]

Note: When in the shell, the up arrow can be used to re-enter the previous command without having to retype everything. Whenever you want to see the recent commands, just use

history

Searching To find files in a directory and all of its subdirectories by name use, for example to find files whose name contains “apple”, use

find /directory -name"*apple*"

To find all files whose filenames contain apple in the current directory and all subdirectories, use

find . -name"*apple*"

To search for a text string within all files in directory dir/ and its subdirectories, use

grep -R"string" dir/

To find and delete all files called ”filename.txt” in the current directory and all of its subdirectories, use

find . -name filename.txt -type f -delete

Wildcards To list all python files in the current directory, you would use

ls *.py

Files and Directories To create a directory at your current location, use the command

mkdir [directory]

To create a text file, just call the (nonexistent) file with the emacs, gedit, or Vim editor:

emacs [filename] & gedit [filename] & vi [filename] & 10 CHAPTER 2. LINUX AND UNIX

The ampersand ensures that emacs opens the file in the background instead of in the same shell window. That way you can still issue commands to the shell while also editing your file in emacs.

To move a file from one location to another, use the command

mv [path1][file] [path2][file]

To move the all contents from one directory to another, use

mv [directory1]/* [directory2]

To rename a file, “move” it to the same location with a different name.

mv [path][old file] [path][new file]

To copy a file from one location to another location:

cp [oldpath][file] [new path]

To copy a file into the current directory use a period to denote the current directory.

cp [path][file] .

To copy a file from one location to another location and rename it:

cp [old path][old file name] [new path][new file name]

To copy a directory and all subdirectories and files

cp -r [directory] [newname]

To view (but not modify) the contents of an ASCII file in the terminal:

more [path][file]

Press the space bar to page through the file. To delete a file, use

rm file

To delete an empty directory, use

rmdir [directory]

To delete a directory and all files and subdirectories in it, use

rm -r [directory]

To get a file over http use 2.2. BASH 11

wget [url to file]

To securely copy a file to or from a remote server use the secure copy command. For example, to securely copy ftp/backup.tgz from my directory on the remote server at site.edu, to wherever I currently am on my local machine, I would use

scp [email protected]:∼/ftp/backup.tgz .

Note the required colon after the target address. The period at the very end instructs it to copy the remote file to my current location. It will ask you for your password after connecting to the server. The general form is

scp [options] username@source_host:/directory/file username@destination:/directory/filename

Note that the file host comes first, and the file destination comes second. If you are copying a directory and its contents, you have to include the “-r” option.

File and Output Manipulation

To redirect command output to a file. If the file doesnt exist, it is created.

[command] > [file]

For example, ls > content, would create a file called “content” that contains a list of the contents of the current directory.

To redirect command output to another command:

[command1] | [command2]

Notice that “>” is used to redirect the output from a command or program to a file and “|” is used to redirect the output of a command or program to another program.

To see the differences between two files:

diff [file1] [file2]

To see the differences between two folders, whose files (and their contents) should be the same, use

diff -arq [folder1] [folder2]

To sort the output of a command use

[command] | sort

To sort numerically from smallest to largest, add the -g option to the sort command. To reverse the order, use -g -r. 12 CHAPTER 2. LINUX AND UNIX

To copy the first 100 lines from one file to another file, use

head -100 file1 > file2

To suppress the standard output from a script, send it to /dev/null. For example: gfortran script.f ./a.out >/dev/null

Images To view an image file, use the command

display image

To convert an image from one format to another, use, for example

convert file.eps file.png

By default, the resolution of the output image is 72 dpi. To increase the resolution, use the density option as in

convert -density 200 file.eps file.png

File Compression To compress a directory and all of its subdirectories and files as a gzipped tar file, use

tar -zcvf [filename].tgz [directory]/

To check the contents of a tar file and their properties, use

tar -ztvf [filename].tgz

To uncompress a directory, use

tar -zxvf [filename].tgz

Storage To check the disk space usage and partitions available (in human readable form) use To uncom- press a directory, use

df -h

Emailing To email a tar file, use

mail -s"[subject]" -a [filename].tgz [email address] 2.2. BASH 13

After hitting enter, you type in your email address. When youre done, hit enter, type a single . on the new line and hit enter again. Note, the subject must be in quotes (as shown) if it is more than one word. To CC your email to another address, use: mail -s"[subject]" -c [email address to be CC’ed] -a [filename].tgz [email address]

To backup your files, just tar them and move the tgz file into a backups folder.

Shell Scripts Shell scripts can be used to run a whole list of commands automatically. Create the file using

emacs [filename].sh

An example script is shown below. Notice the required first line (starting with a hash- bang) since a computer distinguishes between program types by the first line in a file. The file extension itself is for human benefit.

#!/bin/sh # This isa comment. echo"Hello $USER." echo ’Today is ’ date

To exit from the emacs editor and return to the main part of the terminal, press Ctrl + x then Ctrl + c. This is read as “C-x C-c”.

To make the script file executable, you have to change its permissions using

chmod +x [filename].sh

To run or execute the file, you can now just use

./[filename].sh

Below is an example that uses command-line variables. Suppose this script is called myscript.sh, and you have made the file executable and everything. Then if you write ./myscript.sh variable1 then the file will execute. When it does, it creates a directory called “variable1” and writes “You have executed . myscript.sh.” to the terminal. In the script,

$1 refers to the first command line variable, and

$0 refers to the name of the script itself, or the zeroth variable.

#!/bin/sh # Create directory named in command line mkdir $1 14 CHAPTER 2. LINUX AND UNIX

echo"You have executed $0."

The sed command is a stream editor that receives text input.

If Statements Simple if/then commands can be done with one line. For example: if [ ! -d CB ]; then mkdir CB; fi

For multiple lines, it has the form:

if [TEST-COMMAND]; then DO STUFF fi

A test condition like

[ -f file] evaluates to true if file exists and is a regular file. The negative of a condition is

! condition

The if/elseif/else statement has the following form: if [ -f file1.f ]; then echo "file1.f exists" elif [ -f file2.f ]; then echo "file2.f exists" else echo "Neither file exists" fi

Validation Validation includes

• Checking if something already exists rather than just overwriting it • Redirecting output messages • Directing error messages • Checking that input is valid • Checking that output has the expected form.

If you know the number of files that should be in your folder if your scripts ran correctly, count the files and check that the number is correct. num_files=$(ls -l | grep -v ^d | grep -v ^t | wc -l) if [ ! $num_files -eq 10 ]; then echo"There are not exactly 10 files!" fi 2.2. BASH 15

Cleaning Strings Sometimes you want to remove the first several or last several characters from a string. Here’s an example where we strip off the first character and keep only the next three characters. stringa=’Hello’ stringb=${stringa:1:3} echo $stringb

This outputs “ell”.

To replace a substring in a string with another string, use the following. Here we replace the ‘.’ in the variable beta with a ‘p’. beta=’2.3’ new=${beta/’.’/’p’} echo $new

This prints 2p3.

Mathematics in Bash To perform simple calculations in bash, use syntax like echo $((2 + 3)) which prints ‘5’. Another example is: num1=10 num2=5 num3=$(($num1 * $num2)) echo $num3

This prints ‘50’.

You can also define mathematical functions in bash. Here is a bash algorithm for computing the binary logarithm of a number. Courtesy of https://bobcopeland.com/blog/2010/09/ log2-in-bash/ function log2 { local x=0 for (( y=$1-1 ; $y > 0; y >>= 1 )) ; do let x=$x+1 done echo $x } z=$(log2 64) echo $z

Backups via Shell Script You can use a shell script to backup contents on one computer to a distant server. Here’s an example of a backup script that tars everything on your desktop and uploads the compressed 16 CHAPTER 2. LINUX AND UNIX

file to another server.

Create the following shell script called backup.sh, and place it on your desktop.

#!/bin/bash

backup_location="user@server_address" backup_folder="MYBACKUPS"

mkdir $backup_folder date > $backup_folder/backup_date.txt

echo"backup.sh: Copying desktop to backup folder..." cp -rf * $backup_folder

echo"backup.sh: tar backup folder..." tar -zcf $backup_folder.tgz $backup_folder

echo"backup.sh: Upload to server..." sshpass -p ’my_server_password’ scp $backup_folder.tgz backup_location:∼/1_BACKUP

rm $backup_folder.tgz rm -rf $backup_folder

echo"backup.sh: Done."

To do a manual backup, from your Desktop, run

sh backup.sh

This will copy everything on your desktop into a tarred folder and upload it to ∼/1_BACKUP/ on the server. It will overwrite the previous backup that resides at the same place.

You can set up a cron job to automatically run the backup.

To view the user crontab (list of cron jobs), use

crontab -l

To edit a cron job or add a new one, use the command

crontab -e

The cronjob that runs the backup every two hours would be:

* */2 * * * sh /home/user/Desktop/backup.sh

Miscellaneous

Suppose you have a bunch of different directories of the form 64x* each containing multiple directories of the form k* and you want to run a shell script in every subfolder. for folder in 64x*; do cd $folder 2.2. BASH 17

for kfolder in k*; do cd $kfolder

../../myscript.sh

cd.. done cd.. done

Here’s another one that copies myfortranscript.f to every subfolder and runs it therein. The Fortran script writes its important results to a text file like “fortranscriptresult.txt” in the subfolder, so afterwards, the shell script iterates through all the subfolders and concatenates the contents of those files to a new file called “allresults.txt”. for latbet in 64x*; do cd $latbet for kap in k*; do cd $kap

cp ../../myfortranscript.f . gfortran myfortranscript.f ./a.out > /dev/null rm myfortranscript.f rm a.out

cd.. done cd.. done

# Gather all the data into one file find -name fortranscriptresult.d -exec cat {} \; > allresults.txt

Here’s a script that pulls variables from a parameter file by running an adhoc fortran script.

#!/bin/bash

# The following was originally written byD. Clarke echo" program pgrab include ’../../libs/fortran/implicit.sta’ include’mc.par’ include’latmpi.par’ character cntau*3,cflsp*3 open(13,file=’pgrab.sh’,form=’formatted’,status=’unknown’) ! Formatted to match output file. write(cntau,’(i3.3)’) mpifactor*nl1 write(cflsp,’(i3.3)’) nl2 ! Output parameters for reading. write(13,’(\"beta=\",f10.2)’) beta0 write(13,’(\"xkap=\",f10.4)’) xkappa write(13,*)’ntau=’,cntau write(13,*)’mprc=’,msmpi write(13,*)’flsp=’,cflsp write(13,*)’nrpt=’,neq2-neq1+1 write(13,*)’nmea=’,nmeas 18 CHAPTER 2. LINUX AND UNIX

write(13,*)’njob=’,njob write(13,*)’neq2=’,neq2 write(13,*)’nequi=’,nequi close(13) end" > pgrab.f

# Compile and run parameter grabbing program. gfortran -o pgrab.e pgrab.f wait ./pgrab.e wait

# Remove whitespace. sed ’s/\s//g’ pgrab.sh > pgrab.sh.temp mv pgrab.sh.temp pgrab.sh

# Load parameters extracted from pgrab. . ./pgrab.sh rm pgrab.*

# Print stuff to the screen echo $beta echo $xkap echo $njob

2.3 Unix Networks

To connect to a remote server use

ssh -Y @

To check which remote node you’re on, use

hostname

To move to another node while already connected to the network, just use

ssh

For example, to move to the lnxthry06 node when you’re on another node, just use ssh lnxthry06. This is really useful if one node blocks your remote address because of too many failed led login attempts. Just login to another node and then move to the node that you want. However, if you move to another machine, you will stay logged in to the first machine, and that might cause problems with some applications.

To navigate to the “scratch” disk, use

cd /scratch/

To see all users currently logged on, use

w 2.4. VIM 19

2.4 Vim

To open a file using the Vim editor, use

$ vi file

Once the file is open, you have to hit “i” for “insert” before you can edit the file. Hit “esc” to stop editing.

To quit, press “:” then type “wq” (or “write quit”) to save and quit. Type “q!” to force quit without saving.

To customize your Vim experience (e.g. to change the color scheme), create/edit the re- source file ∼/.vimrc

2.5 OpenLava

OpenLava is the batch job scheduling software used on some computing clusters.

To check the nodes available to you, use the command

lsload

To check your running jobs, use

bjobs -w

The -w option shows the ‘wide’ view so the job names are not truncated.

Use the -J option to customize the job name.

To show all the detailed information on a job, use

bjobs -l

To submit a job, use the bsub command, and to kill a running job, use the bkill command.

2.6 SLURM

SLURM is the job scheduler used on some computing clusters.

To get the list of running/pending jobs associated with your username, use

squeue -u

To get more details, use

squeue -u -l

To get even more detailed job info, use

scontrol show job 20 CHAPTER 2. LINUX AND UNIX

For a pending job, for example, this command will give you the estimated start time.

To cancel a running or pending job, use

scancel

To list and get info on completed jobs, use

sacct -u

By default, this only returns jobs that ran the same day.

To get a list of partitions along with nodes, use

sinfo Nel

To get information about a specific node (e.g. processors), use

scontrol show node

To note the node(s) used by your job, check the email you received after the job completed. You can also use the command

sacct -j --format=Nodelist

2.7 System Monitoring and Performance

Processors To check processor usage, use

top

To get more detailed information about a process by PID, use

ps -Flww -p PID

To check exactly what a process is doing, use

sudo strace -p PID

For a graphical view, search for the ‘System Monitor’ application.

To get your processor performance, use the command

lscpu | grep MHz

This will show your current processor speed, as well as the minimum and maximum speeds as determined by the hardware. The processors on the HEPmath cluster run at 1.9 GHz. To get a breakdown of your processor speeds by processor, use the command 2.7. SYSTEM MONITORING AND PERFORMANCE 21

grep MHz /proc/cpuinfo

To stress-test your processor, open a new terminal and initiate a loop

while:; do:; done

In another window, run grep MHz /proc/cpuinfo. Your processors should now be maxed out. To stop the loop, go back to the other window and hit Ctrl + C.

To get all CPU-related info, use the commands

cat /proc/cpuinfo

To increase processor speeds to the maximum as determined by the hardware, you have to override your systems CPU management software. Install cpufrequtils. To get CPU info, use the command

cpufreq-info

To change the CPU management from its current mode to its performance mode, use the command

sudo cpufreq-set -r -g performance to set the mode to performance instead of powersave. Note: This will be reverted to powersave on system reboot. Verify that your processor speed have increased with one of the above commands.

If your processors are running much slower than their hardware maximum even in per- formance mode, their speed might be throttled due to high CPU temperatures. To check your CPU temperatures, install the lm-sensors package. Follow the procedure here: https: //askubuntu.com/questions/15832/how-do-i-get-the-cpu-temperature

Then to check your CPU temperatures, just use the command

sensors

If the temperature is very high (near 100C), then your processors may be getting throttled. If you can keep your machine at a cooler temperature, you may be able to get the processor speed higher.

Hard Drive

To check which processes are using the hard drive, use

sudo iotop -o

To check general stuff about the harddrive, run

gnome-disks 22 CHAPTER 2. LINUX AND UNIX

Then, in the top-right, select “Smart data and self tests...” from the menu.

To do a quick test of the hard drive write speed, use

dd if=/dev/zero of=test bs=1048576 count=2048

To do a quick test of the hard drive read speed, use

dd if=test of=/dev/null bs=1048576 Chapter 3

LaTeX

3.1 Installation

Install the full distribution of LaTeX via the terminal using sudo apt-get install texlive-full. If you don’t install the full distribution, you just run into problems having to manually install packages.

Use the built-in Latex compiler. To edit a LaTeX file, just open it in Gedit. To compile, use the terminal with

pdflatex filename

Note, you have to manually remake the index of LaTeX files. To do so, run pdflatex as shown above, then run

makeindex filename and finally, rerun pdflatex on your file. Note there is no need to include the file extensions (i.e. ”.tex”) when using either of these commands.

3.2 Tables

The basic table format uses the code

\begin{tabular}{ l c r } 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \\ \end{tabular}

which produces:

1 2 3

4 5 6

7 8 9

Note: Wrapping the table in the table environment causes it to float which will not work 23 24 CHAPTER 3. LATEX with multicols. With multicols, only use the tabular part of the wrapping.

To add borders, use the code:

\begin{tabular}{| l | c | r |} \hline 1 & 2 & 3 \\ \hline 4 & 5 & 6 \\ \hline 7 & 8 & 9 \\ \hline \end{tabular}

which produces:

1 2 3

4 5 6

7 8 9

To center cell contents vertically, instead of using l, c, or r when defining the columns, use m{value} where “value” is the width of the cell. To also center it horizontally, use >{\centering\arraybackslash} m{value}. Note, this requires the array package. To remove internal cell padding from the left or the right side, use @{} at the appropriate place in the column definition. To remove internal padding from the top or bottom, use something like \vspace{-2mm}. Here is an example,

\begin{center} % Requires:\usepackage{array} \newcolumntype{C}{ >{\centering\arraybackslash} m{.8cm} } \newcolumntype{D}{@{} >{\centering\arraybackslash} m{2cm} } \begin{tabular}{| C | C | D |} \hline Test1 & Test2 & A lot of text which could also be an image or a graph \\ \hline \end{tabular} \end{center} which produces the following table:

A lot of text which could Test1 Test2 also be an image or a graph

For a long table that spans multiple pages, use the longtable package. Then instead of \begin{tabular} and \end{tabular}, use \begin{longtable} and \end{longtable}.

3.3 Math

The code

\[ \left[ \begin{array}{cc} A & B \\ 3.3. MATH 25

C&D \end{array} \right] \] gives the matrix   AB       CD

To write a piecewise-defined function, use the code

% Requires:\usepackage{amsmath} \[ f(x) = \begin{cases} 1 & \mbox{ if } 0 \leqx<\pi\\ 0 & \mbox{ if } \pi\leqx\leq 2\pi. \end{cases}. \] which gives the result ( 1 if 0 ≤ x < π f(x) = . 0 if π ≤ x ≤ 2π.

To separate the content under a sum or a limit into multiple rows, use substack. For example lim z→z0 z∈C

∞ X

n=k k∈C are given by the code

% Requires:\usepackage{amsmath} \[ \lim_{\substack{z \rightarrow z_0 \\ z \in C}}\] \[ \sum_{\substack{n = k \\ k \in C}}^{\infty} \]

In general, to align multiple equations, use “align”

% Requires:\usepackage{amsmath} \begin{align} \int_0^1 x^2 \, dx &= \frac13 x^3 \Big|_0^1 \\ &= \frac13 1^3 - \frac13 0^3 \\ &= \frac13. \end{align} 26 CHAPTER 3. LATEX which produces

1 1 1 2 3 x dx = x (3.1) ˆ0 3 0 1 1 = 13 − 03 (3.2) 3 3 1 = . (3.3) 3

If you don’t want to produce equation numbers, use “align*” as in

% Requires:\usepackage{amsmath} \begin{align*} \int_0^1 x^2 \, dx &= \frac13 x^3 \Big|_0^1 \\ &= \frac13 1^3 - \frac13 0^3 \\ &= \frac13. \end{align*} which produces

1 1 1 2 3 x dx = x ˆ0 3 0 1 1 = 13 − 03 3 3 1 = . 3

On the other hand, if you want to break a single equation over multiple lines, and you want to reference the equation in the text, use “multline.” For example,

\begin{multline} % Requires:\usepackage{amsmath} \label{labelname} C_{fi}^{(1)}(t) = -\frac{i}{\hbar} \frac{A_{fi}}{\omega_{fi}- \omega}2 e^{i \frac{\omega_{fi}-\omega}{2} t} \sin\left( \frac{(\omega_{fi}-\omega)t}{2}\right) \\ \quad +\frac{i}{\hbar} \frac{A^*_{if}}{\omega_{fi}+ \omega}2 e^{i \frac{\omega_{fi}+\omega}{2} t} \sin\left( \frac{(\omega_{fi}+\omega)t}{2}\right) . \end{multline} produces

ω −ω   (1) i Afi fi (ωfi − ω)t i 2 t Cfi (t) = − 2e sin ~ ωfi − ω 2 ∗ ω +ω   i Aif i fi t (ωfi + ω)t + 2e 2 sin . (3.4) ~ ωfi + ω 2

An example of using align to display equations with explanatory text beside them. The hspace’s are there to push the equations and text descriptions toward each other. You may want to adjust those or remove them entirely.

% Requires:\usepackage{amsmath} \begin{align*} 3.3. MATH 27

\hspace{5cm} R_E &= \frac{\ell_E^2}{\mu_E \gamma} & \leftarrow & \mbox{ Earth} \hspace{5cm} \\ \hspace{5cm} R_M &= \frac{\ell_M^2}{\mu_M \gamma} & \leftarrow & \mbox{ Mars} \hspace{5cm} \end{align*} which produces:

2 `E RE = ← Earth µEγ 2 `M RM = ← Mars µM γ

Here is a way to display multiple lines of text in an equation-like display. Notice that you can adjust the width of each column separately.

\begin{center} % Requires:\usepackage{array} \setlength\tabcolsep{0cm} \begin{tabular}{ >{\centering} m {2.5cm} > {\centering \arraybackslash} m {2.5cm} >{\centering \arraybackslash} m {2.5cm}} area of new parallelogram & $= \quad |\det A| \quad\times $ & area of old parallelogram \end{tabular} \end{center}

area of new area of old = | det A| × parallelogram parallelogram

To box an equation use

% Requires:\usepackage{amsmath} \[ \boxed{ \hbar = \frac{h}{2 \pi}} \] which produces: h = ~ 2π

Multiple aligned and boxed equations.

% Requires:\usepackage{amsmath} \begin{align*} \boxed{ \begin{aligned} L^2 \langle\ell,m| &= \ell(\ell + 1) \hbar^2 \langle\ell,m| \\ L_z \langle\ell,m| &= m \hbar\langle\ell,m| \\ m &= -\ell, -\ell -1, \ldots,\ell-1, \ell\\ L_{\pm}\langle\ell, m| &= \hbar\sqrt{\ell(\ell+1) - m(m \pm 1) } \langle\ell,m \pm 1| \\ L_{+} \langle\ell,\ell| &= L_- \langle\ell, -\ell| = 0. \end{aligned} } 28 CHAPTER 3. LATEX

\end{align*} which produces:

2 2 L h`, m| = `(` + 1)~ h`, m| Lzh`, m| = m~h`, m| m = −`, −` − 1, . . . , ` − 1, ` p L±h`, m| = ~ `(` + 1) − m(m ± 1)h`, m ± 1| L+h`, `| = L−h`, −`| = 0.

3.4 Images

The following code produces the side-by-side images shown below:

% Requires:\usepackage{graphicx} \begin{figure}[h!] \centering \begin{minipage}{.4\textwidth}% \includegraphics[scale=.3]{example-image} \caption{First Caption} \label{fig:label1} \end{minipage} \qquad \begin{minipage}{.4\textwidth}% \includegraphics[scale=.3]{example-image} \caption{Second Caption}% \label{fig:label2}% \end{minipage}% \end{figure}

Figure 3.1: First Caption Figure 3.2: Second Caption

3.5 Referencing

To caption and label a graph, use the code

\begin{figure} \begin{center}

TIKZ or PGFplots Code

\end{center} \caption{Graph Name} \label{fig:graph1} \end{figure} 3.6. TIKZ 29

To reference it, use the code \ref{fig:graph1}. Note, the label tag must appear after the caption tag in order for the reference tag to be properly numbered. Also, notice that the graph must be in a figure environment.

To caption and label a table, use the code

\begin{table} \begin{center} \begin{tabular}

Table Code

\end{tabular} \end{center} \caption{Table Name} \label{tab:table1} \end{table}

To reference it, use the code \ref{tab:table1}. Note, the label tag must appear after the caption tag in order for the reference tag to be properly numbered. Also, notice that the table must be in a table environment.

Annotated Bibliography The only workable solution I’ve found for annotated bibliographies is found here http://www. barik.net/sw/ieee/. At the bottom of your LaTeX document, just above \end{document} include the following:

\nocite{*} \bibliographystyle{IEEEannot} \bibliography{mybib}

Make sure that the file IEEEannot.bst exists in your working directory. It can be downloaded from the link above. The file mybib.bib must also exist in your working directory. It is the file containing your bibliographical information.

Whenever you update the bibliography file associated with your LaTeX document, you have to first typeset the document using “BibTex” and then run the typesetting process again, this time with “PDFLaTeX”, so see your updated document.

3.6 Tikz

In this section, various tikz implementations are illustrated followed by the code required to create them. Add the tikz package in your document preamble. 30 CHAPTER 3. LATEX

% Requires:\usepackage{tikz} \begin{tikzpicture} \draw (0,0) -- (0,2) -- (-2,3) -- cycle;

\draw (1,1) -- (3,2) -- (2,3); \end{tikzpicture}

% Requires:\usepackage{tikz} % Requires:\usetikzlibrary{decorations.markings} \begin{tikzpicture} \draw[ decoration={markings, mark=at position 0 with {\arrow{>}}}, postaction={decorate} ] (0,0) circle (2); \draw[fill=black] (0,0) circle (.3ex);%Center dot \end{tikzpicture}

x, y

t

% Requires:\usepackage{tikz} \begin{tikzpicture} \draw[->] (0,-1) -- (0,1) node[anchor=south] {$x,y$}; \draw[->] (0,0) -- (4,0) node[anchor=north] {$t$}; \draw[samples=100,domain=0:3.5] plot (\x,{pow(2.7,-.7*\x)*.7*cos(10*\x r)}); \end{tikzpicture} 3.6. TIKZ 31

y

(1, 1)

x

% Requires:\usepackage{tikz} \begin{tikzpicture} \draw[->] (-.5,0) -- (6,0) node[anchor=west] {$x$}; \draw[->] (0,-.5) -- (0,4) node[anchor=west] {$y$}; \fill (3,3) circle (0.1) node[anchor=south] {$(1,1)$}; \end{tikzpicture}

x −5 −3 0 5

% Requires:\usepackage{tikz} % Requires:\usetikzlibrary{arrows} \begin{tikzpicture} \draw[<->] (-3.5,0) -- (3.5,0) node[anchor=west] {$x$};

\draw[very thick,blue,[->] (-2.5,0) -- (-3.5,0); \draw[very thick,blue,(->] (0,0) -- (3.5,0);

\fill[blue] (-1.5,0) circle (0.1); \fill[white,draw=black] (2.5,0) circle (0.1);

\node at (0,-.4) {$0$}; \node at (-2.5,-.4) {$-5$}; \node at (2.5,-.4) {$5$}; \node at (-1.5,-.4) {$-3$}; \end{tikzpicture} 32 CHAPTER 3. LATEX

z

(x, y, z)

y

x

% Requires:\usepackage{tikz} \begin{tikzpicture} \draw[->] (0,0) -- (4,0) node[anchor=west] {$y$}; \draw[->] (0,0) -- (0,4) node[anchor=south] {$z$}; \draw[->] (0,0) -- (-2,-2) node[anchor=north] {$x$}; \fill (2,1) circle (0.1) node[anchor=south] {$(x,y,z)$}; \end{tikzpicture}

~r(t)

% Requires:\usepackage{tikz} \begin{tikzpicture} \draw[black, thick, ->] plot [smooth, tension = .8] coordinates {(1,0) (3,2) (5,0) (7,2)}; \node at (7.5,2) {$\vec{r}(t)$}; \end{tikzpicture}

% Requires:\usepackage{tikz} \begin{tikzpicture}[scale=1.5] \filldraw[fill=black!10!white, draw=black] (0,0) rectangle (2,2); \end{tikzpicture} 3.6. TIKZ 33

− +

% Requires:\usepackage{tikz} \begin{tikzpicture} \draw (0,0) circle (0.25cm) node[] {$-$}; \draw (2,0) circle (0.25cm) node[] {$+$}; \end{tikzpicture}

% Requires:\usepackage{tikz} \begin{tikzpicture} \draw[red, line width = 3pt, <->] (-2,0) -- (2,0); \end{tikzpicture}

% Requires:\usepackage{tikz} \begin{tikzpicture} \draw (-2,0) ellipse (2cm and 0.5cm); \draw[thick] (0,0) ellipse (.8cm and 2cm); \end{tikzpicture}

x x x x x x x

x x x x x x x

x x x x x x x

% Requires:\usepackage{tikz} \begin{tikzpicture} \foreach \x in {-3,-2,-1,0,1,2,3} \foreach \y in {-1,0,1} { \draw (\x,\y) node[] {x}; } \end{tikzpicture} 34 CHAPTER 3. LATEX

% Requires:\usepackage{tikz} % Requires:\usetikzlibrary{decorations.pathmorphing} \begin{tikzpicture} \draw[ thick, decoration={aspect=0.3, segment length=3mm, amplitude=8mm,coil}, decorate ] (0,0) -- (2.75,0); \end{tikzpicture}

% Requires:\usepackage{tikz} % Requires:\usetikzlibrary{patterns} \begin{tikzpicture} \filldraw[fill=gray!10!white, draw=black] (-2,-2) -- (-2,2) -- (2,2) -- (2,-2) -- cycle; \filldraw[fill=white!10!white, draw=black] (-1,-1) -- (-1,1) -- (1,1) -- (1,-1) -- cycle; \fill [pattern = north west lines] (2,-1) rectangle (1,1); \fill [pattern = north east lines] (-2,-.5) rectangle (-1,.5); \end{tikzpicture}

m 3.6. TIKZ 35

% Requires:\usepackage{tikz} % Requires: \usetikzlibrary{patterns,calc,decorations.pathmorphing,decorations.markings} \begin{tikzpicture} \tikzstyle{spring}=[thick,decorate, decoration={coil,aspect=.7,amplitude=10}] \tikzstyle{support}=[fill,pattern=north east lines,draw=none, minimum width=0.75cm,minimum height=0.3cm] \tikzstyle{damper}=[thick,decoration={ markings, mark connection node=dmp, mark=at position 0.5 with { \node (dmp) [thick, inner sep=0pt, transform shape,rotate=-90, minimum width=15pt, minimum height=3pt,draw=none] {}; \draw [thick] ($(dmp.north east) + (2pt,0)$) -- (dmp.south east) -- (dmp.south west) -- ($(dmp.north west)+(2pt,0)$); \draw [thick] ($(dmp.north) + (0,-5pt)$) -- ($(dmp.north) + (0,5pt)$); } }, decorate]

\node (wall) [support, minimum width=3cm, yshift=1cm,] {}; \draw[thick,yshift=.85cm] (-1.5,0) -- (1.5,0);

\draw[spring] (.5,.85) -- (.5,-3); \draw[damper] (-.5,.85) -- (-.5,-3);

\draw (-1,-3) -- (1,-3) -- (1,-4) -- (-1,-4) -- cycle; \node at (0,-3.5) {$m$}; \end{tikzpicture}

Q

T1 T2

% Requires:\usepackage{tikz} \begin{tikzpicture} \draw[gray, line width = 3pt] plot [smooth, tension = 1] coordinates {(0,1) (2,1.5) (4,1)}; \draw[->] (0,1) -- (-1,.5) node[anchor=east] {$T_1$}; \draw[->] (4,1) -- (5,.5) node[anchor=west] {$T_2$}; \draw[->] (2,1.5) -- (2,2) node[anchor=south] {$Q$}; \end{tikzpicture} 36 CHAPTER 3. LATEX

% Requires:\usepackage{tikz} \begin{center} \begin{tikzpicture}[scale=1.5] \filldraw[fill=black!10!white, draw=none] (-1,-1) rectangle (1,1); \draw (-1,-1) -- (-1,1); \draw (1,-1) -- (1,1);

\draw[samples=100, domain=0:3.5, scale=0.3, color=blue, xshift=-95, yshift=-20] plot (\x,{pow(2.7,-.7*\x) *1.5*cos(10*\x r)}); \draw[samples=100, domain=0:3.5, scale=0.3, color=red, xshift=95, rotate=180, yshift=-20] plot (\x,{pow(2.7,-.7*\x) *1.5*cos(10*\x r)}); \end{tikzpicture} \end{center}

% Requires:\usepackage{tikz} % Requires:\usetikzlibrary{arrows} \begin{center} \begin{tikzpicture} \draw[->] (0,0) -- (4,0); \draw[->] (0,0) -- (0,4); \draw[->,>=stealth’,semithick] (0:1.2cm) arc (0:45:1.2cm); \draw[->] (0,0) -- (3,3); \end{tikzpicture} \end{center} 3.6. TIKZ 37

U z

w

% Requires:\usepackage{tikz} \begin{tikzpicture} \draw[dashed] plot [smooth cycle, tension = .8] coordinates {(-3,-2) (-2.2,0) (-2,2) (0,1.8) (-1,-1) (1.8,0) (2,-2) (0,-1.6)}; \node at (-1.5,1.5) {$U$}; \fill (-1,1) circle (0.1) node[anchor=south] {$z$}; \fill (1,-1) circle (0.1) node[anchor=south] {$w$}; \draw (-1,1) -- (-1.5,-1.5) -- (1,-1); \end{tikzpicture}

% Requires:\usepackage{tikz} % Requires:\usetikzlibrary{decorations.markings} \begin{tikzpicture} \begin{scope}[decoration = {markings, mark = at position 0.5 with {\arrow{>}}}] \draw[postaction = {decorate}] (0,0) -- (2,2); \draw[postaction = {decorate}] plot [smooth, tension = .8] coordinates {(.3,-.3)(.8,-.7) (.5,-1.5)(1,-2)}; \end{scope} \end{tikzpicture} 38 CHAPTER 3. LATEX

Ueff

E r

rmin

% Requires:\usepackage{tikz} \begin{tikzpicture}[scale=.7] \draw[->] (-1,0) -- (10,0) node[anchor=west] {$r$}; \draw[dashed,->] (-1,1) -- (10,1) node[anchor=west] {$E$}; \draw[->] (0,-3) -- (0,3) node[anchor=south] {$U_{eff}$}; \draw[samples = 100, domain = .4:10] plot (\x,{ (-6*(\x-1))/((\x-1)^2+1) }); \draw[dotted] (.8,1) -- (.8,-3) node[anchor=north] {$r_{min}$}; \end{tikzpicture}

p

V

% Requires:\usepackage{tikz} % Requires:\usetikzlibrary{decorations.markings} \begin{tikzpicture}[scale=1.5] \fill [black!10!white, domain=1:3, variable=\x] (1, 0) -- plot ({\x}, {2/\x}) -- (3, 0) -- cycle;

\draw[->] (0,0) -- (4,0) node[anchor= west] {$V$}; \draw[->] (0,0) -- (0,4) node[anchor=south] {$p$}; \fill[black] (1,2) circle[radius=2pt]; \fill[black] (3,.67) circle[radius=2pt];

\draw[very thick, samples=100, domain=1:3, decoration={markings, mark=at position 0.5 with {\arrow{>}}}, postaction={decorate} ] plot (\x,{2/\x))}); \end{tikzpicture} 3.7. PGFPLOTS 39

% Requires:\usepackage{tikz} % Requires:\usetikzlibrary{calc} \begin{tikzpicture}

\def\centerarc[#1](#2)(#3:#4:#5)% Syntax:[draw options](center)(initial angle:final angle:radius) { \draw[#1] ($(#2)+({#5*cos(#3)},{#5*sin(#3)})$) arc (#3:#4:#5); }

% Draw an arc specifyinga center, angles, and radius \centerarc[](0,0)(0:90:3)

\end{tikzpicture}

+ + + + + + + + + + – – + + – – – +q – + + – – – – + + + + + + + + + + +

% Requires:\usepackage{tikz} % Requires:\usetikzlibrary{decorations.markings} \begin{tikzpicture} \fill[gray!30,draw=black] (0,0) circle (2); \fill[white,draw=black] (.5,0) ellipse (.8cm and .3cm); \fill (.5,0) circle (0.08) node[anchor=east] {$+q$};

\draw[draw=none] (0,0) circle (1.8) [postaction={decorate}, decoration={ markings, mark=between positions 0 and 1 step 0.04 with {\node{+};}}];

\draw[draw=none] (.5,0) ellipse (1cm and .5cm) [postaction={decorate}, decoration={markings, mark=between positions 0 and 1 step 0.1 with {\node{--};}}]; \end{tikzpicture}

3.7 PGFPlots

Following are some examples of what you can do with the package pgfplots. The code follows the illustrations. 40 CHAPTER 3. LATEX

4

2

−4 −2 2 4

−2

−4

% Requires:\usepackage{pgfplots} \begin{tikzpicture} \begin{axis}[ xmin=-5, xmax=5, ymin=-5, ymax=5, axis equal = true, axisx line=middle, axisy line=middle, ]

\addplot [samples=50] {x^2}; \end{axis} \end{tikzpicture}

|G|2

1

ω q k ω ∼ m 3.7. PGFPLOTS 41

% Requires:\usepackage{pgfplots} \begin{tikzpicture} \begin{axis}[ xmin=-.5, xmax=3, ymin=-.5, ymax=3, axis equal = true, axisx line=middle, axisy line=middle, ticks = none, xlabel={$\omega$}, ylabel={$|G|^2$} ]

\addplot [domain=0:3, samples=100] {(1+x^2)/((1-x^2)^2+x^2)}; \addplot [dotted] coordinates {(.85,0) (.85,2.16)}; \node at (axis cs:.85,-.2){$\omega \sim \sqrt{\frac{k}{m}}$}; \node at (axis cs:-.1,1){$1$}; \end{axis} \end{tikzpicture}

4

2

−4 −2 2 4

−2

−4

% Requires:\usepackage{pgfplots} \begin{tikzpicture} \begin{axis}[ xmin=-5, xmax=5, ymin=-5, ymax=5, axis equal = true, axisx line=middle, axisy line=middle, trig format plots=rad, ]

\addplot [samples=50] {sin(x)}; \end{axis} 42 CHAPTER 3. LATEX

\end{tikzpicture}

4

2

−4 −2 2 4

−2

−4

% Requires:\usepackage{pgfplots} \begin{tikzpicture} \begin{axis}[ xmin=-5, xmax=5, ymin=-5, ymax=5, axis equal = true, axisx line=middle, axisy line=middle, ]

\addplot [ domain=-5:0.9, samples=50] {1/(x-1)}; \addplot [ domain=1.1:5, samples=50] {1/(x-1)};

\addplot [dotted] coordinates {(1,5) (1,-5)}; \end{axis} \end{tikzpicture} 3.7. PGFPLOTS 43

4

2

−4 −2 2 4

−2

−4

% Requires:\usepackage{pgfplots} % Requires:\usetikzlibrary{backgrounds} \begin{tikzpicture} \begin{axis}[ xmin=-5, xmax=5, ymin=-5, ymax=5, axis equal = true, axisx line=middle, axisy line=middle, after end axis/.code={ \begin{scope}[on background layer] \foreach \x in {-5,...,5}{ \foreach \y in {-5,...,5}{ \fill[gray!50] (axis cs:\x,\y) circle[radius=0.8pt]; }} \end{scope} }]

\addplot [samples=50] {x^2}; \end{axis} \end{tikzpicture}

Chapter 4

Inkscape

4.1 Installation

Inkscape is a vector graphics drawing program. Avoid drawing in non-vector graphics to avoid pixelation effects when resizing images.

In Ubuntu, Inkscape can be installed via the “Ubuntu Software” application. Install version 0.91 instead of the latest version (0.92) if you want the ability to add LaTeX text to your drawings.

To enable a “snap-to-grid”

1. View > Page Grid 2. Go to File > Document Properties > Grids to change the grid size, enable “snap-to” and so on

To draw a straight line:

1. Select the Bezier Curve tool 2. Hold down Ctrl while drawing the line 3. Left click and hit enter at the end of your line 4. Go to “Stroke and Fill” and change the line thickness if you like

To draw a dashed line, draw the line as above, then change the stroke style to a dashed line.

To rotate an object:

1. Select the Object Selector tool 2. Double-click on on the object to get the “rotate” options

To add an arrow along some point in a line:

1. Draw a line 2. Go to Object > Fill and Stroke > Stroke Style 3. Change the “mid markers” style to an arrow style 4. Return to your drawing, select the “Edit paths by nodes” tool and add a node to the line where you want the arrow to appear by double-clicking on it

To add LaTeX text:

1. Select the text tool and draw a textbox 2. Go to Extensions > Render > LaTeX 3. Enter your LaTeX code and select ’Live Preview’ to see if it looks good 45 46 CHAPTER 4. INKSCAPE

To apply something to all objects at once, such as making all the lines thicker:

1. Use the object selector to draw a rectangle around all your objects 2. Update the attribute (e.g. increase the stroke thickness)

To resize the canvas to include only your objects:

1. Use the object selector to draw a rectangle around your objects 2. Go to File > Document Properties and click “Resize page to drawing or selection”

To export a PNG Image of your drawing:

1. Go to File > Export PNG Image 2. Change the image size to suit (typically width = 500)

An example Feynman diagram drawn in Inkscape is shown below.

To draw more fancy things like gluon or photon lines:

1. Draw a small rectangle 2. Go to Extensions > Render > Parametric Curves 3. Update the parameters and functions appropriately (details below) 4. Check the ’Live Preview’ to see the result. Apply it if it looks sort of right 5. Select the object and change the size as needed

If the object disappears or appears as a solid rectangle, make sure your rectangle is set with an appropriate stroke and no fill.

For photon lines, use the following parameters: 4.1. INSTALLATION 47

For gluon lines, use the following parameters:

Chapter 5

Python

5.1 Installation

Use pip to install python packages using the syntax sudo pip install package-name

To list the current python packages, use pip freeze

To search for a package, use pip search package-name

Install the following python packages using pip:

• numpy • matplotlib • scipy

5.2 General

This chapter assumes you have installed Python 2.7.

A Python file needs to begin with

#!/usr/bin/env python

The Unix server may not recognize a Python file (unless you explicitly use the python command) if you created it in Windows because Windows leaves a carriage return character at the end of lines (most importantly the #! line). To convert to Unix readable file, run the dos2unix utility on the Python file. dos2unix [filename].py

Include the following line with your other package imports to ensure that python 2.7 behaves like python 3.5: 49 50 CHAPTER 5. PYTHON

from __future__ import division, print_function

5.3 Style Guide

Use the PEP 8 standard. PyCharm is helpful in notifying you when your format is not in PEP 8 standard.

The prologue of your code should contain a brief description of the program as well as your name and the date. This should be enclosed in a docstring (i.e. three double quotes).

""" mass_formula.py plots the binding energy per nucleon(for the most stable isotope) for all the elements fromZ=1 toZ= 109.

Your Name Computational Physics Date """

Also describe each user-defined function using a docstring.

When naming variables, use descriptive names. Avoid names that begin with lowercase “L”, uppercase “i”, or uppercase “O”.

Function names should be lowercase with underscores separating words (e.g. solve matrix()).

Variables should be mixed case (e.g. maxHeight).

Constants should be capitalized and words should be separated by underscores (e.g. RA- DIUS EARTH) except in the case of well-known constants (e.g. g).

When plotting, be sure to title your graph and label your axes. If appropriate, add a graph legend as well.

5.4 Plotting

For basic plotting with LaTeX labels and outputting to a PNG file, use the following code: import numpy as np import matplotlib.pyplot as plt

x = np.linspace(-3, 3) y = x**2 plt.rc(’text’, usetex=True) plt.plot(x, y) plt.legend([r"$y=x^2$"]) plt.title("An Example Plot") plt.xlabel(r"$x$") plt.ylabel(r"$y$") plt.savefig("plot.png") plt.show() 5.4. PLOTTING 51

The following program shows how to do multiple plots on a single graph: import matplotlib.pyplot as plt import numpy as np x = np.linspace(-3, 3) y1 = x y2 = x**2 y3 = x**3

# Plot the results plt.rc(’text’, usetex=True) plt.title("A Plot of Multiple Functions") plt.plot(x, y1, label=r"$f(x)= x$") plt.plot(x, y2, label=r"$f(x)=x^2$") plt.plot(x, y3, label=r"$f(x)=x^3$") plt.legend(loc=2) plt.xlabel(r"$x$") plt.show()

If you’re plotting multiple functions on a single graph, you may want to customize the line and marker styles. For example, the function below is plotted with points shaped like “x”, with no connecting lines between the points, and only every 20th point is plotted. These options are helpful, for example, if this function lies on top of and would otherwise obscure another function. plt.plot(xlist, ylist, linestyle="none", marker="x", markevery=20)

Plotting from a File Numpy has a great loadtxt function that makes it painless to plot from data in a file. In the following program, the data is stored as two columns in the textfile. The first column gives the 52 CHAPTER 5. PYTHON x-values, and the second column gives the y values. Each point (x, y) on the graph, occupies one row in the text file. import numpy as np import matplotlib.pyplot as plt

# Load the data from the file data = np.loadtxt("sunspots.txt", float) x = data[:, 0] y = data[:, 1]

# Plot the results plt.plot(x, y) plt.title("Sunspots per Month") plt.xlabel("Month") plt.ylabel("Number of Sunspots") plt.savefig("plot.png") plt.show()

3D Scatter Plot with Error Bars from File

#!/usr/bin/env python """ 3D scatter plot withz-errors """ from __future__ import division, print_function import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as axes3d fig = plt.figure(dpi=100) ax = fig.add_subplot(111, projection=’3d’)

# Load the data from text file data = np.loadtxt("64x12susc-data.txt", float) x = data[:, 0] y = data[:, 1] z = data[:, 2]

#error data zerror = data[:, 3]

#plot points ax.plot(x, y, z, linestyle="None", marker="o")

#plot errorbars fori in np.arange(0, len(x)): ax.plot([x[i], x[i]], [y[i], y[i]], [z[i]+zerror[i], z[i]-zerror[i]], marker="_") plt.title("Action Susceptibility") plt.xlabel("beta") plt.ylabel("kappa") plt.show() 5.4. PLOTTING 53

Parametric Plots Here is a parametric graph produced by python. Note the Latex formatting of the textbox in the graph.

The program that produces this graph is here: import numpy as np import matplotlib.pyplot as plt

# Main body of program 54 CHAPTER 5. PYTHON

# Define the theta values, and give the parametric equations forx andy theta = np.linspace(0, 2*np.pi) x = 2*np.cos(theta) + np.cos(2*theta) y = 2*np.sin(theta) - np.sin(2*theta)

# Plot the results plt.rc(’text’, usetex=True) plt.plot(x, y) plt.text(1.5, 2,r"\begin{eqnarray*}" r"x &=&2\cos\theta+\cos(2\theta)\\" r"y &=&2\sin\theta-\sin(2\theta)" r"\end{eqnarray*}", bbox={’facecolor’:’white’,’alpha’: 0.5,’pad’: 10}) plt.title("Parametric Deltoid Curve") plt.xlabel("x") plt.ylabel("y") plt.savefig("deltoid_curve.png") plt.show()

Polar Plots Here is a polar plot produced by python.

The program that produces this graph is here. Notice the two lines that get the axis limits of the graph and then adjusts the top one. This is so the plot legend doesn’t overlap with the butterfly graph. import numpy as np import matplotlib.pyplot as plt

# Main body of program

# Theta values theta = np.linspace(0, 24*np.pi, 10000) 5.4. PLOTTING 55

# The polar function r = np.exp(np.sin(theta)) - 2*np.cos(4*theta) + (np.sin(theta/12))**5

# Convert to cartesian coordinates x = r*np.cos(theta) y = r*np.sin(theta)

# Plot the results plt.rc(’text’, usetex=True) plt.plot(x, y) left, right, bottom, top = plt.axis() plt.axis((left, right, bottom, top + .75)) plt.legend([r"$r=e^{\sin\theta}-2\cos (4\theta)" r"+\sin^5\left(\frac{\theta}{12}\right)$"]) plt.title("Fay’s Function") plt.savefig("fays_function.png") plt.show()

Density Plots The image below is a scanning tunneling micrograph of the surface of silicon. It is plotted as a density plot using the PyLab module.

This program reads in the 2D data from a textfile. The text file contains space separated floating point numbers. Each number corresponds to a point in the image. The top row of the textfile gives the data for the top row of the pixels in the image, and so on. The textfile is really a giant array, and this function just loads that array and makes a density plot with its values. import numpy as np import pylab as pyl

# Load the data from the file data = np.loadtxt("stm.txt", float) 56 CHAPTER 5. PYTHON

# Createa density plot of the data pyl.imshow(data) pyl.title("STM Image of Silicon Surface") pyl.colorbar()# Shows the range of colors alongsidea numerical scale pyl.savefig("plot.png") pyl.show()

Programmatic Plotting Suppose you want to generate hundreds of plots–each with a different parameter. Manually running your program hundreds of times, is inefficient. You can write the program such that it automatically generates the plots for you.

In this example, we generate 10 plots each containing 100 random points. Make sure that the folder called “images” here exists in your program’s directory. Without the line plt.clf(), each successive image will include all the previous ones. import matplotlib.pyplot as plt import random

# Generatea large number of points def make_points(): forj in range(100): # Makea random point in (-10, 10) point = [random.uniform(-10.0, 10.0), random.uniform(-10.0, 10.0)] x.append(point[0]) y.append(point[1])

# Generate the image def make_image(run): plt.scatter(x, y, c=’k’, s=2) plt.axis(’Off’) plt.axes().set_aspect(’equal’) filename ="images"+ str(run) +".png" plt.savefig("images/" + filename) plt.clf() fori in range(10): x = []#A list ofx-coordinates y = []#A list ofy-coordinates make_points() print("Run:", i) make_image(i)

5.5 File Cleaning

#!/usr/bin/env python """

We havea text file containing theP,L, ands susceptibilities from all lattice sizes and beta values. We want to plot Psus and Psuse(i.e.P susceptibility andP susceptibility error) versus kappa, but only for the 64x12 lattices ata specific beta value. We want to do the same for theL ands susceptibilities. For each 5.6. VECTORIZATION 57

lattice size, we have eight beta values. So from the text file, we extract eight smaller text files, which serve as inputs to gnuplot. Doing the data sorting, grouping, and copy/pasting into the smaller data files takesa long time, so this script was written to automate it.

The input text file has the headers:

lattice njob beta kappa Lsus Lsuse Psus Psuse Ssus Ssuse

Each output file will contain the columns:

kappa*sus*suse where "*" is"L","P", or"S". Each output file has onlya single beta value.

""" import numpy as np

# Import the data from the text file. Commented rows are not imported. data = np.genfromtxt("susceptibilities.txt", comments=’#’, usecols=(0,1,2,3,4,5,6,7,8,9), dtype=str)

# Makea new array containing all rows of data that have # "064x12" as the value in the first column. # The rest of the rows are ignored, as we don’t care # about the other lattice sizes right now. latt64x12 = data[np.where(data[:,0] =="064x12")]

# From this array, makea smaller array for each beta(third column) value beta2p30 = latt64x12[np.where(latt64x12[:,2] =="2.3000")] beta2p40 = latt64x12[np.where(latt64x12[:,2] =="2.4000")] beta2p50 = latt64x12[np.where(latt64x12[:,2] =="2.5000")] beta2p60 = latt64x12[np.where(latt64x12[:,2] =="2.6000")] beta2p70 = latt64x12[np.where(latt64x12[:,2] =="2.7000")] beta2p80 = latt64x12[np.where(latt64x12[:,2] =="2.8000")] beta2p90 = latt64x12[np.where(latt64x12[:,2] =="2.9000")] beta3p00 = latt64x12[np.where(latt64x12[:,2] =="3.0000")]

#print(beta2p50)

# Print all to text files for plotting np.savetxt("beta2p30.d", beta2p30, fmt=’%s’) np.savetxt("beta2p40.d", beta2p40, fmt=’%s’) np.savetxt("beta2p50.d", beta2p50, fmt=’%s’) np.savetxt("beta2p60.d", beta2p60, fmt=’%s’) np.savetxt("beta2p70.d", beta2p70, fmt=’%s’) np.savetxt("beta2p80.d", beta2p80, fmt=’%s’) np.savetxt("beta2p90.d", beta2p90, fmt=’%s’) np.savetxt("beta3p00.d", beta3p00, fmt=’%s’)

5.6 Vectorization

The following program plots f(x) = ex on the region [−2, 2]. from __future__ import division, print_function import matplotlib.pyplot as plt import numpy as np 58 CHAPTER 5. PYTHON

def f(x): """ Definef(x)=e^x. """ return np.exp(x)

# Construct the list ofx-values xlist = [-2.0 + 0.004*i fori in range(1000)]

# Compute the list ofy-values ylist = [] forx in xlist: ylist.append(f(x))

# Plot the results plt.rc(’text’, usetex=True) plt.plot(xlist, ylist, label=r"$f(x)=e^x$") plt.legend(loc=1) plt.xlabel(r"$x$") plt.show()

We can make it a little more succinct by replacing ylist = [] forx in xlist: ylist.append(f(x)) with the single line ylist = [f(x) forx in xlist]

However, even this is not optimal. We still have a for loop that is computing f(x) for each value of x in xlist. Instead, we can use the vectorization capabilities of Numpy to send an entire array of values into f(x) as follows: from __future__ import division, print_function import matplotlib.pyplot as plt import numpy as np def f(x): """ Definef(x)=e^x. """ return np.exp(x)

# Construct the list ofx-values xlist = np.array([-2.0 + 0.004*i fori in range(1000)], float)

# Compute the list ofy-values ylist = f(xlist) 5.6. VECTORIZATION 59

# Plot the results plt.rc(’text’, usetex=True) plt.plot(xlist, ylist, label=r"$f(x)=e^x$") plt.legend(loc=1) plt.xlabel(r"$x$") plt.show()

Modules Object Oriented Programming

1 The following program numerically computes and plots the derivative of f(x) = 1 + 2 tanh(2x). from __future__ import division, print_function import matplotlib.pyplot as plt import numpy as np def f(x): """ Definef(x)=1+ 0.5*tanh(2x). """ return 1 + 0.5*np.tanh(2*x) def diff(x, h=1e-8): """ The numerical derivative evaluated atx, calculated using the central difference. """ return (f(x + h/2) - f(x - h/2))/h res = 1000# Plotting resolution xlo, xhi = -2.0, 2.0# Define the plotting region

# Construct the list ofx-values xlist = np.array([xlo + i*(xhi-xlo)/res fori in range(res+1)], float)

# Compute they-values difflist = diff(xlist)

# Plot the numerical derivative plt.rc(’text’, usetex=True) plt.title("Numerical Derivative") plt.plot(xlist, difflist, label=r"$\frac{df}{dx}$") plt.legend(loc=1) plt.xlabel(r"$x$") plt.show()

Following is the same program written in object-oriented programming. Here, we have created a differential calculator object class. from __future__ import division, print_function import matplotlib.pyplot as plt import numpy as np 60 CHAPTER 5. PYTHON

class DiffCalc(): """Differential calculator object class.""" def __init__(self, func, h=1e-8): """Initialize""" self.f = func self.h = h

def diff(self, x): """Derivative off(x) approximated atx using the central difference method.""" self.x = x return (self.f(self.x + self.h/2)/self.h) - self.f(self.x - self.h/2)/self.h def f(x): """ Definef(x)=1+ 0.5*tanh(2x). """ return 1 + 0.5*np.tanh(2*x) res = 1000# Plotting resolution xlo, xhi = -2.0, 2.0# Define the plotting region

# Construct the list ofx-values xlist = np.array([xlo + i*(xhi-xlo)/res fori in range(res+1)], float)

# Compute they-values der = DiffCalc(f) difflist = der.diff(xlist)

# Plot the numerical derivative plt.rc(’text’, usetex=True) plt.title("Numerical Derivative") plt.plot(xlist, difflist, label=r"$\frac{df}{dx}$") plt.legend(loc=1) plt.xlabel(r"$x$") plt.show()

The following program defines a Rectangle class with two member variables length and width. Various member functions, such as area and perimeter, are defined, and the addition operator is overloaded to define rectangle addition. from __future__ import division, print_function class Rectangle: """Rectangle object declaration"""

def __init__(self, length=1, width=1): """Initialize.""" self.length = length self.width = width

def area(self): """Compute and print the area ofa rectangle.""" return self.length * self.width 5.6. VECTORIZATION 61

def perimeter(self): """Compute and print the perimeter ofa rectangle.""" return 2*self.length + 2*self.width

def print(self): """Print the length, width, area, and circumference.""" print("Length=", self.length, sep="") print("Width=", self.width, sep="") print("Area=", self.area(), sep="") print("Perimeter=", self.perimeter(), sep="")

def __add__(self, other): """Define what it means to add two rectangles.""" return Rectangle(self.length + other.length, self.width + other.width)

A = Rectangle(20, 10) print("\nArea of first rectangle=", A.area(), sep="")

B = Rectangle() C = A + B print("\nSecond Rectangle:") C.print()

This program gives the results:

Area of first rectangle = 200

Second Rectangle: Length = 21 Width = 11 Area = 231 Perimeter = 64

Chapter 6

Fortran

6.1 Installation

GFortran is a free Fortran 95/2003/2008 compiler. To install the package via the command line in Linux, use:

sudo apt install gfortran

6.2 A Basic Program

From the Linux command line, execute

emacs domathstuff.f &

to create a fortran source file. Write your program in the resulting Emacs window. Following is an example of a simple fortran program.

program domathstuff implicit none c This is a comment. c In the next line, I declare several variables along with their types real :: a, b, sum, root, sqroot, product, power! This is alsoa comment c Following are executable statements

a = 25.0 b = 16.0

sum=a+b print*,’The sum is:’, sum

product = a*b print*,’The product is:’, product

root = a**(1.0/3.0) print*,’The cube root of’, a,’ is’, root

sqroot = sqrt(a) print*,’The square root ofa is:’, sqroot 63 64 CHAPTER 6. FORTRAN

power = a**3 print*,’The value ofa^3 is:’, power

end program domathstuff

After writing your program, save it and close emacs. To compile the program, run the following command in your Linux command line:

gfortran domathstuff.f

To execute your compiled program, use

./a.out

To save and name your compiled program as an executable, use

mv a.out domathstuff

Now, whenever you want to run the compiled Fortran program called domathstuff, you would use the command:

./domathstuff

To send the output of your program to a text file, use something like:

./domathstuff > results.txt

Note that Fortran does integer division. For example, it will calculate 5/2 as 2. To get the expected result 2.5, you have to write all divisions using floats, as in 5.0/2.0.

6.3 Syntax

Note, Fortran only recognizes 72 characters per line. Assume that everything past that is completely ignored. If your line is longer than this, you need to break it over two lines using an ampersand as in

write (*,*)"I have received", returnvalue, &" from the subroutine"

Note: The ampersand must be in the sixth position (i.e. column).

Type Declarations and Parameters Explicit Typing Fortran has a confusing way of managing variable types. The proper way to do it is to use only explicit typing. To do this, add the line

implicit none 6.3. SYNTAX 65 right after the program or subroutine name. Fortran will now require you to declare the type of every variable you use. For example, to declare a character variable named “chars” consisting of two characters (e.g. “HH”), and an integer variable named “myint”, we would add

character chars*2 integer myint at the beginning of our program. Explicit typing like this is the right way to do things, because the Fortran compiler will quickly let you know if you have a typo since a typo will look like a variable of undeclared type.

For arrays use something like

dimension x(n) which declares an n-dimensional array called “x”

Implicit Typing Then there’s implicit typing. You can avoid having to declare the type of all your parameters if you leave out the line “implicit none”. Fortran will then decide a variable’s type by its first letter. By default, Fortran will assign variables starting with “a” to “h” and from “o” to “z” with the type “real”, and will assign variables starting with “i” to “n” the type “integer”.

By default, Fortran real numbers have 32-bit precision. If you want to use double precision reals instead, add the line

implicit real*8 (a-h,o-z)

Now, all variables starting with “a-h” or “o-z” will be double precision reals. If you want variables starting with “m” to be logical instead of integers, you would add

implicit logical (m)

If you have a lot of these changes to Fortran’s default implicit typing, put these lines into a separate file called something like implicit.08 and then add the line

include’implicit.08’ at the beginning of your programs.

Parameters

To assign a value to a variable, we create a parameter. For example, if we want to set myint=10, we would say

parameter(myint=10)

A parameter is a quantity that does not change over the course of the program.

If Statements The basic if statement has the syntax: 66 CHAPTER 6. FORTRAN

if (condition) do stuff

Notice that everything is on one line. Block if statements have the following syntax:

if (condition) then do stuff endif

Reading and Writing The Fortran write command has the following syntax:

write(unit, format, options) item1, item 2,...

The “unit” tells Fortran where to write the stuff. This is typically to the terminal or a file. If there is an asterisk here, it will automatically write to the terminal. The “format” tells Fortran how to format the data when it is written. Following the closed parentheses, you list the item(s) to be written.

Confusingly, you can also write to variables. For example,

write (cmy,’(i4.4)’) my_id

“writes” the process rank my_id to the character variable cmy. In this case, this syntax is being used to convert the integer my_id to the string cmy prior to including that string in a filename.

To write to a file using Fortran, you begin by opening the file:

open(iud2,file="filename.D",form=’formatted’)

This opens a formatted file called “filename.D”, and assigns it the label “iud2”. Later, if a read or write statement writes to iud2, it will read from or write to this file. If the file does not exist, it will be created. If the file exists, it will be replaced. To read from a file, use the same syntax. If the file is supposed to exist, use the ’old’ status:

open(iud2,file="filename.D",form=’formatted’,status=’old’)

To write stuff, you need to use “FORMAT edit descriptors”. The symbols used are: w the total width of the field m the minimum number of digits produced on output d the number of digits to the right of the decimal point e the number of digits in the exponent part

Here are some examples:

i = 85 j = -764374683 r = 3.14159 6.3. SYNTAX 67

s = 93843.3847384

write (*,*) i, j, r, s! No format descriptors write(iuo,’(i10)’) i! Basic integer write(iuo,’(i10.5)’) i! Integer with minimum digits specified write(iuo,’(i3,i15)’) i, j! Two integers with different descriptors write(iuo,’(2i15)’) i, j! Two integers with the same descriptors write(iuo,’(f10.8)’) r! Basic float write(iuo,’(2f10.5)’) r, r**2! Two floats with the same descriptors write(iuo,’(e15.5)’) s! Float with exponent write(iuo,’(2e15.5)’) s, s**2! Two floats with exponents and same descriptors write(iuo,’(e15.5e5)’) s! One float with explicit exponent

This outputs

85 -764374683 3.14159012 93843.3828 85 00085 85 -764374683 85 -764374683 3.14159012 3.14159 9.86959 0.93843E+05 0.93843E+05 0.88066E+10 0.93843E+00005

Notice that on line 1, the number printed number “93843.3828” doesn’t even match the number assigned to the variable. Also notice that on line 6, three random numbers have been added to “3.14159”.

Often one wants to write a line that describes a variable and then gives its value. For example,

i = 85 r = 3.14159 write(iuo,’(4x,"i=",i2,",",4x,"r=",f7.5)’) i, r

The above outputs

i = 85, r = 3.14159

Note that the “4x” tells Fortran to put in 4 blank spaces.

To read a line from a file into a row in an array, use something like this

read(iud2,*) (myarray(row,col),col=1,n)

Here, the line in the file contains n items.

To read a column from a file into a row in an array, use something like this

do col=1,n read(iud2,*) myarray(row,col) enddo 68 CHAPTER 6. FORTRAN

Here, the file contains a column of n items, which is read into one row of an array.

To skip a line while reading in a file, use

read(iud2,*) where iud2 is the file you’re reading in.

Functions and Subroutines A function returns at most a single value and can be used in an expression like

avg = average(par, ...) where “average” is the function.

A subroutine, on the other hand, can return multiple values. A subroutine must be “called”, and these calls cannot be placed in an expression. The parameter list of a subroutine includes both the inputs to the subroutine and the outputs that are returned by the subroutine.

call subroutinename(input1, ..., output1, ...)

Sample Program Heres a sample program that uses a simple subroutine c c This program uses a subroutine to perform a calculation, c print it, and return it to this program. c program samplewithsubroutine implicit none integer i, returnvalue

parameter(i=10)

write (*,*)"This is the main program" write (*,*)"I am sending", i," to the subroutine"

call mysubroutine(i, returnvalue)

write (*,*)"This is the main program" write (*,*)"I have received", returnvalue, &" from the subroutine"

end

include’mysubroutine.f’

This program is contained in the file samplewithsubroutine.f. In the same directory, I have a file named mysubroutine.f with the following c c This subroutine prints to the screen whatever is passed to it c 6.4. MPI 69

subroutine mysubroutine(x, ret) implicit none integer x, ret

write (*,*)"This is the subroutine" write (*,*)"I have received the number", x

ret = x*x

write (*,*)"I have squared the number and will return it"

return

end

To run the program, use

gfortran samplewithsubroutine.f followed by

./a.out

The output to the screen is:

This is the main program I am sending 10 to the subroutine This is the subroutine I have received the number 10 I have squared the number and will return it This is the main program I have received 100 from the subroutine

6.4 MPI

MPI stands for “message passing interface”. It is what we use for parallel computing applica- tions. At the beginning of a program that uses MPI, you need the MPI header file.

include’mpif.h’

You also need this in any subroutines that use MPI.

In the main program, you initialize the MPI stuff with the lines

call mpi_init(ierr) call mpi_comm_rank(mpi_comm_world,my_id,ierr)

This starts child process threads until the number equals the number specified with the mpirun command. Each process gets a unique my_id number, and each process runs a version of the rest of the program.

The number of processors to be used is specified like mpirun -n 4 a.out when you run the mpirun command. The mpirun command starts the MPI parent process. When mpi_init(ierr) 70 CHAPTER 6. FORTRAN is called, it creates new child processes until the number of running processes equals the number specified when mpirun was called. Each child process then executes a separate version of the following program. The ierr is just the error return from the mpi_init routine.

The variable my_id gives the number of the current process. This is also called the “rank” of the process. The parent process has my_id=0. If your code depends on my_id, then you know that each version of the program (the different processes) is different. For example, the code within if (my_id.eq.0) then will only execute in the parent process and not in the child processes.

More info: http://condor.cc.ku.edu/~grobe/docs/intro-MPI.shtml Suppose you have a program that runs on multiple threads, but at some point in the program, you want to make sure that all processes have caught up to the same place. To do that, you simply add

call mpi_barrier(mpi_comm_world,ierr)

A call to the mpibarrier basically forces the program to wait until all the process threads have caught up to that point.

To close MPI, use

call mpi_finalize(ierr) Chapter 7

GnuPlot

7.1 Basic Command Line Plot

Gnuplot is a Linux command-line plotting solution.

To learn how to create a basic plot in Linux using gnuplot, create a textfile, called plot.dat with the following data in the following form

1 1 2 4 3 9 4 16 5 25 6 36

After saving and closing the file, type the following command-line

gnuplot --persist -e ’plot"plot.dat" using 1:2’ and hit enter. This tells gnuplot to make a plot of column 2 versus column 1 of plot.dat. The persist option tells gnuplot to keep the plot open for viewing after creating it. You should see a graph like the one below in a new window.

71 72 CHAPTER 7. GNUPLOT

7.2 Plot Files

Suppose you want to plot the following points:

0.401 0.513 0.402 0.589 0.403 0.590 0.404 0.665 0.405 0.695 0.406 0.756 0.407 0.777 0.408 0.800

Start by saving this data in a file like data.txt.

Next, create a new file like plot.plt, to hold your plotting commands: set title"Plot Title" set key bottom right set ylabel"Y-axis" set xlabel"X-axis" set xrange [0.400:0.409] set yrange [0.35:.95] plot’plot.txt’ using 1:2 title"Label" linewidth 3 pause -1

To create the plot, use the command line command gnuplot plot.plt

After running the command, the plot shown below should pop up in a new window. The pause -1 command tells gnuplot to leave this window open until you hit a key. To save an image, you can use that menu option in the gnuplot window.

Alternatively, instead of popping open the window to view the plot, you can send it directly to an image file by modifying your plot file. For example, the following plot file saves the plot to plot.eps instead of displaying it in a popup window. reset set term pos eps color enhanced defaultplex"Helvetica" 26 7.3. ERROR BARS 73 set size 1.5,1 set output’plot.eps’ set title"Plot Title" set key bottom right set ylabel"Y-axis" set xlabel"X-axis" set xrange [0.400:0.409] set yrange [0.35:.95] plot’plot.txt’ using 1:2 title"Label" linewidth 3

7.3 Error Bars

7.4 Commands plot’plot.txt’ using 1:2:3 title"Plot title" with errorbars linecolor 8 linetype 4 pointsize 2,\

You can also break the command over multiple lines to improve readibility: plot’plot.txt’\ using 1:2:3 \ title"Plot title"\ with errorbars \ linecolor 8 \ linetype 4 \ pointsize 2,\

You can also abbreviate the command as: plot’plot.txt’ u 1:2:3 t"Plot title" w e lc 8 lt 4 ps 2,\

7.5 Variable Attributes

Suppose you are creating a single plot from data in a text file. Typically, you set attributes like linecolor, linetype, and pointsize in your plotting command, and these attributes then apply to all of the points in the plot. However, suppose you want to highlight a specific point by making it red and leaving all of the other points black. Or suppose you want to make a few of the plotted points larger. You can do this using variable attributes, where instead of setting the attributes in the plotting command, you set them for each data point by adding additional columns to your text file.

In the example below, I use a different color for each plotted point.

I have the data file plot.txt:

0.401 0.513 0.020 1 0.402 0.589 0.015 2 0.403 0.590 0.020 3 0.404 0.665 0.014 4 0.405 0.695 0.017 5 0.406 0.756 0.013 6 0.407 0.777 0.011 7 74 CHAPTER 7. GNUPLOT

0.408 0.800 0.010 8

And the plot file: set title"Plot Title" set key bottom right set ylabel"Y-axis" set xlabel"X-axis" set xrange [0.400:0.409] plot’plot.txt’ u 1:2:3:4 t"Label" w e lc variable lt 4 ps 2 lw 2 pause -1

Notice that I am using four columns from the data file. The third column contains the error bars and the fourth column contains the linecolor. This produces the plot shown below: Chapter 8

MatLab

8.1 Installation

To install Matlab on a Linux system, download the Linux installer from their website. After extracting the installation files, install from the command line using

sudo ./install

After installing, you can run Matlab with the terminal command

matlab

Matlab will open a graphical user interface just like in Windows.

8.2 Miscellaneous

Use

>> clc to clear the workspace.

To use the last answer in a calculation, just refer to

>> ans

To change a to a fraction, write

>> format rat >> a

Everything after this point will be given in fractions. To change back, use

>> format short >> a

To get decimals with more decimal places, use 75 76 CHAPTER 8. MATLAB

>> format long >> a

Use a semi-colon at the end of your command to prevent the results from being displayed and cluttering up your window.

Be careful with the basic operators in MatLab. The command A/B denotes matrix division, whereas A./B is used for scalar division. Similarly, A∗B is for matrix multiplication and A.∗B is for element by element (i.e. scalar) multiplication. Similarly, AˆB is for raising a matrix A to a power B and A.ˆB is for raising the scalars to the power B. If you’re getting strange errors when trying to do calculations, you may have to add some periods.

8.3 Plotting

Regular 2D Functions To plot, you need to specify the independent values (i.e. the x-values), specify the function (i.e. y), and then issue the plot command. For example, the following code

>> x = 0:10; >> y = x; >> plot(x,y) gives a graph of y = x from x = 0 to x = 10.

For plots that aren’t straight lines, you’ll want to tell MatLab how often to sample the function. For example,

>> x = 0:1/100:2*pi; >> y = sin(x); >> plot(x,y) plots y = sin x from 0 to 2π sampling the function at intervals of 1/100.

The code

>> x = -10:0.1:10; >> y = power(x,2); >> plot(x,y) plots y = x2 from −10 to 10.

Fourier Series Below, we graph a periodic function defined as an infinite repetition to the left and right of the segment ( −1 −π < t < 0 f(t) = . 1 0 < t < π

For example, to plot a straight line from (−1, 0) to (2, 1), you would use the code

>> xx = [-1;2]; >> yy = [0;1]; 8.3. PLOTTING 77

>> plot(xx, yy,’black’)

To plot the black periodic function in the graph below, the same process was used, but for many more points.

The code below also shows how to plot multiple functions on the same graph using the “hold” command. It is used to plot the first term and the first four terms of the fourier series in addition to the periodic function shown above.

>> xx = [-4*pi -4*pi -3*pi -3*pi -2*pi -2*pi-pi-pi00 pi pi 2*pi 2*pi 3*pi 3*pi 4*pi;-4*pi -3*pi -3*pi -2*pi -2*pi-pi-pi00 pi pi 2*pi 2*pi 3*pi 3*pi 4*pi 4*pi]; >> yy = [0 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1;1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 0]; >> t = -4*pi:1/100:4*pi; >> y1 = (4/pi)*sin(t); >> y4 = (4/pi)* sin(t) + (4/(3*pi)) * sin(3*t) + (4/(5*pi)) * sin(5*t) + (4/(7*pi)) * sin(7*t); >> p1 = plot(xx, yy,’black’); >> hold Current plot held >> p2 = plot (t, y1,’red’); >> p3 = plot (t, y4,’blue’); >> legend([p2,p3],’1 Terms’,’4 Terms’);

The Fourier series for the function defined above is ∞ X 2 f(t) = b sin(nt); b = (1 − (−1)n). n n nπ n=1 A better plot of the function (and the code) is given below. The plot is of the first 15 terms of the Fourier series. Although the summation index goes from 1 to 30, every other term drops out, so there are only 15 terms in the plotted expansion.

Note: Plotting this high resolution (this many terms and this fine range) graph takes about 10 minutes or so.

>> syms n >> t = -4*pi:1/100:4*pi; >> b_n = (2/(n*pi))*(1-(-1)^n); >> s = b_n*sin(n*t); 78 CHAPTER 8. MATLAB

>> f = symsum(s,n,1,30); >> plot(t,f)

Integral Functions Suppose you want to plot a function containing an integral. For example, we want to plot the function 2 1 1 y = √ q du, π ˆ0 2 2 2 Φ 1 − u u sin 2 for values of Φ from 0 to 4. So each value of y is calculated by performing a definite integration from u = 0 to u = 1. To plot this in MatLab, we write

>> X = linspace(0,4); >> Y = (2/pi) * int((1./(sqrt(1-u^2) * sqrt(1-(sin(X/2)).^2 * u^2))),u,0,1); >> plot(X,Y) and our result is the graph 8.3. PLOTTING 79

3D Functions To plot a 3D function (i.e. a contour or surface plot), think of the x and y plane as forming a grid. At each point in this grid, the function z has some height. This is essentially how MatLab does it. To plot z = x2 + y2, which is a paraboloid, write

>> x = -10:0.1:10; >> y = -10:0.1:10; >> [X,Y] = meshgrid(x,y); >> Z = X.^2 + Y.^2; >> surf(Z)

With x = -10:0.1:10; and y = -10:0.1:10; you are defining the length and width of your grid as well as the density of the points on the grid. With the command [X,Y] = meshgrid(x,y);, you instruct MatLab to create the grid, and then you define your function Z = X.^2 + Y.^2; in terms of the meshgrid. Finally, you plot the function by writing surf(Z).

3D functions such as 3y f(x, y) = − , x2 + y2 + 1 result in contour or surface plots.

A simple way to do a surface plot of the above function is

>> [x,y] = meshgrid(-2:.1:2); >> z=-3*y./(x.^2+y.^2+1); >> surf(x,y,z)

The above code won’t work for a function like

f(x, y) = sin−1(x2 + y2 − 5), which is only defined in a narrow ring about the origin. To graph such a function, and any 3D function quickly, just use the code fmesh(@(x,y) asin(x.^2 + y.^2 - 5)) fmesh graphs on the region −5 ≤ x, y ≤ 5 by default. To graph in a larger region, use something like fmesh(@(x,y) (x+y)./(x-y),[-10 10 -10 10])

A plot showing the axes in the center of the graph. For example, to plot

>> [x,y] = meshgrid(-2:.1:2); >> z=-3*y./(x.^2+y.^2+1); >> surf(x,y,z) >> axis equal >> xl = xlim();% Get axis dimensions >> yl = ylim(); >> zl = zlim(); >> hold on; >> line(1.2*xl, [0,0], [0,0],’LineWidth’, 1,’Color’,’k’);% Add axes >> line([0,0], 1.2*yl, [0,0],’LineWidth’, 1,’Color’,’k’); >> line([0,0], [0,0], 1.2*zl,’LineWidth’, 1,’Color’,’k’); >> text(1.4*xl(2),0,0,’x’);% Add axis label 80 CHAPTER 8. MATLAB

>> text(0,1.4*yl(2),0,’y’); >> text(0,0,1.4*zl(2),’z’); >> axis off

This shows the graph

To plot the level curves instead of the surface plot, we can write:

>> [x,y]=meshgrid(-2:.1:2); >> z=-3*y./(x.^2+y.^2+1); >> [c,h] = contour(x,y,z,7);% Add7 level curves >> clabel(c,h)% Add labels to the curves >> axis equal >> xl = xlim();% Get axis dimensions >> yl = ylim(); >> hold on; >> line(1.2*xl, [0,0], [0,0],’LineWidth’, 1,’Color’,’k’);% Add axes >> line([0,0], 1.2*yl, [0,0],’LineWidth’, 1,’Color’,’k’); >> text(1.4*xl(2),0,0,’x’);% Add axis label >> text(0,1.4*yl(2),0,’y’); >> axis off

This shows the graph 8.3. PLOTTING 81

We can also combine the surface plot and the level curves using the code

>> [x,y]=meshgrid(-2:.1:2); >> z=-3*y./(x.^2+y.^2+1); >> [c,h] = contour(x,y,z,25); >> hold on >> surf(x,y,z) >> hold on >> axis equal >> xl = xlim(); >> yl = ylim(); >> zl = zlim(); >> hold on; >> line(1.2*xl, [0,0], [0,0],’LineWidth’, 1,’Color’,’k’); >> line([0,0], 1.2*yl, [0,0],’LineWidth’, 1,’Color’,’k’); >> line([0,0], [0,0], 1.2*zl,’LineWidth’, 1,’Color’,’k’); >> text(1.4*xl(2),0,0,’x’); >> text(0,1.4*yl(2),0,’y’); >> text(0,0,1.4*zl(2),’z’);

This shows the graph 82 CHAPTER 8. MATLAB

Vector Fields To plot a vector field like F~ = hx, yi, use

>> [x,y] = meshgrid(0:0.05:1,0:0.05:1); >> u = x; >> v = y; >> quiver(x,y,u,v) >> axis tight

8.4 Vectors

To define a row vector in Matlab enter the elements inside of square brackets like

>> v = [1 2 3]

To enter a column vector you can either enter it as

>> v = [1; 2; 3] or use the transpose of the row vector. The transpose is taken using the apostrophe, so you could also write the column vector as

>> v = [1 2 3]’

To get the dot product of two vectors u and v use

>> dot(u,v)

Since the dot product is commutative, their order doesn’t matter. Also, it doesn’t matter if your vectors are row vectors, column vectors, or one of each.

The cross product of two 3D vectors u and v is obtained with

>> cross(u,v)

Here, the order of u and v matters. 8.5. LINEAR ALGEBRA 83

To access the third element of vector v, use

>> v(3)

To get the first two elements of vector v, use

>> v(1:2)

You can scale a vector by multiplying it by a constant. For example, to scale v by 2, write

>> 2*v

If the dimensions of the vectors agree, you can also add and subtract them

>> u + v

To determine if a set of vectors is linearly independent, use rank. The rank of a matrix is the number of linearly independent columns in the matrix, so we create a matrix with our vectors and then calculate the rank of the matrix. For example, here we create two column vectors u and v which are clearly linearly independent since they are not multiples of each other. Then we find the rank of of the matrix formed by concatenating the two vectors.

>> u = [1 2 3]’; >> v = [1 2 -3]’; >> rank([u,v]) ans= 2

Our result is 2—the same as the number of vectors, so we know they are linearly independent.

8.5 Linear Algebra

Use square brackets to denote a matrix. Separate the elements in a row by spaces or commas and separate the rows with semi-colons. To enter a matrix like   1 2 3   A =  4 5 6 ,   6 7 8 enter

>> A = [1 2 3; 4 5 6; 6 7 8]

You can also define a matrix by concatenating vectors. For example, if you have three column vectors u, v, and w, all of the same size, you can define the matrix A using

>> A = [u v w]

You can also enter complex numbers as elements.

Following are a bunch of functions you can use 84 CHAPTER 8. MATLAB

>> 3*A% Multiplies every element inA by3 >> A*B% Multiplies matrixA by matrixB >> A + B% Adds matrixA andB >> A^2% Multiplies matrixA by itself >> det(A)% Gives the determinant ofA >> inv(A)% Gives the inverse ofA >> trace(A)% Gives the trace ofA >> transpose(A)% Gives the transpose ofA >> ctranspose(A)% Gives the conjugate transpose ofA >> A(2,3)% Gives the element in row 2, column3 of matrixA >> A(2,:)% Gives the second row of matrixA >> A(:,2)% Gives the second column of matrixA

To solve equations like A~x = ~b, we might combine the A and ~b in an augmented matrix and then obtain the reduced echelon form of the augmented matrix.

>> A = [1 2 4; 0 1 5; -2 -4 -3]; >> b = [-2;2;9]; >> rref([A b]) ans=

1 0 0 0 0 1 0 -3 0 0 1 1

The code above defines a 3 × 3 matrix A and a column vector b. The code rref([A b]) gives the reduced echelon form of the matrix formed by concatenating b onto A (i.e. creating an augmented matrix). The reduced echelon matrix is given as the answer, so the ~x that we are looking for is simply the last column of this matrix.

To find the eigenvalues and eigenvectors of a matrix A, use

>> A = [2 3;3 -6]; >> [v,d] = eig(A) v =

-0.3162 -0.9487 0.9487 -0.3162 d =

-7 0 0 3

The diagonal elements of matrix d are the eigenvalues and the columns of v are the eigenvectors. Keep in mind that eigenvectors come with arbitrary scalar multiples, so the exact eigenvectors given isn’t important provided that the ratios between the elements in any eigenvector are correct. 8.5. LINEAR ALGEBRA 85

QM Linear System Consider this set of equations involved in a quantum mechanics calculation:

 ˜ ˜  A = e−iKa Ceka + De−ka

 ˜ ˜  Bk = ke˜ −iKa Ceka − De−ka     ka˜ − ka˜ ka ka Ce 2 + De 2 = A cos + B sin 2 2     ka˜ − ka˜ ka ka kCe˜ 2 − kDe˜ 2 = −kA sin + Bk cos . 2 2 The goal is to eliminate A, B, C, and D, ending up with a single equation–a relationship between the different k’s. Doing this by hand is prohibitively messy and invariably leads to algebra errors. However, we can use MatLab to perform the brunt of the work.

With the following code, we can have MatLab do all the algebraic rearranging and give us the matrix form of the linear system. syms A k a B C K D KK eqn1 = A*cos(k*a/2) + B*sin(k*a/2) == C*exp(K*a/2) + D*exp(-K*a/2); eqn2 = K*C*exp(K*a/2) - K*D*exp(-K*a/2) == -k*A*sin(k*a/2) + B*k*cos(k*a/2); eqn3 = A == exp(-i*KK*a)*(C*exp(K*a) + D*exp(-K*a)); eqn4 = B*k == K*exp(-i*KK*a)*(C*exp(K*a) - D*exp(-K*a));

[R, S] = equationsToMatrix([eqn1, eqn2, eqn3, eqn4], [A, B, C, D])

Its output is

R =

[ cos((a*k)/2), sin((a*k)/2), -exp((K*a)/2), -exp(-(K*a)/2)] [ k*sin((a*k)/2), -k*cos((a*k)/2), K*exp((K*a)/2), -K*exp(-(K*a)/2)] [ 1, 0, -exp(K*a)*exp(-KK*a*1i), -exp(-K*a)*exp(-KK*a*1i)] [ 0, k, -K*exp(K*a)*exp(-KK*a*1i), K*exp(-K*a)*exp(-KK*a*1i)]

S =

0 0 0 0

If we command MatLab to solve the system of equations, we don’t get meaningful results. However, we know that in order to have a solution, the determinant of the matrix R must be 0. So we use simplify(det(R)) to get the determinant in simplified form.

2*K*k - K^2*exp((a*(K - KK*2i))/2)*sin((a*k)/2) + K^2*exp(-(a*(K + KK*2i))/2)*sin((a*k)/2) + k^2*exp((a*(K - KK*2i))/2)*sin((a*k)/2) - k^2*exp(-(a*(K + KK*2i))/2)*sin((a*k)/2) + 2*K*k*exp(-KK*a*2i) - 2*K*k*exp((a*(K - KK*2i))/2)*cos((a*k)/2) - 2*K*k*exp(-(a*(K + KK*2i))/2)*cos((a*k)/2)

Our result is not very readable, so we open a MatLab Live Script file, add the code and run it to see the output in standard mathematical notation. We know the output must be equal to 86 CHAPTER 8. MATLAB zero, so we now work in simplifying it by hand. In the end, we get

! ! k˜2 − k2 ka˜ ka ka˜ ka cos (Ka) = sinh sin + cosh cos . 2kk˜ 2 2 2 2

8.6 Statistics n choose k is calculated using nchoosek(n,k). For example

>> nchoosek(10,2) ans=

45

Factorials are calculated using factorial(n). For example

>> factorial(10) ans=

3628800

To list all permutations of a set of objects, enter the objects as a vector and use perms. For example, the code

>> v = [1 2 3]; >> perms(v) lists all the permutations of 1, 2, and 3. You can also permute the letters of a string using

>> v = [‘abcd’]; >> perms(v)

To list all the combinations of a set of objects v takem k at a time, use combnk(v,k). For example,

>> v = [1 2 3 4 5]; >> combnk(v,2)

8.7 Numerical Differentiation

The code below, takes the first and second derivative of f(x) = x5 and plots all three. h = 0.001;% step size X = -1:h:1;% domain f = X.^5;% range(i.e. your function) Y = diff(f)/h;% first derivative Z = diff(Y)/h;% second derivative plot(X(:,1:length(Y)),Y,’r’,X,f,’b’, X(:,1:length(Z)),Z,’k’) 8.8. INTEGRATION 87

8.8 Integration

For indefinite integration, use the command int(expr, var). For example, to integrate

x2 dx, ˆ you would use

>> syms x >> int(x^2, x) ans= x^3/3

For the definite integral 1 x2 dx, ˆ0 use

>> syms x >> int(x^2, x, 0, 1) ans=

1/3

Line Integrals along Vector Fields Line integrals are a little trickier, to integrate

F~· d~r, ˆ given the vector field F~ = hy, 2xi. We want to integrate over each of the three paths shown in the image below.

y

(1, 1) a

b

x c

The first path can be parametrized as ~r = (x, y) = (1 − cos t, sin t),

π from t = 0 to t = 2 , which defines a quarter circle centered at (1, 0). In MatLab, we write and get the results To do that, we use 88 CHAPTER 8. MATLAB

>> syms x y t >> F = [y, 2*x]; >> r = [1 - cos(t), sin(t)]; >> Fpar = subs(F,[x,y],r); >> g = inline(vectorize(sum(Fpar.*diff(r,t))),’t’); >> quad(g,0,pi/2) ans=

549/452

The first line establishes the symbolic variables we need. The second line gives the vector function, and the third line gives the parametrized curve. The fourth line parametrizes F , and the fifth line gives the necessary dot product.

Path b we can parametrize as

~r = (x, y) = (t, t), for 0 ≤ t ≤ 1, and in MatLab we get

>> syms x y t >> F = [y, 2*x]; >> r = [t, t]; >> Fpar = subs(F,[x,y],r); >> g = inline(vectorize(sum(Fpar.*diff(r,t))),’t’); >> quad(g,0,1) ans=

3/2

For path c, we use the same process but break the integral into two pieces—one over the segment ~r = ht, 0i, for 0 ≤ t ≤ 1, and the other over ~r = h1, ti, for 0 ≤ t ≤ 1.

Find F~· d~r, ˆ over the path ~r = hcos t, sin ti, π ~ 2 from t = 0 to t = 2 given the vector field F = hx , −xyi. >> syms x y t >> F = [x^2, -x*y]; >> r = [cos(t), sin(t)]; >> Fpar = subs(F,[x,y],r); >> g = inline(vectorize(sum(Fpar.*diff(r,t))),’t’); >> quad(g,0,pi/2) ans= 8.9. VECTOR DIFFERENTIAL OPERATORS 89

-2/3

Numerical Integration The following code numerically calculates the integral

1 x2 dx. ˆ−1 h = 0.001;% step size X = -1:h:1;% domain Y = X.^2;% range(i.e. your function) trapz(X,Y)% integrate

What if you want a derivative inside an integral? In the case here, we are calculating

1 df f dx. ˆ−1 dx where 2 f = x x − 1 .

The derivative and the resulting integral are very messy to calculate, so we do it numerically with the following code. format long h = 0.0000001;% step size X = -1:h:1;% domain f = X.*abs(X.^2 - 1);% range(i.e. psi(x)) Y = diff(f)/h;% first derivative Z = diff(Y)/h;% second derivative Z = [Z 1 1];% lost2 elements when taking derivatives F = f.*Z;% function to integrate E_1 = trapz(X, F)% estimation of E_1

8.9 Vector Differential Operators

Gradient The following code plots the gradient of the function f. syms x y f = -3*y./(x.^2+y.^2+1);% The scalar field g = gradient(f, [x, y]) [X, Y] = meshgrid(-2:.5:2,-2:.5:2);% Plot limits G1 = subs(g(1), [x y], {X,Y}); G2 = subs(g(2), [x y], {X,Y}); quiver(X, Y, G1, G2) 90 CHAPTER 8. MATLAB

The following code plots the gradient of the same function overlayed on level curves for the function. syms x y f = -3*y./(x.^2+y.^2+1);% The scalar field g = gradient(f, [x, y]) [X, Y] = meshgrid(-2:.5:2,-2:.5:2);% Plot limits G1 = subs(g(1), [x y], {X,Y}); G2 = subs(g(2), [x y], {X,Y}); quiver(X, Y, G1, G2)% Plot gradient vectors hold on [x,y]=meshgrid(-2:.1:2); z=-3*y./(x.^2+y.^2+1); contour(x,y,z,7);% Plot7 level curves axis equal xl = xlim();% Get axis dimensions yl = ylim(); hold on; line(1.2*xl, [0,0], [0,0],’LineWidth’, 1,’Color’,’k’);% Add axes line([0,0], 1.2*yl, [0,0],’LineWidth’, 1,’Color’,’k’); text(1.3*xl(2),0,0,’x’);% Add axis label text(0,1.3*yl(2),0,’y’); axis off 8.9. VECTOR DIFFERENTIAL OPERATORS 91

Divergence To calculate the divergence of a vector field, use the notation divergence(U, V) where U is the vector field and V is the vector you’re finding the divergence with respect to. Typically, V is just your ordered set of coordinates.

For example, if you gave a vector field V~ (x, y, z) = x2 xˆ + y3 yˆ + z4 zˆ, then the divergence can be calculated as

>> syms x y z >> divergence([x^2, y^3, z^4],[x,y,z]) ans=

3*y^2 + 4*z^3 + 2*x

If U~ = hx sin y, cos y, xyi, then Div U~ = 0 is found as

>> syms x y z >> U = [x*sin(y), cos(y), x*y]; >> V = [x,y,z]; >> divergence(U,V) ans=

0

Curl To calculate the curl of a vector field use the notation curl(U,V) where U is the vector field and V is the vector you’re finding the curl with respect to. Typically, V is just your ordered set of coordinates.

For example, if you gave a vector field V~ (x, y, z) = x2 xˆ + y3 yˆ + z4 zˆ, then the curl can be calculated as

>> syms x y z >> curl([x^2, y^3, z^4],[x,y,z]) 92 CHAPTER 8. MATLAB

ans=

0 0 0

If U~ = hx sin y, cos y, xyi, then curl U~ = hx, −y, −x cos yi is found as

>> syms x y z >> U = [x*sin(y), cos(y), x*y]; >> V = [x,y,z]; >> curl(U,V) ans=

x -y -x*cos(y)

8.10 Differential Equations

The following code plots a direction field for the differential equation

dy = xy, dx and a specific solution

1 x2 y = 0.1e 2 .

>> [x,y]=meshgrid(-5:.5:5,-2:.5:8); >> dy = x.*y; >> dx = ones(size(dy)); >> dyu = dy./sqrt(dx.^2+dy.^2); >> dxu = dx./sqrt(dx.^2+dy.^2); >> quiver(x,y,dxu,dyu) >> hold on >> r = -5:1/100:5; >> s = 0.1*exp(0.5*r.^2); >> plot(r,s)

The plot shown below is the output after some adjustments were made in the plot editor. 8.11. QUANTUM MECHANICS 93

8.11 Quantum Mechanics

Variational Method Suppose we want to approximate the energy of the first excited state of the infinite square well by using the test wavefunction 2 2 p |ψi = x x − L , where p is a parameter to be optimized.

The code below computes the estimation

E1 ≈ hψ|H|ψi , for a range of values for p. We take L = 1 and treat the infinite square well as being in the region −1 < x < 1.

After testing all the given values of p it prints the matrix containing our p’s in the first columns and our E1 in the second column. The lowest value of E1 that we can find, is our best approximation of the actual energy of the first excited state of the infinite square well.

% % The for loop testsa range of values forp, computing % the normalization constant|A|^2 and the estimate of the % energy of the first excited state= E_1. % format long soln = [];% solution matrix for p = [0.8:1/100:2.0]% range ofp h = 0.0000001;% step size X = -1:h:1;% domain f = X.*abs(X.^2 - 1).^p;% range(i.e. psi(x)) Y = diff(f)/h;% first derivative Z = diff(Y)/h;% second derivative Z = [Z 1 1];% lost2 elements when taking derivatives ff = f.*f; A2 = 1/trapz(X, ff);% normalization constant|A|^2 F = -(0.5).*A2.*f.*Z;% function to integrate E_1 = trapz(X, F);% estimation of E_1 94 CHAPTER 8. MATLAB

soln = [soln; p E_1];% add to solution matrix end soln% print solution matrix Chapter 9

Mathematica

9.1 The Basics

Enter a function like so to differentiate it.

D[x^n, x]

To define a function and then differentiate it, use the following syntax: f[x\_] := Sin[x] + x^2 D[f[x],x]

Notice the underscore character that is used when defining a function.

Note that all named functions start with an uppercase letter.

To type a subscript, use CTRL plus the negative sign.

9.2 Quantum Mechanics

Suppose you have the wavefunction

ψ(θ, φ) = C1Y11(θ, φ) + C0Y10(θ, φ) + C−1Y1−1(θ, φ), where Y`,m are the spherical harmonics. In Mathematica, the spherical harmonic functions are referenced by SphericalHarmonicY[`, m, θ, φ]. To define the above function in Mathematica, we would write

\[Psi][\[Theta]\_, \[Phi]\_] := Subscript[C, 1] SphericalHarmonicY[1, 1, \[Theta], \[Phi]] + Subscript[C, 0] SphericalHarmonicY[1, 0, \[Theta], \[Phi]] + Subscript[C, -1] SphericalHarmonicY[1, -1, \[Theta], \[Phi]]

Our goal is to obtain Lxψ(θ, φ) where Lx is the x-component of the angular momentum operator. This involves a lot of algebra, so we use Mathematic to symbolically manipulate everything.

The next step is to define the spherical transformation equations x := r Sin[\[Theta]] Cos[\[Phi]] y := r Sin[\[Theta] ] Sin[\[Phi]] z := r Cos[\[Theta]] 95 96 CHAPTER 9. MATHEMATICA

∂ Next, we define the operator ∂x . The partial derivative with respect to x in spherical coordinates is ∂ ∂ 1 ∂ sin φ ∂ = sin θ cos φ + cos θ cos φ − . ∂x ∂r r ∂θ r sin θ ∂φ We want to define an operator in Mathematica. Note the required “&” at the end of the line partialx := Sin[\[Theta]] Cos[\[Phi]]D[#, r] + Cos[\[Theta]] Cos[\[Phi]] (1/r)D[#, \[Theta]] - Sin[\[Phi]]/(r Sin[\[Theta]])D[#, \[Phi]] &

To apply this operator to a function, we just use partialx[\[Psi][\[Theta], \[Phi]]]

∂ ∂ Similarly, to define ∂y and ∂z , we use partialy := Sin[\[Theta]] Sin[\[Phi]]D[#, r] + Cos[\[Theta]] Sin[\[Phi]] (1/r)D[#, \[Theta]] + Cos[\[Phi]]/(r Sin[\[Theta]])D[#, \[Phi]] & partialz := Cos[\[Theta]]D[#, r] - (Sin[\[Theta]]/r)D[#, \[Theta]] &

The x-component of the angular momentum operator is

 ∂ ∂  L = −i y − z , x ~ ∂z ∂y and to compute this, we use the code

-I \[HBar] (y partialz[\[Psi][\[Theta], \[Phi]]] - z partialy[\[Psi][\[Theta], \[Phi]]])

After simplifying, we get the result

1r 3 √ √  2C cos θ − 2iC sin θ sin φ + 2C cos θ . 4 π ~ −1 0 1