Code

Here you can find all of the code samples from A Student’s Guide to Python for Physical Modeling. The samples are available in three formats:

Some of the samples are drawn directly from the text. Others have been created to illustrate a point or technique. README.txt contains a description of all files in the folder.

These code samples are distributed under the BSD license. Be sure to read LICENSE.txt before using any of the code samples.

This Web page contains the HTML file. If you already know how to use the files, you can Jump to The Index.

Using the files

Please read LICENSE.txt before using any of the code samples.

README.txt contains a brief description of all the available files.

All of the .py files and the plain text code has been tested with Python 3.6. Most programs also run correctly with Python 2.7. However, if you are using Python 2, you should execute the following two commands before running the programs to ensure they perform as intended:

from __future__ import division, print_function
input = raw_input

Two of the scripts, perrin.py and import_text.py, load data files. These data files are included in code_samples.zip and data_sets.zip. They should be copied into the current working directory before executing the scripts.

Code Archive

You can download a zipped folder full of code samples by following this link:

code_samples.zip

The link above will take you to a Google drive Web page where you can download a file called code_samples.zip. To save this file to your computer, click on the Download icon at the top of the page. This is a horizontal bar with a downward-pointing arrow above it.

If you click on code_samples.zip you will be able to see the folders it contains, and you can look inside some of these. However, you will not be able to download any files this way. You must download the entire archive by clicking on the Download icon.

Once you unzip the downloaded file, you should find two folders called code/ and jupyter_notebooks. Each folder contains about 40 Python programs, a couple data files used by the Python files, and two files called LICENSE.txt and README.txt. code/ contains plain text source code. jupyter_notebooks/ contains the same code samples as Jupyter notebooks.

Text File

You can download a single text file that contains all of the code samples by following this link:

code_samples.txt

The link above will take you to a Google drive Web page where you can download a file called code_samples.txt. To save the file to your computer, click on the Download icon at the top of the page. This is a horizontal bar with a downward-pointing arrow above it.

code_samples.txt contains the text of about 40 Python programs, which can be copied and pasted into the text editor of your choice. (This is not a Python script or module. Trying to execute code_samples.txt with Python will result in an error.)

To use this file, first locate the file name you are looking for. Then, use your mouse to select all of the text between lines of asterisks. For example,

***************************************************************************
string_format.py
***************************************************************************

COPY ALL TEXT IN THIS REGION

***************************************************************************
string_percent.py
*************************************************************************** 
...

After you copy and paste this text into your editor, you should be able to run the program with a Python interpreter.

HTML File

On this page, you will find the text of about 40 Python programs, which can be copied and pasted into the text editor of your choice.

If you prefer to work offline, you can save the HTML file that contains the index and code samples to your own computer:

code_samples.html

Just click on the link of the file name you are looking for. Then, use your mouse to select all of the text between lines of asterisks. For example,

***************************************************************************
string_format.py
***************************************************************************

COPY ALL TEXT IN THIS REGION

***************************************************************************
string_percent.py
*************************************************************************** 
...

After you copy and paste this text into your editor, you should be able to run the program in a Python interpreter. Your browser’s “Back” button will return you to the top of this page after you follow a link.

Long lines of code may be wrapped in your browser, but they should paste correctly into your text editor.






Index

HIVseries.csv
LICENSE.txt
README.txt
average.py
branching.py
contour.py
convolution.py
fancy_plot.py
for_loop.py
g26perrindata.npy
gradient.py
graph_modifications.py
heatmap.py
histogram.py
html_movie.py
import_text.py
legend.py
line3d.py
matrix_inversion.py
measurements.py
name_collision.py
nesting.py
parametric_oscillator.py
perrin.py
print_write.py
projectile.py
quadrature.py
quiver.py
random_walk.py
rotate.py
save_load.py
scope.py
shading.py
simple_oscillator.py
simple_plot.py
solve_ode.py
streamlines.py
string_format.py
string_percent.py
subplots.py
surface.py
surprise.py
sympy_examples.py
vectorize.py
vortex.py
walker.py
waves.py
while_loop.py









































