import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.colors import ListedColormap, BoundaryNorm
# Zone d'étude
POLY_LON = [-116.8, -114.2, -112.9, -111.9, -114.2, -115.4, -117.7]
POLY_LAT = [41.3, 42.9, 42.4, 39.8, 37.9, 38.3, 38.6]
POLYGON = np.column_stack([POLY_LON, POLY_LAT])
XMIN, XMAX, YMIN, YMAX = -117.7, -111.9, 37.9, 42.9
NA = np.nan
# Carte de référence (fine, 10x12) et carte prédite (grossière, 5x6)
REFERENCE = np.array([
[NA, NA, NA, NA, NA, NA, 5, 5, NA, NA, NA, NA],
[NA, NA, NA, NA, NA, 3, 5, 5, 5, 5, NA, NA],
[NA, NA, NA, 3, 2, 2, 5, 5, 2, 2, NA, NA],
[NA, NA, 3, 3, 2, 2, 5, 5, 2, 2, 1, NA],
[NA, 4, 2, 2, 2, 2, 5, 5, 4, 4, 1, NA],
[NA, 4, 2, 2, 2, 2, 5, 5, 4, 4, 1, NA],
[NA, 2, 3, 3, 5, 5, 4, 4, 5, 5, 5, NA],
[ 2, 2, 3, 3, 5, 5, 4, 4, 5, 5, NA, NA],
[ 1, 1, 2, 2, 2, 2, 4, 4, 4, NA, NA, NA],
[NA, NA, NA, NA, NA, NA, 4, 4, NA, NA, NA, NA],
], dtype=float)
PRED_COARSE = np.array([
[NA, NA, NA, 5, 5, NA],
[NA, 3, 5, 5, 2, NA],
[NA, 2, 2, 5, 1, 1],
[ 2, 3, 4, 4, 5, NA],
[NA, NA, 2, 4, NA, NA],
], dtype=float)
def cell_polygon_mask(xs, ys, polygon):
"""True pour les cellules dont le centre est à l'intérieur du polygone."""
xx, yy = np.meshgrid(xs, ys)
pts = np.column_stack([xx.ravel(), yy.ravel()])
return Path(polygon).contains_points(pts).reshape(len(ys), len(xs))
def disaggregate(coarse, factor):
"""Désagrège une grille grossière en répétant chaque cellule factor x factor fois."""
return np.repeat(np.repeat(coarse, factor, axis=0), factor, axis=1)
xs_f = XMIN + 0.5 * (np.arange(12) + 0.5)
ys_f = YMAX - 0.5 * (np.arange(10) + 0.5)
mask_ref = cell_polygon_mask(xs_f, ys_f, POLYGON)
reference = np.where(mask_ref, REFERENCE, np.nan)
predicted = np.where(mask_ref, disaggregate(PRED_COARSE, 2), np.nan)