From 677b48c69d3880a6c91cb738f55cf88a7eab3772 Mon Sep 17 00:00:00 2001
From: Bram Veenboer <bram.veenboer@gmail.com>
Date: Fri, 8 Sep 2023 16:32:44 +0200
Subject: [PATCH] Add SubgridsToTiles

---
 idg/Imager.cc | 29 +++++++++++++++++++++++++++++
 1 file changed, 29 insertions(+)

diff --git a/idg/Imager.cc b/idg/Imager.cc
index 8c6ccdf75..0511ecd25 100644
--- a/idg/Imager.cc
+++ b/idg/Imager.cc
@@ -243,6 +243,35 @@ void ApplySubgridFFT(size_t n_threads,
   fftwf_destroy_plan(plan);
 }  // end ApplySubgridFFT
 
+void SubgridsToGrid(size_t n_threads, size_t subgrid_size, size_t grid_size,
+                    const xt::xtensor<SubgridMetadata, 1>& metadata,
+                    const xt::xtensor<std::complex<float>, 3>& subgrids,
+                    xt::xtensor<std::complex<float>, 2>& grid) {
+  aocommon::ParallelFor<size_t> loop(n_threads);
+
+  const size_t nr_subgrids = metadata.size();
+
+  loop.Run(0, n_threads, [&](size_t thread, size_t /*thread*/) {
+    // Iterate over subgrid rows, starting at a row that belongs to this
+    // thread and stepping by the number of threads
+    for (size_t s = 0; s < nr_subgrids; s++) {
+      const SubgridMetadata m = metadata[s];
+      const size_t subgrid_y = m.subgrid_y;
+      const size_t subgrid_x = m.subgrid_x;
+
+      size_t start_y =
+          (n_threads - (subgrid_y % n_threads) + thread) % n_threads;
+      for (size_t y = start_y; y < subgrid_size; y += n_threads) {
+        for (size_t x = 0; x < subgrid_size; x++) {
+          const size_t y_dst = (subgrid_y + y + grid_size / 2) % grid_size;
+          const size_t x_dst = (subgrid_x + y + grid_size / 2) % grid_size;
+          grid(y_dst, x_dst) += subgrids(s, y, x);
+        }
+      }
+    }
+  });
+}
+
 void SubgridsToTiles(size_t n_threads, size_t tile_size, size_t grid_size,
                      const xt::xtensor<SubgridMetadata, 1>& metadata,
                      const xt::xtensor<std::complex<float>, 3>& subgrids,
-- 
GitLab