Lesson 02: Conda Environments, Scientific Libraries & Real UCI Environmental Datasets

The “Boring Stuff” Problem: "Works on My Laptop, Crashes on Grading/Field PC"

Imagine spending three hours writing an air-quality analyzer at home, emailing the notebook to a colleague or regulator, and getting back a frantic email: “ModuleNotFoundError!” or “FileNotFoundError: C:/Users/MyName/Desktop/data.csv”.

Two simple habits make your environmental code 100% portable and reproducible:

  1. Isolated Python Environments (conda): Keep one clean scientific stack (numpy, pandas, scipy, sympy, matplotlib) in a named environment so installing a GIS or LCA library never breaks another project.
  2. Relative pathlib.Path Data Discovery: NEVER hardcode C:\Users\Alex\Downloads\water.csv! Use Python’s built-in pathlib.Path relative to your notebook (datasets/filename.csv) so your notebook runs identically on Windows, macOS, Linux, or cloud JupyterHub.

Let’s inspect our live scientific toolkit AND verify all 14 real open-sourced datasets (archive.ics.uci.edu/datasets + companion website courses) bundled inside datasets/.

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 sys
import numpy as np
import pandas as pd
import scipy
import sympy
import matplotlib

print(f"Python Runtime : {sys.version.split()[0]}")
print(f"NumPy          : {np.__version__}")
print(f"Pandas         : {pd.__version__}")
print(f"SciPy          : {scipy.__version__}")
print(f"SymPy          : {sympy.__version__}")
print(f"Matplotlib     : {matplotlib.__version__}")

# Verify our portable datasets/ helper on real UCI & course datasets
ds_folder = data_file("UCI_Water_Treatment_Plant_Daily.csv").parent
all_ds = sorted(p.name for p in ds_folder.iterdir() if p.is_file() and not p.name.startswith("_"))
print(f"\nFound {len(all_ds)} open-sourced & cross-course datasets in {ds_folder.name}/:")
for name in all_ds:
    size_kb = (ds_folder / name).stat().st_size / 1024.0
    print(f"  - {name:<44s} ({size_kb:7.1f} KB)")
Python Runtime : 3.11.0
NumPy          : 1.23.5
Pandas         : 1.5.2
SciPy          : 1.9.3
SymPy          : 1.11.1
Matplotlib     : 3.6.2

Found 14 open-sourced & cross-course datasets in datasets/:
  - Field_WQ_Sonde_Raw_Log.txt                   (    2.2 KB)
  - Fluids_Pump_and_Pipe_Network.csv             (    0.8 KB)
  - Fluids_Water_Properties_Table.csv            (    0.9 KB)
  - HMT_Diffusivity_Henry_Solubility.csv         (    0.9 KB)
  - LCA1_LCIA_Characterization_Factors.csv       (    0.9 KB)
  - LCA1_Soybean_Coproduction_Allocation.csv     (    0.4 KB)
  - LCA1_System_LCI_Book_Matrix.csv              (    0.8 KB)
  - Solar_Irradiance_Collector_Hourly.csv        (    0.6 KB)
  - UCI_Air_Quality_Italy_Hourly.csv             (  764.7 KB)
  - UCI_Beijing_PM25_Meteorology.csv             ( 1963.4 KB)
  - UCI_Concrete_LowCarbon_SCMs.csv              (   57.5 KB)
  - UCI_Gas_Turbine_2015_Emissions.csv           (  543.9 KB)
  - UCI_QSAR_Aquatic_Toxicity.csv                (   22.4 KB)
  - UCI_Water_Treatment_Plant_Daily.csv          (   91.2 KB)
# Example 2 (Quick Data Recon on Real UCI Datasets without Freezing Excel!)
# Let's peek at 527 days of urban wastewater treatment telemetry & 546 QSAR aquatic toxicity chemicals

wt_lines = data_file("UCI_Water_Treatment_Plant_Daily.csv").read_text(encoding="utf-8").splitlines()
qsar_lines = data_file("UCI_QSAR_Aquatic_Toxicity.csv").read_text(encoding="utf-8").splitlines()
beijing_lines = data_file("UCI_Beijing_PM25_Meteorology.csv").read_text(encoding="utf-8").splitlines()

print("=== Instant Python Open-Data Reconnaissance ===")
print(f"UCI Water Treatment Plant  : {len(wt_lines) - 1:,} daily plant records | Header preview: {', '.join(wt_lines[0].split(',')[:7])}...")
print(f"UCI QSAR Aquatic Toxicity  : {len(qsar_lines) - 1:,} chemical assays      | Columns: {qsar_lines[0]}")
print(f"UCI Beijing PM2.5 Weather  : {len(beijing_lines) - 1:,} hourly records   | Columns: {beijing_lines[0]}")
=== Instant Python Open-Data Reconnaissance ===
UCI Water Treatment Plant  : 527 daily plant records | Header preview: Date, Q_E_m3d, ZN_E_mgL, PH_E, DBO_E_mgL, DQO_E_mgL, SS_E_mgL...
UCI QSAR Aquatic Toxicity  : 546 chemical assays      | Columns: TPSA,SAacc,H050,MLOGP,RDCHI,GATS1p,nN,C040,LC50_neglog_molL
UCI Beijing PM2.5 Weather  : 43,824 hourly records   | Columns: No,year,month,day,hour,pm2.5,DEWP,TEMP,PRES,cbwd,Iws,Is,Ir

Notice that read_text().splitlines() scanned over 44,800 rows across three real environmental monitoring datasets in less than 0.05 seconds—faster than Excel even opens a splash screen!


Concept Check Questions

  1. Why does hardcoding Path("C:/Users/Student/Desktop/PM25.csv") break grading and teammate collaboration?
  2. What does len(lines) - 1 compute after reading a .csv file with .splitlines()?
  3. Why do environmental engineers install packages inside a dedicated conda environment (conda create -n envpy python=3.10 numpy pandas scipy sympy matplotlib) instead of the system base Python?

Guided Practice Problem 1: Inspect Real Concrete & Fluid Course Datasets

Use data_file(...) to inspect line counts and column headers of UCI_Concrete_LowCarbon_SCMs.csv (UCI #165: cement vs. blast-furnace slag/fly ash mixes for LCA Track 1) and LCA1_System_LCI_Book_Matrix.csv (LCA Track 1 Module 3). Print both dataset sizes and column headers cleanly.

# Guided Practice 1 Starter
for fname in ["UCI_Concrete_LowCarbon_SCMs.csv", "LCA1_System_LCI_Book_Matrix.csv"]:
    text_lines = data_file(fname).read_text(encoding="utf-8").splitlines()
    print(f"{fname}: {len(text_lines)-1} rows | Columns = {text_lines[0]}")
UCI_Concrete_LowCarbon_SCMs.csv: 1030 rows | Columns = Cement_kg_m3,BlastFurnaceSlag_kg_m3,FlyAsh_kg_m3,Water_kg_m3,Superplasticizer_kg_m3,CoarseAgg_kg_m3,FineAgg_kg_m3,Age_days,CompressiveStrength_MPa
LCA1_System_LCI_Book_Matrix.csv: 9 rows | Columns = Flow_ID,Flow_Name,Flow_Type,Compartment,Unit,P1_Forestry,P2_Pulping,P3_Papermaking,P4_Printing,Final_Demand_f