You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by kh...@apache.org on 2019/06/02 19:50:14 UTC

[commons-statistics] 01/06: [STATISTICS-14] - BigDecimalStatistics

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

khmarbaise pushed a commit to branch STATISTICS-14
in repository https://gitbox.apache.org/repos/asf/commons-statistics.git

commit 813f5b0aab1d33d15e5fa117a49ba79b83c171c3
Author: Karl Heinz Marbaise <kh...@apache.org>
AuthorDate: Sat Jun 1 21:45:41 2019 +0200

    [STATISTICS-14] - BigDecimalStatistics
---
 commons-statistics-bigdecimal/pom.xml              |  77 ++++++++
 .../descriptive/BigDecimalSummaryStatistics.java   | 216 +++++++++++++++++++++
 .../src/site/resources/profile.jacoco              |  17 ++
 .../BigDecimalSummaryStatisticsAssert.java         |  38 ++++
 .../BigDecimalSummaryStatisticsTest.java           | 130 +++++++++++++
 pom.xml                                            |  19 +-
 6 files changed, 494 insertions(+), 3 deletions(-)

diff --git a/commons-statistics-bigdecimal/pom.xml b/commons-statistics-bigdecimal/pom.xml
new file mode 100644
index 0000000..3f5faa6
--- /dev/null
+++ b/commons-statistics-bigdecimal/pom.xml
@@ -0,0 +1,77 @@
+<?xml version="1.0"?>
+<!--
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+-->
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
+         xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+  <modelVersion>4.0.0</modelVersion>
+
+  <parent>
+    <groupId>org.apache.commons</groupId>
+    <artifactId>commons-statistics-parent</artifactId>
+    <version>0.1-SNAPSHOT</version>
+  </parent>
+
+  <groupId>org.apache.commons</groupId>
+  <artifactId>commons-statistics-bigdecimal</artifactId>
+  <version>0.1-SNAPSHOT</version>
+  <name>Apache Commons Statistics BigDecimal</name>
+
+  <description>BigDecimal.</description>
+
+  <properties>
+    <!-- This value must reflect the current name of the base package. -->
+    <commons.osgi.symbolicName>org.apache.commons.statistics.bigdecimal</commons.osgi.symbolicName>
+    <!-- OSGi -->
+    <commons.osgi.export>org.apache.commons.statistics.bigdecimal</commons.osgi.export>
+    <!-- Workaround to avoid duplicating config files. -->
+    <statistics.parent.dir>${basedir}/..</statistics.parent.dir>
+  </properties>
+
+  <dependencyManagement>
+    <!--
+     ! Should be move to parent if it's decided to go that path or not.
+     -->
+    <dependencies>
+      <dependency>
+        <groupId>org.junit</groupId>
+        <artifactId>junit-bom</artifactId>
+        <version>5.4.2</version>
+        <scope>import</scope>
+        <type>pom</type>
+      </dependency>
+      <dependency>
+        <groupId>org.assertj</groupId>
+        <artifactId>assertj-core</artifactId>
+        <version>3.12.2</version>
+      </dependency>
+    </dependencies>
+  </dependencyManagement>
+  <dependencies>
+    <dependency>
+      <groupId>org.junit.jupiter</groupId>
+      <artifactId>junit-jupiter-engine</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.assertj</groupId>
+      <artifactId>assertj-core</artifactId>
+      <scope>test</scope>
+    </dependency>
+  </dependencies>
+
+</project>
diff --git a/commons-statistics-bigdecimal/src/main/java/org/apache/commons/statistics/bigdecimal/descriptive/BigDecimalSummaryStatistics.java b/commons-statistics-bigdecimal/src/main/java/org/apache/commons/statistics/bigdecimal/descriptive/BigDecimalSummaryStatistics.java
new file mode 100644
index 0000000..137c933
--- /dev/null
+++ b/commons-statistics-bigdecimal/src/main/java/org/apache/commons/statistics/bigdecimal/descriptive/BigDecimalSummaryStatistics.java
@@ -0,0 +1,216 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.statistics.bigdecimal.descriptive;
+
+import java.math.BigDecimal;
+import java.util.function.Consumer;
+
+/**
+ * Implementation for BigDecimalSummaryStatistics based on {@link java.util.DoubleSummaryStatistics}.
+ */
+public class BigDecimalSummaryStatistics implements Consumer<BigDecimal> {
+
+    /**
+     * internal counter.
+     */
+    private long count;
+    /**
+     * The total.
+     */
+    private BigDecimal sum;
+    /**
+     * The minimum.
+     */
+    private BigDecimal min;
+    /**
+     * The maximum.
+     */
+    private BigDecimal max;
+
+    /**
+     * Create an instance of BigDecimalSummaryStatistics. {@code count = 0} and sum = {@link
+     * BigDecimal#ZERO}
+     */
+    public BigDecimalSummaryStatistics() {
+        this.count = 0;
+        this.sum = BigDecimal.ZERO;
+        this.max = null;
+        this.min = null;
+    }
+
+    /**
+     * Constructs a non-empty instance with the specified {@code count}, {@code min}, {@code max},
+     * and {@code sum}.
+     *
+     * <p>If {@code count} is zero then the remaining arguments are ignored and
+     * an empty instance is constructed.
+     *
+     * <p>If the arguments are inconsistent then an {@code IllegalArgumentException}
+     * is thrown.  The necessary consistent argument conditions are:
+     * <ul>
+     * <li>{@code count >= 0}</li>
+     * <li>{@code min <= max}</li>
+     * </ul>
+     *
+     * @param count the count of values
+     * @param min the minimum value
+     * @param max the maximum value
+     * @param sum the sum of all values
+     * @throws IllegalArgumentException if the arguments are inconsistent or given with {@code null}.
+     */
+    public BigDecimalSummaryStatistics(long count, BigDecimal min, BigDecimal max,
+        BigDecimal sum) {
+
+        if (count < 0L) {
+            throw new IllegalArgumentException("count must be greater or equal to zero.");
+        }
+        if (min == null) {
+            throw new IllegalArgumentException("min is not allowed to be null.");
+        }
+        if (max == null) {
+            throw new IllegalArgumentException("max is not allowed to be null.");
+        }
+        if (sum == null) {
+            throw new IllegalArgumentException("sum is not allowed to be null.");
+        }
+
+        if (min.compareTo(max) > 0) {
+            throw new IllegalArgumentException("Minimum is greater than maximum.");
+        }
+
+        this.count = count;
+        this.sum = sum;
+        this.min = min;
+        this.max = max;
+
+        this.count = count;
+        this.sum = sum;
+        this.min = min;
+        this.max = max;
+    }
+
+    /**
+     * Records a new {@code BigDecimal} value into the summary information.
+     *
+     * @param value the input value
+     */
+    @Override
+    public void accept(BigDecimal value) {
+        count++;
+        sum = sum.add(value);
+
+        min = min == null ? value : min.min(value);
+        max = max == null ? value : max.max(value);
+    }
+
+    /**
+     * Combines the state of another {@code BigDecimalSummaryStatistics} into this one.
+     *
+     * @param other another {@code BigDecimalSummaryStatistics}
+     * @throws IllegalArgumentException if {@code other} is null
+     */
+    public void combine(BigDecimalSummaryStatistics other) throws IllegalArgumentException {
+        if (other == null) {
+            throw new IllegalArgumentException("other is not allowed to be null.");
+        }
+
+        count++;
+        sum = sum.add(other.sum);
+
+        min = min == null ? other.min : min.min(other.min);
+        max = max == null ? other.max : max.max(other.max);
+    }
+
+    /**
+     * Returns the count of values recorded.
+     *
+     * @return the count of values
+     */
+    public final long getCount() {
+        return count;
+    }
+
+    /**
+     * Returns the sum of values recorded, or zero if no values have been recorded.
+     *
+     * @return the sum of values, or zero if none
+     */
+    public final BigDecimal getSum() {
+        return sum;
+    }
+
+    /**
+     * Returns the minimum value recorded, or {@link Double#POSITIVE_INFINITY} if no values have
+     * been recorded.
+     *
+     * @return the minimum value, or {@link Double#POSITIVE_INFINITY} if none
+     */
+    public final BigDecimal getMin() {
+        if (this.count == 0) {
+            return BigDecimal.valueOf(Double.NEGATIVE_INFINITY);
+        } else {
+            return min;
+        }
+    }
+
+    /**
+     * Returns the maximum value recorded, or {@link Double#POSITIVE_INFINITY} if no values have
+     * been recorded.
+     *
+     * @return the maximum value, or {@link Double#POSITIVE_INFINITY} if none
+     */
+    public final BigDecimal getMax() {
+        if (this.count == 0) {
+            return BigDecimal.valueOf(Double.POSITIVE_INFINITY);
+        } else {
+            return max;
+        }
+    }
+
+    /**
+     * Returns the arithmetic mean of values recorded, or zero if no values have been recorded.
+     *
+     * @return The arithmetic mean of values, or zero if none
+     */
+    public final BigDecimal getAverage() {
+        if (this.count > 0) {
+            BigDecimal bsum = this.sum;
+            return bsum.divide(BigDecimal.valueOf(this.count));
+        } else {
+            return BigDecimal.ZERO;
+        }
+    }
+
+    /**
+     * Returns a non-empty string representation of this object suitable for debugging. The exact
+     * presentation format is unspecified and may vary between implementations and versions.
+     */
+    @Override
+    public String toString() {
+        return String.format(
+            "%s{count=%s, sum=%s, min=%s, average=%s, max=%s}",
+            this.getClass()
+                .getSimpleName(),
+            getCount(),
+            getSum().toString(),
+            getMin().toString(),
+            getAverage().toString(),
+            getMax().toString()
+        );
+    }
+
+}
diff --git a/commons-statistics-bigdecimal/src/site/resources/profile.jacoco b/commons-statistics-bigdecimal/src/site/resources/profile.jacoco
new file mode 100644
index 0000000..a12755f
--- /dev/null
+++ b/commons-statistics-bigdecimal/src/site/resources/profile.jacoco
@@ -0,0 +1,17 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# -----------------------------------------------------------------------------
+#
+# Empty file used to automatically trigger JaCoCo profile from commons parent pom
diff --git a/commons-statistics-bigdecimal/src/test/java/org/apache/commons/statistics/bigdecimal/descriptive/BigDecimalSummaryStatisticsAssert.java b/commons-statistics-bigdecimal/src/test/java/org/apache/commons/statistics/bigdecimal/descriptive/BigDecimalSummaryStatisticsAssert.java
new file mode 100644
index 0000000..947aefc
--- /dev/null
+++ b/commons-statistics-bigdecimal/src/test/java/org/apache/commons/statistics/bigdecimal/descriptive/BigDecimalSummaryStatisticsAssert.java
@@ -0,0 +1,38 @@
+package org.apache.commons.statistics.bigdecimal.descriptive;
+
+import org.assertj.core.api.AbstractAssert;
+
+public class BigDecimalSummaryStatisticsAssert extends
+    AbstractAssert<BigDecimalSummaryStatisticsAssert, BigDecimalSummaryStatistics> {
+
+    public BigDecimalSummaryStatisticsAssert(BigDecimalSummaryStatistics bigDecimalSummaryStatistics) {
+        super(bigDecimalSummaryStatistics, BigDecimalSummaryStatisticsAssert.class);
+    }
+
+    public static BigDecimalSummaryStatisticsAssert assertThat(BigDecimalSummaryStatistics actual) {
+        return new BigDecimalSummaryStatisticsAssert(actual);
+    }
+
+    public BigDecimalSummaryStatisticsAssert getAverage() {
+        isNotNull();
+        return myself;
+    }
+    public BigDecimalSummaryStatisticsAssert isEqualTo(BigDecimalSummaryStatistics expected) {
+
+        return null;
+    }
+
+//    public BigDecimalSummaryStatisticsAssert isCloseTo(Complex expected, float offset) {
+//        Assertions.assertThat(actual.getImaginary())
+//            .isCloseTo(expected.getImaginary(), Offset.offset(
+//                (double) offset));
+//        Assertions.assertThat(actual.getReal()).isCloseTo(expected.getReal(), Offset.offset(
+//            (double) offset));
+//        return myself;
+//    }
+//
+//    public BigDecimalSummaryStatisticsAssert withDelta(float delta) {
+//        myself.actual.getImaginary();
+//        return myself;
+//    }
+}
diff --git a/commons-statistics-bigdecimal/src/test/java/org/apache/commons/statistics/bigdecimal/descriptive/BigDecimalSummaryStatisticsTest.java b/commons-statistics-bigdecimal/src/test/java/org/apache/commons/statistics/bigdecimal/descriptive/BigDecimalSummaryStatisticsTest.java
new file mode 100644
index 0000000..6f80e4f
--- /dev/null
+++ b/commons-statistics-bigdecimal/src/test/java/org/apache/commons/statistics/bigdecimal/descriptive/BigDecimalSummaryStatisticsTest.java
@@ -0,0 +1,130 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.statistics.bigdecimal.descriptive;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+
+import java.math.BigDecimal;
+import java.util.stream.LongStream;
+import org.assertj.core.data.Offset;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+
+/**
+ * The Unit Test for {@link BigDecimalSummaryStatistics}.
+ */
+@DisplayName("Unit Tests for BigDecimalSummaryStatistics")
+class BigDecimalSummaryStatisticsTest {
+
+    /**
+     * expected accuracy for results.
+     */
+    private static final Offset<Double> EPSILON = Offset.offset(1E-15d);
+
+    @Nested
+    @DisplayName("Constructor parameter validation test")
+    class ConstructorParameterTest {
+
+        @Test
+        @DisplayName("should fail if count is given less than zero.")
+        void shouldFailWithNegativeValueForCount() {
+            assertThatIllegalArgumentException()
+                .isThrownBy(() -> new BigDecimalSummaryStatistics(-1L, null, null, null))
+                .withMessage("count must be greater or equal to zero.");
+        }
+
+        @Test
+        @DisplayName("should fail if max is given null.")
+        void shouldFailWithNullForMin() {
+            assertThatIllegalArgumentException()
+                .isThrownBy(() -> new BigDecimalSummaryStatistics(0L, null, null, null))
+                .withMessage("min is not allowed to be null.");
+        }
+
+        @Test
+        @DisplayName("should fail if max is given null.")
+        void shouldFailWithNullForMax() {
+            assertThatIllegalArgumentException()
+                .isThrownBy(() -> new BigDecimalSummaryStatistics(0L, BigDecimal.ZERO, null, null))
+                .withMessage("max is not allowed to be null.");
+        }
+
+        @Test
+        @DisplayName("should fail if sum is given null.")
+        void sshouldFailWithNullForSum() {
+            assertThatIllegalArgumentException()
+                .isThrownBy(
+                    () -> new BigDecimalSummaryStatistics(0L, BigDecimal.ZERO, BigDecimal.TEN,
+                        null))
+                .withMessage("sum is not allowed to be null.");
+        }
+
+        @Test
+        @DisplayName("should fail if min is greater than max.")
+        void shouldFailForMinGreaterThanMax() {
+            assertThatIllegalArgumentException()
+                .isThrownBy(
+                    () -> new BigDecimalSummaryStatistics(0L, BigDecimal.ONE, BigDecimal.ZERO,
+                        BigDecimal.ZERO))
+                .withMessage("Minimum is greater than maximum.");
+        }
+    }
+
+    @Nested
+    @DisplayName("Edge case test")
+    class EdgeCaseTest {
+
+        @Test
+        @DisplayName("statistics for one element.")
+        void summaryStatisticsForOneElement() {
+            BigDecimalSummaryStatistics collect =
+                LongStream.rangeClosed(1, 1)
+                    .mapToObj(BigDecimal::valueOf)
+                    .collect(BigDecimalSummaryStatistics::new,
+                        BigDecimalSummaryStatistics::accept,
+                        BigDecimalSummaryStatistics::combine);
+            assertThat(collect.getCount()).isEqualTo(1L);
+            assertThat(collect.getAverage()).isEqualTo(BigDecimal.ONE);
+            assertThat(collect.getMin()).isEqualTo(BigDecimal.ONE);
+            assertThat(collect.getMax()).isEqualTo(BigDecimal.ONE);
+            assertThat(collect.getSum()).isEqualTo(BigDecimal.ONE);
+        }
+
+        @Test
+        @DisplayName("statistics for elements 1..10.")
+        void summaryStatisticsForOneToTen() {
+            BigDecimalSummaryStatistics collect =
+                LongStream.rangeClosed(1, 10)
+                    .mapToObj(BigDecimal::valueOf)
+                    .collect(BigDecimalSummaryStatistics::new,
+                        BigDecimalSummaryStatistics::accept,
+                        BigDecimalSummaryStatistics::combine);
+
+            assertThat(collect.getCount()).isEqualTo(10L);
+            assertThat(collect.getAverage().doubleValue()).isEqualTo(5.5d, EPSILON);
+//        BigDecimalSummaryStatisticsAssert.assertThat(collect).getAverage().isEqualTo(5.5d, EPSILON);
+            assertThat(collect.getSum().doubleValue()).isEqualTo(55d, EPSILON);
+            assertThat(collect.getMin()).isEqualTo(BigDecimal.ONE);
+            assertThat(collect.getMax()).isEqualTo(BigDecimal.TEN);
+
+        }
+
+    }
+
+}
diff --git a/pom.xml b/pom.xml
index 1d0bd58..baffe52 100644
--- a/pom.xml
+++ b/pom.xml
@@ -164,14 +164,26 @@
         <artifactId>commons-math3</artifactId>
         <version>${statistics.commons.math3.version}</version>
       </dependency>
+
+      <dependency>
+        <groupId>org.junit</groupId>
+        <artifactId>junit-bom</artifactId>
+        <version>5.4.2</version>
+        <scope>import</scope>
+        <type>pom</type>
+      </dependency>
     </dependencies>
   </dependencyManagement>
 
   <dependencies>
     <dependency>
-      <groupId>junit</groupId>
-      <artifactId>junit</artifactId>
-      <version>4.12</version>
+      <groupId>org.junit.jupiter</groupId>
+      <artifactId>junit-jupiter-engine</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.junit.vintage</groupId>
+      <artifactId>junit-vintage-engine</artifactId>
       <scope>test</scope>
     </dependency>
   </dependencies>
@@ -626,6 +638,7 @@
   <modules>
     <module>commons-statistics-distribution</module>
     <module>commons-statistics-regression</module>
+    <module>commons-statistics-bigdecimal</module>
   </modules>
 
 </project>