This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git

commit 63457de85c3489aaa7912e5b8c10b3947d3066ca
Author: jsorel <[email protected]>
AuthorDate: Fri Nov 27 09:24:26 2026 +0100

    feat(Math): add NDArrays.medianCut
---
 .../main/org/apache/sis/maths/NDArrays.java        | 80 ++++++++++++++++++++++
 .../test/org/apache/sis/maths/NDArraysTest.java    | 39 +++++++++++
 2 files changed, 119 insertions(+)

diff --git 
a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/maths/NDArrays.java 
b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/maths/NDArrays.java
index 79be56f651..95a3661a18 100644
--- 
a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/maths/NDArrays.java
+++ 
b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/maths/NDArrays.java
@@ -18,10 +18,13 @@ package org.apache.sis.maths;
 
 import java.util.AbstractList;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Comparator;
 import java.util.List;
 import java.util.Random;
 import java.util.concurrent.RecursiveAction;
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
 import org.opengis.geometry.Envelope;
 import org.opengis.referencing.crs.CoordinateReferenceSystem;
 import org.opengis.util.FactoryException;
@@ -387,6 +390,83 @@ public final class NDArrays {
         };
     }
 
+    /**
+     * Splits the tuples of the given array in groups of close values, with 
the median cut algorithm.
+     * The group having the largest span on an axis is split at the median of 
that axis,
+     * until there is the requested number of groups. This is typically used 
to build a color palette.
+     *
+     * <ul>
+     *   <li>Identical tuples are always in the same group, so fewer groups 
are returned
+     *       if there are not enough distinct tuples.</li>
+     *   <li>The groups are {@linkplain #subset(Array, long...) views} of the 
given array.
+     *       Their ranges are given by {@link #computeRange(Array)}.</li>
+     * </ul>
+     *
+     * @param  array  the tuples to split.
+     * @param  count  the number of groups wanted.
+     * @return the groups, at most {@code count}.
+     *
+     * @see "https://en.wikipedia.org/wiki/Median_cut";
+     */
+    public static List<Array> medianCut(final Array array, final int count) {
+        ArgumentChecks.ensureStrictlyPositive("count", count);
+        final List<long[]> groups = new ArrayList<>(count);
+        final List<NDRange> ranges = new ArrayList<>(count);
+        if (!array.isEmpty()) {
+            groups.add(LongStream.range(0, array.getLength()).toArray());
+            ranges.add(computeRange(array));
+        }
+        while (groups.size() < count) {
+            int largest = -1, axis = -1;
+            double span = 0;
+            for (int g = 0; g < groups.size(); g++) {
+                final NDRange range = ranges.get(g);
+                for (int i = 0; i < range.getDimension(); i++) {
+                    if (range.getSpan(i) > span) {
+                        span = range.getSpan(i);
+                        largest = g;
+                        axis = i;
+                    }
+                }
+            }
+            if (largest < 0) {
+                break;      // Every group holds identical tuples.
+            }
+            final long[][] halves = splitAtMedian(array, groups.get(largest), 
axis);
+            groups.set(largest, halves[0]);
+            ranges.set(largest, computeRange(subset(array, halves[0])));
+            groups.add(halves[1]);
+            ranges.add(computeRange(subset(array, halves[1])));
+        }
+        return groups.stream().map((indices) -> subset(array, 
indices)).toList();
+    }
+
+    /**
+     * Sorts the given tuple indices by their value on the given axis and 
splits them at the median.
+     * Equal values are kept on the same side. The values shall not be all 
equal.
+     */
+    private static long[][] splitAtMedian(final Array array, final long[] 
indices, final int axis) {
+        final double[] values = new double[indices.length];
+        for (int i = 0; i < indices.length; i++) {
+            values[i] = array.get(indices[i]).get(axis);
+        }
+        final long[] sorted = IntStream.range(0, indices.length).boxed()
+                .sorted(Comparator.comparingDouble((Integer i) -> values[i]))
+                .mapToLong((i) -> indices[i]).toArray();
+        Arrays.sort(values);
+        int split = values.length / 2;
+        while (split < values.length && values[split] == values[split - 1]) {
+            split++;
+        }
+        if (split == values.length) {
+            split = values.length / 2;
+            while (values[split] == values[split - 1]) {
+                split--;
+            }
+        }
+        return new long[][] {Arrays.copyOfRange(sorted, 0, split), 
Arrays.copyOfRange(sorted, split, sorted.length)};
+    }
+
     /**
      * Shuffle tuples in the array
      *
diff --git 
a/incubator/src/org.apache.sis.geometry/test/org/apache/sis/maths/NDArraysTest.java
 
b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/maths/NDArraysTest.java
index eaa836725c..7f3b985e6b 100644
--- 
a/incubator/src/org.apache.sis.geometry/test/org/apache/sis/maths/NDArraysTest.java
+++ 
b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/maths/NDArraysTest.java
@@ -18,6 +18,7 @@ package org.apache.sis.maths;
 
 import java.util.Collections;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Set;
 import java.util.stream.Stream;
 import org.opengis.util.FactoryException;
@@ -135,4 +136,42 @@ public class NDArraysTest {
 
         assertEquals(100, distinct.size());
     }
+
+    /**
+     * Two clusters of four tuples, around (0.5 0.5) and (10.5 0.5).
+     */
+    private static Array twoClusters() {
+        return NDArrays.of(2, 0.0, 0,  10, 0,  1, 0,  11, 0,  0, 1,  10, 1,  
1, 1,  11, 1);
+    }
+
+    /**
+     * Tests {@link NDArrays#medianCut(Array, int)}: the group with the 
largest span is split at the median of that span.
+     */
+    @Test
+    public void testMedianCut() {
+        final Array array = twoClusters();
+        List<Array> groups = NDArrays.medianCut(array, 2);
+        assertEquals(2, groups.size());
+        assertArrayEquals(new double[] { 0,0,  0,1,  1,0,  1,1}, 
groups.get(0).toArrayDouble());
+        assertArrayEquals(new double[] {10,0, 10,1, 11,0, 11,1}, 
groups.get(1).toArrayDouble());
+
+        groups = NDArrays.medianCut(array, 3);
+        assertEquals(3, groups.size());
+        assertArrayEquals(new double[] { 0,0,  0,1}, 
groups.get(0).toArrayDouble());
+        assertArrayEquals(new double[] {10,0, 10,1, 11,0, 11,1}, 
groups.get(1).toArrayDouble());
+        assertArrayEquals(new double[] { 1,0,  1,1}, 
groups.get(2).toArrayDouble());
+    }
+
+    /**
+     * Identical tuples stay in the same group, so there are fewer groups than 
requested.
+     */
+    @Test
+    public void testMedianCutIdenticalTuples() {
+        final Array array = NDArrays.of(2, 5.0, 5,  6, 5,  5, 5,  5, 5);
+        final List<Array> groups = NDArrays.medianCut(array, 4);
+        assertEquals(2, groups.size());
+        assertArrayEquals(new double[] {5,5, 5,5, 5,5}, 
groups.get(0).toArrayDouble());
+        assertArrayEquals(new double[] {6,5}, groups.get(1).toArrayDouble());
+        assertTrue(NDArrays.medianCut(NDArrays.of(2, new double[0]), 
4).isEmpty());
+    }
 }

Reply via email to