# SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES.
# SPDX-FileCopyrightText: All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# %%
"""
CBottle Super Resolution
========================

Climate in a Bottle (cBottle) super resolution workflows for global weather.

This example will demonstrate the cBottle diffusion model for super resolution of global
weather data. The CBottleSR model takes low-resolution climate data and generates
high-resolution outputs using a diffusion-based approach.

For more information on cBottle see:

- https://arxiv.org/abs/2505.06474v1

In this example you will learn:

- Performing super resolution on synthetic data from the cBottle data source
- Performing super resolution on ERA5 data after infilling with cBottle
- Post-processing and visualizing super-resolution results
"""

# /// script
# dependencies = [
#   "earth2studio[cbottle] @ git+https://github.com/NVIDIA/earth2studio.git",
#   "cartopy",
# ]
# ///

# %%
# Set Up
# ------
# For this example we will use the cBottle data source, infill diagnostic, and the
# CBottleSR super resolution model. The workflow demonstrates two approaches:
#
# 1. Super resolution on synthetic data generated by cBottle3D
# 2. Super resolution on real ERA5 data after variable infilling

# %%
# We need the following components:
#
# - Datasource: Generate data from the CBottle3D data api [`earth2studio.data.CBottle3D`][earth2studio.data.CBottle3D].
# - Datasource: Pull data from the WeatherBench2 data api [`earth2studio.data.WB2ERA5`][earth2studio.data.WB2ERA5].
# - Diagnostic Model: Use the built in CBottle Infill Model [`earth2studio.models.dx.CBottleInfill`][earth2studio.models.dx.CBottleInfill].
# - Super Resolution Model: Use the CBottleSR super resolution model [`earth2studio.models.dx.CBottleSR`][earth2studio.models.dx.CBottleSR].

# %%

import os

os.makedirs("outputs", exist_ok=True)
from dotenv import load_dotenv

load_dotenv()  # TODO: make common example prep function

import torch

from earth2studio.data import WB2ERA5, CBottle3D, fetch_data
from earth2studio.grids import Region
from earth2studio.models.dx import CBottleInfill, CBottleSR

# Get the device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Load the cBottle data source
package = CBottle3D.load_default_package()
cbottle_ds = CBottle3D.load_model(package)

# Load the super resolution model, restricted to a region since global super
# resolution is expensive
region = Region.box(west=-120, south=0, east=-40, north=50)
package = CBottleSR.load_default_package()
cbottle_sr = CBottleSR.load_model(
    package,
    output_resolution=(1024, 1024),
    region=region,
    distilled_model=True,
)

# Load the infill model
input_variables = ["u10m", "v10m"]
package = CBottleInfill.load_default_package()
cbottle_infill = CBottleInfill.load_model(
    package, input_variables=input_variables, sampler_steps=18
)

# Load the ERA5 data source
era5_ds = WB2ERA5()

# %%
# Super Resolution on Synthetic Data
# ----------------------------------
# First, let's generate synthetic climate data using the cBottle3D data source
# and then perform super resolution on it. This demonstrates the full cBottle
# pipeline from data generation to super-resolution enhancement.

# %%

import datetime

import numpy as np

from earth2studio.run import map_field

times = np.array([datetime.datetime(2020, 1, 1)], dtype="datetime64[ns]")

# Generate some samples from cBottle
cbottle_ds = cbottle_ds.to(device)
synth_x = fetch_data(
    cbottle_ds,
    times,
    cbottle_sr.input_coords().coords["variable"].values,
    device=device,
)
del cbottle_ds  # Clean up data source model to free GPU memory

# Perform super resolution on synthetic data
cbottle_sr = cbottle_sr.to(device)
synth_x = map_field(synth_x, cbottle_sr.input_coords())
sr_synth_x = cbottle_sr(synth_x)

# %%
# Super Resolution on ERA5 Data
# -----------------------------
# Next, we'll demonstrate super resolution on real ERA5 data. Since ERA5 doesn't
# contain all the variables needed by CBottleSR, we first use the CBottleInfill
# model to predict the missing variables, then perform super resolution.

# %%

# Get the ERA5 data (only u10m and v10m available)
era5_x = fetch_data(
    era5_ds,
    times,
    input_variables,
    device=device,
)

