Skip to content

Commit 3dbc7be

Browse files
committed
fixing the to coarser index conversion for negative integer values
1 parent 1b8e7a5 commit 3dbc7be

File tree

3 files changed

+24
-9
lines changed

3 files changed

+24
-9
lines changed

src/amr/data/field/refine/electric_field_refiner.hpp

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,8 @@ class ElectricFieldRefiner
4343
{
4444
TBOX_ASSERT(coarseField.physicalQuantity() == fineField.physicalQuantity());
4545

46-
auto const locFineIdx = AMRToLocal(fineIndex, fineBox_);
47-
auto constexpr refinementRatio = 2;
48-
auto coarseIdx{fineIndex};
49-
for (auto& idx : coarseIdx)
50-
idx = idx / refinementRatio;
46+
auto const locFineIdx = AMRToLocal(fineIndex, fineBox_);
47+
auto const coarseIdx = toCoarseIndex(fineIndex);
5148
auto const locCoarseIdx = AMRToLocal(coarseIdx, coarseBox_);
5249

5350
if constexpr (dimension == 1)

src/amr/data/field/refine/magnetic_field_refiner.hpp

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,8 @@ class MagneticFieldRefiner
5454
{
5555
TBOX_ASSERT(coarseField.physicalQuantity() == fineField.physicalQuantity());
5656

57-
auto locFineIdx = AMRToLocal(fineIndex, fineBox_);
58-
auto coarseIdx{fineIndex};
59-
for (auto& idx : coarseIdx)
60-
idx = idx / 2;
57+
auto locFineIdx = AMRToLocal(fineIndex, fineBox_);
58+
auto coarseIdx = toCoarseIndex(fineIndex);
6159
auto locCoarseIdx = AMRToLocal(coarseIdx, coarseBox_);
6260

6361

src/amr/resources_manager/amr_utils.hpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,26 @@ namespace amr
109109
return index;
110110
}
111111

112+
/**
113+
* @brief toCoarseIndex returns a coarse index from a fine index assuming a ratio of 2 in AMR
114+
* index
115+
*
116+
* For positive indices, it is simply index / 2. For negative indices, index / 2 doesnt work
117+
* because of integer division. For example, -3 / 2 = -1, but we want it to be -2, while for
118+
* even negative integers e.g. -2 / 2 = -1, this is correct. We thus end up with the following
119+
* formula for negative indices: index / 2 + index % 2 (remember that in C++ the % is signed)
120+
* For example, -3 % 2 = -1, so we have -3 / 2 + -1 = -2.
121+
*
122+
*/
123+
template<std::size_t dimension, template<typename, std::size_t> typename Index>
124+
NO_DISCARD Index<int, dimension> toCoarseIndex(Index<int, dimension> fineIndex)
125+
{
126+
auto coarseIdx{fineIndex};
127+
for (auto& idx : coarseIdx)
128+
idx = (idx >= 0) ? idx / 2 : idx / 2 + idx % 2;
129+
return coarseIdx;
130+
}
131+
112132
/**
113133
* @brief refinedPosition returns an index refined index with the given ratio
114134
* bound

0 commit comments

Comments
 (0)