Source

***************************************************************************
HIVseries.csv
***************************************************************************

0, 1.061e+05
0.0831, 93240
0.1465, 1.6672e+05
0.2587, 1.5378e+05
0.4828, 1.188e+05
0.7448, 1.169e+05
0.9817, 1.0957e+05
1.2563, 1.1135e+05
1.4926, 74388
1.7299, 83291
1.9915, 66435
3.0011, 35408
4.0109, 21125
5.009, 20450
5.9943, 15798
7.0028, 4785.2






***************************************************************************
LICENSE.txt
***************************************************************************

Copyright (c) 2014, Jesse M. Kinder and Philip C. Nelson
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the authors nor the names of other contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL JESSE M. KINDER OR PHILIP C. NELSON BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

================================================================================
Additional license information for html_movie.py:
    html_movie.py was adapted from the scitools module created by Hans Petter
    Langtangen.  The scitools license is reproduced below.
================================================================================
Copyright (c) 2007-2009, Hans Petter Langtangen <hpl@simula.no> and
Simula Resarch Laboratory.

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met: 

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the
      distribution. 

    * Neither the name of Simula Research Laboratory nor the names of
      its contributors may be used to endorse or promote products
      derived from this software without specific prior written 
      permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.






***************************************************************************
README.txt
***************************************************************************

Use of these code fragments is subject to the terms of LICENSE.txt.

CONTENTS:
------------------------------------------------------------------------- 
string_format.py
------------------------------------------------------------------------- 
Illustrate string formatting using the .format() method.

------------------------------------------------------------------------- 
string_percent.py
------------------------------------------------------------------------- 
Illustrate string formatting using the % method.

------------------------------------------------------------------------- 
for_loop.py
------------------------------------------------------------------------- 
Use a for loop to generate multiple solutions to the quadratic equation.

This script illustrates the funamental form of a for loop.  For alternate
solutions to the same problem, see while_loop.py and vectorize.py.

------------------------------------------------------------------------- 
while_loop.py
------------------------------------------------------------------------- 
Use a while loop to generate multiple solutions to the quadratic equation.

For alternate solutions to the same problem, see for_loop.py and
vectorize.py.

------------------------------------------------------------------------- 
vectorize.py
------------------------------------------------------------------------- 
Use vectorized operations to generate multiple solutions to the quadratic
equation.

For alternate solutions to the same problem, see for_loop.py and
while_loop.py.

------------------------------------------------------------------------- 
projectile.py
------------------------------------------------------------------------- 
Calculate how long an object is in the air when thrown from a spcified
height with a range of initial speeds assuming constant acceleration due
to gravity:
    0.5 * g * t**2 - v0 * t - y0 = 0

This script illustrates good coding practice in the solution of a simple
problem: parameters with descriptive names, comments, whitespace, and
blocking with '#%%' for debugging in Spyder.

-------------------------------------------------------------------------
branching.py
------------------------------------------------------------------------- 
This script illustrates branching with the use of multiple conditional
statements:
    if <condition1>:
        ...
    elif <condition2>:
        ...
    else:
        ...

------------------------------------------------------------------------- 
nesting.py
------------------------------------------------------------------------- 
Use nested for loops to fill a two-dimensional array of values.

This script illustrates "nesting"---one for loop inside of another.

------------------------------------------------------------------------- 
import_text.py
------------------------------------------------------------------------- 
Load data from a text file by reading the file line by line.

This script reads in data from a text file and stores it in a NumPy array.
It can be adapted to load data from files that are difficult or impossible
to load with NumPy's np.loadtxt function.

------------------------------------------------------------------------- 
save_load.py
------------------------------------------------------------------------- 
Save array data using NumPy's available methods, then load saved data.

This script demonstrates the various methods of saving and loading data
using NumPy arrays.

------------------------------------------------------------------------- 
perrin.py
------------------------------------------------------------------------- 
Generate figure displaying Perrin's experimental data on Brownian motion.
This script requires the data set 04brownian/g26perrindata.npy.

