Download LAB document for HISTORY and more Summaries History in PDF only on Docsity!
BME 303: INTRODUCTION TO COMPUTING
LAB REPORT
Lab_8: Numpy, Pandas, and Matplotlib
Name: Adhvika Manivannan
EID: am
Lab Section: mon 4- 6
Part A (Preparation for midterms)
Problem A-1 (2 7 points): Numpy basics – Practice problem
A) Arrays a, b, c, d are initialized below. Answer the following questions. What if we ask you this type of
question in midterm_3? Are you able to derive answers in your mind?
import numpy as np
A = np.array([ 1 , 2 , 3 , 4 , 6 , 7 , 10 ])
B = np.array([ 10 , 0 , 10 , 2 , 3 , 0 , 2 ])
C = np.array([[ 3 , 4 ],[ 6 , 7 ]])
D = np.array([[ 1 , 2 ],[ 2 , 2 ]])
E = np.array([[ 11 , 12 , 13 ],[ 14 , 15 , 16 ],[ 17 , 18 , 19 ]])
No. Snippet Result
1 print(A[ 4 :]) [6,7,10]
print(A[ 2 : 5 : 2 ]) [3,6]
3 print(E[: 2 , 0 : 1 ]) [[11],[14]]
4 print(A*B) [10,0,30,8,18,0,20]
5 print(C*D) [[3,8],[12,14]]
6 print(C*A) error
7 print(np.matmul(C,D)) [[11,14],[20,26]]
8 print(C.T) [[3,6],[4,7]]
9 print(np.linalg.inv(C)) [[-2.333, 1.333], [ 2.0, - 1.0]]
B) Find output of below snippet. For each question, C is initialized as below.
C = np.array([[ 3 , 4 ],[ 6 , 7 ]])
No Snippet Output Type of copy operation
1 F = C
F[ 0 ][ 1 ] = 1000
F.shape=( 1 , 4 )
print(C)
print(F)
C: [[3, 1000], [6, 7]]
(shape: 1x4)
F: [[3, 1000, 6, 7]]
No copy
2 G = C.view()
G[ 0 ][ 1 ] = 1000
G.shape=( 1 , 4 )
print(C)
print(G)
C: [[3, 1000], [6, 7]]
(shape: 2x2)
G: [[3, 1000, 6, 7]]
Shallow Copy
3 H = C.copy()
H[ 0 ][ 1 ] = 1000
H.shape=( 1 , 4 )
print(C)
print(H)
C: [[3, 4], [6, 7]]
(shape: 2x2)
H: [[3, 1000, 6, 7]]
Deep Copy
Problem A-2 ( 3 points): Numpy basics - Spring 2025 midterm - Problem 2 Part B
Write the code to make an ndarray called myarr which has 10 elements in its first dimension and 20 in its
second dimension. It can be initialized with elements of your choosing (uninitialized, ones, zeros, etc.). Assume
numpy has been imported and has been given the alias np. This is a one-line answer.
myarr = np.zeros(( 10 , 20 ))
Problem A-3 (10 points) : Numpy basics - Spring 2025 midterm - Bonus
SIR Model of Infectious Diseases (8 points)
Most of this information is not needed to do the problem, so use your time wisely. There is another note below that indicates
where the required information begins.
The SIR model is a compartmental model of the dynamics of an epidemic. S is the number of susceptible individuals, I is the
number of infectious individuals, and R is the number of removed (immune or deceased) individuals, the total population is N.
The SIR model has parameters b (Greek letter beta, infection rate constant) and g (Greek letter gamma, recovery/removal rate
Using the previous equations, write a function sir_model which predicts S, I, and R across time.
sir_model function should have the following inputs:
- s0, i0, and r0 (which are S[0], I[0], and R[0], respectively)
- dt (Dt)
- beta (b)
- gamma (g)
- nt (the total number of time points, the number of elements in/length of S, I, and R)
sir_model should return a tuple containing S, I, and R, each being an ndarray of size nt.
You must use numpy, make sure to import it at the beginning of your response.
import numpy as np def sir_model(s0, i0, r0, dt, beta, gamma, nt):
Initialize arrays to hold the results
S = np.zeros(nt) I = np.zeros(nt) R = np.zeros(nt)
initial conditions at index 0
S[ 0 ] = s I[ 0 ] = i R[ 0 ] = r
Total population N
N = s0 + i0 + r
loop to calculate the values for each time step
for t in range(nt - 1 ):
Calculate the rates of change (derivatives)
dSdt = - (beta / N) * I[t] * S[t] dIdt = (beta / N) * I[t] * S[t] - gamma * I[t] dRdt = gamma * I[t]
Linear approximation: Next = Current + (Rate * dt)
S[t + 1 ] = S[t] + dSdt * dt I[t + 1 ] = I[t] + dIdt * dt R[t + 1 ] = R[t] + dRdt * dt return S, I, R s_out, i_out, r_out = sir_model(s0= 990 , i0= 10 , r0= 0 , dt=0.1, beta=0.3, gamma=0.1, nt= 10 ) print("Susceptible Array:", s_out) print("Infected Array: ", i_out) print("Removed Array: ", r_out)
Part B (Python Coding)
Problem B-1 [15 pts].
We want to check how uniform is the sampling of random.randint. To check it, you must:
- Create 2 × 2 subplots.
- In subplot(2,2,1), plot the histogram of 20 random samples of random.randint(0,10).
- In subplot(2,2,2), plot the histogram of 200 random samples of random.randint(0,10).
- In subplot(2,2,3), plot the histogram of 2,000 random samples of random.randint(0,10).
- In subplot(2,2,4), plot the histogram of 20,000 random samples of random.randint(0,10).
- Save the figure as a pdf file.
Your work starts here.
Code:
import matplotlib.pyplot as plt import random sample_sizes = [ 20 , 200 , 2000 , 20000 ]
Create a 2x2 subplot figure
fig, axes = plt.subplots( 2 , 2 , figsize=( 10 , 8 )) axes = axes.flatten() # Flatten to easily iterate through 0- 3 for i, size in enumerate(sample_sizes):
Generate the random samples
data = [random.randint( 0 , 10 ) for _ in range(size)]
Plot the histogram
axes[i].hist(data, bins=range( 12 ), align='left', rwidth=0.8, color='skyblue', edgecolor='black') axes[i].set_title(f'Samples: {size}') axes[i].set_xticks(range( 11 )) plt.tight_layout()
Save the figure as a PDF
plt.savefig("randint_uniformity_check.pdf") plt.show()
Results:
- Plot the spatial distribution, if the value is 0, color it with white, if the value is 1, color it with black. Check
if you can identify a pattern. Save the figure as a pdf file.
Your work starts here.
Code: import numpy as np
import matplotlib.pyplot as plt
1. Create a 512 x 512 matrix filled with random 0s or 1s
np.random.randint(low, high, size) - > high is exclusive, so (0, 2) gives 0 or 1
matrix = np.random.randint( 0 , 2 , size=( 512 , 512 ))
2. Plot the spatial distribution
plt.figure(figsize=( 8 , 8 ))
cmap='binary' maps 0 to white and 1 to black
plt.imshow(matrix, cmap='binary', interpolation='nearest')
Remove axes for a cleaner "static" look similar to the image
plt.axis('off') plt.title("Spatial Distribution of Random Generator")
3. Save the figure as a PDF file
plt.savefig("random_pattern_check.pdf", bbox_inches='tight')
Display the plot
plt.show()
Results:
Your answer ends here.
Problem B-3 [25 pts].
You have a vitals dataset for 3000 patients. You need to clean the data, filter and store it in a new csv file. Below
are the steps:
1) Read raw_vitals.csv into a Pandas DataFrame. (Download the file from Canvas)
2) Remove any duplicate entries based on patient ID.
3) Remove 'System_Error_Code ' column.
4) Add a new column at index 1 called ' Status ' with the value ' Processe d'.
5) Filter the entries with patients whose Zip Code is 78717 and Health_Score is greater than 90. Store
them in a new dataframe called “ refined_data ”.
6) Save the refined_data dataframe into a csv named “ refined_vitals.csv ”
7) Print the refined_data to terminal and submit the output.
Your work starts here.
Code:
import pandas as pd df = pd.read_csv('raw_vitals.csv') print(df.columns.tolist())
2) Remove any duplicate entries based on patient ID
df = df.drop_duplicates(subset=['Patient_ID'])