From dd5641f3e2b129f8376b8bc16c26a7a0411e43b2 Mon Sep 17 00:00:00 2001
From: Lukas Kluft <lukas.kluft@gmail.com>
Date: Sun, 16 Feb 2025 11:06:27 +0100
Subject: [PATCH] Properly normalize remap weights after coarsening

For ocean grids, the re-scaling factor is not always 4, but determined
by the actual number of links to the destination address.
---
 coarsen_weights.py | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/coarsen_weights.py b/coarsen_weights.py
index b84a22d..d619954 100755
--- a/coarsen_weights.py
+++ b/coarsen_weights.py
@@ -17,9 +17,14 @@ def coarsen_weight_file(inweights, outweights, nbisections=1):
 
     w = weights[["src_address", "dst_address", "remap_matrix"]].to_dataframe()
     w.dst_address = ((w.dst_address - 1) // coarsen) + 1
-    w.remap_matrix = w.remap_matrix / coarsen
 
-    new_w = w.groupby(["src_address", "dst_address"]).sum().reset_index()
+    # Normalize weights by actual number of links to new destination address
+    new_w = w.set_index("dst_address")
+    new_w["remap_matrix"] = new_w["remap_matrix"] / new_w["remap_matrix"].groupby("dst_address").count()
+    new_w = new_w.reset_index()
+
+    # Combine equivalent links into one
+    new_w = new_w.groupby(["src_address", "dst_address"]).sum().reset_index()
     new_w.index.name = "num_links"
     new_w = new_w.to_xarray()
 
-- 
GitLab