Skip to content

Commit

Permalink
metric formulas plus a highlight
Browse files Browse the repository at this point in the history
  • Loading branch information
GondekNP committed Jan 8, 2024
1 parent d4868c2 commit dd71196
Show file tree
Hide file tree
Showing 4 changed files with 141 additions and 70 deletions.
17 changes: 12 additions & 5 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from fastapi import FastAPI, Depends, HTTPException, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles

from titiler.core.factory import TilerFactory
from titiler.core.errors import DEFAULT_STATUS_CODES, add_exception_handlers
Expand All @@ -29,12 +30,14 @@
app.include_router(cog.router, prefix='/cog', tags=["Cloud Optimized GeoTIFF"])
add_exception_handlers(app, DEFAULT_STATUS_CODES)

templates = Jinja2Templates(directory="src/")

logging_client = logging.Client(project='dse-nps')
log_name = "burn-backend"
logger = logging_client.logger(log_name)

app.mount("/static", StaticFiles(directory="src/static"), name="static")
templates = Jinja2Templates(directory="src/static")

@app.get("/")
def index():
logger.log_text("ping pong")
Expand Down Expand Up @@ -143,19 +146,23 @@ def analyze_burn(body: AnaylzeBurnPOSTBody, sftp_client: SFTPClient = Depends(ge
logger.log_text(f"Error: {e}")
return f"Error: {e}", 400

@app.get("/map/{fire_event_name}", response_class=HTMLResponse)
def serve_map(request: Request, fire_event_name: str, manifest: dict = Depends(get_manifest)):
@app.get("/map/{fire_event_name}/{burn_metric}", response_class=HTMLResponse)
def serve_map(request: Request, fire_event_name: str, burn_metric: str, manifest: dict = Depends(get_manifest)):
tileserver_endpoint = 'https://tf-rest-burn-severity-ohi6r6qs2a-uc.a.run.app'
# tileserver_endpoint = 'http://localhost:5050'
cog_url = f"https://burn-severity-backend.s3.us-east-2.amazonaws.com/public/{fire_event_name}/rbr.tif"
cog_url = f"https://burn-severity-backend.s3.us-east-2.amazonaws.com/public/{fire_event_name}/{burn_metric}.tif"
cog_tileserver_url_prefix = tileserver_endpoint + f"/cog/tiles/WebMercatorQuad/{{z}}/{{x}}/{{y}}.png?url={cog_url}&return_mask=true&nodata=-.9999&algorithm=classify&algorithm_params="

fire_metadata = manifest[fire_event_name]
fire_metadata_json = json.dumps(fire_metadata)

with open('src/static/burn_metric_text.json') as json_file:
burn_metric_text = json.load(json_file)

return templates.TemplateResponse("index.html", {
"request": request,
"fire_event_name": fire_event_name,
"burn_metric": burn_metric,
"burn_metric_text": burn_metric_text,
"fire_metadata_json": fire_metadata_json,
"cog_tileserver_url_prefix": cog_tileserver_url_prefix
})
65 changes: 0 additions & 65 deletions src/index.html

This file was deleted.

18 changes: 18 additions & 0 deletions src/static/burn_metric_text.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"NBR": {
"metric_name": "Normalized Burn Ratio",
"formula": "NBR = \\\\frac{NIR - SWIR}{NIR + SWIR}"
},
"dNBR": {
"metric_name": "Difference in Normalized Burn Ratio",
"formula": "dNBR = NBR_{prefire} - NBR_{postfire}"
},
"RdNBR": {
"metric_name": "Relative Difference in Normalized Burn Ratio",
"formula": "RdNBR = \\\\frac{dNBR}{|(NBR_{prefire})^{0.5}|}"
},
"RBR": {
"metric_name": "Relativized Burn Ratio",
"formula": "RBR = \\\\frac{dNBR}{NBR_{prefire} +1.001}"
}
}
111 changes: 111 additions & 0 deletions src/static/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Map</title>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<!-- Include Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />

<!-- Include Leaflet JS -->
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>

<!-- Include MathJax -->
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>

<style>
#mapid {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100%;
}
</style>
</head>
<body>
<div id="mapid"></div>
<div style="position: absolute; top: 10px; right: 10px; z-index: 1000; padding: 10px; border-radius: 10px; background-color: #f0f0f0;">
<label for="opacity-slider">Burn Severity Layer Opacity</label>
<input type="range" min="0" max="1" step="0.1" value=".7" id="opacity-slider">
</div>
<script>
var map = L.map('mapid');

// Data from Jinja2
console.log("burn_metric - {{ burn_metric }}")
var burn_metric = "{{ burn_metric }}";

console.log("fire metadata")
var fireMetadata = JSON.parse({{fire_metadata_json | tojson | safe}});
console.log(fireMetadata);

var fire_bounds = [[fireMetadata.bounds[1], fireMetadata.bounds[0]], [fireMetadata.bounds[3], fireMetadata.bounds[2]]]
console.log("fire bounds - ", fire_bounds)

// Content for the webpage, defined as JSON
var burnMetricText = JSON.parse('{{ burn_metric_text | tojson | safe }}');

// Add base map
L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);

// Add COG tile layer, with opacity slider
var cogTileLayer = L.tileLayer('{{ cog_tileserver_url_prefix | safe }}{"thresholds":{"-0.9998":0, "0.045":175,"0.222":100,"0.8":25}}', {
maxZoom: 20,
setOpacity: 0.7,
}).addTo(map);
var slider = document.getElementById('opacity-slider');
slider.addEventListener('input', function(e) {
cogTileLayer.setOpacity(e.target.value);
});

// Add tooltip for burn metrics, in bottom left
// Get the container
var container = document.createElement('div');
container.style.position = 'absolute';
container.style.bottom = '10px';
container.style.left = '10px';
container.style.zIndex = '1000';
container.style.padding = '10px';
container.style.borderRadius = '10px';
container.style.backgroundColor = '#f0f0f0';

// Iterate over each metric
for (var key in burnMetricText) {
// Create a div for the metric
var div = document.createElement('div');

// Add the metric name and formula
div.innerHTML = '<strong>' + burnMetricText[key].metric_name + '</strong><br>&nbsp;&nbsp;&nbsp;&nbsp;<span class="math">\\(' + burnMetricText[key].formula + '\\)</span>';

// Add padding between divs
div.style.padding = '10px';

// Highlight the current metric
if (key.toLowerCase() === burn_metric.toLowerCase()) {
div.style.backgroundColor = '#ffe875';
}

// Append the div to the container
container.appendChild(div);

// Ask MathJax to typeset the new div
MathJax.typeset([div]);
}

// Append the container to the body
document.body.appendChild(container);

// Center map on fire, based on `bounds` metadata
map.fitBounds(fire_bounds);

</script>

</body>
</html>

0 comments on commit dd71196

Please sign in to comment.