The script illustrates loading and plotting a data set and includes
LaTeX formatting of axis labels and grid lines.

You must copy g26perrindata.npy into the current folder to run the script.

------------------------------------------------------------------------- 
print_write.py
------------------------------------------------------------------------- 
Write same data to a file and print to display.

This script illustrates the similarites between writing to a text file and
printing to the screen.

------------------------------------------------------------------------- 
simple_plot.py
------------------------------------------------------------------------- 
Create and display a basic plot.

------------------------------------------------------------------------- 
graph_modifications.py
------------------------------------------------------------------------- 
This script creates a simple plot with two lines, then modifies several
features of the plot, including axis labels, labels and legend, line
style, tick labels, and title.

------------------------------------------------------------------------- 
line3d.py
------------------------------------------------------------------------- 
Create a three-dimensional parametric plot.

This script demonstrates how to create three-dimensional plots using the
Axes3D method from the mpl_toolkits.mplot3d module.  See also surface.py.

------------------------------------------------------------------------- 
subplots.py
------------------------------------------------------------------------- 
Create four plots in the same figure.

This script demonstrates PyPlot's subplot method, which can be used to
display several plots side-by-side in the same figure.

------------------------------------------------------------------------- 
rotate.py
------------------------------------------------------------------------- 
Define function to rotate a vector in two dimensions.

------------------------------------------------------------------------- 
average.py
-------------------------------------------------------------------------
Compute and return the cummulative average of an array.

This script illustrates the principles of functional programming.

------------------------------------------------------------------------- 
histogram.py
-------------------------------------------------------------------------
Create histograms of random numbers.

This script illustrates how to use NumPy and PyPlot to create histograms
and bar plots.

------------------------------------------------------------------------- 
contour.py
-------------------------------------------------------------------------
Create a labeled contour plot.

This script illustrates how to generate a grid of coordinates for contour
and surface plots.  It also demonstrates some options of plt.contour and
shows how to label contour lines.

------------------------------------------------------------------------- 
matrix_inversion.py
------------------------------------------------------------------------- 
Invert a simple matrix to solve a system of linear equations.

This script illustrates the use of a special method from the SciPy linear
algebra library, scipy.linalg.

------------------------------------------------------------------------- 
quadrature.py
------------------------------------------------------------------------- 
Integrate two functions using quad.

This script demonstrates numerical integration using the quad method of
scipy.integrate.  The first function is a built-in NumPy funciton whose
integral can be computed with pencil and paper for comparison.  The second
is a user-defined function.

------------------------------------------------------------------------- 
simple_oscillator.py
------------------------------------------------------------------------- 
Define function to use in solution of differential equation for a simple
harmonic oscillator.

This script illustrates how to write a function that generates the array
required to integrate a second-order ordinary differential equation.  It
is imported and used in solve_ode.py.

------------------------------------------------------------------------- 
solve_ode.py
------------------------------------------------------------------------- 
Solution of ODE for harmonic oscillator.

This script imports the function F(y,t) in simple_oscillator.py then uses
the odeint method of scipy.integrate to solve the ordinary differential
equation defined by F(y,t).

------------------------------------------------------------------------- 
parametric_oscillator.py
------------------------------------------------------------------------- 
Define a parametric function that accepts 4 parameters then integrate it
using odeint.

This script illustrates two methods for using scipy.integrate's odeint
methods to integrate a function that accepts more than two parameters.

------------------------------------------------------------------------- 
quiver.py
------------------------------------------------------------------------- 
Create a quiver plot.

This script illustrates the use of PyPlot's quiver method.

------------------------------------------------------------------------- 
gradient.py
------------------------------------------------------------------------- 
Calculate and display the gradient of a two-dimensional Gaussian.

This script illustrates the use of NumPy's gradient function and
demonstrates how to display a vector field.  It displays the gradient as a
quiver plot superimposed on a filled contour plot of the Gaussian.