# Perform infilling to get all required variables
cbottle_infill = cbottle_infill.to(device)
infill_x = cbottle_infill(map_field(era5_x, cbottle_infill.input_coords()))
del cbottle_infill  # Clean up infill model to free GPU memory

# Select the required variables and reshape for super resolution
infill_x = map_field(infill_x, cbottle_sr.input_coords())
sr_infill_x = cbottle_sr(infill_x)

# %%
# Post Processing CBottle Super Resolution Data
# ---------------------------------------------
# Let's visualize the super resolution results to compare the synthetic data
# approach with the ERA5 infilling approach. We'll plot the total cloud liquid
# water (tclw) variable as an example.

# %%
import cartopy.crs as ccrs
import matplotlib.pyplot as plt

plt.close("all")

# Convert only the plotting products to host arrays.
synth_coords = synth_x.coords
sr_synth_coords = sr_synth_x.coords
era5_coords = era5_x.coords
sr_infill_coords = sr_infill_x.coords
synth_x = synth_x.e2s.as_numpy()
sr_synth_x = sr_synth_x.e2s.as_numpy()
era5_x = era5_x.e2s.as_numpy()
sr_infill_x = sr_infill_x.e2s.as_numpy()

# Create projection focused on the super-resolved region
projection = ccrs.PlateCarree()
fig = plt.figure(figsize=(24, 24))

# Plot synthetic data
ax0 = fig.add_subplot(2, 2, 1, projection=projection)
west, south, east, north = region.params
extent = [west - 10, east + 10, south - 10, north + 10]
ax0.set_extent(extent, crs=ccrs.PlateCarree())
c = ax0.pcolormesh(
    synth_coords["lon"],
    synth_coords["lat"],
    synth_x.sel(variable="u10m").squeeze().values,
    transform=ccrs.PlateCarree(),
    cmap="RdBu_r",
    vmin=-20,
    vmax=20,
)
plt.colorbar(c, ax=ax0, shrink=0.6, label="u10m (m/s)")
ax0.coastlines()
ax0.gridlines(draw_labels=True)
ax0.set_title("Synthetic Data (cBottle3D, low resolution)")

# Plot the synthetic super resolution data
ax1 = fig.add_subplot(2, 2, 2, projection=projection)
ax1.set_extent(extent, crs=ccrs.PlateCarree())
c = ax1.pcolormesh(
    sr_synth_coords["lon"],
    sr_synth_coords["lat"],
    sr_synth_x.sel(variable="u10m").squeeze().values,
    transform=ccrs.PlateCarree(),
    cmap="RdBu_r",
    vmin=-20,
    vmax=20,
)
plt.colorbar(c, ax=ax1, shrink=0.6, label="u10m (m/s)")
ax1.coastlines()
ax1.gridlines(draw_labels=True)
ax1.set_title("Synthetic Data Super Resolution (cBottle3D → CBottleSR)")

# Plot the ERA5 data
ax2 = fig.add_subplot(2, 2, 3, projection=projection)
ax2.set_extent(extent, crs=ccrs.PlateCarree())
c = ax2.pcolormesh(
    era5_coords["lon"],
    era5_coords["lat"],
    era5_x.sel(variable="u10m").squeeze().values,
    transform=ccrs.PlateCarree(),
    cmap="RdBu_r",
    vmin=-20,
    vmax=20,
)
plt.colorbar(c, ax=ax2, shrink=0.6, label="u10m (m/s)")
ax2.coastlines()
ax2.gridlines(draw_labels=True)
ax2.set_title("ERA5 Data (low resolution)")

# Plot the ERA5 infilled super resolution data
ax3 = fig.add_subplot(2, 2, 4, projection=projection)
ax3.set_extent(extent, crs=ccrs.PlateCarree())
c = ax3.pcolormesh(
    sr_infill_coords["lon"],
    sr_infill_coords["lat"],
    sr_infill_x.sel(variable="u10m").squeeze().values,
    transform=ccrs.PlateCarree(),
    cmap="RdBu_r",
    vmin=-20,
    vmax=20,
)
plt.colorbar(c, ax=ax3, shrink=0.6, label="u10m (m/s)")
ax3.coastlines()
ax3.gridlines(draw_labels=True)
ax3.set_title("ERA5 Infilled Super Resolution (ERA5 → CBottleInfill → CBottleSR)")

plt.tight_layout()
plt.savefig("outputs/16_cbottle_super_resolution.jpg", dpi=150, bbox_inches="tight")
