Open In Colab

Geophysics Lab 1: Intro to Python#

Name: Firstname Lastname

If you don’t put your name in both the spot above AND the filename, you will not receive a grade for this lab. Click this cell to add your name, run the cell when you’re done.

📄 Lab Instructions: Lab1-Instructions-sp26.pdf

# run this cell to import the packages needed to complete this lab:
import numpy as np               # more on numpy here:       https://numpy.org/doc/stable/user/absolute_beginners.html
import matplotlib.pyplot as plt  # more on matplotlib here:  https://matplotlib.org/stable/users/explain/quick_start.html

Section 1: Python for babies#

This section will focus on the most basic use of python as a computational tool. There are three questions at the end of this section for you to answer. Let’s get started!

Many basic commands are available in Python, including arithmetic functions. For example, type 2+2 into a code cell and press SHIFT+ENTER.

2+2 

Arithmetic operators are + for addition, - for subtraction, * for multiplication, and / for division. Raising a value to a power is accomplished by using ** (e.g. 3**2).

Type a=2 into the next cell. This will assign the value 2 to the variable a, which will hold this value until it is reassigned. To reassign a, type a=3 in the subsequent cell.

a = 2 
a = 3 # you can use the pound sign to makes comments, for instance: what a represents in your code, and what the units of a are

Assign a value to b. Now type c = a+b and Python will calculate the value of c. Note that Python will not print out the result of c automatically unless it is told to do so. To see the value of c, type print(c).

b = 4
c = a + b
c # typing the variable alone will print its value below the cell

There are several kinds of variables in Python. Numbers can be integers, like a, whole numbers without a decimal point. Numbers designated as float have a decimal value. For computational purposes, float numbers are more useful. Python also allows the designation of text, or ‘strings’ as variables. Type d = 7.2 and e = 'hello!' to utilize float and string variables.

d = 7.2
e = 'hello!'

To see all variables, their type, and their value, use the command %whos. Deleting a single variable can be accomplished using the command del following by the desired variable (e.g., del a). To delete all defined variables, use %reset. Check if the deletions were successful using %whos.

del a 
%whos

It is important to note that variables in Python can consist of numbers, upper and lowercase letters, and underscores. A variable name cannot start with a number. Variable names are generally more useful when they are more descriptive (e.g., gravity_anomaly rather than ga). Remember to comment-in details on your variables (longer names, units) to make your code easier to debug.

Questions for Section 1#

Question 1.1:
What command would be used to clear just the b variable?

# replace this comment with the command to answer Question 1.1
# after typing the command, run the cell.

Question 1.2:
What command would be used to clear all variables?

# replace this comment with the command to answer Question 1.2
# after typing the command, run the cell.

Question 1.3:
Which of the following are valid variable names?

  1. _n

  2. n6

  3. n_

  4. 6n

  5. nnnnnnnnnnnnnnnnnnnnn

answer1 = 'list, of, your, answers' # answer to question 1.3
answer1
# after replacing the above list with your answer, run the cell.

Section 2: NumPy and basic commands#

This section focuses on using the python package ‘numpy’. There are three questions at the end of this section for you to answer.

In order to perform more advanced calculations, you’ll need to import certain Python packages. For example, ‘numerical python’ (‘NumPy’) is a key package. To import this, you can use the command ‘import numpy’. However, it’s conventional to import NumPy with a shorter name, like in the first code cell of this notebook: ‘import numpy as np’ (use this command in your future notebooks).

import numpy as np

To use numpy, commands must begin with np. For example, type ‘np.pi’ and you will see the result printed to the screen. To round this number to a certain number of decimal places, assign the result to a variable, then use the function ‘round’, for example:

pi = np.pi
round(pi, 2)

In numpy, log(x) calculates the natural log of a number. log10(x) will return the log base 10 and log2(x) will return the log base 2.

np.log10(10)

The command np.sqrt() can be used to calculate the square root of positive numbers.

np.sqrt(3)

Trigonometric functions in NumPy take angles in radians, so make sure your input angles are not in degrees. You can also use the built-in NumPy conversion between degrees and radians.

print(np.sin(np.pi/2))
print(np.sin(np.deg2rad(90))) # You can also use np.rad2deg() for other calculations

Inverse trigonometric functions can be calculated using np.arcsin(), np.arccos(), and np.arctan().

print(np.arcsin(np.sin(np.pi/3)))
print(np.pi/3)

Questions for Section 2#

Question 2.1:
What is the command to return the value of e (Euler’s number)?

# replace this comment with the command to answer Question 2.1
# after typing the command, run the cell.

Question 2.2:
What is the sine of 270 degrees?