------------------------------------------------------------------------- 
streamlines.py
------------------------------------------------------------------------- 
Create streamlines from a vector field.

This script demonstrates the use of PyPlot's streamplot method for
visualizing solutions to a differential equation defined by a vector
field.

------------------------------------------------------------------------- 
walker.py
------------------------------------------------------------------------- 
Make a movie out of the steps of a two-dimensional random walk.

This script demonstrates the use of the FuncAnimation method of
Matplotlib's animation module to create a movie.  If ffmpeg or mencoder is
installed on this computer, the script will save the movie to an mp4 file.

------------------------------------------------------------------------- 
html_movie.py
------------------------------------------------------------------------- 
Module to generate an HTML document from a collection of images.  When
viewed in a Web browser, the document will display a movie whose frames
are the individual images.

This module is adapted from the scitools library developed by Hans Petter
Langtangen.

------------------------------------------------------------------------- 
waves.py
------------------------------------------------------------------------- 
Create an HTML animation of a moving Gaussian waves.

This script illustrates a method for combining a series of plots into an
animation using HTML and Javascript.  It uses the html_movie.py module,
which is  adapted from the scitools library developed by Hans Petter
Langtangen.

------------------------------------------------------------------------- 
sympy_examples.py
------------------------------------------------------------------------- 
Demonstrate some useful methods available in the SymPy module.

Python may complain about undefined variables if you attempt to run this
script.  init_session() defines several variables, but Python may not be
aware of this.  It is better to run the commands one at a time from the
command line.

------------------------------------------------------------------------- 
convolution.py
------------------------------------------------------------------------- 
This script creates an eLoG (elongated Laplacian of Gaussian) filter that
emphasizes long, vertical lines in a figure.  The effect of the filter is
demonstrated on a plus sign.

------------------------------------------------------------------------- 
scope.py
-------------------------------------------------------------------------
Demonstrate Python's rules of scope.

------------------------------------------------------------------------- 
name_collision.py
-------------------------------------------------------------------------
Illustrate how Python's rules of scope prevent name collisions.

------------------------------------------------------------------------- 
fancy_plot.py
-------------------------------------------------------------------------
Add a title and axis labels to a simple plot.

------------------------------------------------------------------------- 
legend.py
-------------------------------------------------------------------------
Create a plot with a legend to distinguish multiple curves.

------------------------------------------------------------------------- 
measurement.py
------------------------------------------------------------------------- 
Functions to calculate distance between points using different metrics.

This script illustrates the fundamental form of user-defined functions as
well as keyword arguments and default values.

------------------------------------------------------------------------- 
random_walk.py
------------------------------------------------------------------------- 
Monte Carlo simulation of a two-dimensional random walk.

This script illustrates the use of a random number generator to create a
time series for a random walk.

------------------------------------------------------------------------- 
surface.py
------------------------------------------------------------------------- 
Create a three-dimensional surface plot.

This script demonstrates how to create three-dimensional plots using the
Axes3D method from the mpl_toolkits.mplot3d module.  See also line3d.py.

------------------------------------------------------------------------- 
surprise.py
------------------------------------------------------------------------- 
This script will create a familar but interesting image.
It may take about a minute to run.






***************************************************************************
average.py
***************************************************************************

# average.py
# -------------------------------------------------------------------------
# Compute and return the cummulative average of an array.
# ------------------------------------------------------------------------- 
import numpy as np

def running_average(x):
    """
    Return cummulative average of an array.
    """
    y = np.zeros(len(x))                    # empty array to store result
    current_sum = 0.0                       # running sum of elements of x
    for i in range(len(x)):
        current_sum += x[i]                 # increment sum
        y[i] = current_sum / (i + 1.0)      # update running average
    return y






***************************************************************************
branching.py
***************************************************************************

# branching.py (Python 3.6)
"""
This script illustrates branching.
"""
import numpy as np

