Coding Lab 4

Debugging, testing, and troubleshooting

by Eugeniy E. Mikhailov and Greg Bentsen

Logistics and Agenda

Homework 2 due Monday Sept 14 at 11:59pm


Agenda


Today

Homework logistics:

Implementation file

Test file

Debugging, testing, and troubleshooting

For better or for worse: most of your time will be spent debugging, testing, and troubleshooting your code.

This is especially true now that AI tools have become available.


Debugging is like detective work


It also pays to “think like a scientist”

Testing, troubleshooting and the scientific method

It pays to “think like a scientist”

  1. Make observations
  2. Form hypotheses
  3. Design an experiment to test your hypotheses
  4. Draw conclusions
  1. “This function is returning 0 when it should be returning 3.14”
  2. “Perhaps my loop is not doing any iterations”
  3. “Include an increment variable count that counts how many times the loop runs”
  4. “I see that count = 5 so my loop is iterating correctly. The problem must lie elsewhere”

Debugging, testing, and troubleshooting

Useful questions to ask before errors occur:


Useful questions to ask when errors occur:

Practical advice

Debugging practice

Practice using 2D arrays and the debugger to parse error messages

import numpy as np
from plot_array import *

# Define array
temperature = np.array([
    [20.1, 20.4, 20.8, 21.0],
    [19.8, 20.2, 20.6, 20.9],
    [19.5, 19.9, 20.3, 20.7]
])

# Plot array
plot_array(temperature, "temps.png")


# -----------------------------------------------------------------

# Array indexing
val_00 = temperature[0,0]
val_23 = temperature[2,3]
# val_32 = temperature[3,2]

col_0 = temperature[:,0]
col_1 = temperature[:,1]
row_1 = temperature[1,:]

col_m1 = temperature[-1,:]



# -----------------------------------------------------------------

# Combing rows and columns?
# combined = col_0 + row_1

combined = col_0 + col_1



# -----------------------------------------------------------------

# Find all grid points hotter than 20.5 degrees
hot_points = temperature > 20.5

plot_array(hot_points, "hot_points.png")



# -----------------------------------------------------------------

# Computing averages across rows and columns
column_means = np.mean(temperature, axis=1)
print("Column means:", column_means)



# -----------------------------------------------------------------

# Compute approximate derivative in x direction
dx = 0.5
dTdx = np.zeros_like(temperature)

for i in range(temperature.shape[0]):
    for j in range(1, temperature.shape[1]-1):
        dTdx[i, j] = (temperature[i, j + 1] - temperature[i, j - 1]) / (2 * dx)

print("dT/dx:")
print(dTdx)