fluxmapPy Tutorial¶
Getting Started¶
Installation¶
python -m pip install "fluxmappy @ git+https://github.com/AtmoFacts/fluxmapPy"
# Or Into a fresh virtual environment (recommended over installing system-wide):
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install --upgrade pip
python -m pip install "fluxmappy @ git+https://github.com/AtmoFacts/fluxmapPy"
Data Format for Package¶
Data layout¶
Most functions expect a directory holding both the flux measurement rasters and their companion quality-flag rasters, so each measurement raster can be paired with its quality layer:
my_fluxmaps/
├── ...fluxH2oEngy....tif # measurement raster
├── ...fluxH2oEngy..._qf.tif # matching quality-flag raster
├── ...fluxCo2....tif
└── ...fluxCo2..._qf.tif
Each quality-flag layer grades every pixel from 0 to 5, where 0 carries the least uncertainty and 5 the most.
fluxmapPy Structure Notes¶
fluxmapPy adopts Eddy4R terms and structuring.
There are a collection of definition functions that allow for the analysis of FluxMaps. These functions can be found on the git page. These definition functions start with def_.
Wrapper functions exacute a collection of def_ functions, and they start with wrap_.
The next term following the def_ function is what wrapper function the def_ function belongs to.
You can call def_ functions, or just use wrap_ functions for convenience.
FluxmapPy Package Main Wrapper Functions¶
1.) wrap_open_fm¶
- Saves a single FluxMap into an object to allow for easy plotting.
2.) wrap_filt_qf¶
- Filters out repository of FluxMap pixels based on a quality threshold set.
3.) wrap_diu¶
- Computes FluxMap-wide or polygon specific mean and cumulative diurnal cycles
4.) wrap_stat¶
- Computes FluxMap-wide or polygon specific spatial statistics.
# Function that downloads public NEON data (KONA) from the google cloud bucket
from pathlib import Path
import requests
def download_gcs_folder(bucket, prefix, dest):
"""Download every object under gs://bucket/prefix, keeping folder layout."""
api = f"https://storage.googleapis.com/storage/v1/b/{bucket}/o"
params = {"prefix": prefix, "fields": "items(name,size),nextPageToken"}
while True:
listing = requests.get(api, params=params, timeout=60)
listing.raise_for_status()
listing = listing.json()
for obj in listing.get("items", []):
out = dest / obj["name"]
if out.exists() and out.stat().st_size == int(obj["size"]):
continue # already downloaded
out.parent.mkdir(parents=True, exist_ok=True)
with requests.get(f"https://storage.googleapis.com/{bucket}/{obj['name']}", stream=True, timeout=60) as r:
r.raise_for_status()
with open(out, "wb") as f:
for chunk in r.iter_content(chunk_size=1 << 20):
f.write(chunk)
print("downloaded", obj["name"])
if "nextPageToken" not in listing:
break
params["pageToken"] = listing["nextPageToken"]
# Setting the google bucket to it reads the KONA data
BUCKET = "data-neon"
PREFIX = "KONA/fluxCo2/2024/" # site / flux type / year (can change for different sets of public data)
DATA_DIR = Path("KONA") # local folder the rest of the tutorial reads from
#Actually obtaining the data
download_gcs_folder(BUCKET, PREFIX, DATA_DIR)
# If you have FluxMap tif files saved on your local computer already, you would not need this step. This step is mainly used for tutorial purposes.
1.) wrap_open_fm (raster, flux=fluxCo2, band = 0, qf_path = None, qf_thresh = 5, qf_keep = 'lte')¶
Opens a singular FluxMap .tif/_qa.tif
Parameters:
flux (fluxCo2, fluxTempEngy, fluxH2oEngy)
- Specifies which type of FluxMap to analyze if you have different variations. fluxCo2 (carbon), fluxTempEngy (latent heat), fluxH2oEngy (sensible heat)
band
- Which band out of the 48 you want to visualize
qf_path
- Location of the _qf.tif file you want to use for pixel quality filtering
qf_thsh
- Threshold in which you want to filter out pixels. 0-5 depedning on level of quality.
qf_keep ('lte', 'gte')
- When you set the qf threshold, you can decide if you want to keep the pixels less than or greater than the threshold provided.
- 'gte' greater than
- 'lte' less than
# Import new fluxmapPy package and the functions required for analysis.
from fluxmappy import wrap_filt_qf, wrap_diu, wrap_stat, wrap_open_fm
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Locations to the datasets
raster = DATA_DIR / "KONA/fluxCo2/2024/07/01/kona_fluxCo2_20240701.tif"
qf_raster = DATA_DIR / "KONA/fluxCo2/2024/07/01/kona_fluxCo2_20240701_qa.tif"
# Opening flux map function
fluxmap = wrap_open_fm(raster, band = 32, qf_path = qf_raster, qf_thsh = 4, qf_keep = 'lte')
# Creates an object for visualization
fluxmap.data # Filtered 2D masked array
fluxmap.band # Selected band number
fluxmap.description # Raster band description
fluxmap.profile # Spatial raster metadata
fluxmap.tags # Band-level metadata
fluxmap.record # Site, flux type, date, and path
fluxmap.quality_path # Quality raster that was used
# Quick Plot of the FluxMap
import matplotlib.pyplot as plt
plt.imshow(fluxmap.data, cmap="RdYlBu_r")
plt.colorbar(label="Flux")
plt.title(f"Filtered flux map — band {fluxmap.band}")
plt.show()
(2) wrap_filt_qf (rasters, flux = 'fluxCo2', qf_thsh = 5, qf_keep = 'lte')¶
Allows for a folder of FluxMaps to be edited, by taking each .tif file and filtering out the pixels based on a qf threshold.
Parameters:
flux (fluxCo2, fluxTempEngy, fluxH2oEngy)
- Specifies which type of FluxMap to analyze if you have different variations. fluxCo2 (carbon), fluxTempEngy (latent heat), fluxH2oEngy (sensible heat)
qf_thsh
- Threshold in which you want to filter out pixels. 0-5 depedning on level of quality.
qf_keep ('lte', 'gte')
- When you set the qf threshold, you can decide if you want to keep the pixels less than or greater than the threshold provided.
- 'gte' greater than
- 'lte' less than
# Make a 500 m radius circle around the flux tower (the centre of the FluxMap grid)
import geopandas as gpd
import rasterio
from shapely.geometry import box
with rasterio.open(raster) as src:
tower = box(*src.bounds).centroid # tower sits at the centre of the 3 km x 3 km FluxMap
gpd.GeoDataFrame(geometry=[tower.buffer(500)], crs=src.crs).to_file("500m_radius.shp")
filtered = wrap_filt_qf('KONA',flux = 'fluxCo2', qf_thsh = 1, qf_keep = 'lte')
(3) wrap_diu (FluxMaps, vector = None, in_tz = 'UTC', out_tz = 'UTC', incomplete_local_days = 'inculde', timestep_seconds = 1800))¶
Computes a mean and cumulative diurnal cycle, with the ability to input a new timezone for noon centering. Allows for the ability to compute a diurnal cycle within vector polygons.
Parameters
vector
- Location of the vector file containing polygons in which you want to analyze and clip the FluxMap to.
in_tz
- Input timezone of the FluxMaps, almost always UTC.
out_tz
- Output timezone of the FluxMaps depending on where analysis takes place geographically. Defaults to UTC.
incomplete_local_days ('drop' (drop missing days) , 'include' (all days even if missing) , 'error' (rejects missing days). Default is 'drop')
- Defines what happens to missing days of data.
Timestamp_seconds
- Math in which the time steps will be divided by. Typically meant for cumulative diurnal cycles.
Callable Features using wrap_diu¶
While wrap_diu breaks apart the raster based on each polygon within the shapefile, you can analyze each polygon indiviudally. For example, if you set wrap_diu equal to "cycles" then each polygon can be called by calling cycles[0], cycles[1], cycles[2], etc. It is zero indexed. You just need to know the order of your polygons (can be found in qgis easily with the attribute table)
You can call new features after running wrap_diu
Cumulative_Cycle
- Cumulative diurnal cycle pattern for plotting.
Mean_cycle
- Mean diurnal cycle pattern for plotting.
Valid_day_count
- How many valid days of data you were able to run.
Standard_deviation
- std of each raster while the mean was being computed.
cycles = wrap_diu(filtered, vector = "500m_radius.shp", in_tz = 'UTC', out_tz = 'America/Chicago',incomplete_local_days='drop')
cycles[0]
# Plotting Example
hours = np.arange(48) / 2
fig = plt.figure(figsize=(12, 8))
# Must specify result.mean (mean diurnal) or result.cumulative (cumulative diurnal)
#Set control to the first element of the cycles list, will have more if additional polygons.
#control = cycles[0]
#plt.plot(hours,np.roll(control.mean_cycle, 16), label = 'Control', color = 'pink',marker= 'o')
#plt.fill_between(hours, np.roll(control[0].mean_cycle, 16) - np.roll(control[0].standard_deviation, 16), np.roll(control[0].mean_cycle, 16) + np.roll(control[0].standard_deviation, 16), alpha=0.3, color = 'orange')
plt.plot(hours, cycles[0].mean_cycle, label = '500m', color = 'orange',marker= 'o')
plt.xlabel("Hour of day (America/Chicago)")
plt.ylabel("Mean Diurnal Carbon Flux (µmol m⁻² s⁻¹)")
plt.title("Mean Diurnal Cycle KONA [QF=1]")
plt.xticks(np.arange(0, 25, 2))
plt.grid(alpha=0.3)
plt.legend(title="Polygon")
plt.tight_layout()
plt.show()
(4) wrap_stat (FluxMaps, vector = None, product = 'daily')¶
Computes the statistics of FluxMaps or a polygon within FluxMaps. Not needed if you already ran wrap_diu.
vector
- Location of the vector file containing polygons in which you want to analyze and clip the FluxMap to.
Product ('half-hourly', 'daily')
- 'Half-hourly' will aggregate each 30-minute file into an average. 'Daily' will aggregate each file into a daily average for statistics.
# Half hourly spatial statistics
filtered_for_stats_half = wrap_filt_qf(
data="KONA",
flux="fluxCo2",
qf_thsh=1,
)
#Daily spatial statistics
filtered_for_stats_daily = wrap_filt_qf(
data="KONA",
flux="fluxCo2",
qf_thsh=1,
)
# wrap_stat function for just half-hourly stats
stats_half = wrap_stat(filtered_for_stats_half, product = "half-hourly", vector= "500m_radius.shp")
# wrap_stat function for just daily stats
stats_daily = wrap_stat(filtered_for_stats_daily, product = "daily", vector= "500m_radius.shp")
# Plotting a time series using wrap_stats() Half-Hourly Plotting
plot = [result.mean for result in stats_half]
data = np.concatenate((plot[0], plot[1], plot[2], plot[3], plot[4], plot[5], plot[6], plot[7], plot[8], plot[9], plot[10], plot[11], plot[12], plot[13],plot[14], plot[15], plot[16], plot[17], plot[18], plot[19], plot[20], plot[21], plot[22], plot[23], plot[24], plot[25], plot[26], plot[27], plot[28], plot[29], plot[30], plot[31]))
plt.plot(data, label = 'Mean Flux (Half-hourly)', color = 'red')
plt.title('Half_Hourly Time Series of KONA')
plt.xlabel('Time')
plt.ylabel('Average Half-Hourly fluxCo2 values')
#Plotting a Time Series using wrap_stats() Daily Plotting
#print("Number of results:", len(stats))
#for result in stats:
#print("Mean:", result.mean)
hours = np.arange(32)
#Each computed statistics out of the 32 Kona files can be called like this (daily):
stats0 = stats_daily[0].mean
stats1 = stats_daily[1].mean
#Plotting the time series
fig = plt.figure(figsize=(12, 8))
plt.plot(hours,
[result.mean for result in stats_daily],
marker = 'o',
color = 'purple')
plt.xlabel('KONA Day')
plt.ylabel('Daily fluxCo2 Mean of Flux Map')
plt.title('Daily Average Time Series of KONA')
Author: Allen Kaplan (akaplan@atmofacts.com)