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: height (m)\text{height}\,(\text{m}), gravity=9.81 m/s2\text{gravity} = 9.81\,\text{m/s}^2
  • Find: time (s)\text{time}\,(\text{s})
  • Assumptions: No air resistance, dropped from rest
  • Equation: t=2×heightgravityt = \sqrt{\frac{2 \times \text{height}}{\text{gravity}}}

IPO Pseudocode:

  • INPUT: height
  • PROCESS: time=2×heightgravity\text{time} = \sqrt{\frac{2 \times \text{height}}{\text{gravity}}}
  • 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: voltage (V)\text{voltage}\,(\text{V}), resistance (Ω)\text{resistance}\,(\Omega)
  • Find: power (W)\text{power}\,(\text{W})
  • Assumptions: Constant resistance, direct current (DC) circuit
  • Equation: P=V2RP = \frac{V^2}{R}

IPO Pseudocode:

  • INPUT: voltage, resistance
  • PROCESS: power=voltage2resistance\text{power} = \frac{\text{voltage}^2}{\text{resistance}}
  • 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 r=0.25 mr = 0.25\,\text{m} and height h=3.2 mh = 3.2\,\text{m}. Raw concrete costs n110\\n110 per cubic meter (m3\text{m}^3).

Model:

  • Given: radius=0.25 m\text{radius} = 0.25\,\text{m}, height=3.2 m\text{height} = 3.2\,\text{m}, concrete_cost=$110 per m3\text{concrete\_cost} = \$110\,\text{per m}^3
  • Find: volume (m3)\text{volume}\,(\text{m}^3), \text{total\_cost}\,(\)
  • Assumptions: Perfect geometric cylinder
  • Equations: V=π×r2×hV = \pi \times r^2 \times h, cost=V×cost_per_m3\text{cost} = V \times \text{cost\_per\_m}^3

IPO Pseudocode:

  • INPUT: radius, height, concrete_cost
  • PROCESS: volume=π×radius2×height\text{volume} = \pi \times \text{radius}^2 \times \text{height}, total_cost=volume×cost_per_m3\text{total\_cost} = \text{volume} \times \text{cost\_per\_m}^3
  • 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: fixed_cost=8500\text{fixed\_cost} = 8500, variable_cost=12.50\text{variable\_cost} = 12.50, price=29.99\text{price} = 29.99
  • Find: profit_per_unit\text{profit\_per\_unit}, break_even_units\text{break\_even\_units}, total_revenue\text{total\_revenue}
  • Assumptions: Costs and price remain constant regardless of production volume
  • Equations:   profit_per_unit=price−variable_cost\text{profit\_per\_unit} = \text{price} - \text{variable\_cost}break_even_units=⌈fixed_costprofit_per_unit⌉\text{break\_even\_units} = \left\lceil \frac{\text{fixed\_cost}}{\text{profit\_per\_unit}} \right\rceiltotal_revenue=price×break_even_units\text{total\_revenue} = \text{price} \times \text{break\_even\_units}

IPO Pseudocode:

  • INPUT: fixed_cost = 8500, variable_cost = 12.50, price = 29.99
  • PROCESS: profit_per_unit=price−variable_cost\text{profit\_per\_unit} = \text{price} - \text{variable\_cost}, break_even_units=ceil(fixed_costprofit_per_unit)\text{break\_even\_units} = \text{ceil}\left(\frac{\text{fixed\_cost}}{\text{profit\_per\_unit}}\right), total_revenue=price×break_even_units\text{total\_revenue} = \text{price} \times \text{break\_even\_units}
  • 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 F=C×95+32F = C \times \frac{9}{5} + 32:

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: I=[1.2,0.8,2.5,1.0,3.1] AI = [1.2, 0.8, 2.5, 1.0, 3.1]\,\text{A}, with constant resistance R=40 ΩR = 40\,\Omega. Voltage calculation via Ohm's Law V=I×RV = I \times R:

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 from start up to (excluding) stop at increments of step.
  • np.linspace(start, stop, num): Generates num evenly 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 position i.
  • array[-1]: Accesses final element from the end.
  • array[start:stop]: Extracts elements from index start up to stop - 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 μ=1N∑i=1Nxi\mu = \frac{1}{N} \sum_{i=1}^N x_i
  • .min(): Extracts minimum value
  • .max(): Extracts maximum value
  • .std(): Computes population standard deviation σ=1N∑i=1N(xi−μ)2\sigma = \sqrt{\frac{1}{N} \sum_{i=1}^N (x_i - \mu)^2}
  • .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 A=0.02 m2A = 0.02\,\text{m}^2 experiences 6 measured loads P=[1200,1450,980,1600,1100,1380] NP = [1200, 1450, 980, 1600, 1100, 1380]\,\text{N}. Mechanical stress is calculated as σ=PA\sigma = \frac{P}{A}.

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 gallon
  • cylinders: Engine cylinder count
  • displacement: Total engine cylinder displacement (in3\text{in}^3)
  • horsepower: Engine power output
  • weight: Total vehicle weight (lbs\text{lbs}
  • acceleration: Time to reach speed threshold (s\text{s}
  • model_year: Vehicle production year
  • origin: Geographic region (USA, Europe, Japan)
  • name: Vehicle model name

To clean real data for NumPy operations:

  1. Extract column series: mpg['horsepower']
  2. Strip missing/null records: .dropna()
  3. 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) →\rightarrow Planning (IPO Pseudocode) →\rightarrow 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(), and np.linspace() depending on bound specifications.
  • Positional selection uses standard indexing array[i], range slicing array[start:stop], and step modifications array[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).