import geopandas as gpd
from shapely.geometry import box
locations = [
{ "aoi_name": "tunis",
"target_crs": "EPSG:32632", # UTM 32N
"bbox": (10.00, 36.7, 10.36, 36.95), # minlon, minlat, maxlon, maxlat
"timezone": "Africa/Tunis",
"start_date": "2026-06-01",
"end_date": "2026-06-30",
},
{ "aoi_name": "kitchener-waterloo",
"target_crs": "EPSG:32617", # UTM 17N
"bbox": (-80.60, 43.38, -80.35, 43.53),
"timezone": "America/Toronto",
"start_date": "2026-06-01",
"end_date": "2026-06-30",
},
{ "aoi_name": "paris",
"target_crs": "EPSG:32631", # UTM 31N
"bbox": (2.2, 48.75, 2.55, 48.95),
"timezone": "Europe/Paris",
"start_date": "2026-06-01",
"end_date": "2026-06-30",
},
]
locations_gdf = gpd.GeoDataFrame(
[
{
"AOI Name": loc["aoi_name"],
"Target CRS": loc["target_crs"],
"Timezone": loc["timezone"],
"Start Date": loc["start_date"],
"End Date": loc["end_date"],
"geometry": box(*loc["bbox"]),
}
for loc in locations
],
crs="EPSG:4326",
)
locations_gdf.to_file("locations.geojson", driver="GeoJSON")Mapping Urban Heat at Higher Resolution: Machine Learning–Based Downscaling of ECOSTRESS LST from 70 m to 10 m in Python
by Aycha Tammour
In this notebook, I demonstrate the process of downscaling ECOSTRESS Land Surface Temperature (LST) data from its native 70 m resolution to 10 m. I follow the approach presented in a NASA ARSET training module using Google Earth Engine (highly recommended), but implement it in Python using open-source libraries and data.
Google Earth Engine is genuinely great for this kind of work: you can draw a polygon directly on an interactive map, click through a few checkboxes for cloud masking and date ranges, and get results in minutes with no local setup at all. The code itself is also open and shareable. That accessibility is exactly what makes it well suited for one-off analyses, exploratory work, or academic applications.
For production use, though, it becomes less practical. GEE ties you to Google’s runtime, quotas, and pricing, which can get expensive at scale, and its interactive workflow does not map cleanly onto standard software engineering practices like automated testing, containerization, or CI/CD. Building this pipeline in Python instead means it can be scheduled, tested, containerized, and deployed anywhere: a local machine, a cloud VM, or a CI/CD pipeline, without depending on a specific vendor’s runtime or API quotas. It also means the workflow is fully reproducible and auditable.
How does the downscaling work?
The core idea relies on a well-established relationship: land surface temperature is strongly correlated with surface reflectance and terrain characteristics. Vegetated areas tend to run cooler, impervious surfaces run hotter, and elevation/slope influence local thermal patterns.
We can exploit this relationship. If we have paired samples of low-resolution LST (70 m ECOSTRESS) and high-resolution predictors (10 m Sentinel-2 reflectance and DEM, aggregated to 70 m) for the same area, we can train a machine learning model (in this case, a Random Forest) to learn the relationship between them.
Once trained, the model no longer needs LST as an input. We can feed it the native 10 m resolution Sentinel-2 and DEM data, and it predicts LST at that same 10 m resolution: effectively downscaling the coarse 70 m thermal signal using the fine-scale spatial patterns already present in the higher resolution predictors.
The flowchart below illustrates the process:

Locations and Dates
I will demonstrate the downscaling process using data from Paris, France, for June 2026, since good quality ECOSTRESS LST data is available for both day and night during this month. I ran the same workflow across multiple other cities (Madrid, Cairo, Tunis, Toronto, Vancouver, and Kitchener-Waterloo) and will show results for Tunis and Kitchener-Waterloo at the end. The idea of testing multiple locations and dates is to ensure the workflow generalizes to any location and date where ECOSTRESS LST coverage is available.
The dataframe below lists the entries used for each city, including bounding boxes, dates, target CRS, and timezones.
locations_gdf| AOI Name | Target CRS | Timezone | Start Date | End Date | geometry | |
|---|---|---|---|---|---|---|
| 0 | tunis | EPSG:32632 | Africa/Tunis | 2026-06-01 | 2026-06-30 | POLYGON ((10.36 36.7, 10.36 36.95, 10 36.95, 1... |
| 1 | kitchener-waterloo | EPSG:32617 | America/Toronto | 2026-06-01 | 2026-06-30 | POLYGON ((-80.35 43.38, -80.35 43.53, -80.6 43... |
| 2 | paris | EPSG:32631 | Europe/Paris | 2026-06-01 | 2026-06-30 | POLYGON ((2.55 48.75, 2.55 48.95, 2.2 48.95, 2... |
aoi_name = "paris" # Change this to the desired AOI namelocation_info = locations_gdf.loc[locations_gdf['AOI Name'] == aoi_name].copy()
location_info.explore()aoi_name = location_info['AOI Name'].values[0]
target_crs = location_info['Target CRS'].values[0]
timezone = location_info['Timezone'].values[0]
start_date = location_info['Start Date'].values[0]
end_date = location_info['End Date'].values[0]
(west, south, east, north) = location_info['geometry'].values[0].bounds
bbox = (west, south, east, north)
area = location_info.to_crs(target_crs).geometry.area.values[0] # Area in square meters
print("Extracted Location Information:")
print("-" * 30)
print(f"AOI Name: {aoi_name}")
print(f"Area: {area/1000000:.6f} square kilometers")
print(f"Target CRS: {target_crs}")
print(f"Timezone: {timezone}")
print(f"Start Date: {start_date}")
print(f"End Date: {end_date}")
print(f"Bounding Box: (west: {west}, south: {south}, east: {east}, north: {north})")Extracted Location Information:
------------------------------
AOI Name: paris
Area: 570.883939 square kilometers
Target CRS: EPSG:32631
Timezone: Europe/Paris
Start Date: 2026-06-01
End Date: 2026-06-30
Bounding Box: (west: 2.2, south: 48.75, east: 2.55, north: 48.95)
The Data
The data used in this notebook includes:
- ECOSTRESS LST: 70 m resolution from NASA’s ECOSTRESS mission. This is the main variable we want to downscale.
- Sentinel-2: 10 m native resolution from ESA’s Sentinel-2 mission, downloaded at 70 m to train the model and at 10 m to predict the downscaled LST.
- DEM: 30 m resolution from Copernicus DEM, downloaded at 70 m to train the model and resampled to 10 m to predict the downscaled LST.
For the ECOSTRESS LST data, we use the earthaccess library to search for and download the granules that intersect our AOI and fall within the specified date range, followed by some preprocessing to prepare the data for training. For the Sentinel-2 and DEM data, we use pystac_client, odc-stac, and Xarray to search for and download the data at the desired resolution.
Unfortunately, ECOSTRESS data is only accessible via STAC in a cloud environment (e.g. Google Colab), not on a local machine. So in this notebook, I demonstrate searching for and downloading ECOSTRESS LST via earthaccess, then use that downloaded data to train the model and perform the downscaling.
LST Data at 70 m Spatial Resolution
To get the ECOSTRESS LST data, we will use the earthaccess library to search for and download the relevant granules that intersect with our AOI and fall within our specified date range. This requires setting up an Earthdata account and configuring the earthaccess library with your credentials. Once you have that set up, you can use the following code to search for and download the ECOSTRESS LST data for our AOI and date range.
# Authenticate
import earthaccess
auth = earthaccess.login(persist=True)
print(auth.authenticated)True
Now let’s search for the ECOSTRESS LST data using earthaccess. We will specify our AOI, date range, and the collection we want to search. Then we can download the relevant granules to our local machine:
# ignore warnings
import warnings
warnings.filterwarnings('ignore')# Search
lst_granules = earthaccess.search_data(
short_name="ECO_L2T_LSTE",
version="002",
bounding_box=(west, south, east, north),
temporal=(start_date, end_date),
)
print(f"Found {len(lst_granules)} LST granules in the AOI and date range.")Found 84 LST granules in the AOI and date range.
At this point, we only have a count of the granules. We can filter further so that we only download granules with good quality. To do this, we loop through the LST granules and check the following conditions before downloading:
- Time range falls within our range of interest (checked on the fly by looking at the
TemporalExtentof each granule, before saving any data) - Stream the data (via earthaccess’s
fsspecsupport) and check the percentage of valid (notnull) pixels in the LST band - If the percentage of valid pixels exceeds a set threshold (e.g., 75%), save the granule to disk along with its associated water, cloud, and QC mask files
This approach is efficient and avoids downloading and processing granules with large amounts of missing data, saving both time and storage space.
The script for this process is available on GitHub here. The GranuleFilter class filters granules based on the conditions above, and the filtered granules can then be downloaded to disk for further processing.
Let’s take a look at an example:
# import and instantiate the GranuleFilter class
from granules_filter import GranuleFilter
gfilter = GranuleFilter(aoi_name=aoi_name,
timezone=timezone,
valid_pixel_threshold=0.8 # <- threshold for valid pixels
)Now we can specify the time range that we are interested in. For land surface temperature, both day and night data can be interesting as they can help provide a more complete picture of the thermal environment. Nighttime data can be particularly useful for studying the urban heat island effect, as it can help identify areas that retain heat overnight. I will show the daytime run for Paris here, but I also ran the same workflow for nighttime data and will show results for both day and night at the end. For Tunis and Kitchener-Waterloo, I was only able to find good quality daytime data, so I will only show results for daytime for those two cities.
# -----
# day 🌞
#------
start_hour = 13
end_hour = 16
#-------
# night 🌃
#-------
# start_hour = 1
# end_hour = 4Now we run the keep_valid_granules function to filter the granules we found through the earthaccess search. This function will check the time range and the % of valid pixels in the LST band for each granule, and only download the granules that meet our criteria.
# Download the granules that meet the filtering criteria
good_granules = gfilter.keep_valid_granules(lst_granules,
local_hour_range=(start_hour, end_hour))I cleared the output of the cell above to avoid cluttering the notebook with too much output. The script will print out either why it skipped a granule e.g. Skipping (hour 10 outside 13–16): 2026-06-10T08:44:13.668Z or Skipping 09_31UDP_20260610T115757_0713_01_LST.tif: valid fraction 0.06 below threshold 0.8 or will show it is being downloaded.
print(f"\nKept {len(good_granules)} clean granules for {aoi_name} for the time range: {start_hour}-{end_hour} LST.")
Kept 2 clean granules for paris for the time range: 13-16 LST.
Let’s have a look at what was downloaded. The script creates a directory for the AOI data and saves the granules that meet the filtering criteria there. The filtering process reduced the number of files and the size of the data that we need to download, which can save time and storage space. The downloaded files include the LST data, water mask, cloud mask, and QC mask for each granule that meets the filtering criteria.
! ls -sh {gfilter.aoi_name}_{start_hour}_{end_hour}_ecostress_datatotal 7.9M
32K ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01_cloud.tif
3.4M ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01_LST.tif
600K ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01_QC.tif
12K ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01_water.tif
8.0K ECOv002_L2T_LSTE_45007_011_31UDQ_20260613T111156_0713_01_cloud.tif
3.4M ECOv002_L2T_LSTE_45007_011_31UDQ_20260613T111156_0713_01_LST.tif
484K ECOv002_L2T_LSTE_45007_011_31UDQ_20260613T111156_0713_01_QC.tif
12K ECOv002_L2T_LSTE_45007_011_31UDQ_20260613T111156_0713_01_water.tif
good_granules is a list of the granules that were downloaded and meet the filtering criteria. Let’s have a look at what is inside the list:
from pprint import pprint
pprint(good_granules[0]){'cloud_file': 'paris_13_16_ecostress_data\\ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01_cloud.tif',
'granule': Collection: {'ShortName': 'ECO_L2T_LSTE', 'Version': '002'}
Spatial coverage: {'HorizontalSpatialDomain': {'Geometry': {'BoundingRectangles': [{'WestBoundingCoordinate': 1.6142723681935194, 'EastBoundingCoordinate': 3.134659443316608, 'NorthBoundingCoordinate': 49.652644514047225, 'SouthBoundingCoordinate': 48.65738051948537}]}}}
Temporal coverage: {'RangeDateTime': {'BeginningDateTime': '2026-06-01T12:43:17.089Z', 'EndingDateTime': '2026-06-01T12:44:09.059Z'}}
Size(MB): 18.41
Data: ['https://data.lpdaac.earthdatacloud.nasa.gov/lp-prod-protected/ECO_L2T_LSTE.002/ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01/ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01_water.tif', 'https://data.lpdaac.earthdatacloud.nasa.gov/lp-prod-protected/ECO_L2T_LSTE.002/ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01/ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01_cloud.tif', 'https://data.lpdaac.earthdatacloud.nasa.gov/lp-prod-protected/ECO_L2T_LSTE.002/ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01/ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01_view_zenith.tif', 'https://data.lpdaac.earthdatacloud.nasa.gov/lp-prod-protected/ECO_L2T_LSTE.002/ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01/ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01_height.tif', 'https://data.lpdaac.earthdatacloud.nasa.gov/lp-prod-protected/ECO_L2T_LSTE.002/ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01/ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01_QC.tif', 'https://data.lpdaac.earthdatacloud.nasa.gov/lp-prod-protected/ECO_L2T_LSTE.002/ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01/ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01_LST.tif', 'https://data.lpdaac.earthdatacloud.nasa.gov/lp-prod-protected/ECO_L2T_LSTE.002/ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01/ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01_LST_err.tif', 'https://data.lpdaac.earthdatacloud.nasa.gov/lp-prod-protected/ECO_L2T_LSTE.002/ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01/ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01_EmisWB.tif'],
'lst_file': 'paris_13_16_ecostress_data\\ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01_LST.tif',
'qc_file': 'paris_13_16_ecostress_data\\ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01_QC.tif',
'water_file': 'paris_13_16_ecostress_data\\ECOv002_L2T_LSTE_44822_002_31UDQ_20260601T124317_0713_01_water.tif'}
Let’s save the filtered granules’ information in a json file for future reference. This will allow us to easily access the list of granules that meet our criteria without having to repeat the filtering process.
import json
def serialize_entry(entry):
return {
'granule': dict(entry['granule']),
'lst_file': entry['lst_file'],
'water_file': entry['water_file'],
'qc_file': entry['qc_file'],
'cloud_file': entry['cloud_file']
}
serializable = [serialize_entry(e) for e in good_granules]
with open(f'{aoi_name}_{start_hour}_{end_hour}_granules.json', 'w') as f:
json.dump(serializable, f, indent=2, default=str) # default=str catches any stray datetimesLST Data Processing and Stacking
We need to pause here for a moment to check the data we have. The AOI we chose may not be fully covered by a single tile. We can check this from the file names, which include parts such as 32SPG and 32SPF.
32S here is the UTM zone, while PG and PF are the tile identifiers in the Military Grid Reference System (MGRS) which is the same tiling system used by Sentinel-2 and HLS as well.
This means we need to be careful to handle the tiles separately when we stack the data.
Whether we end up with one tile or multiple tiles for the selected AOI, there are a few steps we need to take to ensure our final product is a good quality LST image. As a reminder, we are still working with the 70 m resolution LST data that will be used to train the ML model, which we later use to downscale LST to 10 m resolution.
The steps involved in building the composite are as follows:
- Group the granules by tile
- For each tile, apply QC, cloud, and water masks to each granule’s LST
- Reproject each masked LST to a common grid defined by the AOI and target CRS
- Average the reprojected LSTs across time to create a composite for that tile
The masking step uses the QC, cloud, and water mask files associated with the image(s) we downloaded earlier. At every masking and clipping step, we check that a decent percentage of valid pixels remains in the data. If the percentage is too low, we discard that granule from the stack to ensure we have enough good quality data to build a meaningful composite.
Once the LST data has been processed, we stack the granules and create a mean composite for our AOI. The full preprocessing script is available on GitHub here.
The diagram below illustrates the full process, from search through masking, reprojection, and compositing:
%%{init: {'flowchart': {'curve': 'linear'}}}%%
flowchart LR
A[Search] --> B[Filter <br/> date + time + valid pixels]
B --> C[Download]
C --> D[Group by tile]
D --> E[QC mask <br/> water mask <br/> cloud mask <br/> clip to AOI]
E[Reproject to common grid] --> F[Stack]
classDef acquireNode fill:#9CAFAA,stroke:#FBF3D5,stroke-width:2px,color:#ffffff
classDef preprocessNode fill:#415E72,stroke:#FBF3D5,stroke-width:2px,color:#ffffff
classDef outputNode fill:#D6A99D,stroke:#FBF3D5,stroke-width:2px,color:#ffffff
class A,B,C acquireNode
class D,E preprocessNode
class F outputNode
Let’s start by writing a function to group the granules by tile, which will allow us to handle each tile separately during stacking. The function reads the JSON file we saved earlier and groups the granules accordingly:
from collections import defaultdict
import json
def group_granules_by_tile(json_file_path: str) -> dict:
with open(json_file_path) as f:
loaded = json.load(f)
tiles = defaultdict(list)
for entry in loaded:
# normalize \ and / then take just the filename
filename = entry['lst_file'].replace('\\', '/').split('/')[-1]
tile_id = filename.split('_')[-5]
tiles[tile_id].append(entry)
return dict(tiles)tiles = group_granules_by_tile(f'{aoi_name}_{start_hour}_{end_hour}_granules.json')
print(list(tiles.keys()))['31UDQ']
As a first step before creating the composite, we create a reference grid for the AOI. This grid will be used to reproject the LST data to a common grid before averaging. The reference grid is defined by the AOI and the target CRS, and the resolution of the grid is set to 70 m to match the resolution of the LST data.
from build_composite import build_reference_grid
resolution = 70 # ECOSTRESS native resolution in meters
transform, shape = build_reference_grid(bbox, target_crs, resolution)Now we move to creating the composite for each tile. The input parameters for this function are a list of granules for the tile, the AOI bounding box, the target CRS, reference grid, and the maximum cloud cover threshold. The function will return a composite LST xarray.DataArray for the tile, or None if there are no valid granules for the tile.
from build_composite import build_composite
max_cloud_cover = 5 # percent. Feel free to experiment with this
tile_composites = {}
for tile_id, entries in tiles.items():
print("*" * 50)
print(f" >>> Building composite for tile {tile_id} ({len(entries)} granules)")
print("*" * 50)
composite = build_composite(entries,
bbox,
target_crs,
transform, shape,
max_cloud_cover=max_cloud_cover)
if composite is not None:
tile_composites[tile_id] = composite**************************************************
>>> Building composite for tile 31UDQ (2 granules)
**************************************************
QC mask applied >>> 89.1% pixels retained
Cloud cover in AOI: 0.7%
QC mask applied >>> 97.0% pixels retained
Cloud cover in AOI: 0.0%
--->>> Building composite from the following acquisition dates:
['2026-06-01T12:43:17.089Z', '2026-06-13T11:11:56.105Z']
Note, how we skipped one granule in the stack because it did not “meaningfully” overlap with out AOI. This is triggered by the NoDataInBounds or OneDimensionalRaster errors as a result of clipping the granule to the AOI.
In the next step, we merge the tile composites into a single composite. Obviously if we only have one tile, then we don’t need to do anything, but with different dates/times and quality levels, we may have multiple tiles so let’s go over the process of merging the tiles.
The main thing that is worth highlighting here is that the code performs a feathering of the edges of the tiles to avoid sharp transitions between the tiles in the final composite. There are a few ways this can be done, in this case we apply a weighted average of the overlapping pixels where the weights are based on the distance from the edge of the tile. This helps to create a smooth transition between the tiles in the final composite.
from build_composite import merge_tiles
lst_mosaic_70m_K = merge_tiles(tile_composites,
target_crs,
feather_px=15 # <- number of pixels to feather the edges
)Let’s have a quick look at the LST mosiac 1t 70 m resolution:
lst_mosaic_70m_K<xarray.DataArray (y: 321, x: 370)> Size: 950kB
array([[318.41000366, 316.94000244, 316.45001221, ..., 311.33001709,
311.32998657, 311.77999878],
[316.02001953, 316.10998535, 316.17999268, ..., 311.66998291,
311.88000488, 311.67999268],
[315.65002441, 316.58999634, 316.58999634, ..., 311. ,
311.55999756, 311.91998291],
...,
[299.86999512, 298.82000732, 299.52999878, ..., 295.08001709,
294.91998291, 294.44000244],
[299.72000122, 299.20001221, 298.21002197, ..., 294.58999634,
295.07000732, 295.01000977],
[300.57000732, 299.33001709, 298.05999756, ..., 294.63000488,
294.72000122, 295.29998779]], shape=(321, 370))
Coordinates:
* x (x) float64 3kB 4.412e+05 4.413e+05 ... 4.67e+05 4.671e+05
* y (y) float64 3kB 5.422e+06 5.422e+06 ... 5.4e+06 5.4e+06
band int64 8B 1
spatial_ref int64 8B 0
Attributes:
_FillValue: nanlst_mosaic_70m_K.attrs.update({
"long_name": "LST",
"units": "K"
})We can also make a quick plot to see how the final composite looks like. The plot shows the LST values in Kelvin, with the color scale indicating the temperature range
import hvplot.xarray
lst_70m_K = lst_mosaic_70m_K.rio.reproject("EPSG:4326").hvplot.image(
x="x",
y="y",
rasterize=True,
cmap="RdYlBu_r",
title="LST",
frame_width=500,
frame_height=500,
geo=True)
hvplot.save(lst_70m_K, f"./heatmaps/{aoi_name}_{start_hour}_{end_hour}_lst_70m.html")
from IPython.display import IFrame
IFrame(f"./heatmaps/{aoi_name}_{start_hour}_{end_hour}_lst_70m.html", width="100%", height=600)Note that the map has small, irregular closed areas of cooler pixels surrounding hotter pixels. These are spots where clouds were masked in one granule but not another, so the unmasked edges of the cloud area show up as cooler pixels while the centers appear hotter. This is a common artifact when compositing multiple granules with different cloud masks, and it is something to be aware of when interpreting the final composite.
Also, the water mask does not perfectly mask the Seine river, which shows up as a thin line of cooler pixels through the middle of the city.
Now that we are done with the hard part, let’s move on to the next step: getting the rest of the training data: Sentinel-2 reflectance and Copernicus DEM data, both resampled to 70 m resolution.
Sentinel-2 Data at 70 m Spatial Resolution
For the rest of this exercise, we can use the pystac_client and odc-stac libraries to search for and download the remaining training and inference data.
For Sentinel-2, we need to specify the STAC collection we want to search (e.g. sentinel-2-l2a) and the bands we want to download (e.g. ‘red’, ‘blue’). We also need to specify the resolution: for the training data, the spatial resolution should match the LST data (70 m), while for the inference data, we use 10 m to predict the downscaled LST.
I went through the process of searching a STAC catalog and downloading data with odc-stac in detail in two previous notebooks, here and here, so I won’t repeat those details again. A lot of what we did manually for the ECOSTRESS LST data (searching, aligning to a common grid) is done with considerably less effort using odc-stac.
Let’s start by searching for the Sentinel-2 data using pystac_client. For the dates, we will use the same date range as the ECOSTRESS LST data, padded by a few days on each side to ensure enough cloud free coverage. This padding can be adjusted based on the specific needs of the analysis.
from datetime import datetime, timedelta
# parse existing ECOSTRESS dates
eco_start = datetime.strptime(start_date, "%Y-%m-%d").replace(hour=start_hour)
eco_end = datetime.strptime(end_date, "%Y-%m-%d").replace(hour=end_hour)
# S2 doesn't need hour precision so we just use the date range
# optionally pad by a few days on each side for better cloud-free coverage
pad_days = 7
s2_start = (eco_start - timedelta(days=pad_days)).strftime("%Y-%m-%d")
s2_end = (eco_end + timedelta(days=pad_days)).strftime("%Y-%m-%d")
print(f"ECOSTRESS date range: {eco_start} to {eco_end}")
print(f"Sentinel-2 date range: {s2_start} to {s2_end}")ECOSTRESS date range: 2026-06-01 13:00:00 to 2026-06-30 16:00:00
Sentinel-2 date range: 2026-05-25 to 2026-07-07
Now we can search the Sentinel-2 STAC catalog:
import pystac_client
s2_catalog = pystac_client.Client.open("https://earth-search.aws.element84.com/v1")
s2_collection = "sentinel-2-l2a"
s2_items = s2_catalog.search(
collections=s2_collection,
bbox=bbox,
datetime=f"{s2_start}/{s2_end}",
query={"eo:cloud_cover": {"lt": 10}}
).item_collection()
print(f"Found {len(s2_items)} Sentinel-2 items in the AOI and date range")Found 6 Sentinel-2 items in the AOI and date range
Now we can load the items into an xarray.Dataset using the odc-stac library:
import odc.stac
s2_70m_ds = odc.stac.load(
s2_items,
bbox=bbox,
bands=["red", "green", "blue", "nir"],
resolution=70, # <- use the same resolution as the LST data
chunks={}, # <- use default chunking
groupby="solar_day",
crs=target_crs, # <- use the same CRS as the LST data
resampling="bilinear",
)s2_70m_ds<xarray.Dataset> Size: 5MB
Dimensions: (y: 322, x: 371, time: 5)
Coordinates:
* y (y) float64 3kB 5.422e+06 5.422e+06 ... 5.4e+06 5.4e+06
* x (x) float64 3kB 4.412e+05 4.412e+05 ... 4.67e+05 4.671e+05
spatial_ref int32 4B 32631
* time (time) datetime64[ns] 40B 2026-05-27T11:07:19.332000 ... 202...
Data variables:
red (time, y, x) uint16 1MB dask.array<chunksize=(1, 322, 371), meta=np.ndarray>
green (time, y, x) uint16 1MB dask.array<chunksize=(1, 322, 371), meta=np.ndarray>
blue (time, y, x) uint16 1MB dask.array<chunksize=(1, 322, 371), meta=np.ndarray>
nir (time, y, x) uint16 1MB dask.array<chunksize=(1, 322, 371), meta=np.ndarray>Before we use the Sentinel-2 data, we need to make sure that it is aligned with the ECOSTRESS LST data in terms of spatial resolution and CRS. This is critical to ensure that the training data is consistent and that the model can learn the relationship between the LST and reflectance data effectively.
from rasterio.enums import Resampling
# force S2 onto exactly the same grid as LST
s2_70m_ds_matched = s2_70m_ds.rio.reproject_match(lst_mosaic_70m_K,
# use average resampling here
resampling=Resampling.average
)
# verify
print("LST shape:", lst_mosaic_70m_K.shape)
print("S2 shape: ", s2_70m_ds_matched["blue"].mean(dim="time").shape)
print("LST bounds:", lst_mosaic_70m_K.rio.bounds())
print("S2 bounds: ", s2_70m_ds_matched.rio.bounds())LST shape: (321, 370)
S2 shape: (321, 370)
LST bounds: (441193.93255634734, 5399735.927550922, 467093.93255634734, 5422205.927550922)
S2 bounds: (441193.93255634734, 5399735.927550922, 467093.93255634734, 5422205.927550922)
Now we can calculate the different Sentinel-2 bands that we will use as features for the training data by averaging over time
# import numpy as np
# squeeze time dim and take mean composite
blue_70m = s2_70m_ds_matched["blue"].mean(dim="time").values.astype(float)
green_70m = s2_70m_ds_matched["green"].mean(dim="time").values.astype(float)
red_70m = s2_70m_ds_matched["red"].mean(dim="time").values.astype(float)
nir_70m = s2_70m_ds_matched["nir"].mean(dim="time").values.astype(float)DEM Data at 70 m Spatial Resolution
We will do the same for the elevation data. Elevation might not have a big impact on the model for a given AOI if it does not vary much across the area, but it is still worth including as a predictor both in case it does have some influence on LST values, and to stay consistent with the approach used in the NASA ARSET training module.
To search, we use the collection name and the AOI bounding box. The collection name for the Copernicus DEM is cop-dem-glo-30. Note that we do not need to specify a date range for the DEM data, since it is a static dataset.
dem_catalog = pystac_client.Client.open("https://earth-search.aws.element84.com/v1")
dem_collection = "cop-dem-glo-30"
dem_items = dem_catalog.search(
collections=dem_collection,
bbox=bbox
).item_collection()
print(f"Found {len(dem_items)} DEM items")Found 1 DEM items
Now load the DEM into an xarray.Dataset. Note that this too is loaded as a 70 m spatial resolution to match the LST and Sentinel-2 data. The DEM data will be used as an additional feature in the training data for the machine learning model.
dem_70m_ds = odc.stac.load(
dem_items,
bbox=bbox,
bands=["data"],
resolution=70, # <- use the same resolution as the LST data
chunks={},
crs=target_crs, # <- use the same CRS as the LST data
resampling="bilinear"
)dem_70m_ds<xarray.Dataset> Size: 483kB
Dimensions: (y: 322, x: 371, time: 1)
Coordinates:
* y (y) float64 3kB 5.422e+06 5.422e+06 ... 5.4e+06 5.4e+06
* x (x) float64 3kB 4.412e+05 4.412e+05 ... 4.67e+05 4.671e+05
spatial_ref int32 4B 32631
* time (time) datetime64[ns] 8B 2021-04-22
Data variables:
data (time, y, x) float32 478kB dask.array<chunksize=(1, 322, 371), meta=np.ndarray>Again for the DEM data, we need to make sure that it is aligned with the ECOSTRESS LST data in terms of spatial resolution and CRS.
# force DEM onto exactly the same grid as LST
dem_70m_matched = dem_70m_ds.rio.reproject_match(lst_mosaic_70m_K,
resampling=Resampling.average
)
# squeeze dem
dem_70m = dem_70m_matched["data"].squeeze().values.astype(float)
# verify
print("LST shape:", lst_mosaic_70m_K.shape)
print("DEM shape: ", dem_70m.shape)
print("LST bounds:", lst_mosaic_70m_K.rio.bounds())
print("DEM bounds: ", dem_70m_matched.rio.bounds())LST shape: (321, 370)
DEM shape: (321, 370)
LST bounds: (441193.93255634734, 5399735.927550922, 467093.93255634734, 5422205.927550922)
DEM bounds: (441193.93255634734, 5399735.927550922, 467093.93255634734, 5422205.927550922)
Finally, we need to apply the same mask to the Sentinel-2 and DEM data that was used on the LST data, keeping only the pixels that survived the QC, water, and cloud masking. This ensures the training data stays consistent, with predictors and target aligned to the same set of valid pixels.
import numpy as np
# extract numpy array from xarray
lst_70m = lst_mosaic_70m_K.values.astype(float)
# combined mask — land + valid LST + valid S2 + valid DEM
valid_training_mask = (
np.isfinite(lst_70m) & # <- valid land LST (not water/cloud)
(lst_70m > 100) & # <- rule out weird values if any
np.isfinite(blue_70m) & # <- valid S2 Blue
np.isfinite(green_70m) & # <- valid S2 Green
np.isfinite(red_70m) & # <- valid S2 Red
np.isfinite(nir_70m) & # <- valid S2 NIR
np.isfinite(dem_70m) # <- valid DEM
)
print(f"Valid training pixels after all masks: {valid_training_mask.sum()}")Valid training pixels after all masks: 118556
Now let’s create the feature and target arrays. The features consist of the Sentinel-2 bands and DEM data, while the target variable is LST.
# flatten
def flat(arr):
return arr[valid_training_mask].ravel()
# features array
X_full = np.column_stack([flat(blue_70m),
flat(green_70m),
flat(red_70m),
flat(nir_70m),
flat(dem_70m)
])
# target array
y_full = flat(lst_70m)
print(f"X shape: {X_full.shape}")
print(f"y range: {y_full.min():.1f} — {y_full.max():.1f} K")X shape: (118556, 5)
y range: 293.2 — 325.1 K
Our training data has 5 features: the four Sentinel-2 bands (Blue, Green, Red, NIR) and the DEM data. The target variable is LST. All are at 70 m spatial resolution.
We will use these features to train a Random Forest model to learn the relationship between the features and the target variable. It is possible that other models might perform better (this is worth exploring in future work), but Random Forest is a good starting point given its robustness to feature scaling and ability to capture non-linear relationships. In addition, Random Forest models are relatively easy to interpret and can provide insights into the importance of different features in predicting LST.
Model Training & Evaluation
To train the model, we start by splitting the training data into a training set and a validation set. This will allow us to evaluate the performance of the model on unseen data and ensure that it is not overfitting to the training data.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X_full,
y_full,
test_size=0.2,
random_state=11)
print(f"Training samples: {X_train.shape[0]}, Testing samples: {X_test.shape[0]}")Training samples: 94844, Testing samples: 23712
# fit
from sklearn.ensemble import RandomForestRegressor
rf = RandomForestRegressor(n_estimators=100,
max_depth=15,
min_samples_leaf=5,
random_state=79,
n_jobs=-1)
rf.fit(X_train, y_train)RandomForestRegressor(max_depth=15, min_samples_leaf=5, n_jobs=-1,
random_state=79)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| n_estimators | 100 | |
| criterion | 'squared_error' | |
| max_depth | 15 | |
| min_samples_split | 2 | |
| min_samples_leaf | 5 | |
| min_weight_fraction_leaf | 0.0 | |
| max_features | 1.0 | |
| max_leaf_nodes | None | |
| min_impurity_decrease | 0.0 | |
| bootstrap | True | |
| oob_score | False | |
| n_jobs | -1 | |
| random_state | 79 | |
| verbose | 0 | |
| warm_start | False | |
| ccp_alpha | 0.0 | |
| max_samples | None | |
| monotonic_cst | None |
from sklearn.metrics import mean_absolute_error as mae, root_mean_squared_error
# predict on the test set
y_pred = rf.predict(X_test)
# calculate mean absolute error
mae = mae(y_test, y_pred)
rmse = root_mean_squared_error(y_test, y_pred)
print(f">>> Mean Absolute Error: {mae:.2f} K")
print(f">>> Root Mean Squared Error: {rmse:.2f} K")>>> Mean Absolute Error: 1.92 K
>>> Root Mean Squared Error: 2.59 K
import matplotlib.pyplot as plt
import numpy as np
# Calculate residuals
residuals = y_pred - y_test
fig, ax = plt.subplots(1, 2, figsize=(13, 5))
ax1 = ax[0]
ax1.scatter(y_test,
y_pred,
alpha=0.3,
s=8,
color='#3C779E')
# 1:1 reference line
lims = [min(y_test.min(), y_pred.min()), max(y_test.max(), y_pred.max())]
ax1.plot(lims, lims, 'k--', linewidth=1, label='1:1 line')
ax1.set_xlabel('Actual LST (K)')
ax1.set_ylabel('Predicted LST (K)')
ax1.set_title('Predicted vs Actual LST (Test Set)')
ax1.legend(frameon=False)
ax1.spines[['top', 'right']].set_visible(False)
ax2 = ax[1]
ax2.hist(residuals,
bins=30,
color="#3C779E",
edgecolor='k',
alpha=0.7)
ax2.axvline(0,
color='k',
linestyle='--',
linewidth=1)
ax2.set_xlabel('Residual (Predicted − Actual, K)')
ax2.set_ylabel('Count')
ax2.set_title('Residual Distribution')
ax2.spines[['top', 'right']].set_visible(False)
plt.tight_layout()
plt.show()
The residual distribution is approximately normal and centered near zero, indicating the model has no strong overall bias and that most prediction errors fall within a modest, well-behaved range consistent with the MAE (1.92 K) and RMSE (2.59 K) reported above. However, the predicted-vs-actual scatter reveals a systematic pattern typical of Random Forest regressors: the model slightly overpredicts LST at the cooler end of the range and underpredicts at the warmer end, compressing extreme values toward the mean. This behavior is an inherent property of tree-based ensemble averaging rather than a data quality issue, and it is a useful diagnostic to keep in mind, since it suggests the model may slightly underestimate the most extreme hot or cold pixels (precisely the areas most relevant to urban heat island analysis).
Feature Importance
Feature importance tells us how much each predictor contributes to the model’s ability to predict LST. Understanding this helps validate whether the model is learning physically meaningful relationships (e.g., vegetation and built-up surfaces driving thermal patterns) rather than picking up on spurious correlations, and it can help guide future feature engineering, for example, by revealing whether adding a feature like DEM was worthwhile, or whether a spectral index might outperform a raw band.
We compare two importance metrics: + Mean Decrease in Impurity (MDI): the default feature_importances_ from the Random Forest itself + Permutation importance: computed by measuring how much model performance drops when each feature’s values are randomly shuffled on the test set.
MDI is computed during training and can be biased toward continuous or high-cardinality features, while permutation importance is measured on held-out data and is generally considered more reliable for interpreting real predictive contribution
from sklearn.inspection import permutation_importance
import pandas as pd
perm = permutation_importance(
rf, X_test, y_test, # use the test data for validation
n_repeats=10,
random_state=42,
n_jobs=-1
)
feature_names = ['Blue', 'Green', 'Red', 'NIR', 'DEM']
perm_imp = pd.DataFrame({
'feature': feature_names,
'importance_mean': perm.importances_mean,
'importance_std': perm.importances_std
}).sort_values('importance_mean', ascending=False)
print(perm_imp) feature importance_mean importance_std
2 Red 0.623556 0.004204
3 NIR 0.302107 0.005912
4 DEM 0.137485 0.001553
1 Green 0.064999 0.001185
0 Blue 0.057449 0.001781
import matplotlib.pyplot as plt
# assumes you have `rf` (fitted model) and `feature_names` (list of predictor names, in the same order as X_train columns)
importances = rf.feature_importances_
feat_imp = pd.DataFrame({
'feature': feature_names,
'importance': importances
}).sort_values('importance', ascending=False)
print(feat_imp) feature importance
2 Red 0.648275
3 NIR 0.129958
4 DEM 0.123618
0 Blue 0.052179
1 Green 0.045969
order = feat_imp.sort_values('importance', ascending=True)['feature']
fi = feat_imp.set_index('feature').loc[order, 'importance']
pi = perm_imp.set_index('feature').loc[order, 'importance_mean']
pi_err = perm_imp.set_index('feature').loc[order, 'importance_std'] # if available
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 4), sharey=True)
ax1.barh(fi.index, fi, color='#3C779E', edgecolor='grey', height=0.5)
ax1.set_xlabel('Mean Decrease in Impurity')
ax1.set_title('MDI Importance')
ax2.barh(pi.index, pi, xerr=pi_err, color='#E1D9BC', edgecolor='grey', height=0.5)
ax2.set_xlabel('Permutation Importance (score decrease)')
ax2.set_title('Permutation Importance')
for ax in (ax1, ax2):
ax.spines[['top', 'right']].set_visible(False)
ax.grid(axis='x', linestyle='--', alpha=0.5)
plt.tight_layout()
plt.show()
Both methods agree on the overall ranking: Red is by far the most important predictor, followed by NIR, then DEM, with Blue and Green contributing the least. The dominance of Red and NIR makes physical sense. Together they are the basis for vegetation indices like NDVI, and vegetation cover is a strong driver of surface temperature. DEM’s moderate importance suggests elevation and terrain do meaningfully influence LST in this AOI, despite our earlier expectation that it might contribute little in areas of low relief. Blue and Green swap rank slightly between the two methods (Green ranks above Blue in permutation importance, but below it in MDI), though both contribute only marginally to the model compared to Red, NIR, and DEM (a difference likely within the noise given how small both values are in either metric).
Inference at 10 m Spatial Resolution
For inference, we use the trained model, which learned the relationship between 70 m LST and 70 m reflectance/DEM data, to predict LST at 10 m resolution — this time using the native 10 m Sentinel-2 and DEM data as input.
The required inputs are the same as during training (Sentinel-2 bands and DEM), just at their native 10 m resolution instead of the 70 m resolution used to match the LST training data.
We use the same odc-stac workflow to search for and download the 10 m Sentinel-2 and DEM data, then apply the same preprocessing steps (masking, reprojection, etc.) to ensure the data is aligned with the model’s expectations. Once the 10 m data is prepared, we feed it into the trained Random Forest model to generate downscaled LST predictions at 10 m resolution.
# load S2 at 10m
s2_10m_ds = odc.stac.load(
s2_items,
bbox=bbox,
bands=["blue", "green", "red", "nir"],
resolution=10, # <- use the 10 m resolution for downscaling
chunks={},
groupby="solar_day",
crs=target_crs,
resampling="bilinear",
)Now, extract the reflectance averaged over time:
blue_10m = s2_10m_ds["blue"].mean(dim="time").values.astype(float)
green_10m = s2_10m_ds["green"].mean(dim="time").values.astype(float)
red_10m = s2_10m_ds["red"].mean(dim="time").values.astype(float)
nir_10m = s2_10m_ds["nir"].mean(dim="time").values.astype(float)For the DEM, we load a fresh copy at 10 m resolution (matching the Sentinel-2 inference grid).Since Copernicus DEM’s native resolution is 30 m, this involves resampling the data. The DEM is static, so unlike the LST and Sentinel-2 data, there’s no need to account for time or compositing here.
# load DEM at 10 m resolution for inference
dem_10m_ds = odc.stac.load(
dem_items,
bbox=bbox,
bands=["data"],
resolution=10, # <- match Sentinel-2 inference resolution
chunks={},
crs=target_crs,
resampling="bilinear"
)# force DEM onto exactly the same grid as S2 10 m
dem_10m_matched = dem_10m_ds["data"].rio.reproject_match(s2_10m_ds,
resampling=Resampling.bilinear)
dem_10m = dem_10m_matched.squeeze().values.astype(float)Now we mask the 10 m data to keep only pixels that are finite across all bands and the DEM, then stack the data into a single array to use as input for prediction. The input array has the same 5 features as the training data (Blue, Green, Red, NIR, DEM), but at 10 m spatial resolution
# valid mask at 10m
mask_10m = (
np.isfinite(blue_10m) &
np.isfinite(green_10m) &
np.isfinite(red_10m) &
np.isfinite(nir_10m) &
np.isfinite(dem_10m)
)
X_pred_10m = np.column_stack([blue_10m[mask_10m],
green_10m[mask_10m],
red_10m[mask_10m],
nir_10m[mask_10m],
dem_10m[mask_10m]])
print(f"Predicting over {X_pred_10m.shape[0]} pixels at 10 m")Predicting over 5807815 pixels at 10 m
Now predict:
y_pred_10m = rf.predict(X_pred_10m)Reshape the predictions back to the 10m grid
# reconstruct 2D
lst_10m = np.full(mask_10m.shape, np.nan)
lst_10m[mask_10m] = y_pred_10m
print(f"LST 10m shape: {lst_10m.shape}")
print(f"Value range: {np.nanmin(lst_10m):.1f} — {np.nanmax(lst_10m):.1f} K")LST 10m shape: (2245, 2587)
Value range: 295.6 — 317.9 K
One final step to generate our final downscaled LST product is to account for residuals. We already have the 70 m LST data, so all we need to do is reproject the predicted 10 m LST back to 70 m resolution and calculate the residual by subtracting the reprojected prediction from the original 70 m LST. We then project the residual back to 10 m resolution and add it to the predicted 10 m LST to get the final, residual-corrected downscaled LST product at 10 m resolution.
First, let’s wrap our prediction into an xarray.DataArray:
import xarray as xr
# wrap 10m prediction as DataArray
lst_10m_da = xr.DataArray(
lst_10m,
dims=["y", "x"],
coords={"y": s2_10m_ds.y, "x": s2_10m_ds.x}
).rio.write_crs(target_crs)# -1- reproject the prediction back to 70m
lst_pred_agg = lst_10m_da.rio.reproject_match(lst_mosaic_70m_K,
resampling=Resampling.average)
# -2- residual = original 70m LST - prediction projected to 70m
residual_70m = lst_mosaic_70m_K - lst_pred_agg
# -3- project residules back to 10m
residual_10m = residual_70m.rio.reproject_match(lst_10m_da,
resampling=Resampling.bilinear)
# -4- final residule-corrected 10m LST = predicted + residule
lst_final_10m = lst_10m_da + residual_10m
print(f"Final LST 10 m range: {float(lst_final_10m.min()):.1f} — {float(lst_final_10m.max()):.1f} K")Final LST 10 m range: 288.6 — 329.9 K
# convert residual to numpy for easier indexing
residual_vals = residual_70m.values.squeeze()
# flag outliers beyond N standard deviations
threshold_std = 5
res_mean = np.nanmean(residual_vals)
res_std = np.nanstd(residual_vals)
outlier_mask = np.abs(residual_vals - res_mean) > (threshold_std * res_std)
n_outliers = np.sum(outlier_mask)
print(f"Residual mean: {res_mean:.2f} K, std: {res_std:.2f} K")
print(f"Pixels beyond {threshold_std} std: {n_outliers} "
f"({100 * n_outliers / np.isfinite(residual_vals).sum():.3f}% of valid pixels)")
# get coordinates of all outliers directly from the mask
rows, cols = np.where(outlier_mask)
# put the outlier info in a dataframe
outlier_df = pd.DataFrame({
'Residual (K)': [residual_vals[r, c] for r, c in zip(rows, cols)],
'X': [residual_70m.x.values[c] for c in cols],
'Y': [residual_70m.y.values[r] for r in rows],
'Row': rows,
'Col': cols
}).round({'Residual (K)': 2, 'X': 0, 'Y': 0})
print(f"All {n_outliers} outliers beyond {threshold_std} std:")
outlier_dfResidual mean: 0.46 K, std: 2.75 K
Pixels beyond 5 std: 10 (0.008% of valid pixels)
All 10 outliers beyond 5 std:
| Residual (K) | X | Y | Row | Col | |
|---|---|---|---|---|---|
| 0 | 14.74 | 450119.0 | 5420001.0 | 31 | 127 |
| 1 | -13.57 | 461179.0 | 5402011.0 | 288 | 285 |
| 2 | -13.97 | 460969.0 | 5400121.0 | 315 | 282 |
| 3 | -13.31 | 460899.0 | 5400051.0 | 316 | 281 |
| 4 | -13.52 | 460969.0 | 5400051.0 | 316 | 282 |
| 5 | -13.86 | 460899.0 | 5399911.0 | 318 | 281 |
| 6 | -14.39 | 461039.0 | 5399841.0 | 319 | 283 |
| 7 | -14.03 | 461109.0 | 5399841.0 | 319 | 284 |
| 8 | -13.92 | 461039.0 | 5399771.0 | 320 | 283 |
| 9 | -15.17 | 461109.0 | 5399771.0 | 320 | 284 |
- The near-zero mean is consistent with the roughly centered residual histogram plotted earlier, indicating that the correction step is fine-tuning the predictions rather than compensating for a fundamentally biased model.
- The standard deviation is close to the RMSE (2.59 K) calculated earlier, confirming that the residual spread reflects the same underlying prediction error, just measured at the (reprojected) 70 m scale rather than the original 10 m test-set scale.
- The largest residuals might look like large errors at first glance, but closer inspection against satellite imagery shows most of them have physical explanations. The positive outlier corresponds to a genuinely hot surface (it looks like a parking lot or a dark metal rooftop). The negative outliers cluster tightly together and mostly coincide with cloud edges or unmasked water bodies — known sources of anomalously cool apparent temperature in thermal imagery — rather than genuine model failure.
Below, I plot the residual map with the locations of the 10 largest residuals overlaid as small circles. These correspond to the coordinates and values printed above.
import hvplot.xarray
import hvplot.pandas
# residual raster
base = residual_70m.hvplot.image(x='x', y='y',
cmap='RdBu_r', clim=(-10, 10),
height=500, width=600,
title='Residual Map with Outliers')
# outlier points
outlier_df = pd.DataFrame({'x': residual_70m.x.values[cols],
'y': residual_70m.y.values[rows]})
points = outlier_df.hvplot.points(x='x', y='y', color='lime', size=50,
marker='o', fill_color=None, line_width=2)
combined = base * points
combinedSince we are more used to temperatures in Celsius, let’s convert our LST 70 and 10 m data to C before we save them to disk:
# convert to Celsius for easier reading
lst_70m_C = lst_mosaic_70m_K - 273.15
lst_10m_C = lst_final_10m - 273.15paris_70m_path = f"./products/{aoi_name}_{start_hour}_{end_hour}_lst_70m_C.tif"
paris_10m_path = f"./products/{aoi_name}_{start_hour}_{end_hour}_lst_10m_C.tif"# write to disk
import rasterio
with rasterio.open(
paris_70m_path,
"w",
driver="GTiff",
height=lst_70m_C.shape[0],
width=lst_70m_C.shape[1],
count=1,
dtype="float32",
crs=lst_70m_C.rio.crs,
transform=lst_70m_C.rio.transform(),
) as dst:
dst.write(lst_70m_C.values.astype("float32"), 1)
dst.set_band_description(1, "LST")
dst.update_tags(1, units="C")
with rasterio.open(
paris_10m_path,
"w",
driver="GTiff",
height=lst_10m_C.shape[0],
width=lst_10m_C.shape[1],
count=1,
dtype="float32",
crs=lst_10m_C.rio.crs,
transform=lst_10m_C.rio.transform(),
) as dst:
dst.write(lst_10m_C.values.astype("float32"), 1)
dst.set_band_description(1, "LST")
dst.update_tags(1, units="C")from comparison_plots import plot_comparison
plot_comparison(paris_70m_path, paris_10m_path, "Paris", "June 2026 13:00-16:00")