Lesson
18: Matrix Linear Algebra (np.linalg.solve) β
LCA (\(\mathbf{s} =
\mathbf{A}^{-1}\mathbf{f}\)), MFA (\(\mathbf{x} =
\mathbf{A}\mathbf{x}+\mathbf{y}\)) & Coupled Lakes
The βBoring Stuffβ Problem: Feedback Loops That Make Hand Substitution Impossible
Notice something remarkable across three core Environmental Engineering courses on this portal:
Life Cycle Assessment (
LCA Track 1 Week 5&LCA Track 2 Module 2): Every process needs upstream electricity, paper, steel, and fuels simultaneously: \[\mathbf{A}\mathbf{s} = \mathbf{f} \implies \mathbf{g} = \mathbf{B}\mathbf{s}\]Material Flow Analysis (
3-material-flow-analysis Meeting 6): Recycled metal returns from Waste Recovery back into Manufacturing (x = A x + y -> (I - A) x = y)!Coupled Lakes / Reactors: Pollutants flow forward AND backward through interconnected Great Lakes basins or WWTP recycle streams!
Instead of doing ugly substitution across 4 or 4,000 equations by
hand, np.linalg.solve(A, rhs) solves ALL
coupled balances simultaneously to machine precision!
from pathlib import Path
def data_file(name):
"""Locate a dataset file whether running from SRC_DIR, module folder, HOMEWORK, or EXAMS."""
for p in [
Path("datasets") / name,
Path("../datasets") / name,
Path("../../datasets") / name,
]:
if p.exists():
return p
raise FileNotFoundError(f"Missing dataset {name} in datasets/")
import csv
import numpy as np
import matplotlib.pyplot as plt
# Example 1 (Exact LCA Track 1 Module 3 & 5 Book Printing Matrix from Website CSV!)
with data_file("LCA1_System_LCI_Book_Matrix.csv").open(encoding="utf-8", newline="") as f:
lci_rows = list(csv.DictReader(f))
with data_file("LCA1_LCIA_Characterization_Factors.csv").open(encoding="utf-8", newline="") as f:
cf_map = {r["Flow_ID"]: r for r in csv.DictReader(f)}
proc_cols = ["P1_Forestry", "P2_Pulping", "P3_Papermaking", "P4_Printing"]
tech_rows = [r for r in lci_rows if r["Flow_Type"] == "technosphere"]
bio_rows = [r for r in lci_rows if r["Flow_Type"] == "biosphere"]
A = np.array([[float(r[c]) for c in proc_cols] for r in tech_rows])
f_demand = np.array([float(r["Final_Demand_f"]) for r in tech_rows])
B = np.array([[float(r[c]) for c in proc_cols] for r in bio_rows])
# Solve A s = f cleanly using np.linalg.solve (NEVER compute np.linalg.inv(A)!)
s_scale = np.linalg.solve(A, f_demand)
g_inventory = B @ s_scale
# Multiply biosphere inventory by GWP100 characterization factors
gwp_vec = np.array([float(cf_map[r["Flow_ID"]]["GWP100_kgCO2eq"]) if r["Flow_ID"] in cf_map else 0.0 for r in bio_rows])
total_gwp = float(gwp_vec @ g_inventory)
print("=== Exact Matrix LCA Solution (LCA Track 1 Course Integration: 1,000 Printed Books) ===")
for name, sc in zip(proc_cols, s_scale):
print(f" Scaling Factor {name:<14s} = {sc:8.2f}")
print(f"Net System GWP100 Impact = {total_gwp:,.2f} kg CO2-eq for 1,000 books ({total_gwp/1000:.2f} kg/book)")=== Exact Matrix LCA Solution (LCA Track 1 Course Integration: 1,000 Printed Books) ===
Scaling Factor P1_Forestry = 3300.00
Scaling Factor P2_Pulping = 1320.00
Scaling Factor P3_Papermaking = 1200.00
Scaling Factor P4_Printing = 1000.00
Net System GWP100 Impact = 10,649.40 kg CO2-eq for 1,000 books (10.65 kg/book)
# Example 2 (Material Flow Analysis Course Integration + Coupled Lakes): Circular MFA System
# Circular aluminum loop from MFA Meeting 6:
# x0 (Market Consumption) = 100 external + 0.80 * x2 (Secondary Recycled Scrap)
# x1 (Waste Collection) = 1.00 * x0
# x2 (Recycling Plant) = 0.60 * x1
# Rearrange (I - T) x = y:
I_minus_T = np.array([
[ 1.0, 0.0, -0.80],
[-1.0, 1.0, 0.00],
[ 0.0, -0.60, 1.00],
])
y_ext = np.array([100.0, 0.0, 0.0])
x_mfa = np.linalg.solve(I_minus_T, y_ext)
landfill_loss = 0.40 * x_mfa[1] + 0.20 * x_mfa[2]
print("=== Circular Economy Material Flow Balance (MFA Course) ===")
print(f"Market Throughput : {x_mfa[0]:6.2f} kt/yr (1.92x multiplier over 100 kt virgin input!)")
print(f"Waste Collected : {x_mfa[1]:6.2f} kt/yr")
print(f"Recycled Secondary : {x_mfa[2]:6.2f} kt/yr")
print(f"Mass Closure Check : Virgin In = 100.00 vs Total Landfill Out = {landfill_loss:.2f} kt/yr")
# Plot LCA Process Contribution by Stage
stage_gwp = (gwp_vec @ B) * s_scale
fig, ax = plt.subplots(figsize=(7.2, 3.8))
colors = ["#059669" if v < 0 else "#dc2626" for v in stage_gwp]
ax.bar(proc_cols, stage_gwp, color=colors, edgecolor="#0f172a", width=0.55)
ax.axhline(0, color="#0f172a", lw=0.9)
for i, v in enumerate(stage_gwp):
ax.text(i, v + (80 if v >= 0 else -180), f"{v:,.0f}", ha="center", fontweight="bold", fontsize=9)
ax.set_title(f"Net Carbon Footprint by LCA Stage (1,000 Books; Net Total = {total_gwp:,.0f} kg CO2-eq)")
ax.set_ylabel("Stage Net GWP100 [kg CO2-eq]")
ax.grid(True, axis="y", alpha=0.3)
fig.tight_layout()
=== Circular Economy Material Flow Balance (MFA Course) ===
Market Throughput : 192.31 kt/yr (1.92x multiplier over 100 kt virgin input!)
Waste Collected : 192.31 kt/yr
Recycled Secondary : 115.38 kt/yr
Mass Closure Check : Virgin In = 100.00 vs Total Landfill Out = 100.00 kt/yr
Look at that mass-balance verification in Example 2: 100
kt/yr virgin input equals 100.00 kt/yr landfill outflow, yet
circular recycling boosts total societal material service
(x0) to 192.31 kt/yr! That exact matrix
algebra underlies BOTH LCA Track 1/2
(s = A^-1 f) and MFA / ODYM!
Concept Check Questions
- Why should you call
np.linalg.solve(A, f)instead of computingnp.linalg.inv(A) @ f? - Look at the bar plot: why does
P1_Forestryhave a negative net GWP100 bar in our textbook LCA system? - What physical conservation check verified our 3-process circular economy MFA solver had zero arithmetic bugs?
Guided Practice Problem 1: 4-Reactor Linked Wastewater / Lake Matrix Balance
Four interconnected lakes (1 -> 2 -> 3 -> 4,
plus return exchange between 2 <-> 3) receive
tributary chloride loads W = [800, 300, 1200, 500] kg/day:
\[M\mathbf{c} = \mathbf{W}, \quad M =
\begin{bmatrix} 55 & 0 & 0 & 0 \\ -40 & 85 & -10
& 0 \\ 0 & -60 & 110 & 0 \\ 0 & 0 & -90 &
140 \end{bmatrix} \times 10^3\text{ m}^3/\text{d}\] Solve for
steady-state lake concentrations \(\mathbf{c}
= [C_1, C_2, C_3, C_4]\) in \(\text{kg/m}^3\) and convert to \(\text{mg/L}\)!
# Guided Practice 1 Starter
M = np.array([
[ 55., 0., 0., 0.],
[-40., 85., -10., 0.],
[ 0., -60., 110., 0.],
[ 0., 0., -90., 140.]
]) * 1e3
W = np.array([800., 300., 1200., 500.])
C_mgL = np.linalg.solve(M, W) * 1000.0
for idx, c in enumerate(C_mgL, 1):
print(f"Lake {idx} Steady Chloride = {c:.2f} mg/L")Lake 1 Steady Chloride = 14.55 mg/L
Lake 2 Steady Chloride = 12.46 mg/L
Lake 3 Steady Chloride = 17.70 mg/L
Lake 4 Steady Chloride = 14.95 mg/L