ENGR 2130: Introduction to Engineering Computing - Math Models, IPO Pseudocode, and NumPy Array Fundamentals
Introduction to Google Colaboratory (Colab)
Google Colaboratory, commonly referred to as Colab, is an interactive cloud-based environment that allows users to write and execute Python code directly within a web browser.
Key features include:
- Zero configuration required to begin coding.
- Free access to Graphical Processing Units (GPUs).
- Simplified sharing capabilities across team members and collaborators.
Colab caters to students, data scientists, and AI researchers. Introductory resources for the platform include video tutorials such as Introduction to Colab and Colab Features You May Have Missed.
An interactive Colab notebook is structured with executable code cells rather than static web elements. Variables computed and stored in one cell persist across the session and can be referenced in subsequent code cells.
Cell execution can be triggered by clicking the play icon located to the left of a code cell or using the keyboard shortcut Command/Ctrl+Enter. Code cells can be modified directly by clicking inside them.
seconds_in_a_day = 24 * 60 * 60
seconds_in_a_day
# Output: 86400
seconds_in_a_week = 7 * seconds_in_a_day
seconds_in_a_week
# Output: 604800
Google Colab AI and DeepMind Gemini API Integration
All users have access to popular Large Language Models (LLMs) using the google-colab-ai Python library without requiring an individual API key. Paid users receive access to an expanded selection of models.
from google.colab import ai
response = ai.generate_text("What is the capital of France?")
The Gemini API provides direct access to Gemini models engineered by Google DeepMind. Gemini models are built natively as multimodal architectures capable of processing text, images, code, and audio seamlessly.
Workflow to initiate Gemini API usage:
- Log in to Google AI Studio with a Google account.
- Generate a personal API key.
- Interface with the model via Python quickstart scripts or HTTP REST requests using
curl.
Capabilities of the Gemini API include:
- Iterative multimodal outputs combining text and images.
- Multimodal Live API integration.
- Computer vision tasks including image analysis and 3D item detection.
- Complex problem solving using the Gemini thinking model to trace internal reasoning steps.
Advanced enterprise use cases include:
- Automated business intelligence report generation grounded in real-time internet search results.
- Structured data and invoice extraction from unstructured PDF documents.
- Full-book illustrations generated via large context windows combined with Imagen.
Data Science and Visualization Workflows in Colab
Colab integrates with the Python scientific computing stack to support data analysis and visualization. Libraries such as numpy generate and manipulate numeric datasets, while matplotlib renders graphical plots.
External data can be imported directly into notebooks from sources including Google Drive (including Google Sheets), GitHub repositories, and direct file uploads.
import base64
import io
import IPython.display as display
from matplotlib import pyplot as plt
import numpy as np
ys = 200 + np.random.randn(100)
x = [x for x in range(len(ys))]
fig = plt.figure(figsize=(4, 3), facecolor="w")
plt.plot(x, ys, "-")
plt.fill_between(x, ys, 195, where=(ys > 195), facecolor="g", alpha=0.6)
plt.title("Sample Visualization", fontsize=10)
data = io.BytesIO()
plt.savefig(data)
image = f"data:image/png;base64,{base64.b64encode(data.getvalue()).decode()}"
alt = "Sample Visualization"
display.display(display.Markdown(f""))
plt.close(fig)
Math Models and Algorithm Planning (IPO Pseudocode)
In engineering computing (ENGR 2130), physical problems are converted into mathematical models, planned via pseudocode, and implemented as code cells.
Planning before coding relies on Input-Process-Output (IPO) pseudocode written in plain text Markdown cells. This preserves reasoning steps and clarifies code structure.
Components of an Engineering Model:
- Given: The known numerical values, constants, and parameters.
- Find: The unknown variables or desired results.
- Assumptions: Physical simplifications (e.g., neglecting friction or drag).
- Equations: Mathematical relations governing the physical process.
Components of IPO Pseudocode:
- INPUT: Identifies required input parameters and constants.
- PROCESS: Specifies exact mathematical calculations.
- OUTPUT: Specifies formatted display values.
Worked Example 1: Free-Fall Time Analysis
Model:
- Given: ,
- Find:
- Assumptions: No air resistance, dropped from rest
- Equation:
IPO Pseudocode:
- INPUT: height
- PROCESS:
- OUTPUT: print time
Python Implementation:
import math
height = 45.0 # meters
gravity = 9.81 # m/s^2
time = math.sqrt(2 * height / gravity)
print("Time to fall:", round(time, 2), "seconds")
Worked Example 2: Resistor Power Dissipation
Model:
- Given: ,
- Find:
- Assumptions: Constant resistance, direct current (DC) circuit
- Equation:
IPO Pseudocode:
- INPUT: voltage, resistance
- PROCESS:
- OUTPUT: print power
Python Implementation:
voltage = 120 # Volts
resistance = 60 # Ohms
power = voltage**2 / resistance
print("Power dissipated:", round(power, 2), "Watts")
Applied Engineering Planning Challenges
Challenge 1: Cylindrical Concrete Column Volume and Cost
A cylindrical concrete column features radius and height . Raw concrete costs per cubic meter ().
Model:
- Given: , ,
- Find: , \text{total\_cost}\,(\)
- Assumptions: Perfect geometric cylinder
- Equations: ,
IPO Pseudocode:
- INPUT: radius, height, concrete_cost
- PROCESS: ,
- OUTPUT: print volume, print total cost
Python Implementation:
import math
radius = 0.25 # meters
height = 3.2 # meters
cost_per_m3 = 110 # dollars
volume = math.pi * radius**2 * height
total_cost = volume * cost_per_m3
print("Volume:", round(volume, 2), "m^3")
print("total cost:", round(total_cost, 2))
Output:
Volume: 0.63 m^3total cost: 69.12
Challenge 2: Business Economics Break-Even Analysis
Model:
- Given: , ,
- Find: , ,
- Assumptions: Costs and price remain constant regardless of production volume
- Equations:
IPO Pseudocode:
- INPUT: fixed_cost = 8500, variable_cost = 12.50, price = 29.99
- PROCESS: , ,
- OUTPUT: print profit_per_unit, print break_even_units, print total_revenue
Python Implementation:
import math
fixed_cost = 8500
variable_cost = 12.50
price = 29.99
profit_per_unit = price - variable_cost
break_even_units = math.ceil(fixed_cost / profit_per_unit)
total_revenue = price * break_even_units
print("Profit per unit: $", round(profit_per_unit, 2))
print("Break-even quantity:", break_even_units, "units")
print("Total revenue at break-even: $", round(total_revenue, 2))
Output:
Profit per unit: $ 17.49Break-even quantity: 486 unitsTotal revenue at break-even: $ 14575.14
Fundamentals of NumPy Arrays and Vectorized Computations
Standard Python lists perform scalar multiplication by sequence replication rather than element-wise arithmetic (e.g., [72, 75, 68] * 2 yields [72, 75, 68, 72, 75, 68]). Operating on individual entries in standard lists requires iterative scalar operations.
NumPy ("Numerical Python") provides contiguous data structures designed for numerical computing. It serves as the foundational dependency for Matplotlib, pandas, and SciPy.
The core object is the NumPy array (ndarray). Math operations applied to an array automatically evaluate across all elements simultaneously. This execution pattern is termed vectorized operation.
Temperature Array Conversion Example
Converting 10 temperature readings from Celsius to Fahrenheit using the standard linear formula :
import numpy as np
temps = np.array([72, 75, 68, 70, 74, 71, 69, 73, 76, 70])
temps_f = temps * 9 / 5 + 32
print("Celsius:", temps)
print("Fahrenheit:", temps_f)
Output:
Celsius: [72 75 68 70 74 71 69 73 76 70]Fahrenheit: [161.6 167. 154.4 158. 165.2 159.8 156.2 163.4 168.8 158. ]
Individual element indexing:
print(temps[0], "C =", temps_f[0], "F") # Output: 72 C = 161.6 F
print(temps[1], "C =", temps_f[1], "F") # Output: 75 C = 167.0 F
print(temps[2], "C =", temps_f[2], "F") # Output: 68 C = 154.4 F
Ohm's Law Application across Circuits
Current measurements across 5 circuits: , with constant resistance . Voltage calculation via Ohm's Law :
current = np.array([1.2, 0.8, 2.5, 1.0, 3.1])
r = 40
voltage = current * r
print("Currents: ", current)
print("Voltage: ", voltage)
Output:
Currents: [1.2 0.8 2.5 1. 3.1]Voltage: [48. 32. 100. 40. 124.]
Array Creation, Indexing, and Slicing Mechanics
Array Creation Functions
np.array(list_object): Creates an array from an explicit list or sequence.np.arange(start, stop, step): Generates values fromstartup to (excluding)stopat increments ofstep.np.linspace(start, stop, num): Generatesnumevenly spaced values across the closed interval[start, stop].
Code Examples:
time_steps = np.arange(0, 20, 2)
# Output: [0 2 4 6 8 10 12 14 16 18]
positions = np.linspace(0, 100, 5)
# Output: [0. 25. 50. 75. 100.]
# Challenge: arange every 5 minutes from 0 to 60 (inclusive)
time_steps_60 = np.arange(0, 61, 5)
# Output: [ 0 5 10 15 20 25 30 35 40 45 50 55 60]
# Challenge: linspace 6 test points between 0 and 15 meters
spaces = np.linspace(0, 15, 6)
# Output: [ 0. 3. 6. 9. 12. 15.]
Indexing and Slicing Operations
array[i]: Accesses element at 0-indexed positioni.array[-1]: Accesses final element from the end.array[start:stop]: Extracts elements from indexstartup tostop - 1.array[start:stop:step]: Extracts elements with step size increment.array[::-1]: Reverses sequence ordering.
Code Examples using temps and temps_f:
print("First reading:", temps[0]) # 72
print("Last reading:", temps[-1]) # 70
print("Readings 2 to 4:", temps[2:5]) # [68 70 74]
print("First three:", temps[:3]) # [72 75 68]
print("Every other reading:", temps[::2]) # [72 68 74 69 76]
print("Reversed:", temps[::-1]) # [70 76 73 69 71 74 70 68 75 72]
# Slicing Challenges
print("Last 3 readings:", temps[-3:]) # [73 76 70]
print("Except first:", temps[1:]) # [75 68 70 74 71 69 73 76 70]
print("Every 3rd temp_f:", temps_f[::3]) # [161.6 158. 156.2 158. ]
print("Reversed temp_f:", temps_f[::-1]) # Reverses temps_f array
Array Statistical Methods and Engineering Analysis
NumPy provides built-in statistical functions operating across array dimensions without explicit loops:
.mean(): Computes the arithmetic mean.min(): Extracts minimum value.max(): Extracts maximum value.std(): Computes population standard deviation.sum(): Computes total sum of values
Celsius Temperature Array Summary statistics
- Mean:
71.8 - Min:
68 - Max:
76 - Standard Deviation:
2.52 - Sum:
718
Fahrenheit Temperature Array Summary statistics
- Mean:
161.2 - Min:
154.4 - Max:
168.8
Structural Beam Load Stress Analysis
A beam with cross-sectional area experiences 6 measured loads . Mechanical stress is calculated as .
loads = np.array([1200, 1450, 980, 1600, 1100, 1380])
area = 0.02
stress = loads / area
print("Mean:", round(stress.mean(), 2))
print("Min:", round(stress.min(), 2))
print("Max:", round(stress.max(), 2))
Real-World Engineering Data Analysis (Seaborn MPG Dataset)
The mpg dataset in seaborn contains real specifications for 398 vehicle models from the late 1970s and early 1980s.
Dataset Schema:
mpg: Fuel economy in miles per galloncylinders: Engine cylinder countdisplacement: Total engine cylinder displacement ()horsepower: Engine power outputweight: Total vehicle weight (acceleration: Time to reach speed threshold (model_year: Vehicle production yearorigin: Geographic region (USA, Europe, Japan)name: Vehicle model name
To clean real data for NumPy operations:
- Extract column series:
mpg['horsepower'] - Strip missing/null records:
.dropna() - Convert underlying values to NumPy array:
.values
Horsepower Column Analysis
import matplotlib.pyplot as plt
import seaborn as sns
mpg = sns.load_dataset("mpg")
horsepower = mpg["horsepower"].dropna().values
print(horsepower[:10])
print("Number of readings:", len(horsepower))
print("Mean horsepower:", round(horsepower.mean(), 2))
print("Min horsepower:", horsepower.min())
print("Max horsepower:", horsepower.max())
print("Std deviation:", round(horsepower.std(), 2))
Results:
- Valid Records Count:
392 - Mean:
104.47 - Min:
46.0 - Max:
230.0 - Standard Deviation:
38.44
Boolean Indexing / Filtering
Boolean indexing extracts elements satisfying conditional criteria: filtered_array = array[array > condition]
Filtering vehicles with horsepower above average:
avg_hp = horsepower.mean()
above_avg = horsepower[horsepower > avg_hp]
print("Quantity:", len(above_avg))
# Output: Quantity: 148
plt.hist(horsepower, bins=20)
plt.title("Horsepower Distribution (mpg dataset)")
plt.show()
Vehicle Weight Column Analysis
weight = mpg["weight"].dropna().values
print("Mean weight:", round(weight.mean(), 2))
print("Min weight:", round(weight.min(), 2))
print("Max weight:", round(weight.max(), 2))
plt.hist(weight, bins=20)
plt.title("Weight Distribution (mpg dataset)")
plt.show()
Results:
- Mean Weight:
2970.42 - Min Weight:
1613 - Max Weight:
5140
Fuel Economy (MPG) Column Analysis
mpg_arr = mpg["mpg"].dropna().values
print("Mean mpg:", round(mpg_arr.mean(), 2))
print("Min mpg:", round(mpg_arr.min(), 2))
print("Max mpg:", round(mpg_arr.max(), 2))
print("Vehicles > 30 mpg:", len(mpg_arr[mpg_arr > 30]))
Results:
- Mean MPG:
23.51 - Min MPG:
9.0 - Max MPG:
46.6 - Count of Vehicles > 30 MPG:
85
Summary of Key Computing Principles
- Engineering computing problems proceed through structured phases: Model Definition (Given, Find, Assumptions, Equations) Planning (IPO Pseudocode) Code Execution.
- Input-Process-Output (IPO) pseudocode provides structured pre-coding planning.
- NumPy arrays execute element-wise mathematical calculations without manual iteration loops.
- Standard Python lists replicate sequence elements under multiplication; NumPy arrays perform array arithmetic.
- Array creation relies on
np.array(),np.arange(), andnp.linspace()depending on bound specifications. - Positional selection uses standard indexing
array[i], range slicingarray[start:stop], and step modificationsarray[start:stop:step]. - Built-in array statistical routines (
.mean(),.min(),.max(),.std(),.sum()) provide instantaneous array aggregation. - Conditional filtering relies on boolean indexing constructs (
array[array > target]). - Preprocessing real-world datasets requires stripping missing records (
.dropna()) before converting underlying data series into 1D NumPy arrays (.values).