Added plot of timeseries with sentinel-2 and fusion.

This commit is contained in:
Felix Delattre 2026-01-26 09:36:00 +01:00
parent 31dc536c3a
commit 41f363220f
3 changed files with 421 additions and 147 deletions

285
ndvi.py
View file

@ -7,6 +7,8 @@ from datetime import datetime
RED_BAND = 3
NIR_BAND = 4
BLUE_BAND = 1
GREEN_BAND = 2
def _calculate_and_write_ndvi(input_file, output_file):
@ -62,21 +64,53 @@ def _get_ndvi_value(ndvi_file, site_position):
return None
def _create_timeseries_for_dir(output_dir, site_position, source_name):
def _get_ndvi_from_original(input_file, site_position):
"""Calculate NDVI directly from original file without creating GeoTIFF."""
try:
with rasterio.open(input_file) as src:
if src.count < 4:
return None
red = src.read(RED_BAND).astype(np.float32)
nir = src.read(NIR_BAND).astype(np.float32)
lon, lat = site_position[1], site_position[0]
x, y = transform_coords("EPSG:4326", src.crs, [lon], [lat])
if not (
src.bounds.left <= x[0] <= src.bounds.right
and src.bounds.bottom <= y[0] <= src.bounds.top
):
return None
row, col = src.index(x[0], y[0])
if row < 0 or row >= src.height or col < 0 or col >= src.width:
return None
r_val = float(red[row, col])
n_val = float(nir[row, col])
if r_val <= 0 or n_val <= 0 or np.isnan(r_val) or np.isnan(n_val):
return None
ndvi = (n_val - r_val) / (n_val + r_val)
return ndvi if not np.isnan(ndvi) else None
except Exception as e:
return None
def _create_timeseries_for_dir(input_dir, output_dir, site_position, source_name, pattern="*.geotiff"):
print(f"[NDVI-{source_name}] Creating timeseries.json...")
timeseries = []
for ndvi_file in sorted(output_dir.glob("*.geotiff")):
filename = ndvi_file.name
# Extract date from filename
# Format examples:
# - YYYYMMDD_ndvi.geotiff -> date is at [0]
# - YYYYMMDD_0.geotiff -> date is at [0]
# - composite_YYYYMMDD.geotiff -> date is at [1]
for input_file in sorted(input_dir.glob(pattern)):
if "DIST_CLOUD" in input_file.name:
continue
filename = input_file.name
parts = filename.replace(".geotiff", "").split("_")
date_str = None
# Try to find a date pattern (8 digits)
for part in parts:
if len(part) == 8 and part.isdigit():
date_str = part
@ -88,21 +122,17 @@ def _create_timeseries_for_dir(output_dir, site_position, source_name):
except ValueError:
date = date_str
else:
# Fallback: use first part (for old MSIL2A_ndvi.geotiff files)
date_str = parts[0]
date = date_str
print(
f"[NDVI-{source_name}] Warning: Could not extract date from {filename}, using '{date_str}'"
)
ndvi_value = _get_ndvi_value(ndvi_file, site_position)
ndvi_value = _get_ndvi_from_original(input_file, site_position)
if ndvi_value is None:
print(
f"[NDVI-{source_name}] Warning: Could not sample {filename} (outside bounds or nodata)"
)
# Note: 0 is a valid NDVI value (no vegetation), so we keep it
# The _get_ndvi_value function now properly distinguishes between
# valid 0 values and nodata values
timeseries.append({"date": date, "filename": filename, "ndvi": ndvi_value})
@ -154,16 +184,15 @@ def _process_ndvi_files(
def generate_ndvi_raw(season, site_position, site_name):
for source in ["s2", "s3"]:
input_dir = Path(f"data/{site_name}/{season}/raw/{source}/")
output_dir = Path(f"data/{site_name}/{season}/raw/ndvi/{source}/")
_process_ndvi_files(input_dir, output_dir, source.upper())
# No longer creating NDVI GeoTIFF files, only timeseries
pass
def create_ndvi_timeseries_raw(season, site_position, site_name):
for source in ["s2", "s3"]:
input_dir = Path(f"data/{site_name}/{season}/raw/{source}/")
output_dir = Path(f"data/{site_name}/{season}/raw/ndvi/{source}/")
_create_timeseries_for_dir(output_dir, site_position, source.upper())
_create_timeseries_for_dir(input_dir, output_dir, site_position, source.upper())
def _get_output_name_prepared(geotiff_file):
@ -192,34 +221,208 @@ def _fusion_namer(f):
def generate_ndvi_post_process(season, site_position, site_name):
for source in ["s2", "s3"]:
input_dir = Path(f"data/{site_name}/{season}/processed/{source}/")
output_dir = Path(f"data/{site_name}/{season}/processed/ndvi/{source}/")
_process_ndvi_files(
input_dir,
output_dir,
f"POST-PROCESS-{source.upper()}",
pattern="*.geotiff",
output_namer=lambda f: f.name.replace(".geotiff", "_ndvi.geotiff"),
)
input_dir = Path(f"data/{site_name}/{season}/processed/fusion/")
output_dir = Path(f"data/{site_name}/{season}/processed/ndvi/fusion/")
_process_ndvi_files(
input_dir,
output_dir,
"POST-PROCESS-FUSION",
pattern="*.geotiff",
output_namer=lambda f: f.name.replace(".geotiff", "_ndvi.geotiff"),
)
# No longer creating NDVI GeoTIFF files, only timeseries
pass
def create_ndvi_timeseries_post_process(season, site_position, site_name):
for source in ["s2", "s3"]:
input_dir = Path(f"data/{site_name}/{season}/processed/{source}/")
output_dir = Path(f"data/{site_name}/{season}/processed/ndvi/{source}/")
_create_timeseries_for_dir(
output_dir, site_position, f"POST-PROCESS-{source.upper()}"
input_dir, output_dir, site_position, f"POST-PROCESS-{source.upper()}"
)
input_dir = Path(f"data/{site_name}/{season}/processed/fusion/")
output_dir = Path(f"data/{site_name}/{season}/processed/ndvi/fusion/")
_create_timeseries_for_dir(output_dir, site_position, "POST-PROCESS-FUSION")
_create_timeseries_for_dir(input_dir, output_dir, site_position, "POST-PROCESS-FUSION")
def _calculate_and_write_gcc(input_file, output_file):
with rasterio.open(input_file) as src:
blue = src.read(BLUE_BAND).astype(np.float32)
green = src.read(GREEN_BAND).astype(np.float32)
red = src.read(RED_BAND).astype(np.float32)
total = red + green + blue
mask = total > 0
gcc = np.zeros_like(green, dtype=np.float32)
gcc[mask] = green[mask] / total[mask]
profile = src.profile.copy()
profile.update(
{
"count": 1,
"dtype": "float32",
"nodata": 0,
"compress": "lzw",
}
)
with rasterio.open(output_file, "w", **profile) as dst:
dst.write(gcc, 1)
dst.set_band_description(1, "GCC")
def _get_gcc_value(gcc_file, site_position):
try:
with rasterio.open(gcc_file) as src:
lon, lat = site_position[1], site_position[0]
x, y = transform_coords("EPSG:4326", src.crs, [lon], [lat])
if not (
src.bounds.left <= x[0] <= src.bounds.right
and src.bounds.bottom <= y[0] <= src.bounds.top
):
return None
samples = list(src.sample([(x[0], y[0])]))
if samples:
value = float(samples[0][0])
if src.nodata is not None and value == src.nodata:
return None
if np.isnan(value):
return None
return value
except Exception as e:
print(f"Error sampling {gcc_file.name}: {e}")
pass
return None
def _get_gcc_from_original(input_file, site_position):
"""Calculate GCC directly from original file without creating GeoTIFF."""
try:
with rasterio.open(input_file) as src:
if src.count < 3:
return None
blue = src.read(BLUE_BAND).astype(np.float32)
green = src.read(GREEN_BAND).astype(np.float32)
red = src.read(RED_BAND).astype(np.float32)
lon, lat = site_position[1], site_position[0]
x, y = transform_coords("EPSG:4326", src.crs, [lon], [lat])
if not (
src.bounds.left <= x[0] <= src.bounds.right
and src.bounds.bottom <= y[0] <= src.bounds.top
):
return None
row, col = src.index(x[0], y[0])
if row < 0 or row >= src.height or col < 0 or col >= src.width:
return None
b_val = float(blue[row, col])
g_val = float(green[row, col])
r_val = float(red[row, col])
total = r_val + g_val + b_val
if total <= 0 or np.isnan(total):
return None
gcc = g_val / total
return gcc if not np.isnan(gcc) else None
except Exception as e:
return None
def _create_gcc_timeseries_for_dir(input_dir, output_dir, site_position, source_name, pattern="*.geotiff"):
print(f"[GCC-{source_name}] Creating timeseries.json...")
timeseries = []
for input_file in sorted(input_dir.glob(pattern)):
if "DIST_CLOUD" in input_file.name:
continue
filename = input_file.name
parts = filename.replace(".geotiff", "").split("_")
date_str = None
for part in parts:
if len(part) == 8 and part.isdigit():
date_str = part
break
if date_str:
try:
date = datetime.strptime(date_str, "%Y%m%d").isoformat()
except ValueError:
date = date_str
else:
date_str = parts[0]
date = date_str
print(
f"[GCC-{source_name}] Warning: Could not extract date from {filename}, using '{date_str}'"
)
gcc_value = _get_gcc_from_original(input_file, site_position)
if gcc_value is None:
print(
f"[GCC-{source_name}] Warning: Could not sample {filename} (outside bounds or nodata)"
)
timeseries.append({"date": date, "filename": filename, "greenness_index": gcc_value})
timeseries.sort(key=lambda x: x["date"])
output_dir.mkdir(parents=True, exist_ok=True)
timeseries_file = output_dir / "timeseries.json"
with open(timeseries_file, "w") as f:
json.dump(timeseries, f, indent=2)
print(f"[GCC-{source_name}] Saved: {timeseries_file} ({len(timeseries)} entries)")
def _process_gcc_files(
input_dir, output_dir, source_name, pattern="*.geotiff", output_namer=None
):
output_dir.mkdir(parents=True, exist_ok=True)
print(f"[GCC-{source_name}] Processing {input_dir}...")
geotiff_files = sorted(input_dir.glob(pattern))
if not geotiff_files:
print(f"[GCC-{source_name}] No files found")
return
for geotiff_file in geotiff_files:
if "DIST_CLOUD" in geotiff_file.name:
continue
try:
with rasterio.open(geotiff_file) as src:
if src.count < 3:
print(
f"[GCC-{source_name}] Skipping {geotiff_file.name} (only {src.count} band(s), need 3+)"
)
continue
except Exception as e:
print(
f"[GCC-{source_name}] Skipping {geotiff_file.name} (error reading: {e})"
)
continue
output_file = output_dir / (
output_namer(geotiff_file) if output_namer else geotiff_file.name
)
_calculate_and_write_gcc(geotiff_file, output_file)
print(f"[GCC-{source_name}] Saved: {output_file}")
def generate_gcc_post_process(season, site_position, site_name):
# No longer creating GCC GeoTIFF files, only timeseries
pass
def create_gcc_timeseries_post_process(season, site_position, site_name):
for source in ["s2", "s3"]:
input_dir = Path(f"data/{site_name}/{season}/processed/{source}/")
output_dir = Path(f"data/{site_name}/{season}/processed/gcc/{source}/")
_create_gcc_timeseries_for_dir(
input_dir, output_dir, site_position, f"POST-PROCESS-{source.upper()}"
)
input_dir = Path(f"data/{site_name}/{season}/processed/fusion/")
output_dir = Path(f"data/{site_name}/{season}/processed/gcc/fusion/")
_create_gcc_timeseries_for_dir(input_dir, output_dir, site_position, "POST-PROCESS-FUSION")

7
run.py
View file

@ -5,6 +5,8 @@ from ndvi import (
create_ndvi_timeseries_raw,
generate_ndvi_post_process,
create_ndvi_timeseries_post_process,
generate_gcc_post_process,
create_gcc_timeseries_post_process,
)
from download_s2 import download_s2
from download_s3 import download_s3
@ -18,7 +20,7 @@ def run_pipeline(season, site_position, site_name):
# download_s2(season, site_position, site_name)
# download_s3(season, site_position, site_name)
# download_phenocam(season, site_position, site_name)
download_phenocam_greenness(season, site_position, site_name)
#download_phenocam_greenness(season, site_position, site_name)
# print(f"Generating NDVI for raw data: {site_name}, {season}")
# generate_ndvi_raw(season, site_position, site_name)
@ -39,6 +41,9 @@ def run_pipeline(season, site_position, site_name):
#print(f"Generating NDVI for final outputs: {site_name}, {season}")
#generate_ndvi_post_process(season, site_position, site_name)
#create_ndvi_timeseries_post_process(season, site_position, site_name)
#print(f"Generating GCC for final outputs: {site_name}, {season}")
generate_gcc_post_process(season, site_position, site_name)
create_gcc_timeseries_post_process(season, site_position, site_name)
except Exception as e:
print(f"Error: {e}")

View file

@ -29,6 +29,9 @@
.map-label { font-size: 12px; margin-bottom: 5px; color: #666; }
.map-date { font-size: 11px; margin-top: 5px; color: #999; }
.map { height: 500px; border: 1px solid #ccc; }
.combined-plot { margin-top: 20px; }
.combined-plot-label { font-size: 12px; margin-bottom: 5px; color: #666; }
.combined-plot-canvas { width: 100%; height: 120px; border: 1px solid #ccc; }
.leaflet-image-layer { image-rendering: pixelated; }
.leaflet-control-attribution { display: none; }
</style>
@ -60,36 +63,37 @@
<h3>S2</h3>
<div class="timeseries-label">NDVI Timeseries</div>
<canvas id="s2timeseries" class="timeseries"></canvas>
<div class="timeseries-label">Greenness Index Timeseries</div>
<canvas id="s2gcctimeseries" class="timeseries"></canvas>
<div class="map-label">RGB Composite</div>
<div id="s2rgbdate" class="map-date"></div>
<div id="s2map" class="map"></div>
<div class="map-label">NDVI</div>
<div id="s2ndvidate" class="map-date"></div>
<div id="s2ndvimap" class="map"></div>
</div>
<div class="map-container">
<h3>Fusion</h3>
<div class="timeseries-label">NDVI Timeseries</div>
<canvas id="fusiontimeseries" class="timeseries"></canvas>
<div class="timeseries-label">Greenness Index Timeseries</div>
<canvas id="fusiongcctimeseries" class="timeseries"></canvas>
<div class="map-label">RGB Composite</div>
<div id="fusionrgbdate" class="map-date"></div>
<div id="fusionmap" class="map"></div>
<div class="map-label">NDVI</div>
<div id="fusionndvidate" class="map-date"></div>
<div id="fusionndvimap" class="map"></div>
</div>
<div class="map-container">
<h3>S3</h3>
<div class="timeseries-label">NDVI Timeseries</div>
<canvas id="s3timeseries" class="timeseries"></canvas>
<div class="timeseries-label">Greenness Index Timeseries</div>
<canvas id="s3gcctimeseries" class="timeseries"></canvas>
<div class="map-label">RGB Composite</div>
<div id="s3rgbdate" class="map-date"></div>
<div id="s3map" class="map"></div>
<div class="map-label">NDVI</div>
<div id="s3ndvidate" class="map-date"></div>
<div id="s3ndvimap" class="map"></div>
</div>
</div>
<div class="combined-plot">
<div class="combined-plot-label">Greenness Index Timeseries (S2 & Fusion)</div>
<canvas id="combinedgcctimeseries" class="combined-plot-canvas"></canvas>
</div>
</div>
<script>
proj4.defs("EPSG:32632", "+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs");
@ -109,26 +113,19 @@
fusion: L.map("fusionmap", mapOpts).setView(sitePosition, 12).addLayer(L.tileLayer(osmUrl, osmOpts)),
s3: L.map("s3map", mapOpts).setView(sitePosition, 12).addLayer(L.tileLayer(osmUrl, osmOpts))
};
const ndvimaps = {
s2: L.map("s2ndvimap", mapOpts).setView(sitePosition, 12).addLayer(L.tileLayer(osmUrl, osmOpts)),
fusion: L.map("fusionndvimap", mapOpts).setView(sitePosition, 12).addLayer(L.tileLayer(osmUrl, osmOpts)),
s3: L.map("s3ndvimap", mapOpts).setView(sitePosition, 12).addLayer(L.tileLayer(osmUrl, osmOpts))
};
const overlays = { s2: null, fusion: null, s3: null };
const ndviOverlays = { s2: null, fusion: null, s3: null };
const markers = { s2: null, fusion: null, s3: null };
const ndviMarkers = { s2: null, fusion: null, s3: null };
let timeseries = { s2: [], fusion: [], s3: [] };
let greennessTimeseries = [];
let greennessTimeseries = { s2: [], fusion: [], s3: [] };
let phenocamGreennessTimeseries = [];
// Add site marker to all maps
for (const source of ["s2", "fusion", "s3"]) {
markers[source] = L.marker(sitePosition, { icon: L.divIcon({ className: "site-marker", html: "<div style='width:5px;height:5px;background:red;border:1px solid white;border-radius:50%;box-shadow:0 0 1px rgba(0,0,0,0.5);'></div>", iconSize: [5, 5] }) }).addTo(maps[source]);
ndviMarkers[source] = L.marker(sitePosition, { icon: L.divIcon({ className: "site-marker", html: "<div style='width:5px;height:5px;background:red;border:1px solid white;border-radius:50%;box-shadow:0 0 1px rgba(0,0,0,0.5);'></div>", iconSize: [5, 5] }) }).addTo(ndvimaps[source]);
}
let syncing = false;
const allMaps = Object.values(maps).concat(Object.values(ndvimaps));
const allMaps = Object.values(maps);
const syncMaps = (sourceMap) => {
if (syncing) return;
syncing = true;
@ -144,19 +141,95 @@
});
async function loadTimeseries() {
const [s2, fusion, s3, greenness] = await Promise.all([
const [s2, fusion, s3, s2gcc, fusiongcc, s3gcc, phenocam] = await Promise.all([
fetch("../data/innsbruck/2024/processed/ndvi/s2/timeseries.json").then(r => r.json()),
fetch("../data/innsbruck/2024/processed/ndvi/fusion/timeseries.json").then(r => r.json()).catch(() => []),
fetch("../data/innsbruck/2024/processed/ndvi/s3/timeseries.json").then(r => r.json()),
fetch("../data/innsbruck/2024/processed/gcc/s2/timeseries.json").then(r => r.json()).catch(() => []),
fetch("../data/innsbruck/2024/processed/gcc/fusion/timeseries.json").then(r => r.json()).catch(() => []),
fetch("../data/innsbruck/2024/processed/gcc/s3/timeseries.json").then(r => r.json()).catch(() => []),
fetch("../data/innsbruck/2024/raw/phenocam/timeseries.json").then(r => r.json()).catch(() => [])
]);
timeseries = { s2, fusion, s3 };
greennessTimeseries = greenness;
greennessTimeseries = { s2: s2gcc, fusion: fusiongcc, s3: s3gcc };
phenocamGreennessTimeseries = phenocam;
drawTimeseries();
drawGreennessTimeseries();
drawPhenocamGreennessTimeseries();
drawCombinedGreennessTimeseries();
}
function drawGreennessTimeseries() {
const currentDate = dateFromDays(parseInt(slider.value));
for (const source of ["s2", "fusion", "s3"]) {
const canvas = document.getElementById(`${source}gcctimeseries`);
const ctx = canvas.getContext("2d");
canvas.width = canvas.offsetWidth;
canvas.height = 120;
const w = canvas.width, h = canvas.height;
const pad = 30;
const plotW = w - pad * 2, plotH = h - pad * 2;
ctx.clearRect(0, 0, w, h);
let data = greennessTimeseries[source].filter(t => t.date && t.greenness_index !== null && t.greenness_index !== undefined);
if (!data.length) continue;
const dates = data.map(t => new Date(t.date));
const minDate = new Date(Math.min(...dates));
const maxDate = new Date(Math.max(...dates));
const dateRange = maxDate - minDate || 1;
const values = data.map(t => t.greenness_index);
const minVal = Math.min(...values);
const maxVal = Math.max(...values);
const valRange = maxVal - minVal || 1;
const x = (d) => pad + ((new Date(d) - minDate) / dateRange) * plotW;
const y = (v) => pad + plotH - ((v - minVal) / valRange) * plotH;
ctx.strokeStyle = "#ccc";
ctx.beginPath();
ctx.moveTo(pad, pad);
ctx.lineTo(pad, pad + plotH);
ctx.lineTo(pad + plotW, pad + plotH);
ctx.stroke();
ctx.fillStyle = "#000";
ctx.font = "9px sans-serif";
ctx.fillText(minVal.toFixed(3), 2, pad + plotH + 10);
ctx.fillText(maxVal.toFixed(3), 2, pad + 3);
ctx.strokeStyle = "#00aa00";
ctx.beginPath();
let first = true;
for (const t of data) {
const px = x(t.date), py = y(t.greenness_index);
if (first) { ctx.moveTo(px, py); first = false; }
else ctx.lineTo(px, py);
}
ctx.stroke();
const xPos = x(currentDate);
ctx.strokeStyle = "#f00";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(xPos, pad);
ctx.lineTo(xPos, pad + plotH);
ctx.stroke();
const closest = data.reduce((c, t) =>
Math.abs(new Date(t.date) - new Date(currentDate)) < Math.abs(new Date(c.date) - new Date(currentDate)) ? t : c
);
if (closest && closest.greenness_index !== null) {
const yPos = y(closest.greenness_index);
ctx.fillStyle = "#f00";
ctx.font = "bold 10px sans-serif";
ctx.fillText(closest.greenness_index.toFixed(3), xPos + 5, yPos - 5);
}
}
}
function drawPhenocamGreennessTimeseries() {
const canvas = document.getElementById("greennesstimeseries");
const ctx = canvas.getContext("2d");
canvas.width = canvas.offsetWidth;
@ -166,7 +239,7 @@
const plotW = w - pad * 2, plotH = h - pad * 2;
ctx.clearRect(0, 0, w, h);
const data = greennessTimeseries.filter(t => t.date && t.greenness_index !== null && t.greenness_index !== undefined);
const data = phenocamGreennessTimeseries.filter(t => t.date && t.greenness_index !== null && t.greenness_index !== undefined);
if (!data.length) return;
const dates = data.map(t => new Date(t.date));
@ -224,6 +297,79 @@
}
}
function drawCombinedGreennessTimeseries() {
const canvas = document.getElementById("combinedgcctimeseries");
const ctx = canvas.getContext("2d");
canvas.width = canvas.offsetWidth;
canvas.height = 120;
const w = canvas.width, h = canvas.height;
const pad = 30;
const plotW = w - pad * 2, plotH = h - pad * 2;
ctx.clearRect(0, 0, w, h);
const s2data = greennessTimeseries.s2.filter(t => t.date && t.greenness_index !== null && t.greenness_index !== undefined);
const fusiondata = greennessTimeseries.fusion.filter(t => t.date && t.greenness_index !== null && t.greenness_index !== undefined);
if (!s2data.length && !fusiondata.length) return;
const allDates = [...s2data.map(t => new Date(t.date)), ...fusiondata.map(t => new Date(t.date))];
const minDate = new Date(Math.min(...allDates));
const maxDate = new Date(Math.max(...allDates));
const dateRange = maxDate - minDate || 1;
const allValues = [...s2data.map(t => t.greenness_index), ...fusiondata.map(t => t.greenness_index)];
const minVal = Math.min(...allValues);
const maxVal = Math.max(...allValues);
const valRange = maxVal - minVal || 1;
const x = (d) => pad + ((new Date(d) - minDate) / dateRange) * plotW;
const y = (v) => pad + plotH - ((v - minVal) / valRange) * plotH;
ctx.strokeStyle = "#ccc";
ctx.beginPath();
ctx.moveTo(pad, pad);
ctx.lineTo(pad, pad + plotH);
ctx.lineTo(pad + plotW, pad + plotH);
ctx.stroke();
ctx.fillStyle = "#000";
ctx.font = "9px sans-serif";
ctx.fillText(minVal.toFixed(3), 2, pad + plotH + 10);
ctx.fillText(maxVal.toFixed(3), 2, pad + 3);
if (s2data.length) {
ctx.strokeStyle = "#ff6600";
ctx.beginPath();
let first = true;
for (const t of s2data) {
const px = x(t.date), py = y(t.greenness_index);
if (first) { ctx.moveTo(px, py); first = false; }
else ctx.lineTo(px, py);
}
ctx.stroke();
}
if (fusiondata.length) {
ctx.strokeStyle = "#9900cc";
ctx.beginPath();
let first = true;
for (const t of fusiondata) {
const px = x(t.date), py = y(t.greenness_index);
if (first) { ctx.moveTo(px, py); first = false; }
else ctx.lineTo(px, py);
}
ctx.stroke();
}
const currentDate = dateFromDays(parseInt(slider.value));
const xPos = x(currentDate);
ctx.strokeStyle = "#f00";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(xPos, pad);
ctx.lineTo(xPos, pad + plotH);
ctx.stroke();
}
function drawTimeseries() {
const currentDate = dateFromDays(parseInt(slider.value));
for (const source of ["s2", "fusion", "s3"]) {
@ -275,7 +421,7 @@
ctx.fillText(minNdvi.toFixed(2), 2, pad + plotH + 10);
ctx.fillText(maxNdvi.toFixed(2), 2, pad + 3);
ctx.strokeStyle = source === "s2" ? "#0066ff" : source === "fusion" ? "#00aa00" : "#ff6600";
ctx.strokeStyle = "#0066ff";
ctx.beginPath();
let first = true;
for (const t of data) {
@ -395,49 +541,6 @@
document.getElementById(`${source}rgbdate`).textContent = date;
}
async function loadNDVI(source, filename, dateStr) {
const tiff = await GeoTIFF.fromArrayBuffer(await (await fetch(`../data/innsbruck/2024/processed/ndvi/${source}/${filename}`)).arrayBuffer());
const image = await tiff.getImage();
const data = Array.from((await image.readRasters())[0]);
const width = image.getWidth();
const height = image.getHeight();
const bbox = image.getBoundingBox();
const geoKeys = image.getGeoKeys();
const crsCode = geoKeys.ProjectedCSTypeGeoKey ? `EPSG:${geoKeys.ProjectedCSTypeGeoKey}` :
geoKeys.GeographicTypeGeoKey !== 4326 ? `EPSG:${geoKeys.GeographicTypeGeoKey}` : "EPSG:4326";
let minVal = Infinity, maxVal = -Infinity;
for (const v of data) if (!isNaN(v) && v !== 0) { minVal = Math.min(minVal, v); maxVal = Math.max(maxVal, v); }
const canvas = Object.assign(document.createElement("canvas"), { width, height });
const ctx = canvas.getContext("2d");
ctx.imageSmoothingEnabled = false;
const imgData = ctx.createImageData(width, height);
for (let i = 0; i < data.length; i++) {
const val = data[i];
const idx = i * 4;
if (val === 0 || isNaN(val)) {
imgData.data[idx + 3] = 0;
} else {
const n = ((val - minVal) / (maxVal - minVal || 1)) * 255;
imgData.data[idx] = imgData.data[idx + 1] = imgData.data[idx + 2] = n;
imgData.data[idx + 3] = 255;
}
}
ctx.putImageData(imgData, 0, 0);
const bounds = crsCode === "EPSG:4326" ? [[bbox[1], bbox[0]], [bbox[3], bbox[2]]] : transformBounds(bbox, crsCode);
if (ndviOverlays[source]) ndvimaps[source].removeLayer(ndviOverlays[source]);
ndviOverlays[source] = L.imageOverlay(canvas.toDataURL(), bounds, { opacity: 0.95 }).addTo(ndvimaps[source]);
ndvimaps[source].fitBounds(bounds);
// Extract date from filename to show the actual date of the file found (closest available date)
const extractedDateStr = filename.split("_")[0];
const date = `${extractedDateStr.slice(0,4)}-${extractedDateStr.slice(4,6)}-${extractedDateStr.slice(6,8)}`;
document.getElementById(`${source}ndvidate`).textContent = date;
}
const fmtDate = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
const dateFromDays = (days) => fmtDate(new Date(start.getTime() + days * 86400000));
const daysFromDate = (dateStr) => {
@ -445,37 +548,6 @@
return Math.floor((new Date(y, m - 1, d) - start) / 86400000);
};
async function findNDVIFile(dateStr, source) {
const target = new Date(dateStr);
// Search outward from target date (0, ±1, ±2, ±3, ...) until we find the closest file
// Check dates in order: exact, then -1, +1, then -2, +2, etc.
// Limit to ±365 days to avoid infinite search
for (let offset = 0; offset <= 365; offset++) {
// Check exact date first (offset=0)
if (offset === 0) {
const date = target.toISOString().split("T")[0].replace(/-/g, "");
const filename = `${date}_0_ndvi.geotiff`;
try {
const res = await fetch(`../data/innsbruck/2024/processed/ndvi/${source}/${filename}`, { method: 'HEAD' });
if (res.ok) return filename;
} catch {}
} else {
// Check -offset and +offset days
for (const dir of [-1, 1]) {
const d = new Date(target);
d.setDate(d.getDate() + offset * dir);
const date = d.toISOString().split("T")[0].replace(/-/g, "");
const filename = `${date}_0_ndvi.geotiff`;
try {
const res = await fetch(`../data/innsbruck/2024/processed/ndvi/${source}/${filename}`, { method: 'HEAD' });
if (res.ok) return filename;
} catch {}
}
}
}
return null;
}
async function loadPhenoCam(dateStr) {
const target = new Date(dateStr);
for (let offset = 0; offset < 15; offset++) {
@ -506,6 +578,8 @@
history.replaceState({}, "", `?${params}`);
drawTimeseries();
drawGreennessTimeseries();
drawPhenocamGreennessTimeseries();
drawCombinedGreennessTimeseries();
for (const source of ["s2", "fusion", "s3"]) {
const filename = await findFile(date, source);
if (filename) {
@ -515,14 +589,6 @@
console.error(`Error loading ${source}:`, e);
}
}
const ndviFilename = await findNDVIFile(date, source);
if (ndviFilename) {
try {
await loadNDVI(source, ndviFilename, date);
} catch (e) {
console.error(`Error loading NDVI ${source}:`, e);
}
}
}
await loadPhenoCam(date);
}