for trial in range(5):
    userInput = input('Pick a number: ')
    userNumber = float(userInput)
    if userNumber < 0:
        print('Square root is not real.')
    else:
        print('Square root of {} is {:.4f}.'.format(userNumber, np.sqrt(userNumber)))
    userAgain = input('Another [y/n]? ')
    if userAgain != 'y':
        break

if trial == 4:
    print('Sorry, only 5 per customer.')
elif userAgain == 'n':
    print('Bye!')
else:
    print('Sorry, I did not understand that.')






***************************************************************************
contour.py
***************************************************************************

# contour.py
# -------------------------------------------------------------------------
# Create a labeled contour plot.
# ------------------------------------------------------------------------- 
import numpy as np
import matplotlib.pyplot as plt

#%% Create a grid of x and y coordinates
x_vals = np.linspace(-3, 3, 21)
y_vals = np.linspace(0, 10, 11)
X, Y = np.meshgrid(x_vals, y_vals)

#%% Generate function values. 
Z = np.cos(X) * np.sin(Y)

#%% Plot and label contours.
plt.figure()
cs = plt.contour(X, Y, Z, 10, linewidths=3, colors='k')
plt.clabel(cs,fontsize=10)
plt.show()






***************************************************************************
convolution.py
***************************************************************************

# convolution.py
# -------------------------------------------------------------------------
# This script creates an eLoG (elongated Laplacian of Gaussian) filter that
# emphasizes long, vertical lines in a figure.  The effect of the filter is
# demonstrated on a plus sign.
# ------------------------------------------------------------------------- 
import numpy as np
import matplotlib.pyplot as plt
import scipy.ndimage as sim

#%% Create a grid of points for the Gaussian filter.
v = np.arange(-25, 26)
X, Y = np.meshgrid(v, v)

#%% Create elongated Gaussian filter, apply Laplacian.
gauss_filter = np.exp(-0.5*(X**2/2 + Y**2/45))
laplace_filter = np.array( [[0, -1, 0], [-1, 4, -1], [0, -1, 0]])
combined_filter  = sim.convolve(gauss_filter, laplace_filter)

#%% Create a plus sign '+' to demonstrate effect of filter.
plus = np.zeros((51, 51))
plus[23:28, 25] = 1.0
plus[25, 23:28] = 1.0

plt.figure()
plt.imshow(plus)
plt.gray()

#%% Apply filter to '+' and display resulting image.
#   Use vmin/vmax to emphasize features within a restricted range of intensity.
cplus = sim.convolve(plus, combined_filter)

plt.figure()
plt.imshow(cplus, vmin=0, vmax=0.5*cplus.max())
plt.gray()

plt.show()






***************************************************************************
fancy_plot.py
***************************************************************************

# fancy_plot.py
# -------------------------------------------------------------------------
# Add a title and axis labels to a simple plot.
# ------------------------------------------------------------------------- 
import numpy as np
import matplotlib.pyplot as plt

x_min, x_max = -4, 4
num_points = 51
x_list = np.linspace(x_min, x_max, num_points)
y_list = x_list**2

plt.figure()
plt.plot(x_list, y_list, 'r', linewidth=3)

ax = plt.gca()
ax.set_title("A Second Order Polynomial", fontsize=16)
ax.set_xlabel("$x$", fontsize=24)
ax.set_ylabel("$y = x^2$", fontsize=24)

plt.show()






***************************************************************************
for_loop.py
***************************************************************************

# for_loop.py
# -------------------------------------------------------------------------
# Use a for loop to generate multiple solutions to the quadratic equation.
# ------------------------------------------------------------------------- 
import numpy as np

b, c = 2, -1
for a in np.arange(-1, 2, 0.3):
    x = (-b + np.sqrt(b**2 - 4*a*c)) / (2*a)
    print("a= {:.4f}, x= {:.4f}".format(a,x))






``` *************************************************************************** g26perrindata.npy ***************************************************************************

?NUMPY

No comments:

Post a Comment

Thank you for your input!
To avoid duplication, spam, and inappropriate content, we will review comments before posting them.


— Jesse & Phil