Fixed preselection viewer.

This commit is contained in:
Felix Delattre 2026-02-21 00:27:43 +01:00
parent ac0e687956
commit 585b2d31b0
4 changed files with 82 additions and 401 deletions

View file

@ -10,7 +10,8 @@ from datetime import datetime
WINDOW_DAYS = 14 WINDOW_DAYS = 14
MIN_WINDOW_SIZE = 3 MIN_WINDOW_SIZE = 3
THRESHOLDS = {"aggressive": {"threshold": 0.3, "delta": 0.15}, "nonaggressive": {"threshold": 0.2, "delta": 0.25}} THRESHOLDS = {"aggressive": {"threshold": 0.3, "delta": 0.15}, "nonaggressive": {"threshold": 0.2, "delta": 0.25}}
BLUE_MIN = 0.01 # S2 uses reflectance * 10000, S3 uses 0-1
BLUE_MIN = {"s2": 100, "s3": 0.01}
GREEN_BAND = 2 GREEN_BAND = 2
RED_BAND = 3 RED_BAND = 3
@ -57,12 +58,13 @@ def _extract_date(filename):
return None, None return None, None
def _is_excluded(entry, entries, strategy): def _is_excluded(entry, entries, strategy, source="s2"):
"""True if entry is excluded by strategy (NDVI threshold/delta or dark blue).""" """True if entry is excluded by strategy (NDVI threshold/delta or dark blue)."""
th = THRESHOLDS[strategy] th = THRESHOLDS[strategy]
if entry.get("ndvi") is None: if entry.get("ndvi") is None:
return True return True
if entry.get("b02") is not None and entry["b02"] < BLUE_MIN: blue_min = BLUE_MIN.get(source, BLUE_MIN["s2"])
if entry.get("b02") is not None and entry["b02"] < blue_min:
return True return True
entry_date = datetime.fromisoformat(entry["date"].replace("Z", "+00:00")) entry_date = datetime.fromisoformat(entry["date"].replace("Z", "+00:00"))
window_ndvi = [] window_ndvi = []
@ -110,8 +112,8 @@ def create_timeseries(season, site_position, site_name):
timeseries.sort(key=lambda e: e["date"]) timeseries.sort(key=lambda e: e["date"])
for e in timeseries: for e in timeseries:
e["excluded_aggressive"] = _is_excluded(e, timeseries, "aggressive") e["excluded_aggressive"] = _is_excluded(e, timeseries, "aggressive", source)
e["excluded_nonaggressive"] = _is_excluded(e, timeseries, "nonaggressive") e["excluded_nonaggressive"] = _is_excluded(e, timeseries, "nonaggressive", source)
with open(output_file, "w") as out: with open(output_file, "w") as out:
json.dump(timeseries, out, indent=2) json.dump(timeseries, out, indent=2)

15
run.py
View file

@ -15,6 +15,7 @@ from preselection import create_timeseries
def run_pipeline(season, site_position, site_name): def run_pipeline(season, site_position, site_name):
"""Run pipeline (downloads + preselection).""" """Run pipeline (downloads + preselection)."""
try: try:
print(f"Downloading S2, S3, and PhenoCam: {site_name}, {season}")
download_s2(season, site_position, site_name) download_s2(season, site_position, site_name)
download_s3(season, site_position, site_name) download_s3(season, site_position, site_name)
download_phenocam(season, site_position, site_name) download_phenocam(season, site_position, site_name)
@ -41,11 +42,11 @@ def run_pipeline(season, site_position, site_name):
if __name__ == "__main__": if __name__ == "__main__":
#run_pipeline(2024, (35.3045, 25.0743), "forthgr") run_pipeline(2024, (35.3045, 25.0743), "forthgr")
run_pipeline(2024, (47.116171, 11.320308), "innsbruck") #run_pipeline(2024, (47.116171, 11.320308), "innsbruck")
#run_pipeline(2020, (47.116171, 11.320308), "innsbruck") run_pipeline(2020, (47.116171, 11.320308), "innsbruck")
#run_pipeline(2024, (58.5633, 24.3688), "pitsalu") run_pipeline(2024, (58.5633, 24.3688), "pitsalu")
#run_pipeline(2023, (64.2437, 19.7673), "vindeln2") run_pipeline(2023, (64.2437, 19.7673), "vindeln2")
#run_pipeline(2024, (36.7455, -6.0033), "sunflowerjerez1") run_pipeline(2024, (36.7455, -6.0033), "sunflowerjerez1")
#run_pipeline(2024, (42.6558, 26.9837), "institutekarnobat") run_pipeline(2024, (42.6558, 26.9837), "institutekarnobat")

