Lesson
14: Immutable Coordinate Tuples & Pollutant Sets
(union, intersection,
difference)
The βBoring Stuffβ Problem: Locking Field Well GPS Coordinates & Comparing Exceedance Lists
Two common tasks require specialized Python containers instead of plain mutable lists:
- Monitoring Coordinates That Must Never Shift
(
tuple): A tuple(well_id, x_km, y_km, screen_elev_m)is immutableβif code accidentally tries to reassignwell[1] = 0.0, Python raisesTypeErrorimmediately instead of moving a monitoring well 5 km off-map! - Unique Species & Regulatory Set Audits
(
set): Suppose Upstream Lab A detected{"Nitrate", "Atrazine", "Chloride", "Sulfate"}while Downstream Lab B detected{"Nitrate", "Atrazine", "PFAS", "Lead", "Zinc"}. Sets answer βWhich NEW contaminants entered downstream between Site A and Site B?β in one symbol:downstream - upstream!
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 math
# Example 1 (Watershed Forensics): Set Difference Comparing Upstream vs Downstream Species
upstream_detected = {"Nitrate", "Chloride", "Sulfate", "Atrazine", "Iron"}
downstream_detected = {"Nitrate", "Atrazine", "PFOS", "Benzene", "Lead", "Zinc"}
new_downstream = downstream_detected - upstream_detected
persistent_both = upstream_detected & downstream_detected
all_watershed = upstream_detected | downstream_detected
print("=== Watershed Source-Tracking Set Algebra ===")
print("New Pollutants Entering Reach :", sorted(new_downstream))
print("Persistent Upstream -> Down :", sorted(persistent_both))
print("Combined Monitoring Panel :", sorted(all_watershed))
# Check unique wind sectors inside UCI_Beijing_PM25_Meteorology.csv using a set!
with data_file("UCI_Beijing_PM25_Meteorology.csv").open(encoding="utf-8", newline="") as f:
wind_sectors = {r["cbwd"] for r in csv.DictReader(f)}
print("Unique Wind Direction Codes in Beijing UCI Dataset:", sorted(wind_sectors))=== Watershed Source-Tracking Set Algebra ===
New Pollutants Entering Reach : ['Benzene', 'Lead', 'PFOS', 'Zinc']
Persistent Upstream -> Down : ['Atrazine', 'Nitrate']
Combined Monitoring Panel : ['Atrazine', 'Benzene', 'Chloride', 'Iron', 'Lead', 'Nitrate', 'PFOS', 'Sulfate', 'Zinc']
Unique Wind Direction Codes in Beijing UCI Dataset: ['NE', 'NW', 'SE', 'cv']
# Example 2: Immutable Well Coordinate Tuples + Pairwise Well Distance Check
wells = [
("MW-01_Source", 1.2, 3.4, 185.0),
("MW-02_Mid", 2.8, 3.9, 181.2),
("MW-03_Well", 4.5, 4.1, 177.5),
]
for i in range(len(wells) - 1):
w1_id, x1, y1, h1 = wells[i]
w2_id, x2, y2, h2 = wells[i + 1]
dist_km = math.hypot(x2 - x1, y2 - y1)
grad = (h1 - h2) / (dist_km * 1000.0) # Hydraulic gradient dh / dL [m/m]
print(f"Reach {w1_id} -> {w2_id}: d={dist_km:.2f} km | Hydraulic Gradient i = {grad:.5f} m/m")Reach MW-01_Source -> MW-02_Mid: d=1.68 km | Hydraulic Gradient i = 0.00227 m/m
Reach MW-02_Mid -> MW-03_Well: d=1.71 km | Hydraulic Gradient i = 0.00216 m/m
Concept Check Questions
- Why is
("MW-01", 1.2, 3.4)safer as a tuple than a mutable list when storing GPS monitoring station locations? - What is the difference between
set_a & set_b,set_a | set_b, andset_a - set_b? - Note how
{r["cbwd"] for r in ...}uses curly braces like a dict without colons (set comprehension). Can a Python set contain duplicates?
Guided
Practice Problem 1: LCA Biosphere Compartment Deduplication
(LCA1_LCIA_Characterization_Factors.csv)
Load LCA1_LCIA_Characterization_Factors.csv, build two
sets: air_flows (where Compartment == "air")
and high_gwp (where GWP100_kgCO2eq >= 1.0).
Print all compartments present and find
high_gwp & air_flows.
# Guided Practice 1 Starter
with data_file("LCA1_LCIA_Characterization_Factors.csv").open(encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
compartments = {r["Compartment"] for r in rows}
high_gwp = {r["Flow_ID"] for r in rows if float(r["GWP100_kgCO2eq"]) >= 1.0}
print("LCA Compartments:", sorted(compartments), "| High GWP Flows:", sorted(high_gwp))LCA Compartments: ['air', 'water'] | High GWP Flows: ['elem_ch4', 'elem_co2', 'elem_co2_fos', 'elem_n2o']