answer2 = ... # replace the '...' with your answer to question 2.2
answer2
# after typing your answer, run the cell.

Question 2.3:
What is arccos(0.5) in radians?

answer3 = ... # replace the '...' with your answer to question 2.3
answer3
# after typing your answer, run the cell.

Section 3: Vectors and matrices#

This section focuses on using the python package ‘numpy’ to create vectors and matrices. There are three questions at the end of this section for you to answer.

NumPy can be utilized to create “arrays”, which function as vectors or matrices. The size of a matrix with r rows and c columns is 𝑟 × 𝑐. Think of a row vector as a matrix with 𝑟 = 1, and a column vector as a matrix with 𝑐 = 1.

Use the command np.array() to create row and column vectors as follows:

row_vector = np.array([[1, 2, 3]])
print(row_vector)

col_vector = np.array([[1], [2], [3]])
print(col_vector)

# You can check that these vectors are indeed the dimensions you seek by using the following command:

print(row_vector.shape) # Should be (1, 3) for (r, c)
print(col_vector.shape) # Should be (3, 1) for (r, c)

Selecting specific values in a vector or matrix is known as indexing. Start by creating a 3 x 4 matrix as follows:

matrix = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(matrix)

To select elements within the matrix, specify their location within the rows and columns, making sure to begin counting at 0. If you are used to MATLAB, it is important to remember that Python indexing starts at 0, not 1. Here are some examples of indexing:

print(matrix[1,2])     # The number 7 from the matrix in the cell above
print(matrix[2,0])     # The number 9 from the matrix in the cell above
print(matrix[0, :])    # The first row from the matrix in the cell above
column1 = matrix[:, 0] # The first column - but note it only has one dimension - from the matrix in the cell above
print(column1)
column1.shape          # but note it only has one dimension and is not technically a 'row' or 'column'

matrixT = np.transpose(matrix) # Transpose a matrix using this command
print(matrixT)

There are other ways to create more specialized kinds of arrays, such as those made out of zeroes, ones, or a linearly spaced array.

print(np.zeros([3,1]))

print(np.ones([4,1]))

print(np.linspace(0,10,5)) # Specify (start, stop, and the number of elements for a linearly spaced array)

print(np.arange(0, 10, 2)) # Specify (start, stop, and spacing)

# Note the difference between the following: 

print(np.linspace(0,10,10))
print(np.linspace(0,10,11))

You can concatenate or truncate vectors once they are created. The two arrays must have the same shape, except in the direction of the axis.

g = np.ones([4,3])
print(g)

h = np.zeros([2,3])
print(h)

i = np.concatenate((g,h)) # axis is assumed 0 unless specified 
print(i)


j = np.ones([1,2])
print(j)

k = np.zeros([1, 3])
print(k)

l = np.concatenate((j, k), axis=1)
print(l)

m = np.concatenate((k, j), axis=1) # reverses the order from above
print(m)
# vectors for this section's questions:
v = np.array([[1, 2, 3]])
w = np.array([[1], [2], [3]])

Questions for Section 3#

Question 3.1:
What is the difference between v and w?

Double-click this text and replace it with your answer to question 3.1

Question 3.2:
Explain the function of np.transpose().

Double-click this text and replace it with your answer to question 3.2

Question 3.3:
Create a matrix with three columns, each of which is a copy of the vector w.

answer4 = ... # replace the '...' with your answer to question 3.3
answer4
# after typing your answer, run the cell.

Section 4: Vector and matrix operations#

This section focuses on operations with vectors and matrices. There is one question at the end of this section for you to answer.

# set up the example:
v = np.array([[1, 2, 3]])
w = np.array([[1], [2], [3]])
p = ([[3, 4, 5, 6]])
M = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
N = np.concatenate((v, v, v))

Adding a scalar to a vector or matrix is the same as adding two scalar values. Similarly, multiplying a vector or matrix by a scalar value looks just like multiplying two scalars.
To add 2 to all elements of your vector v, type v+2.
To multiply each element of matrix M by 3, type M*3.

print(v+2)
print(M*3)

Adding two matrices may work differently than you expect. Try adding v+N, v+p, v+w:

v+N

To perform matrix multiplication, just multiply the two matrices by each other. Recall that to multiply two matrices together, the number of columns in the first must equal the number of rows in the second.
Try multiplying vector v by vector w. Make sure and show that they have the complementary dimensions.

print(v.shape)
print(w.shape)
v*w

For square matrices, you can also raise the matrix to a power using the same function as you did with scalar values. Square the matrix M using the command M**2, then review the output.

M**2

Operations that apply to each element of the matrix individually are sometimes called array operations or element-wise operations. Many functions, such as trig functions, will operate on a matrix element-by-element. For example, try np.sin(N):