View file

@ -1,354 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>NDVI Viewer</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://cdn.jsdelivr.net/npm/geotiff@2.0.7/dist-browser/geotiff.js"></script>
<script src="https://cdn.jsdelivr.net/npm/proj4@2.9.0/dist/proj4.js"></script>
<style>
body { margin: 0; font-family: sans-serif; }
.slider-container { position: sticky; top: 0; background: white; padding: 20px; z-index: 1000; border-bottom: 1px solid #ccc; }
.container { max-width: 1400px; margin: 0 auto; padding: 20px; }
#dateSlider { width: 100%; }
#dateDisplay { text-align: center; margin: 10px 0; font-size: 18px; }
.maps { display: flex; gap: 20px; }
.map-container { flex: 1; }
.map-container h3 { margin: 10px 0; text-align: center; }
.timeseries-label { font-size: 12px; margin-bottom: 5px; color: #666; }
.timeseries { width: 100%; height: 120px; border: 1px solid #ccc; margin-bottom: 10px; }
.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; }
.leaflet-image-layer { image-rendering: pixelated; }
.leaflet-control-attribution { display: none; }
</style>
</head>
<body>
<div class="container">
<div class="slider-container">
<input type="range" id="dateSlider" min="0" max="365" value="0">
<div id="dateDisplay">2024-01-01</div>
<label style="display: flex; align-items: center; justify-content: center; gap: 8px; margin-top: 10px;">
<input type="checkbox" id="showClouds" checked>
<span>Show cloud-covered data</span>
</label>
</div>
<div class="maps">
<div class="map-container">
<h3>S2</h3>
<div class="timeseries-label">NDVI Timeseries</div>
<canvas id="s2timeseries" class="timeseries"></canvas>
<div class="map-label">RGB Imagery</div>
<div id="s2rgbdate" class="map-date"></div>
<div id="s2map" class="map"></div>
<div class="map-label">NDVI Imagery</div>
<div id="s2ndvidate" class="map-date"></div>
<div id="s2ndvimap" 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="map-label">RGB Imagery</div>
<div id="s3rgbdate" class="map-date"></div>
<div id="s3map" class="map"></div>
<div class="map-label">NDVI Imagery</div>
<div id="s3ndvidate" class="map-date"></div>
<div id="s3ndvimap" class="map"></div>
</div>
</div>
</div>
<script>
proj4.defs("EPSG:32632", "+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs");
proj4.defs("EPSG:4326", "+proj=longlat +datum=WGS84 +no_defs");
const start = new Date(2024, 0, 1);
const slider = document.getElementById("dateSlider");
const dateDisplay = document.getElementById("dateDisplay");
const osmUrl = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png";
const osmOpts = { attribution: "OpenStreetMap", opacity: 0.4 };
const mapOpts = { zoomControl: false };
const maps = {
s2: L.map("s2map", mapOpts).setView([47.27, 11.39], 12).addLayer(L.tileLayer(osmUrl, osmOpts)),
s3: L.map("s3map", mapOpts).setView([47.27, 11.39], 12).addLayer(L.tileLayer(osmUrl, osmOpts))
};
const ndvimaps = {
s2: L.map("s2ndvimap", mapOpts).setView([47.27, 11.39], 12).addLayer(L.tileLayer(osmUrl, osmOpts)),
s3: L.map("s3ndvimap", mapOpts).setView([47.27, 11.39], 12).addLayer(L.tileLayer(osmUrl, osmOpts))
};
const overlays = { s2: null, s3: null };
const ndviOverlays = { s2: null, s3: null };
let timeseries = { s2: [], s3: [] };
let clouds = { s2: new Set(), s3: new Set() };
const showCloudsCheckbox = document.getElementById("showClouds");
async function loadTimeseries() {
const [s2, s3] = await Promise.all([
fetch("../data/innsbruck/2024/raw/preselection/s2_preselection.json").then(r => r.json()),
fetch("../data/innsbruck/2024/raw/preselection/s3_preselection.json").then(r => r.json())
]);
timeseries = { s2, s3 };
clouds = {
s2: new Set((s2 || []).filter(e => e.excluded_aggressive).map(e => e.filename)),
s3: new Set((s3 || []).filter(e => e.excluded_aggressive).map(e => e.filename))
};
drawTimeseries();
}
function drawTimeseries() {
const currentDate = dateFromDays(parseInt(slider.value));
for (const source of ["s2", "s3"]) {
const canvas = document.getElementById(`${source}timeseries`);
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 = timeseries[source].filter(t => t.ndvi !== null);
if (!showCloudsCheckbox.checked && clouds[source]) {
data = data.filter(t => !clouds[source].has(t.filename));
}
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;
const ndvi = data.map(t => t.ndvi);
const minNdvi = Math.min(...ndvi);
const maxNdvi = Math.max(...ndvi);
const ndviRange = maxNdvi - minNdvi;
const x = (d) => pad + ((new Date(d) - minDate) / dateRange) * plotW;
const y = (v) => pad + plotH - ((v - minNdvi) / ndviRange) * 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(minNdvi.toFixed(2), 2, pad + plotH + 10);
ctx.fillText(maxNdvi.toFixed(2), 2, pad + 3);
ctx.strokeStyle = source === "s2" ? "#0066ff" : "#ff6600";
ctx.beginPath();
let first = true;
for (const t of data) {
const px = x(t.date), py = y(t.ndvi);
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.ndvi !== null) {
const yPos = y(closest.ndvi);
ctx.fillStyle = "#f00";
ctx.font = "bold 10px sans-serif";
ctx.fillText(closest.ndvi.toFixed(3), xPos + 5, yPos - 5);
}
}
}
async function findFile(dateStr, source) {
const target = new Date(dateStr);
for (let offset = 0; offset < 15; offset++) {
for (const dir of [0, -1, 1]) {
const d = new Date(target);
d.setDate(d.getDate() + offset * dir);
const date = d.toISOString().split("T")[0].replace(/-/g, "");
for (let i = 0; i < 3; i++) {
const filename = `${date}_${i}.geotiff`;
if (!showCloudsCheckbox.checked && clouds[source] && clouds[source].has(filename)) continue;
try {
const res = await fetch(`../data/innsbruck/2024/raw/${source}/${filename}`);
if (res.ok) return filename;
} catch {}
}
}
}
return null;
}
function transformBounds(bbox, fromCRS) {
const [sw, ne] = [proj4(fromCRS, "EPSG:4326", [bbox[0], bbox[1]]), proj4(fromCRS, "EPSG:4326", [bbox[2], bbox[3]])];
return [[sw[1], sw[0]], [ne[1], ne[0]]];
}
async function loadGeotiff(source, filename) {
const path = `../data/innsbruck/2024/raw/${source}/${filename}`;
const tiff = await GeoTIFF.fromArrayBuffer(await (await fetch(path)).arrayBuffer());
const image = await tiff.getImage();
const rasters = await image.readRasters();
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";
const bandIndices = [0, 1, 2];
const [blue, green, red] = bandIndices.map(i => Array.from(rasters[i]));
const normalize = (arr) => {
let min = Infinity, max = -Infinity;
for (const v of arr) if (!isNaN(v) && v > 0) { min = Math.min(min, v); max = Math.max(max, v); }
return arr.map(v => Math.max(0, Math.min(255, ((v - min) / (max - min || 1)) * 255)));
};
const [rNorm, gNorm, bNorm] = [red, green, blue].map(normalize);
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 < rNorm.length; i++) {
const idx = i * 4;
if (rNorm[i] === 0 && gNorm[i] === 0 && bNorm[i] === 0) {
imgData.data[idx + 3] = 0;
} else {
imgData.data[idx] = rNorm[i];
imgData.data[idx + 1] = gNorm[i];
imgData.data[idx + 2] = bNorm[i];
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 (overlays[source]) maps[source].removeLayer(overlays[source]);
overlays[source] = L.imageOverlay(canvas.toDataURL(), bounds, { opacity: 0.95 }).addTo(maps[source]);
maps[source].fitBounds(bounds);
const dateStr = filename.split("_")[0];
const date = `${dateStr.slice(0,4)}-${dateStr.slice(4,6)}-${dateStr.slice(6,8)}`;
document.getElementById(`${source}rgbdate`).textContent = date;
}
async function loadNDVI(source, filename) {
const tiff = await GeoTIFF.fromArrayBuffer(await (await fetch(`../data/innsbruck/2024/raw/${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);
const dateStr = filename.split("_")[0];
const date = `${dateStr.slice(0,4)}-${dateStr.slice(4,6)}-${dateStr.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) => {
const [y, m, d] = dateStr.split("-").map(Number);
return Math.floor((new Date(y, m - 1, d) - start) / 86400000);
};
async function findNDVIFile(dateStr, source) {
const target = new Date(dateStr);
for (let offset = 0; offset < 15; offset++) {
for (const dir of [0, -1, 1]) {
const d = new Date(target);
d.setDate(d.getDate() + offset * dir);
const date = d.toISOString().split("T")[0].replace(/-/g, "");
for (let i = 0; i < 3; i++) {
const filename = `${date}_${i}.geotiff`;
if (!showCloudsCheckbox.checked && clouds[source] && clouds[source].has(filename)) continue;
try {
const res = await fetch(`../data/innsbruck/2024/raw/${source}/${filename}`);
if (res.ok) return filename;
} catch {}
}
}
}
return null;
}
async function updateImages() {
const date = dateFromDays(parseInt(slider.value));
dateDisplay.textContent = date;
const params = new URLSearchParams();
params.set("date", date);
if (!showCloudsCheckbox.checked) params.set("hideClouds", "1");
history.replaceState({}, "", `?${params}`);
drawTimeseries();
for (const source of ["s2", "s3"]) {
const filename = await findFile(date, source);
if (filename) {
try {
await loadGeotiff(source, filename);
} catch (e) {
console.error(`Error loading ${source}:`, e);
}
}
const ndviFilename = await findNDVIFile(date, source);
if (ndviFilename) {
try {
await loadNDVI(source, ndviFilename);
} catch (e) {
console.error(`Error loading NDVI ${source}:`, e);
}
}
}
}
const urlParams = new URLSearchParams(location.search);
const urlDate = urlParams.get("date");
if (urlDate) slider.value = daysFromDate(urlDate);
if (urlParams.get("hideClouds") === "1") showCloudsCheckbox.checked = false;
slider.addEventListener("input", updateImages);
showCloudsCheckbox.addEventListener("change", updateImages);
loadTimeseries().then(updateImages);
</script>
</body>
</html>

View file

@ -12,7 +12,11 @@
.selectors { margin-bottom: 20px; } .selectors { margin-bottom: 20px; }
.selectors select { padding: 5px 10px; font-size: 14px; margin-right: 15px; } .selectors select { padding: 5px 10px; font-size: 14px; margin-right: 15px; }
h1 { margin: 0 0 5px 0; font-size: 22px; } h1 { margin: 0 0 5px 0; font-size: 22px; }
h2 { margin: 0 0 15px 0; font-size: 16px; color: #666; } .season-row { padding-bottom: 15px; }
h2 { margin: 0; font-size: 16px; color: #666; display: inline; }
.download-links { margin-left: 10px; font-size: 14px; }
.download-links a { margin-right: 8px; color: #0066cc; text-decoration: none; }
.download-links a:hover { text-decoration: underline; }
.plot { width: 100%; height: 100px; border: 1px solid #ccc; margin-bottom: 15px; } .plot { width: 100%; height: 100px; border: 1px solid #ccc; margin-bottom: 15px; }
.plot-label { font-size: 12px; margin-bottom: 3px; color: #666; } .plot-label { font-size: 12px; margin-bottom: 3px; color: #666; }
#dateSlider { width: 100%; margin: 15px 0; } #dateSlider { width: 100%; margin: 15px 0; }
@ -27,23 +31,27 @@
<body> <body>
<div class="container"> <div class="container">
<h1 id="siteName">Innsbruck</h1> <h1 id="siteName">Innsbruck</h1>
<h2 id="season">2024</h2> <div class="season-row"><h2 id="season">2024</h2><span class="download-links" id="downloadLinks"></span></div>
<div class="selectors"> <div class="selectors">
<label>Site:</label> <label>Site:</label>
<select id="siteSelect"></select> <select id="siteSelect"></select>
<label>Season:</label> <label>Season:</label>
<select id="seasonSelect"></select> <select id="seasonSelect"></select>
<label>Scenario:</label> <label>Source:</label>
<select id="scenarioSelect"> <select id="sourceSelect">
<option value="aggressive_20">Aggressive σ20</option> <option value="s2">S2</option>
<option value="aggressive_30">Aggressive σ30</option> <option value="s3">S3</option>
<option value="nonaggressive_20">Non-aggressive σ20</option> </select>
<option value="nonaggressive_30">Non-aggressive σ30</option> <label>Exclusion:</label>
<select id="exclusionSelect">
<option value="none">None</option>
<option value="aggressive">Aggressive</option>
<option value="nonaggressive">Non-aggressive</option>
</select> </select>
</div> </div>
<input type="range" id="dateSlider" min="0" max="365" value="0"> <input type="range" id="dateSlider" min="0" max="365" value="0">
<div id="dateDisplay">2024-01-01</div> <div id="dateDisplay">2024-01-01</div>
<div class="map-label">S2 RGB (closest available)</div> <div class="map-label" id="mapLabel">S2 RGB (closest available)</div>
<div id="s2rgbdate" class="map-date"></div> <div id="s2rgbdate" class="map-date"></div>
<div id="s2map"></div> <div id="s2map"></div>
<div id="bandPlots"></div> <div id="bandPlots"></div>
@ -59,6 +67,8 @@
{ key: "b8a", label: "B8A (NIR)", color: "#9900cc" } { key: "b8a", label: "B8A (NIR)", color: "#9900cc" }
]; ];
let siteName = "innsbruck", season = "2024"; let siteName = "innsbruck", season = "2024";
let source = "s2";
let exclusion = "none";
let sitePosition = [47.116171, 11.320308]; let sitePosition = [47.116171, 11.320308];
let start = new Date(2024, 0, 1); let start = new Date(2024, 0, 1);
let timeseries = []; let timeseries = [];
@ -68,10 +78,11 @@
let s2Map = null, s2Overlay = null, s2Marker = null; let s2Map = null, s2Overlay = null, s2Marker = null;
const urlParams = new URLSearchParams(location.search); const urlParams = new URLSearchParams(location.search);
const [strategy, sigma] = (urlParams.get("scenario") || "aggressive_20").split("_");
function getBasePath() { function filteredTimeseries(arr) {
return `processed_${strategy}_sigma${sigma || "20"}`; if (exclusion === "none") return arr;
const key = exclusion === "aggressive" ? "excluded_aggressive" : "excluded_nonaggressive";
return arr.filter(t => !t[key]);
} }
function fmtDate(d) { function fmtDate(d) {
@ -92,7 +103,7 @@
const w = canvas.width, h = canvas.height, pad = 30; const w = canvas.width, h = canvas.height, pad = 30;
const plotW = w - pad * 2, plotH = h - pad * 2; const plotW = w - pad * 2, plotH = h - pad * 2;
const data = timeseries.filter(t => t[bandKey] != null); const data = filteredTimeseries(timeseries).filter(t => t[bandKey] != null);
if (!data.length) return; if (!data.length) return;
const dates = data.map(t => new Date(t.date)); const dates = data.map(t => new Date(t.date));
@ -157,7 +168,7 @@
canvas.height = 100; canvas.height = 100;
const w = canvas.width, h = canvas.height, pad = 30; const w = canvas.width, h = canvas.height, pad = 30;
const plotW = w - pad * 2, plotH = h - pad * 2; const plotW = w - pad * 2, plotH = h - pad * 2;
const data = ndviTimeseries.filter(t => t.ndvi != null); const data = filteredTimeseries(ndviTimeseries).filter(t => t.ndvi != null);
if (!data.length) return; if (!data.length) return;
const dates = data.map(t => new Date(t.date)); const dates = data.map(t => new Date(t.date));
@ -221,7 +232,7 @@
canvas.height = 100; canvas.height = 100;
const w = canvas.width, h = canvas.height, pad = 30; const w = canvas.width, h = canvas.height, pad = 30;
const plotW = w - pad * 2, plotH = h - pad * 2; const plotW = w - pad * 2, plotH = h - pad * 2;
const data = gccTimeseries.filter(t => t.greenness_index != null); const data = filteredTimeseries(gccTimeseries).filter(t => t.greenness_index != null);
if (!data.length) return; if (!data.length) return;
const dates = data.map(t => new Date(t.date)); const dates = data.map(t => new Date(t.date));
@ -283,25 +294,36 @@
BANDS.forEach(b => drawBandPlot(`plot_${b.key}`, b.key, b.label, b.color)); BANDS.forEach(b => drawBandPlot(`plot_${b.key}`, b.key, b.label, b.color));
} }
function computeGcc(entry) {
const b = entry.b02 + entry.b03 + entry.b04;
return b > 0 ? entry.b03 / b : null;
}
async function loadTimeseries() { async function loadTimeseries() {
const base = `../data/${siteName}/${season}/${getBasePath()}`; const rawBase = `../data/${siteName}/${season}/raw`;
const src = document.getElementById("sourceSelect")?.value || "s2";
source = src;
try { try {
const [bandsRes, gccRes, ndviRes] = await Promise.all([ const preselectionRes = await fetch(`${rawBase}/preselection/${source}_preselection.json`);
fetch(`${base}/s2_bands/timeseries.json`), const preselection = preselectionRes.ok ? await preselectionRes.json() : [];
fetch(`${base}/gcc/s2/timeseries.json`), timeseries = preselection;
fetch(`${base}/ndvi/s2/timeseries.json`) ndviTimeseries = preselection;
]); gccTimeseries = preselection.map(t => ({ ...t, greenness_index: computeGcc(t) })).filter(t => t.greenness_index != null);
timeseries = bandsRes.ok ? await bandsRes.json() : [];
gccTimeseries = gccRes.ok ? await gccRes.json() : [];
ndviTimeseries = ndviRes.ok ? await ndviRes.json() : [];
} catch { } catch {
timeseries = []; timeseries = [];
gccTimeseries = [];
ndviTimeseries = []; ndviTimeseries = [];
gccTimeseries = [];
} }
const srcLabel = source.toUpperCase();
document.getElementById("mapLabel").textContent = `${srcLabel} RGB (closest available)`;
const jsonUrl = `${rawBase}/preselection/${source}_preselection.json`;
const csvUrl = `${rawBase}/preselection/${source}_preselection.csv`;
document.getElementById("downloadLinks").innerHTML =
`<a href="${jsonUrl}" download="${siteName}_${season}_${source}_preselection.json" target="_blank">[JSON]</a>` +
`<a href="${csvUrl}" download="${siteName}_${season}_${source}_preselection.csv" target="_blank">[CSV]</a>`;
document.getElementById("bandPlots").innerHTML = document.getElementById("bandPlots").innerHTML =
`<div class="plot-label">S2 NDVI</div><canvas id="plot_ndvi" class="plot"></canvas>` + `<div class="plot-label">${srcLabel} NDVI</div><canvas id="plot_ndvi" class="plot"></canvas>` +
`<div class="plot-label">S2 GCC (Greenness Index)</div><canvas id="plot_gcc" class="plot"></canvas>` + `<div class="plot-label">${srcLabel} GCC (Greenness Index)</div><canvas id="plot_gcc" class="plot"></canvas>` +
BANDS.map(b => `<div class="plot-label">${b.label}</div><canvas id="plot_${b.key}" class="plot"></canvas>`).join(""); BANDS.map(b => `<div class="plot-label">${b.label}</div><canvas id="plot_${b.key}" class="plot"></canvas>`).join("");
const yearEnd = new Date(parseInt(season), 11, 31); const yearEnd = new Date(parseInt(season), 11, 31);
document.getElementById("dateSlider").max = Math.ceil((yearEnd - start) / 86400000); document.getElementById("dateSlider").max = Math.ceil((yearEnd - start) / 86400000);
@ -312,7 +334,7 @@
async function probeDataExists(sitename, s) { async function probeDataExists(sitename, s) {
try { try {
const res = await fetch(`../data/${sitename}/${s}/processed_aggressive_sigma20/s2_bands/timeseries.json`, { method: "HEAD" }); const res = await fetch(`../data/${sitename}/${s}/raw/preselection/s2_preselection.json`, { method: "HEAD" });
return res.ok; return res.ok;
} catch { return false; } } catch { return false; }
} }
@ -381,7 +403,9 @@
`<option value="${s}">${s}</option>` `<option value="${s}">${s}</option>`
).join(""); ).join("");
document.getElementById("seasonSelect").value = initialSeason; document.getElementById("seasonSelect").value = initialSeason;
document.getElementById("scenarioSelect").value = `${strategy}_${sigma || "20"}`; document.getElementById("sourceSelect").value = urlParams.get("source") || "s2";
exclusion = urlParams.get("exclusion") || "none";
document.getElementById("exclusionSelect").value = exclusion;
const initSite = getSiteBySitename(initialSite); const initSite = getSiteBySitename(initialSite);
if (initSite?.geometry?.coordinates) { if (initSite?.geometry?.coordinates) {
@ -403,10 +427,18 @@
document.getElementById("seasonSelect").addEventListener("change", function() { document.getElementById("seasonSelect").addEventListener("change", function() {
setSiteSeason(siteSelect.value, this.value); setSiteSeason(siteSelect.value, this.value);
}); });
document.getElementById("scenarioSelect").addEventListener("change", function() { document.getElementById("sourceSelect").addEventListener("change", async function() {
const p = new URLSearchParams(location.search); source = this.value;
p.set("scenario", this.value); urlParams.set("source", source);
window.location.search = p.toString(); history.replaceState({}, "", `?${urlParams}`);
await loadTimeseries();
});
document.getElementById("exclusionSelect").addEventListener("change", function() {
exclusion = this.value;
urlParams.set("exclusion", exclusion);
history.replaceState({}, "", `?${urlParams}`);
drawAllPlots();
updateS2Imagery();
}); });
await setSiteSeason(initialSite, initialSeason); await setSiteSeason(initialSite, initialSeason);
@ -420,7 +452,7 @@
function closestFilename(dateStr) { function closestFilename(dateStr) {
const target = new Date(dateStr); const target = new Date(dateStr);
const withData = timeseries.filter(t => t.filename); const withData = filteredTimeseries(timeseries).filter(t => t.filename);
if (!withData.length) return null; if (!withData.length) return null;
const closest = withData.reduce((c, t) => const closest = withData.reduce((c, t) =>
Math.abs(new Date(t.date) - target) < Math.abs(new Date(c.date) - target) ? t : c Math.abs(new Date(t.date) - target) < Math.abs(new Date(c.date) - target) ? t : c
@ -435,7 +467,7 @@
} }
async function loadS2Geotiff(filename) { async function loadS2Geotiff(filename) {
const path = `../data/${siteName}/${season}/${getBasePath()}/s2/${filename}`; const path = `../data/${siteName}/${season}/raw/${source}/${filename}`;
const tiff = await GeoTIFF.fromArrayBuffer(await (await fetch(path)).arrayBuffer()); const tiff = await GeoTIFF.fromArrayBuffer(await (await fetch(path)).arrayBuffer());
const image = await tiff.getImage(); const image = await tiff.getImage();
const rasters = await image.readRasters(); const rasters = await image.readRasters();