np.sin(N)

Question for Section 4#

Question 4.1:
What does Python do when you ask it to add v+M? What about p+M? Describe as best you can from your own experiments the logic that Python uses to add two matrices together. Include any relevant errors that might occur.

Double-click this text and replace it with your answer to question 4.1

Section 5: Plotting#

This section focuses on making plots using the python package ‘matplotlib’, which you hopefully saw was imported in the first code cell of this notebook. For reference, the import command most relevant to you is ‘import matplotlib.pyplot as plt’, and then all commands using this package must start with ‘plt.’. Tutorials can be found here: https://matplotlib.org/stable/tutorials/index.html

There are two questions at the end of this section for you to answer.

import matplotlib.pyplot as plt

To get started: create a row vector x with the numbers 1 through 50. Then, use the sine function to vector y where each element is the sine of the corresponding value in x.

x = np.linspace(1,50,50)
y = np.sin(x)

Next, create a simple plot using matplotlib:

plt.figure(figsize=(10, 5), dpi=100) # define the figure size (figsize) and resolution (dpi)
plt.plot(x,y,'g:') # 'g:' defines the color (g) and the pattern (:) of the lines here. 
# You can search for color legends and more line patterns. For instance: - is a line, o is dots. 
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Example Plot 1")
plt.show(); # the ; at the end keeps it from printing a bunch of extra text with the plot

Now, create a figure with 2 subplots.

z = np.cos(x) # first we have to define another vector, in this case z
plt.figure(figsize=(10, 5), dpi=100) # control how many rows and columns here

plt.subplot(1, 2, 1) # split figure into 1 row, 2 columns, and plot on the 1st subplot
plt.plot(x,y, 'r-', label='sin(x)')
plt.title('Example Plot 2a')
plt.xlabel('This is x (radians)')
plt.ylabel('Sine of x')
plt.legend()

plt.subplot(1, 2, 2) # split figure into 1 row, 2 columns, and plot on the 2nd subplot
plt.plot(x, z, 'bo', label='cos(x)')
plt.title('Example Plot 2b')
plt.xlabel('This is x (radians)')
plt.ylabel('Cosine of x')
plt.legend()

plt.tight_layout() # This will add space between your subplots (try commenting out this line!)
plt.show();

# Un-comment the following command to save the image
# plt.savefig('example.png')

Redefine x with twice as many points (i.e., define x as a row vector from 1 to 50, but include points at every half integer). Try to plot x and y again. What’s wrong?

x = np.linspace(1,50,99)
fig = plt.plot(x, y, 'b-')

Questions for Section 5#

Question 5.1:
Redefine y as appropriate. Keep iterating on the resolution of x and y until you’re satisfied that the graph looks like a sine wave. Add a title and axis labels.
Hint: you can use ?np.linspace to check the manual of the function quickly.

?np.linspace
# type your fix to address question 5.1 here
x = ... # replace '...' with your redefined x
y = ... # replace '...' with your redefined y
plt.figure(figsize=(10, 5), dpi=100)
plt.scatter()
...

Question 5.2:
Plot x and y with maroon upward-facing triangles?

Hint: check the manual here:

# add to the code started below to generate a plot for question 5.2:
plt.figure(figsize = (10, 4), dpi = 100)
...

Section 6: Plotting two functions on one plot#

This is a short section, focusing on expanding your plotting skills. This section consists of four questions for you to address.

Question 6.1:
Define a new row vector x where the values range from 1 to 90 in degrees with a 0.5 interval (1, 1.5, 2, …), and convert the vector to radians.

# type your solution to question 6.1 in this cell
x = ...
x

Question 6.2:
Define a vector y that is equal to x^2 + 50cos(x + 30).

# type your solution to question 6.2 in this cell
y = ...
y

Question 6.3:
Define a vector z that is equal to 1.5*(tan(y)).

# type your solution to question 6.3 in this cell
z = ...
z

Question 6.4:
Plot y vs. x and z vs. x on the same graph.

  • Plot the y function as a blue solid line, and the z function as a red dotted line.

  • Add a title, and label the x axes x, y(x) and z(y(x)), respectively.

# add to the code in this cell to address question 6.4
plt.figure(figsize = (10, 4), dpi = 100)
plt.plot(...)
plt.legend()
plt.xlabel(...)
...

Submission#

Make sure you have run all cells in your notebook, in order, before saving and submitting, so that all images/graphs appear in the output in your submission. Save the final version of this notebook with your name in the filename and at the beginning (where there is a spot for it). Upload a copy of your notebook to Canvas.

This concludes Lab 1. Congrats, you made it!