diff --git a/adapter-cqld4/pom.xml b/adapter-cqld4/pom.xml index a7a10ec9d..fb63c0fab 100644 --- a/adapter-cqld4/pom.xml +++ b/adapter-cqld4/pom.xml @@ -140,48 +140,6 @@ false - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - diff --git a/adapter-cqld4/src/main/java/io/nosqlbench/cqlgen/transformers/CqlSchemaStatsParser.java b/adapter-cqld4/src/main/java/io/nosqlbench/cqlgen/transformers/CqlSchemaStatsParser.java index b4c824644..5c947db79 100644 --- a/adapter-cqld4/src/main/java/io/nosqlbench/cqlgen/transformers/CqlSchemaStatsParser.java +++ b/adapter-cqld4/src/main/java/io/nosqlbench/cqlgen/transformers/CqlSchemaStatsParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ package io.nosqlbench.cqlgen.transformers; import io.nosqlbench.cqlgen.core.CGKeyspaceStats; import io.nosqlbench.cqlgen.core.CGSchemaStats; import io.nosqlbench.cqlgen.core.CGTableStats; -import org.apache.commons.math4.util.Pair; +import org.apache.commons.math4.legacy.core.Pair; import java.io.BufferedReader; import java.io.IOException; diff --git a/adapter-dynamodb/pom.xml b/adapter-dynamodb/pom.xml index 61e2648dc..f0e2da0df 100644 --- a/adapter-dynamodb/pom.xml +++ b/adapter-dynamodb/pom.xml @@ -48,53 +48,4 @@ - - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - - - diff --git a/adapter-http/pom.xml b/adapter-http/pom.xml index 04b6d00f8..8c1e071ce 100644 --- a/adapter-http/pom.xml +++ b/adapter-http/pom.xml @@ -33,53 +33,6 @@ This provides the ability to generate HTTP requests with nosqlbench - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - - diff --git a/adapter-kafka/pom.xml b/adapter-kafka/pom.xml index 378bea8f5..d971c248f 100644 --- a/adapter-kafka/pom.xml +++ b/adapter-kafka/pom.xml @@ -36,53 +36,7 @@ 3.3.1 - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - io.nosqlbench diff --git a/adapter-mongodb/pom.xml b/adapter-mongodb/pom.xml index a60bc51d2..e1f79bba7 100644 --- a/adapter-mongodb/pom.xml +++ b/adapter-mongodb/pom.xml @@ -46,50 +46,4 @@ - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - diff --git a/adapter-pulsar/pom.xml b/adapter-pulsar/pom.xml index 88e6f58b4..5075eaf1c 100644 --- a/adapter-pulsar/pom.xml +++ b/adapter-pulsar/pom.xml @@ -91,51 +91,4 @@ - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - - diff --git a/adapter-s4j/pom.xml b/adapter-s4j/pom.xml index 61d40877b..4f139d724 100644 --- a/adapter-s4j/pom.xml +++ b/adapter-s4j/pom.xml @@ -100,50 +100,6 @@ 1.7.1 - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - diff --git a/adapter-stdout/pom.xml b/adapter-stdout/pom.xml index be7d7179d..62dfc2548 100644 --- a/adapter-stdout/pom.xml +++ b/adapter-stdout/pom.xml @@ -53,50 +53,9 @@ - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - + + + - - diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/package-info.java b/adapter-stdout/src/test/java/io/nosqlbench/adapter/stdout/TemplateFormatTest.java similarity index 52% rename from virtdata-lib-curves4/src/main/java/org/apache/commons/package-info.java rename to adapter-stdout/src/test/java/io/nosqlbench/adapter/stdout/TemplateFormatTest.java index 508d6b6cf..c4314bbaf 100644 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/package-info.java +++ b/adapter-stdout/src/test/java/io/nosqlbench/adapter/stdout/TemplateFormatTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,12 +14,26 @@ * limitations under the License. */ -/** - * This package is an import of some org.apache.commons source trees. - * Once the state of the newer o.a.c.math4 and distributions modules is stable, - * these will be removed and the release artifacts will be used. - * The enclosed packages were included here as the least worst of several options, - * given the confluence of JPMS, the status of the math4 repos, and the need - * to access stable CDF functions across the extant distributions. - */ -package org.apache.commons; +package io.nosqlbench.adapter.stdout; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class TemplateFormatTest { + + @Test + public void testBasicFormats() { + assertThat(TemplateFormat.json.format(true, List.of("f1","f2"))) + .isEqualTo(""" + { + "f1":"{f1}", + "f2":"{f2}" + } + + """); + } + +} diff --git a/adapter-tcp/pom.xml b/adapter-tcp/pom.xml index 2baab2131..0855ec341 100644 --- a/adapter-tcp/pom.xml +++ b/adapter-tcp/pom.xml @@ -51,51 +51,4 @@ - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - - diff --git a/adapters-api/pom.xml b/adapters-api/pom.xml index 52bedd0df..209085743 100644 --- a/adapters-api/pom.xml +++ b/adapters-api/pom.xml @@ -63,50 +63,6 @@ - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - src/main/resources diff --git a/docsys/pom.xml b/docsys/pom.xml index 3f63e3b87..e2c27cce4 100644 --- a/docsys/pom.xml +++ b/docsys/pom.xml @@ -133,51 +133,4 @@ - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - - diff --git a/driver-cockroachdb/pom.xml b/driver-cockroachdb/pom.xml index 8c228df0c..3fa69b7a6 100644 --- a/driver-cockroachdb/pom.xml +++ b/driver-cockroachdb/pom.xml @@ -47,51 +47,4 @@ - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - - diff --git a/driver-jdbc/pom.xml b/driver-jdbc/pom.xml index ebe1c34cc..055be3aeb 100644 --- a/driver-jdbc/pom.xml +++ b/driver-jdbc/pom.xml @@ -41,54 +41,4 @@ - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - - - - - diff --git a/driver-jmx/pom.xml b/driver-jmx/pom.xml index d85c655fe..3b1fcfb75 100644 --- a/driver-jmx/pom.xml +++ b/driver-jmx/pom.xml @@ -42,52 +42,5 @@ compile - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - - diff --git a/driver-kafka/pom.xml b/driver-kafka/pom.xml index 576d0b4e8..0d8ff4b4b 100644 --- a/driver-kafka/pom.xml +++ b/driver-kafka/pom.xml @@ -65,54 +65,6 @@ - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - - - confluent diff --git a/driver-pulsar/pom.xml b/driver-pulsar/pom.xml index c17f292c7..b05b8266a 100644 --- a/driver-pulsar/pom.xml +++ b/driver-pulsar/pom.xml @@ -90,52 +90,5 @@ - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - - diff --git a/engine-api/pom.xml b/engine-api/pom.xml index cb02185b4..f7c9a1717 100644 --- a/engine-api/pom.xml +++ b/engine-api/pom.xml @@ -136,51 +136,6 @@ false - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - diff --git a/engine-api/src/test/java/io/nosqlbench/engine/api/scripting/GraalJsEvaluatorTest.java b/engine-api/src/test/java/io/nosqlbench/engine/api/scripting/GraalJsEvaluatorTest.java index 0a8c84e2f..a73d69157 100644 --- a/engine-api/src/test/java/io/nosqlbench/engine/api/scripting/GraalJsEvaluatorTest.java +++ b/engine-api/src/test/java/io/nosqlbench/engine/api/scripting/GraalJsEvaluatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,22 @@ import static org.assertj.core.api.Assertions.assertThat; public class GraalJsEvaluatorTest { + // TODO: + + /** + * This evaluator may benefit from being compiled. Presently it give a warning: + *
{@code
+     * [To redirect Truffle log output to a file use one of the following options:
+     * * '--log.file=' if the option is passed using a guest language launcher.
+     * * '-Dpolyglot.log.file=' if the option is passed using the host Java launcher.
+     * * Configure logging using the polyglot embedding API.]
+     * [engine] WARNING: The polyglot context is using an implementation that does not support runtime compilation.
+     * The guest application code will therefore be executed in interpreted mode only.
+     * Execution only in interpreted mode will strongly impact the guest application performance.
+     * For more information on using GraalVM see https://www.graalvm.org/java/quickstart/.
+     * To disable this warning the '--engine.WarnInterpreterOnly=false' option or use the '-Dpolyglot.engine.WarnInterpreterOnly=false' system property.
+     * }
+ */ @Test public void testBasicOperations() { GraalJsEvaluator ne = new GraalJsEvaluator<>(Long.class); diff --git a/engine-cli/pom.xml b/engine-cli/pom.xml index 29b9caff8..7aa5025c4 100644 --- a/engine-cli/pom.xml +++ b/engine-cli/pom.xml @@ -51,51 +51,6 @@ - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - src/main/resources diff --git a/engine-clients/pom.xml b/engine-clients/pom.xml index 7ea03a113..f4f0ac181 100644 --- a/engine-clients/pom.xml +++ b/engine-clients/pom.xml @@ -58,51 +58,6 @@ - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - diff --git a/engine-core/pom.xml b/engine-core/pom.xml index 5be1c8c0f..12de63b1a 100644 --- a/engine-core/pom.xml +++ b/engine-core/pom.xml @@ -93,49 +93,5 @@ true
- - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - diff --git a/engine-docker/pom.xml b/engine-docker/pom.xml index 944fdc3ee..0f2001249 100644 --- a/engine-docker/pom.xml +++ b/engine-docker/pom.xml @@ -76,53 +76,4 @@ - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - - - - diff --git a/engine-docs/pom.xml b/engine-docs/pom.xml index 69e46c136..88ae32cc2 100644 --- a/engine-docs/pom.xml +++ b/engine-docs/pom.xml @@ -66,49 +66,6 @@ - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - org.apache.maven.plugins maven-assembly-plugin diff --git a/engine-extensions/pom.xml b/engine-extensions/pom.xml index 02f3d7b6e..e17a64a1e 100644 --- a/engine-extensions/pom.xml +++ b/engine-extensions/pom.xml @@ -45,7 +45,6 @@ - src/main/java @@ -54,71 +53,6 @@ - - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/engine-rest/pom.xml b/engine-rest/pom.xml index c9790c0b0..86f22f37e 100644 --- a/engine-rest/pom.xml +++ b/engine-rest/pom.xml @@ -56,52 +56,4 @@ - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - - - diff --git a/mvn-defaults/pom.xml b/mvn-defaults/pom.xml index dac0edfea..d29d8e9e0 100644 --- a/mvn-defaults/pom.xml +++ b/mvn-defaults/pom.xml @@ -14,7 +14,9 @@ ~ limitations under the License. --> - + 4.0.0 io.nosqlbench @@ -34,8 +36,9 @@ UTF-8 nosqlbench - 0.8.8 + 17 + 17 @@ -134,6 +137,32 @@ 1.10.0 + + org.apache.commons + commons-math4-core + 4.0-beta1 + + + org.apache.commons + commons-math4-legacy + 4.0-beta1 + + + org.apache.commons + commons-math4-legacy-core + 4.0-beta1 + + + org.apache.commons + commons-math4-legacy-exception + 4.0-beta1 + + + org.apache.commons + commons-statistics-distribution + 1.0 + + org.openjdk.jmh jmh-core @@ -262,7 +291,7 @@ com.amazonaws aws-java-sdk-s3 - 1.12.382 + 1.12.393 @@ -295,12 +324,6 @@ 2.12.2 - - org.apache.commons - commons-math3 - 3.6.1 - - org.apache.commons commons-csv @@ -464,7 +487,118 @@ 1.7.1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.apache.maven.plugins maven-resources-plugin @@ -502,7 +636,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.9.0 + 3.10.1 true 17 @@ -520,8 +654,10 @@ maven-surefire-plugin 3.0.0-M6 + -ea ${argLine} - org.apache.logging.log4j.core.async.AsyncLoggerContextSelector + + org.apache.logging.log4j.core.async.AsyncLoggerContextSelector methods @@ -538,6 +674,57 @@ + + org.jacoco + jacoco-maven-plugin + 0.8.8 + + + prepare-agent + process-test-classes + + prepare-agent + + + ${build.directory}/jacoco-data.exec + + + + report + verify + + report + + + ${build.directory}/jacoco-data.exec + ${build.directory}/jacoco-reports + + + + jacoco-check + verify + + check + + + + + BUNDLE + + + INSTRUCTION + COVEREDRATIO + 0.00 + 1.00 + + + + + + + + + org.apache.maven.plugins maven-failsafe-plugin @@ -698,7 +885,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.1 + 3.10.1 org.apache.maven.plugins diff --git a/nb-annotations/pom.xml b/nb-annotations/pom.xml index 1c95dcb10..cbc0e7d12 100644 --- a/nb-annotations/pom.xml +++ b/nb-annotations/pom.xml @@ -45,52 +45,4 @@ - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - - - diff --git a/nb-api/pom.xml b/nb-api/pom.xml index 38e4550f2..9ee183629 100644 --- a/nb-api/pom.xml +++ b/nb-api/pom.xml @@ -150,52 +150,6 @@ - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - src/main/resources diff --git a/nb-spectest/pom.xml b/nb-spectest/pom.xml index 8d9901f47..a0b6fdb37 100644 --- a/nb-spectest/pom.xml +++ b/nb-spectest/pom.xml @@ -65,50 +65,6 @@ - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - src/main/resources diff --git a/nb5/pom.xml b/nb5/pom.xml index ccbfeba90..639c0e031 100644 --- a/nb5/pom.xml +++ b/nb5/pom.xml @@ -190,48 +190,6 @@ - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - @@ -288,50 +246,6 @@ - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - diff --git a/nbr-examples/pom.xml b/nbr-examples/pom.xml index 44028da45..820262ef2 100644 --- a/nbr-examples/pom.xml +++ b/nbr-examples/pom.xml @@ -68,49 +68,6 @@ - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - org.apache.maven.plugins maven-failsafe-plugin diff --git a/nbr/pom.xml b/nbr/pom.xml index a58294370..7eafb9e28 100644 --- a/nbr/pom.xml +++ b/nbr/pom.xml @@ -136,48 +136,6 @@ - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - diff --git a/pom.xml b/pom.xml index b8cd0dcba..a117565f8 100644 --- a/pom.xml +++ b/pom.xml @@ -155,249 +155,6 @@ - - org.apache.maven.plugins - maven-antrun-plugin - 1.6 - - - post-integration-test - - run - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - org.jacoco - org.jacoco.ant - ${jacoco.version} - - - diff --git a/virtdata-api/pom.xml b/virtdata-api/pom.xml index 09809b834..fca7bdc14 100644 --- a/virtdata-api/pom.xml +++ b/virtdata-api/pom.xml @@ -60,52 +60,28 @@ javapoet + + org.apache.commons + commons-math4-core + + + org.apache.commons + commons-math4-legacy + + + org.apache.commons + commons-math4-legacy-core + + + org.apache.commons + commons-math4-legacy-exception + 4.0-beta1 + + + org.apache.commons + commons-statistics-distribution + + - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - diff --git a/virtdata-lang/pom.xml b/virtdata-lang/pom.xml index 6bb6181da..e5075a130 100644 --- a/virtdata-lang/pom.xml +++ b/virtdata-lang/pom.xml @@ -80,49 +80,6 @@ false - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - diff --git a/virtdata-lib-basics/pom.xml b/virtdata-lib-basics/pom.xml index c172ee28b..f2c268b2c 100644 --- a/virtdata-lib-basics/pom.xml +++ b/virtdata-lib-basics/pom.xml @@ -63,10 +63,6 @@ joda-time joda-time - - org.apache.commons - commons-math3 - com.elega9t @@ -75,51 +71,4 @@ - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - - diff --git a/virtdata-lib-curves4/pom.xml b/virtdata-lib-curves4/pom.xml index aa0348051..5411f4d82 100644 --- a/virtdata-lib-curves4/pom.xml +++ b/virtdata-lib-curves4/pom.xml @@ -47,59 +47,21 @@ ${revision} + + org.apache.commons + commons-math4-core + 4.0-beta1 + + + org.apache.commons + commons-math4-legacy-core + 4.0-beta1 + + + org.apache.commons + commons-statistics-distribution + 1.0 + - - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - ${project.reporting.outputDirectory}/jacoco-ut - - org/apache/**/* - - - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - - - diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Beta.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Beta.java index e8f727788..ed9879814 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Beta.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Beta.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.BetaDistribution; @ThreadSafeMapper public class Beta extends IntToDoubleContinuousCurve { public Beta(double alpha, double beta, String... mods) { - super(new BetaDistribution(alpha, beta), mods); + super(BetaDistribution.of(alpha, beta), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Cauchy.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Cauchy.java index a9a8d6ef7..190c3654b 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Cauchy.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Cauchy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.CauchyDistribution; @Categories({Category.distributions}) public class Cauchy extends IntToDoubleContinuousCurve { public Cauchy(double median, double scale, String... mods) { - super(new CauchyDistribution(median, scale), mods); + super(CauchyDistribution.of(median, scale), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/ChiSquared.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/ChiSquared.java index 4c4f3fb6c..cbb72b9f6 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/ChiSquared.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/ChiSquared.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.ChiSquaredDistribution; @Categories({Category.distributions}) public class ChiSquared extends IntToDoubleContinuousCurve { public ChiSquared(double degreesOfFreedom, String... mods) { - super(new ChiSquaredDistribution(degreesOfFreedom), mods); + super(ChiSquaredDistribution.of(degreesOfFreedom), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/ConstantContinuous.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/ConstantContinuous.java index 70665ff28..09f4b551f 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/ConstantContinuous.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/ConstantContinuous.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ package io.nosqlbench.virtdata.library.curves4.continuous.int_double; import io.nosqlbench.virtdata.api.annotations.Categories; import io.nosqlbench.virtdata.api.annotations.Category; import io.nosqlbench.virtdata.api.annotations.ThreadSafeMapper; -import org.apache.commons.statistics.distribution.ConstantContinuousDistribution; +import org.apache.commons.math4.legacy.distribution.EmpiricalDistribution; /** * Always yields the same value. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.ConstantContinuousDistribution @Categories({Category.distributions}) public class ConstantContinuous extends IntToDoubleContinuousCurve { public ConstantContinuous(double value, String... mods) { - super(new ConstantContinuousDistribution(value), mods); + super(EmpiricalDistribution.from(1, new double[]{value}), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Enumerated.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Enumerated.java index fa52a1d8f..ab24aba45 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Enumerated.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Enumerated.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import io.nosqlbench.virtdata.api.annotations.Categories; import io.nosqlbench.virtdata.api.annotations.Category; import io.nosqlbench.virtdata.api.annotations.Example; import io.nosqlbench.virtdata.api.annotations.ThreadSafeMapper; -import org.apache.commons.math4.distribution.EnumeratedRealDistribution; +import org.apache.commons.math4.legacy.distribution.EnumeratedRealDistribution; /** * Creates a probability density given the values and optional weights provided, in "value:weight value:weight ..." form. diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Exponential.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Exponential.java index 1153a4a61..46272e6db 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Exponential.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Exponential.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.ExponentialDistribution; @Categories({Category.distributions}) public class Exponential extends IntToDoubleContinuousCurve { public Exponential(double mean, String... mods) { - super(new ExponentialDistribution(mean), mods); + super(ExponentialDistribution.of(mean), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/F.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/F.java index a3c28b1c5..2531cb3b3 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/F.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/F.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,6 +34,6 @@ import org.apache.commons.statistics.distribution.FDistribution; @Categories({Category.distributions}) public class F extends IntToDoubleContinuousCurve { public F(double numeratorDegreesOfFreedom, double denominatorDegreesOfFreedom, String... mods) { - super(new FDistribution(numeratorDegreesOfFreedom, denominatorDegreesOfFreedom), mods); + super(FDistribution.of(numeratorDegreesOfFreedom, denominatorDegreesOfFreedom), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Gamma.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Gamma.java index fce828cc3..c23cae407 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Gamma.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Gamma.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.GammaDistribution; @Categories({Category.distributions}) public class Gamma extends IntToDoubleContinuousCurve { public Gamma(double shape, double scale, String... mods) { - super(new GammaDistribution(shape, scale), mods); + super(GammaDistribution.of(shape, scale), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Gumbel.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Gumbel.java index a6cdc1f46..ae295e458 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Gumbel.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Gumbel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.GumbelDistribution; @Categories({Category.distributions}) public class Gumbel extends IntToDoubleContinuousCurve { public Gumbel(double mu, double beta, String... mods) { - super(new GumbelDistribution(mu, beta), mods); + super(GumbelDistribution.of(mu, beta), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Laplace.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Laplace.java index 8f0bba00b..7bb271f77 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Laplace.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Laplace.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.LaplaceDistribution; @Categories({Category.distributions}) public class Laplace extends IntToDoubleContinuousCurve { public Laplace(double mu, double beta, String... mods) { - super(new LaplaceDistribution(mu, beta), mods); + super(LaplaceDistribution.of(mu, beta), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Levy.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Levy.java index 76257eafd..521c6d549 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Levy.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Levy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,6 +30,6 @@ import org.apache.commons.statistics.distribution.LevyDistribution; */ @ThreadSafeMapper @Categories({Category.distributions}) -public class Levy extends IntToDoubleContinuousCurve { public Levy(double mu, double c, String... mods) { super(new LevyDistribution(mu,c), mods); +public class Levy extends IntToDoubleContinuousCurve { public Levy(double mu, double c, String... mods) { super(LevyDistribution.of(mu,c), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/LogNormal.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/LogNormal.java index 7196acb42..3d411a38d 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/LogNormal.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/LogNormal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.LogNormalDistribution; @Categories({Category.distributions}) public class LogNormal extends IntToDoubleContinuousCurve { public LogNormal(double scale, double shape, String... mods) { - super(new LogNormalDistribution(scale, shape), mods); + super(LogNormalDistribution.of(scale, shape), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Logistic.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Logistic.java index e786b4e55..cdd252b42 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Logistic.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Logistic.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.LogisticDistribution; @Categories({Category.distributions}) public class Logistic extends IntToDoubleContinuousCurve { public Logistic(double mu, double scale, String... mods) { - super(new LogisticDistribution(mu, scale), mods); + super(LogisticDistribution.of(mu, scale), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Nakagami.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Nakagami.java index 38ab51c83..1eeba8789 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Nakagami.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Nakagami.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.NakagamiDistribution; @Categories({Category.distributions}) public class Nakagami extends IntToDoubleContinuousCurve { public Nakagami(double mu, double omega, String... mods) { - super(new NakagamiDistribution(mu, omega), mods); + super(NakagamiDistribution.of(mu, omega), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Normal.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Normal.java index 79a5bd11a..545a32a1c 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Normal.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Normal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.NormalDistribution; @Categories({Category.distributions}) public class Normal extends IntToDoubleContinuousCurve { public Normal(double mean, double sd, String... mods) { - super(new NormalDistribution(mean, sd), mods); + super(NormalDistribution.of(mean, sd), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Pareto.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Pareto.java index 6c75e7f89..1c685e89b 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Pareto.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Pareto.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.ParetoDistribution; @Categories({Category.distributions}) public class Pareto extends IntToDoubleContinuousCurve { public Pareto(double scale, double shape, String... mods) { - super(new ParetoDistribution(scale, shape), mods); + super(ParetoDistribution.of(scale, shape), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/T.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/T.java index 590c9d512..08af02fe8 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/T.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/T.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.TDistribution; @Categories({Category.distributions}) public class T extends IntToDoubleContinuousCurve { public T(double degreesOfFreedom, String... mods) { - super(new TDistribution(degreesOfFreedom), mods); + super(TDistribution.of(degreesOfFreedom), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Triangular.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Triangular.java index b3a5d73a3..960b817e6 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Triangular.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Triangular.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.TriangularDistribution; @Categories({Category.distributions}) public class Triangular extends IntToDoubleContinuousCurve { public Triangular(double a, double c, double b, String... mods) { - super(new TriangularDistribution(a,c,b), mods); + super(TriangularDistribution.of(a,c,b), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Uniform.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Uniform.java index 169b3ef8b..d05dccffc 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Uniform.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Uniform.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.UniformContinuousDistribution; @Categories({Category.distributions}) public class Uniform extends IntToDoubleContinuousCurve { public Uniform(double lower, double upper, String... mods) { - super(new UniformContinuousDistribution(lower, upper), mods); + super(UniformContinuousDistribution.of(lower, upper), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Weibull.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Weibull.java index ae0d980f6..3370860af 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Weibull.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Weibull.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,6 +34,6 @@ import org.apache.commons.statistics.distribution.WeibullDistribution; @Categories({Category.distributions}) public class Weibull extends IntToDoubleContinuousCurve { public Weibull(double alpha, double beta, String... mods) { - super(new WeibullDistribution(alpha, beta), mods); + super(WeibullDistribution.of(alpha, beta), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Beta.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Beta.java index 16cb274e7..d48eb33d2 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Beta.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Beta.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.BetaDistribution; @ThreadSafeMapper public class Beta extends LongToDoubleContinuousCurve { public Beta(double alpha, double beta, String... mods) { - super(new BetaDistribution(alpha, beta), mods); + super(BetaDistribution.of(alpha, beta), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Cauchy.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Cauchy.java index 579646bcf..ed7ad3132 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Cauchy.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Cauchy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.CauchyDistribution; @Categories({Category.distributions}) public class Cauchy extends LongToDoubleContinuousCurve { public Cauchy(double median, double scale, String... mods) { - super(new CauchyDistribution(median, scale), mods); + super(CauchyDistribution.of(median, scale), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/ChiSquared.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/ChiSquared.java index 34dfac1c0..edd71a1f1 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/ChiSquared.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/ChiSquared.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.ChiSquaredDistribution; @Categories({Category.distributions}) public class ChiSquared extends LongToDoubleContinuousCurve { public ChiSquared(double degreesOfFreedom, String... mods) { - super(new ChiSquaredDistribution(degreesOfFreedom), mods); + super(ChiSquaredDistribution.of(degreesOfFreedom), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/ConstantContinuous.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/ConstantContinuous.java index fdfe4f7d0..d2b5f02c5 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/ConstantContinuous.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/ConstantContinuous.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,12 @@ package io.nosqlbench.virtdata.library.curves4.continuous.long_double; import io.nosqlbench.virtdata.api.annotations.Categories; import io.nosqlbench.virtdata.api.annotations.Category; import io.nosqlbench.virtdata.api.annotations.ThreadSafeMapper; -import org.apache.commons.statistics.distribution.ConstantContinuousDistribution; +import org.apache.commons.math4.legacy.distribution.EmpiricalDistribution; @ThreadSafeMapper @Categories({Category.distributions}) public class ConstantContinuous extends LongToDoubleContinuousCurve { public ConstantContinuous(double value, String... mods) { - super(new ConstantContinuousDistribution(value), mods); + super(EmpiricalDistribution.from(1,new double[]{value}), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Enumerated.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Enumerated.java index 61559d9b2..3267f90de 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Enumerated.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Enumerated.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import io.nosqlbench.virtdata.api.annotations.Categories; import io.nosqlbench.virtdata.api.annotations.Category; import io.nosqlbench.virtdata.api.annotations.Example; import io.nosqlbench.virtdata.api.annotations.ThreadSafeMapper; -import org.apache.commons.math4.distribution.EnumeratedRealDistribution; +import org.apache.commons.math4.legacy.distribution.EnumeratedRealDistribution; @ThreadSafeMapper @Categories({Category.distributions}) diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Exponential.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Exponential.java index a51ff0827..b516cb2b5 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Exponential.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Exponential.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.ExponentialDistribution; @Categories({Category.distributions}) public class Exponential extends LongToDoubleContinuousCurve { public Exponential(double mean, String... mods) { - super(new ExponentialDistribution(mean), mods); + super(ExponentialDistribution.of(mean), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/F.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/F.java index 9c605d894..d81991faa 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/F.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/F.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.FDistribution; @Categories({Category.distributions}) public class F extends LongToDoubleContinuousCurve { public F(double numeratorDegreesOfFreedom, double denominatorDegreesOfFreedom, String... mods) { - super(new FDistribution(numeratorDegreesOfFreedom, denominatorDegreesOfFreedom), mods); + super(FDistribution.of(numeratorDegreesOfFreedom, denominatorDegreesOfFreedom), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Gamma.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Gamma.java index 44cd3660a..0484b408f 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Gamma.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Gamma.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.GammaDistribution; @Categories({Category.distributions}) public class Gamma extends LongToDoubleContinuousCurve { public Gamma(double shape, double scale, String... mods) { - super(new GammaDistribution(shape, scale), mods); + super(GammaDistribution.of(shape, scale), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Gumbel.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Gumbel.java index 80f8ecc12..0b4c49e20 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Gumbel.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Gumbel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,10 +21,11 @@ import io.nosqlbench.virtdata.api.annotations.Category; import io.nosqlbench.virtdata.api.annotations.ThreadSafeMapper; import org.apache.commons.statistics.distribution.GumbelDistribution; + @ThreadSafeMapper @Categories({Category.distributions}) public class Gumbel extends LongToDoubleContinuousCurve { public Gumbel(double mu, double beta, String... mods) { - super(new GumbelDistribution(mu, beta), mods); + super(GumbelDistribution.of(mu, beta), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Laplace.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Laplace.java index b019844f6..0d58ce800 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Laplace.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Laplace.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.LaplaceDistribution; @Categories({Category.distributions}) public class Laplace extends LongToDoubleContinuousCurve { public Laplace(double mu, double beta, String... mods) { - super(new LaplaceDistribution(mu, beta), mods); + super(LaplaceDistribution.of(mu, beta), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Levy.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Levy.java index e86fe7c7d..b6651f96f 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Levy.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Levy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,6 @@ import org.apache.commons.statistics.distribution.LevyDistribution; @ThreadSafeMapper @Categories({Category.distributions}) -public class Levy extends LongToDoubleContinuousCurve { public Levy(double mu, double c, String... mods) { super(new LevyDistribution(mu,c), mods); +public class Levy extends LongToDoubleContinuousCurve { public Levy(double mu, double c, String... mods) { super(LevyDistribution.of(mu,c), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/LogNormal.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/LogNormal.java index f8d5716a4..69a12c0ea 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/LogNormal.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/LogNormal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.LogNormalDistribution; @Categories({Category.distributions}) public class LogNormal extends LongToDoubleContinuousCurve { public LogNormal(double scale, double shape, String... mods) { - super(new LogNormalDistribution(scale, shape), mods); + super(LogNormalDistribution.of(scale, shape), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Logistic.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Logistic.java index 4caff87de..809cbcef3 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Logistic.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Logistic.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.LogisticDistribution; @Categories({Category.distributions}) public class Logistic extends LongToDoubleContinuousCurve { public Logistic(double mu, double scale, String... mods) { - super(new LogisticDistribution(mu, scale), mods); + super(LogisticDistribution.of(mu, scale), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Nakagami.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Nakagami.java index fff5684b3..75bbf5b36 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Nakagami.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Nakagami.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.NakagamiDistribution; @Categories({Category.distributions}) public class Nakagami extends LongToDoubleContinuousCurve { public Nakagami(double mu, double omega, String... mods) { - super(new NakagamiDistribution(mu, omega), mods); + super(NakagamiDistribution.of(mu, omega), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Normal.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Normal.java index b681757cf..7ab01fe7d 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Normal.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Normal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.NormalDistribution; @Categories({Category.distributions}) public class Normal extends LongToDoubleContinuousCurve { public Normal(double mean, double sd, String... mods) { - super(new NormalDistribution(mean, sd), mods); + super(NormalDistribution.of(mean, sd), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Pareto.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Pareto.java index 87fce74e1..a700a5f96 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Pareto.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Pareto.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.ParetoDistribution; @Categories({Category.distributions}) public class Pareto extends LongToDoubleContinuousCurve { public Pareto(double scale, double shape, String... mods) { - super(new ParetoDistribution(scale, shape), mods); + super(ParetoDistribution.of(scale, shape), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/T.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/T.java index a7bd2cb15..ba81dc8cb 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/T.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/T.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.TDistribution; @Categories({Category.distributions}) public class T extends LongToDoubleContinuousCurve { public T(double degreesOfFreedom, String... mods) { - super(new TDistribution(degreesOfFreedom), mods); + super(TDistribution.of(degreesOfFreedom), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Triangular.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Triangular.java index 25b915297..01a4325d0 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Triangular.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Triangular.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.TriangularDistribution; @Categories({Category.distributions}) public class Triangular extends LongToDoubleContinuousCurve { public Triangular(double a, double c, double b, String... mods) { - super(new TriangularDistribution(a,c,b), mods); + super(TriangularDistribution.of(a,c,b), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Uniform.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Uniform.java index 11d2369e0..b72d54b39 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Uniform.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Uniform.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.UniformContinuousDistribution; @Categories({Category.distributions}) public class Uniform extends LongToDoubleContinuousCurve { public Uniform(double lower, double upper, String... mods) { - super(new UniformContinuousDistribution(lower, upper), mods); + super(UniformContinuousDistribution.of(lower, upper), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Weibull.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Weibull.java index 254c09584..0c29e6671 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Weibull.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/long_double/Weibull.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.WeibullDistribution; @Categories({Category.distributions}) public class Weibull extends LongToDoubleContinuousCurve { public Weibull(double alpha, double beta, String... mods) { - super(new WeibullDistribution(alpha, beta), mods); + super(WeibullDistribution.of(alpha, beta), mods); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Binomial.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Binomial.java index 334b46d66..df8cc2221 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Binomial.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Binomial.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.BinomialDistribution; @Categories({Category.distributions}) public class Binomial extends IntToIntDiscreteCurve { public Binomial(int trials, double p, String... modslist) { - super(new BinomialDistribution(trials, p), modslist); + super(BinomialDistribution.of(trials, p), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Geometric.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Geometric.java index 07a729ee3..c75f7023f 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Geometric.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Geometric.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.GeometricDistribution; @Categories({Category.distributions}) public class Geometric extends IntToIntDiscreteCurve { public Geometric(double p, String... modslist) { - super(new GeometricDistribution(p), modslist); + super(GeometricDistribution.of(p), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Hypergeometric.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Hypergeometric.java index 4accfd99f..5f29dc1ca 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Hypergeometric.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Hypergeometric.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.HypergeometricDistribution; @Categories({Category.distributions}) public class Hypergeometric extends IntToIntDiscreteCurve { public Hypergeometric(int populationSize, int numberOfSuccesses, int sampleSize, String... modslist) { - super(new HypergeometricDistribution(populationSize, numberOfSuccesses, sampleSize), modslist); + super(HypergeometricDistribution.of(populationSize, numberOfSuccesses, sampleSize), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Pascal.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Pascal.java index e6c5d07dc..cf109d446 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Pascal.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Pascal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.PascalDistribution; @Categories({Category.distributions}) public class Pascal extends IntToIntDiscreteCurve { public Pascal(int r, double p, String... modslist) { - super(new PascalDistribution(r, p), modslist); + super(PascalDistribution.of(r, p), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Poisson.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Poisson.java index c892782f3..22e4a0b8f 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Poisson.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Poisson.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.PoissonDistribution; @Categories({Category.distributions}) public class Poisson extends IntToIntDiscreteCurve { public Poisson(double p, String... modslist) { - super(new PoissonDistribution(p), modslist); + super(PoissonDistribution.of(p), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Uniform.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Uniform.java index bdb4f5122..ae4d5a908 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Uniform.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Uniform.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.UniformDiscreteDistribution; @Categories({Category.distributions}) public class Uniform extends IntToIntDiscreteCurve { public Uniform(int lower, int upper, String... modslist) { - super(new UniformDiscreteDistribution(lower, upper), modslist); + super(UniformDiscreteDistribution.of(lower, upper), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Zipf.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Zipf.java index bb4d54892..4b504536a 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Zipf.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_int/Zipf.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,6 @@ import org.apache.commons.statistics.distribution.ZipfDistribution; @Categories({Category.distributions}) public class Zipf extends IntToIntDiscreteCurve { public Zipf(int numberOfElements, double exponent, String... modslist) { - super(new ZipfDistribution(numberOfElements, exponent), modslist); + super(ZipfDistribution.of(numberOfElements, exponent), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Binomial.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Binomial.java index 1da9bfd8c..5417de047 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Binomial.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Binomial.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.BinomialDistribution; @ThreadSafeMapper public class Binomial extends IntToLongDiscreteCurve { public Binomial(int trials, double p, String... modslist) { - super(new BinomialDistribution(trials, p), modslist); + super(BinomialDistribution.of(trials, p), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Geometric.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Geometric.java index 6d122a150..9d3469c42 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Geometric.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Geometric.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.GeometricDistribution; @Categories({Category.distributions}) public class Geometric extends IntToLongDiscreteCurve { public Geometric(double p, String... modslist) { - super(new GeometricDistribution(p), modslist); + super(GeometricDistribution.of(p), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Hypergeometric.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Hypergeometric.java index 0bf689802..0d9f8da65 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Hypergeometric.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Hypergeometric.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.HypergeometricDistribution; @Categories({Category.distributions}) public class Hypergeometric extends IntToLongDiscreteCurve { public Hypergeometric(int populationSize, int numberOfSuccesses, int sampleSize, String... modslist) { - super(new HypergeometricDistribution(populationSize, numberOfSuccesses, sampleSize), modslist); + super(HypergeometricDistribution.of(populationSize, numberOfSuccesses, sampleSize), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Pascal.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Pascal.java index 5cdc129c9..64835d5c8 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Pascal.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Pascal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.PascalDistribution; @Categories({Category.distributions}) public class Pascal extends IntToLongDiscreteCurve { public Pascal(int r, double p, String... modslist) { - super(new PascalDistribution(r, p), modslist); + super(PascalDistribution.of(r, p), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Poisson.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Poisson.java index b17241f97..fc33175b3 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Poisson.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Poisson.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.PoissonDistribution; @Categories({Category.distributions}) public class Poisson extends IntToLongDiscreteCurve { public Poisson(double p, String... modslist) { - super(new PoissonDistribution(p), modslist); + super(PoissonDistribution.of(p), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Uniform.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Uniform.java index 6af4b3293..85212acd2 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Uniform.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Uniform.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.UniformDiscreteDistribution; @Categories({Category.distributions}) public class Uniform extends IntToLongDiscreteCurve { public Uniform(int lower, int upper, String... modslist) { - super(new UniformDiscreteDistribution(lower, upper), modslist); + super(UniformDiscreteDistribution.of(lower, upper), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Zipf.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Zipf.java index 280e72bd2..8c56bb017 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Zipf.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/int_long/Zipf.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.ZipfDistribution; @Categories({Category.distributions}) public class Zipf extends IntToLongDiscreteCurve { public Zipf(int numberOfElements, double exponent, String... modslist) { - super(new ZipfDistribution(numberOfElements, exponent), modslist); + super(ZipfDistribution.of(numberOfElements, exponent), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Binomial.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Binomial.java index 3487504b7..613f5c9af 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Binomial.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Binomial.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.BinomialDistribution; @Categories({Category.distributions}) public class Binomial extends LongToIntDiscreteCurve { public Binomial(int trials, double p, String... modslist) { - super(new BinomialDistribution(trials, p), modslist); + super(BinomialDistribution.of(trials, p), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Geometric.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Geometric.java index 3bb90e6be..15eab7681 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Geometric.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Geometric.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.GeometricDistribution; @Categories({Category.distributions}) public class Geometric extends LongToIntDiscreteCurve { public Geometric(double p, String... modslist) { - super(new GeometricDistribution(p), modslist); + super(GeometricDistribution.of(p), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Hypergeometric.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Hypergeometric.java index dea739ebd..795e25360 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Hypergeometric.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Hypergeometric.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.HypergeometricDistribution; @Categories({Category.distributions}) public class Hypergeometric extends LongToIntDiscreteCurve { public Hypergeometric(int populationSize, int numberOfSuccesses, int sampleSize, String... modslist) { - super(new HypergeometricDistribution(populationSize, numberOfSuccesses, sampleSize), modslist); + super(HypergeometricDistribution.of(populationSize, numberOfSuccesses, sampleSize), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Pascal.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Pascal.java index 255ddad89..8b01613e0 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Pascal.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Pascal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.PascalDistribution; @Categories({Category.distributions}) public class Pascal extends LongToIntDiscreteCurve { public Pascal(int r, double p, String... modslist) { - super(new PascalDistribution(r, p), modslist); + super(PascalDistribution.of(r, p), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Poisson.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Poisson.java index b2298cf24..affe037a3 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Poisson.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Poisson.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.PoissonDistribution; @Categories({Category.distributions}) public class Poisson extends LongToIntDiscreteCurve { public Poisson(double p, String... modslist) { - super(new PoissonDistribution(p), modslist); + super(PoissonDistribution.of(p), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Uniform.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Uniform.java index 73c64dd6e..0eeac4fe4 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Uniform.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Uniform.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.UniformDiscreteDistribution; @Categories({Category.distributions}) public class Uniform extends LongToIntDiscreteCurve { public Uniform(int lower, int upper, String... modslist) { - super(new UniformDiscreteDistribution(lower, upper), modslist); + super(UniformDiscreteDistribution.of(lower, upper), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Zipf.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Zipf.java index 3a03c525e..deb667a38 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Zipf.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_int/Zipf.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.ZipfDistribution; @Categories({Category.distributions}) public class Zipf extends LongToIntDiscreteCurve { public Zipf(int numberOfElements, double exponent, String... modslist) { - super(new ZipfDistribution(numberOfElements, exponent), modslist); + super(ZipfDistribution.of(numberOfElements, exponent), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Binomial.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Binomial.java index 85d786398..bd668ea41 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Binomial.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Binomial.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.BinomialDistribution; @Categories({Category.distributions}) public class Binomial extends LongToLongDiscreteCurve { public Binomial(int trials, double p, String... modslist) { - super(new BinomialDistribution(trials, p), modslist); + super(BinomialDistribution.of(trials, p), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Geometric.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Geometric.java index 95500777f..886d29f63 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Geometric.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Geometric.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.GeometricDistribution; @Categories({Category.distributions}) public class Geometric extends LongToLongDiscreteCurve { public Geometric(double p, String... modslist) { - super(new GeometricDistribution(p), modslist); + super(GeometricDistribution.of(p), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Hypergeometric.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Hypergeometric.java index 40bc61c22..6f1667db0 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Hypergeometric.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Hypergeometric.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.HypergeometricDistribution; @Categories({Category.distributions}) public class Hypergeometric extends LongToLongDiscreteCurve { public Hypergeometric(int populationSize, int numberOfSuccesses, int sampleSize, String... modslist) { - super(new HypergeometricDistribution(populationSize, numberOfSuccesses, sampleSize), modslist); + super(HypergeometricDistribution.of(populationSize, numberOfSuccesses, sampleSize), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Pascal.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Pascal.java index a357d5ff0..0e1293486 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Pascal.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Pascal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.PascalDistribution; @Categories({Category.distributions}) public class Pascal extends LongToLongDiscreteCurve { public Pascal(int r, double p, String... modslist) { - super(new PascalDistribution(r, p), modslist); + super(PascalDistribution.of(r, p), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Poisson.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Poisson.java index 1bbc921ca..02c8163d2 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Poisson.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Poisson.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.PoissonDistribution; @Categories({Category.distributions}) public class Poisson extends LongToLongDiscreteCurve { public Poisson(double p, String... modslist) { - super(new PoissonDistribution(p), modslist); + super(PoissonDistribution.of(p), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Uniform.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Uniform.java index 39d554360..01c5e4311 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Uniform.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Uniform.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.UniformDiscreteDistribution; @Categories({Category.distributions}) public class Uniform extends LongToLongDiscreteCurve { public Uniform(int lower, int upper, String... modslist) { - super(new UniformDiscreteDistribution(lower, upper), modslist); + super(UniformDiscreteDistribution.of(lower, upper), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Zipf.java b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Zipf.java index 651980994..0874c86fe 100644 --- a/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Zipf.java +++ b/virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/discrete/long_long/Zipf.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.apache.commons.statistics.distribution.ZipfDistribution; @Categories({Category.distributions}) public class Zipf extends LongToLongDiscreteCurve { public Zipf(int numberOfElements, double exponent, String... modslist) { - super(new ZipfDistribution(numberOfElements, exponent), modslist); + super(ZipfDistribution.of(numberOfElements, exponent), modslist); } } diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/Field.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/Field.java deleted file mode 100644 index ecc9342f8..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/Field.java +++ /dev/null @@ -1,58 +0,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. - */ -package org.apache.commons.math4; - -/** - * Interface representing a field. - *

- * Classes implementing this interface will often be singletons. - *

- * @param the type of the field elements - * @see FieldElement - * @since 2.0 - */ -public interface Field { - - /** Get the additive identity of the field. - *

- * The additive identity is the element e0 of the field such that - * for all elements a of the field, the equalities a + e0 = - * e0 + a = a hold. - *

- * @return additive identity of the field - */ - T getZero(); - - /** Get the multiplicative identity of the field. - *

- * The multiplicative identity is the element e1 of the field such that - * for all elements a of the field, the equalities a × e1 = - * e1 × a = a hold. - *

- * @return multiplicative identity of the field - */ - T getOne(); - - /** - * Returns the runtime class of the FieldElement. - * - * @return The {@code Class} object that represents the runtime - * class of this object. - */ - Class> getRuntimeClass(); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/FieldElement.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/FieldElement.java deleted file mode 100644 index 3e66d6ae2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/FieldElement.java +++ /dev/null @@ -1,85 +0,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. - */ -package org.apache.commons.math4; - -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.NullArgumentException; - - -/** - * Interface representing field elements. - * @param the type of the field elements - * @see Field - * @since 2.0 - */ -public interface FieldElement { - - /** Compute this + a. - * @param a element to add - * @return a new element representing this + a - * @throws NullArgumentException if {@code a} is {@code null}. - */ - T add(T a) throws NullArgumentException; - - /** Compute this - a. - * @param a element to subtract - * @return a new element representing this - a - * @throws NullArgumentException if {@code a} is {@code null}. - */ - T subtract(T a) throws NullArgumentException; - - /** - * Returns the additive inverse of {@code this} element. - * @return the opposite of {@code this}. - */ - T negate(); - - /** Compute n × this. Multiplication by an integer number is defined - * as the following sum - * n × this = ∑i=1n this. - * @param n Number of times {@code this} must be added to itself. - * @return A new element representing n × this. - */ - T multiply(int n); - - /** Compute this × a. - * @param a element to multiply - * @return a new element representing this × a - * @throws NullArgumentException if {@code a} is {@code null}. - */ - T multiply(T a) throws NullArgumentException; - - /** Compute this ÷ a. - * @param a element to divide by - * @return a new element representing this ÷ a - * @throws NullArgumentException if {@code a} is {@code null}. - * @throws MathArithmeticException if {@code a} is zero - */ - T divide(T a) throws NullArgumentException, MathArithmeticException; - - /** - * Returns the multiplicative inverse of {@code this} element. - * @return the inverse of {@code this}. - * @throws MathArithmeticException if {@code this} is zero - */ - T reciprocal() throws MathArithmeticException; - - /** Get the {@link Field} to which the instance belongs. - * @return {@link Field} to which the instance belongs - */ - Field getField(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/RealFieldElement.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/RealFieldElement.java deleted file mode 100644 index c5d586ed1..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/RealFieldElement.java +++ /dev/null @@ -1,402 +0,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. - */ -package org.apache.commons.math4; - -import org.apache.commons.math4.exception.DimensionMismatchException; - -/** - * Interface representing a real - * field. - * @param the type of the field elements - * @see FieldElement - * @since 3.2 - */ -public interface RealFieldElement extends FieldElement { - - /** Get the real value of the number. - * @return real value - */ - double getReal(); - - /** '+' operator. - * @param a right hand side parameter of the operator - * @return this+a - */ - T add(double a); - - /** '-' operator. - * @param a right hand side parameter of the operator - * @return this-a - */ - T subtract(double a); - - /** '×' operator. - * @param a right hand side parameter of the operator - * @return this×a - */ - T multiply(double a); - - /** '÷' operator. - * @param a right hand side parameter of the operator - * @return this÷a - */ - T divide(double a); - - /** IEEE remainder operator. - * @param a right hand side parameter of the operator - * @return this - n × a where n is the closest integer to this/a - * (the even integer is chosen for n if this/a is halfway between two integers) - */ - T remainder(double a); - - /** IEEE remainder operator. - * @param a right hand side parameter of the operator - * @return this - n × a where n is the closest integer to this/a - * (the even integer is chosen for n if this/a is halfway between two integers) - * @exception DimensionMismatchException if number of free parameters or orders are inconsistent - */ - T remainder(T a) - throws DimensionMismatchException; - - /** absolute value. - * @return abs(this) - */ - T abs(); - - /** Get the smallest whole number larger than instance. - * @return ceil(this) - */ - T ceil(); - - /** Get the largest whole number smaller than instance. - * @return floor(this) - */ - T floor(); - - /** Get the whole number that is the nearest to the instance, or the even one if x is exactly half way between two integers. - * @return a double number r such that r is an integer r - 0.5 ≤ this ≤ r + 0.5 - */ - T rint(); - - /** Get the closest long to instance value. - * @return closest long to {@link #getReal()} - */ - long round(); - - /** Compute the signum of the instance. - * The signum is -1 for negative numbers, +1 for positive numbers and 0 otherwise - * @return -1.0, -0.0, +0.0, +1.0 or NaN depending on sign of a - */ - T signum(); - - /** - * Returns the instance with the sign of the argument. - * A NaN {@code sign} argument is treated as positive. - * - * @param sign the sign for the returned value - * @return the instance with the same sign as the {@code sign} argument - */ - T copySign(T sign); - - /** - * Returns the instance with the sign of the argument. - * A NaN {@code sign} argument is treated as positive. - * - * @param sign the sign for the returned value - * @return the instance with the same sign as the {@code sign} argument - */ - T copySign(double sign); - - /** - * Multiply the instance by a power of 2. - * @param n power of 2 - * @return this × 2n - */ - T scalb(int n); - - /** - * Returns the hypotenuse of a triangle with sides {@code this} and {@code y} - * - sqrt(this2 +y2) - * avoiding intermediate overflow or underflow. - * - *
    - *
  • If either argument is infinite, then the result is positive infinity.
  • - *
  • else, if either argument is NaN then the result is NaN.
  • - *
- * - * @param y a value - * @return sqrt(this2 +y2) - * @exception DimensionMismatchException if number of free parameters or orders are inconsistent - */ - T hypot(T y) - throws DimensionMismatchException; - - /** {@inheritDoc} */ - @Override - T reciprocal(); - - /** Square root. - * @return square root of the instance - */ - T sqrt(); - - /** Cubic root. - * @return cubic root of the instance - */ - T cbrt(); - - /** Nth root. - * @param n order of the root - * @return nth root of the instance - */ - T rootN(int n); - - /** Power operation. - * @param p power to apply - * @return thisp - */ - T pow(double p); - - /** Integer power operation. - * @param n power to apply - * @return thisn - */ - T pow(int n); - - /** Power operation. - * @param e exponent - * @return thise - * @exception DimensionMismatchException if number of free parameters or orders are inconsistent - */ - T pow(T e) - throws DimensionMismatchException; - - /** Exponential. - * @return exponential of the instance - */ - T exp(); - - /** Exponential minus 1. - * @return exponential minus one of the instance - */ - T expm1(); - - /** Natural logarithm. - * @return logarithm of the instance - */ - T log(); - - /** Shifted natural logarithm. - * @return logarithm of one plus the instance - */ - T log1p(); - - /** Base 10 logarithm. - * @return base 10 logarithm of the instance - * @since 4.0 - */ - T log10(); - - /** Cosine operation. - * @return cos(this) - */ - T cos(); - - /** Sine operation. - * @return sin(this) - */ - T sin(); - - /** Tangent operation. - * @return tan(this) - */ - T tan(); - - /** Arc cosine operation. - * @return acos(this) - */ - T acos(); - - /** Arc sine operation. - * @return asin(this) - */ - T asin(); - - /** Arc tangent operation. - * @return atan(this) - */ - T atan(); - - /** Two arguments arc tangent operation. - * @param x second argument of the arc tangent - * @return atan2(this, x) - * @exception DimensionMismatchException if number of free parameters or orders are inconsistent - */ - T atan2(T x) - throws DimensionMismatchException; - - /** Hyperbolic cosine operation. - * @return cosh(this) - */ - T cosh(); - - /** Hyperbolic sine operation. - * @return sinh(this) - */ - T sinh(); - - /** Hyperbolic tangent operation. - * @return tanh(this) - */ - T tanh(); - - /** Inverse hyperbolic cosine operation. - * @return acosh(this) - */ - T acosh(); - - /** Inverse hyperbolic sine operation. - * @return asin(this) - */ - T asinh(); - - /** Inverse hyperbolic tangent operation. - * @return atanh(this) - */ - T atanh(); - - /** - * Compute a linear combination. - * @param a Factors. - * @param b Factors. - * @return Σi ai bi. - * @throws DimensionMismatchException if arrays dimensions don't match - * @since 3.2 - */ - T linearCombination(T[] a, T[] b) - throws DimensionMismatchException; - - /** - * Compute a linear combination. - * @param a Factors. - * @param b Factors. - * @return Σi ai bi. - * @throws DimensionMismatchException if arrays dimensions don't match - * @since 3.2 - */ - T linearCombination(double[] a, T[] b) - throws DimensionMismatchException; - - /** - * Compute a linear combination. - * @param a1 first factor of the first term - * @param b1 second factor of the first term - * @param a2 first factor of the second term - * @param b2 second factor of the second term - * @return a1×b1 + - * a2×b2 - * @see #linearCombination(Object, Object, Object, Object, Object, Object) - * @see #linearCombination(Object, Object, Object, Object, Object, Object, Object, Object) - * @since 3.2 - */ - T linearCombination(T a1, T b1, T a2, T b2); - - /** - * Compute a linear combination. - * @param a1 first factor of the first term - * @param b1 second factor of the first term - * @param a2 first factor of the second term - * @param b2 second factor of the second term - * @return a1×b1 + - * a2×b2 - * @see #linearCombination(double, Object, double, Object, double, Object) - * @see #linearCombination(double, Object, double, Object, double, Object, double, Object) - * @since 3.2 - */ - T linearCombination(double a1, T b1, double a2, T b2); - - /** - * Compute a linear combination. - * @param a1 first factor of the first term - * @param b1 second factor of the first term - * @param a2 first factor of the second term - * @param b2 second factor of the second term - * @param a3 first factor of the third term - * @param b3 second factor of the third term - * @return a1×b1 + - * a2×b2 + a3×b3 - * @see #linearCombination(Object, Object, Object, Object) - * @see #linearCombination(Object, Object, Object, Object, Object, Object, Object, Object) - * @since 3.2 - */ - T linearCombination(T a1, T b1, T a2, T b2, T a3, T b3); - - /** - * Compute a linear combination. - * @param a1 first factor of the first term - * @param b1 second factor of the first term - * @param a2 first factor of the second term - * @param b2 second factor of the second term - * @param a3 first factor of the third term - * @param b3 second factor of the third term - * @return a1×b1 + - * a2×b2 + a3×b3 - * @see #linearCombination(double, Object, double, Object) - * @see #linearCombination(double, Object, double, Object, double, Object, double, Object) - * @since 3.2 - */ - T linearCombination(double a1, T b1, double a2, T b2, double a3, T b3); - - /** - * Compute a linear combination. - * @param a1 first factor of the first term - * @param b1 second factor of the first term - * @param a2 first factor of the second term - * @param b2 second factor of the second term - * @param a3 first factor of the third term - * @param b3 second factor of the third term - * @param a4 first factor of the third term - * @param b4 second factor of the third term - * @return a1×b1 + - * a2×b2 + a3×b3 + - * a4×b4 - * @see #linearCombination(Object, Object, Object, Object) - * @see #linearCombination(Object, Object, Object, Object, Object, Object) - * @since 3.2 - */ - T linearCombination(T a1, T b1, T a2, T b2, T a3, T b3, T a4, T b4); - - /** - * Compute a linear combination. - * @param a1 first factor of the first term - * @param b1 second factor of the first term - * @param a2 first factor of the second term - * @param b2 second factor of the second term - * @param a3 first factor of the third term - * @param b3 second factor of the third term - * @param a4 first factor of the third term - * @param b4 second factor of the third term - * @return a1×b1 + - * a2×b2 + a3×b3 + - * a4×b4 - * @see #linearCombination(double, Object, double, Object) - * @see #linearCombination(double, Object, double, Object, double, Object) - * @since 3.2 - */ - T linearCombination(double a1, T b1, double a2, T b2, double a3, T b3, double a4, T b4); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/BivariateFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/BivariateFunction.java deleted file mode 100644 index 49ca2102a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/BivariateFunction.java +++ /dev/null @@ -1,35 +0,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. - */ - -package org.apache.commons.math4.analysis; - -/** - * An interface representing a bivariate real function. - * - * @since 2.1 - */ -public interface BivariateFunction { - /** - * Compute the value for the function. - * - * @param x Abscissa for which the function value should be computed. - * @param y Ordinate for which the function value should be computed. - * @return the value. - */ - double value(double x, double y); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/FunctionUtils.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/FunctionUtils.java deleted file mode 100644 index 6c5487937..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/FunctionUtils.java +++ /dev/null @@ -1,544 +0,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. - */ - -package org.apache.commons.math4.analysis; - -import org.apache.commons.numbers.arrays.LinearCombination; -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.MultivariateDifferentiableFunction; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.analysis.function.Identity; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Utilities for manipulating function objects. - * - * @since 3.0 - */ -public class FunctionUtils { - /** - * Class only contains static methods. - */ - private FunctionUtils() {} - - /** - * Composes functions. - *

- * The functions in the argument list are composed sequentially, in the - * given order. For example, compose(f1,f2,f3) acts like f1(f2(f3(x))).

- * - * @param f List of functions. - * @return the composite function. - */ - public static UnivariateFunction compose(final UnivariateFunction ... f) { - return new UnivariateFunction() { - /** {@inheritDoc} */ - @Override - public double value(double x) { - double r = x; - for (int i = f.length - 1; i >= 0; i--) { - r = f[i].value(r); - } - return r; - } - }; - } - - /** - * Composes functions. - *

- * The functions in the argument list are composed sequentially, in the - * given order. For example, compose(f1,f2,f3) acts like f1(f2(f3(x))).

- * - * @param f List of functions. - * @return the composite function. - * @since 3.1 - */ - public static UnivariateDifferentiableFunction compose(final UnivariateDifferentiableFunction ... f) { - return new UnivariateDifferentiableFunction() { - - /** {@inheritDoc} */ - @Override - public double value(final double t) { - double r = t; - for (int i = f.length - 1; i >= 0; i--) { - r = f[i].value(r); - } - return r; - } - - /** {@inheritDoc} */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - DerivativeStructure r = t; - for (int i = f.length - 1; i >= 0; i--) { - r = f[i].value(r); - } - return r; - } - - }; - } - - /** - * Adds functions. - * - * @param f List of functions. - * @return a function that computes the sum of the functions. - */ - public static UnivariateFunction add(final UnivariateFunction ... f) { - return new UnivariateFunction() { - /** {@inheritDoc} */ - @Override - public double value(double x) { - double r = f[0].value(x); - for (int i = 1; i < f.length; i++) { - r += f[i].value(x); - } - return r; - } - }; - } - - /** - * Adds functions. - * - * @param f List of functions. - * @return a function that computes the sum of the functions. - * @since 3.1 - */ - public static UnivariateDifferentiableFunction add(final UnivariateDifferentiableFunction ... f) { - return new UnivariateDifferentiableFunction() { - - /** {@inheritDoc} */ - @Override - public double value(final double t) { - double r = f[0].value(t); - for (int i = 1; i < f.length; i++) { - r += f[i].value(t); - } - return r; - } - - /** {@inheritDoc} - * @throws DimensionMismatchException if functions are not consistent with each other - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) - throws DimensionMismatchException { - DerivativeStructure r = f[0].value(t); - for (int i = 1; i < f.length; i++) { - r = r.add(f[i].value(t)); - } - return r; - } - - }; - } - - /** - * Multiplies functions. - * - * @param f List of functions. - * @return a function that computes the product of the functions. - */ - public static UnivariateFunction multiply(final UnivariateFunction ... f) { - return new UnivariateFunction() { - /** {@inheritDoc} */ - @Override - public double value(double x) { - double r = f[0].value(x); - for (int i = 1; i < f.length; i++) { - r *= f[i].value(x); - } - return r; - } - }; - } - - /** - * Multiplies functions. - * - * @param f List of functions. - * @return a function that computes the product of the functions. - * @since 3.1 - */ - public static UnivariateDifferentiableFunction multiply(final UnivariateDifferentiableFunction ... f) { - return new UnivariateDifferentiableFunction() { - - /** {@inheritDoc} */ - @Override - public double value(final double t) { - double r = f[0].value(t); - for (int i = 1; i < f.length; i++) { - r *= f[i].value(t); - } - return r; - } - - /** {@inheritDoc} */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - DerivativeStructure r = f[0].value(t); - for (int i = 1; i < f.length; i++) { - r = r.multiply(f[i].value(t)); - } - return r; - } - - }; - } - - /** - * Returns the univariate function - * {@code h(x) = combiner(f(x), g(x)).} - * - * @param combiner Combiner function. - * @param f Function. - * @param g Function. - * @return the composite function. - */ - public static UnivariateFunction combine(final BivariateFunction combiner, - final UnivariateFunction f, - final UnivariateFunction g) { - return new UnivariateFunction() { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return combiner.value(f.value(x), g.value(x)); - } - }; - } - - /** - * Returns a MultivariateFunction h(x[]) defined by
 
-     * h(x[]) = combiner(...combiner(combiner(initialValue,f(x[0])),f(x[1]))...),f(x[x.length-1]))
-     * 
- * - * @param combiner Combiner function. - * @param f Function. - * @param initialValue Initial value. - * @return a collector function. - */ - public static MultivariateFunction collector(final BivariateFunction combiner, - final UnivariateFunction f, - final double initialValue) { - return new MultivariateFunction() { - /** {@inheritDoc} */ - @Override - public double value(double[] point) { - double result = combiner.value(initialValue, f.value(point[0])); - for (int i = 1; i < point.length; i++) { - result = combiner.value(result, f.value(point[i])); - } - return result; - } - }; - } - - /** - * Returns a MultivariateFunction h(x[]) defined by
 
-     * h(x[]) = combiner(...combiner(combiner(initialValue,x[0]),x[1])...),x[x.length-1])
-     * 
- * - * @param combiner Combiner function. - * @param initialValue Initial value. - * @return a collector function. - */ - public static MultivariateFunction collector(final BivariateFunction combiner, - final double initialValue) { - return collector(combiner, new Identity(), initialValue); - } - - /** - * Creates a unary function by fixing the first argument of a binary function. - * - * @param f Binary function. - * @param fixed value to which the first argument of {@code f} is set. - * @return the unary function h(x) = f(fixed, x) - */ - public static UnivariateFunction fix1stArgument(final BivariateFunction f, - final double fixed) { - return new UnivariateFunction() { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return f.value(fixed, x); - } - }; - } - /** - * Creates a unary function by fixing the second argument of a binary function. - * - * @param f Binary function. - * @param fixed value to which the second argument of {@code f} is set. - * @return the unary function h(x) = f(x, fixed) - */ - public static UnivariateFunction fix2ndArgument(final BivariateFunction f, - final double fixed) { - return new UnivariateFunction() { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return f.value(x, fixed); - } - }; - } - - /** - * Samples the specified univariate real function on the specified interval. - *

- * The interval is divided equally into {@code n} sections and sample points - * are taken from {@code min} to {@code max - (max - min) / n}; therefore - * {@code f} is not sampled at the upper bound {@code max}.

- * - * @param f Function to be sampled - * @param min Lower bound of the interval (included). - * @param max Upper bound of the interval (excluded). - * @param n Number of sample points. - * @return the array of samples. - * @throws NumberIsTooLargeException if the lower bound {@code min} is - * greater than, or equal to the upper bound {@code max}. - * @throws NotStrictlyPositiveException if the number of sample points - * {@code n} is negative. - */ - public static double[] sample(UnivariateFunction f, double min, double max, int n) - throws NumberIsTooLargeException, NotStrictlyPositiveException { - - if (n <= 0) { - throw new NotStrictlyPositiveException( - LocalizedFormats.NOT_POSITIVE_NUMBER_OF_SAMPLES, - Integer.valueOf(n)); - } - if (min >= max) { - throw new NumberIsTooLargeException(min, max, false); - } - - final double[] s = new double[n]; - final double h = (max - min) / n; - for (int i = 0; i < n; i++) { - s[i] = f.value(min + i * h); - } - return s; - } - - /** Convert regular functions to {@link UnivariateDifferentiableFunction}. - *

- * This method handle the case with one free parameter and several derivatives. - * For the case with several free parameters and only first order derivatives, - * see {@link #toDifferentiable(MultivariateFunction, MultivariateVectorFunction)}. - * There are no direct support for intermediate cases, with several free parameters - * and order 2 or more derivatives, as is would be difficult to specify all the - * cross derivatives. - *

- *

- * Note that the derivatives are expected to be computed only with respect to the - * raw parameter x of the base function, i.e. they are df/dx, df2/dx2, ... - * Even if the built function is later used in a composition like f(sin(t)), the provided - * derivatives should not apply the composition with sine and its derivatives by - * themselves. The composition will be done automatically here and the result will properly - * contain f(sin(t)), df(sin(t))/dt, df2(sin(t))/dt2 despite the - * provided derivatives functions know nothing about the sine function. - *

- * @param f base function f(x) - * @param derivatives derivatives of the base function, in increasing differentiation order - * @return a differentiable function with value and all specified derivatives - * @see #toDifferentiable(MultivariateFunction, MultivariateVectorFunction) - * @see #derivative(UnivariateDifferentiableFunction, int) - */ - public static UnivariateDifferentiableFunction toDifferentiable(final UnivariateFunction f, - final UnivariateFunction ... derivatives) { - - return new UnivariateDifferentiableFunction() { - - /** {@inheritDoc} */ - @Override - public double value(final double x) { - return f.value(x); - } - - /** {@inheritDoc} */ - @Override - public DerivativeStructure value(final DerivativeStructure x) { - if (x.getOrder() > derivatives.length) { - throw new NumberIsTooLargeException(x.getOrder(), derivatives.length, true); - } - final double[] packed = new double[x.getOrder() + 1]; - packed[0] = f.value(x.getValue()); - for (int i = 0; i < x.getOrder(); ++i) { - packed[i + 1] = derivatives[i].value(x.getValue()); - } - return x.compose(packed); - } - - }; - - } - - /** Convert regular functions to {@link MultivariateDifferentiableFunction}. - *

- * This method handle the case with several free parameters and only first order derivatives. - * For the case with one free parameter and several derivatives, - * see {@link #toDifferentiable(UnivariateFunction, UnivariateFunction...)}. - * There are no direct support for intermediate cases, with several free parameters - * and order 2 or more derivatives, as is would be difficult to specify all the - * cross derivatives. - *

- *

- * Note that the gradient is expected to be computed only with respect to the - * raw parameter x of the base function, i.e. it is df/dx1, df/dx2, ... - * Even if the built function is later used in a composition like f(sin(t), cos(t)), the provided - * gradient should not apply the composition with sine or cosine and their derivative by - * itself. The composition will be done automatically here and the result will properly - * contain f(sin(t), cos(t)), df(sin(t), cos(t))/dt despite the provided derivatives functions - * know nothing about the sine or cosine functions. - *

- * @param f base function f(x) - * @param gradient gradient of the base function - * @return a differentiable function with value and gradient - * @see #toDifferentiable(UnivariateFunction, UnivariateFunction...) - * @see #derivative(MultivariateDifferentiableFunction, int[]) - */ - public static MultivariateDifferentiableFunction toDifferentiable(final MultivariateFunction f, - final MultivariateVectorFunction gradient) { - - return new MultivariateDifferentiableFunction() { - - /** {@inheritDoc} */ - @Override - public double value(final double[] point) { - return f.value(point); - } - - /** {@inheritDoc} */ - @Override - public DerivativeStructure value(final DerivativeStructure[] point) { - - // set up the input parameters - final double[] dPoint = new double[point.length]; - for (int i = 0; i < point.length; ++i) { - dPoint[i] = point[i].getValue(); - if (point[i].getOrder() > 1) { - throw new NumberIsTooLargeException(point[i].getOrder(), 1, true); - } - } - - // evaluate regular functions - final double v = f.value(dPoint); - final double[] dv = gradient.value(dPoint); - if (dv.length != point.length) { - // the gradient function is inconsistent - throw new DimensionMismatchException(dv.length, point.length); - } - - // build the combined derivative - final int parameters = point[0].getFreeParameters(); - final double[] partials = new double[point.length]; - final double[] packed = new double[parameters + 1]; - packed[0] = v; - final int orders[] = new int[parameters]; - for (int i = 0; i < parameters; ++i) { - - // we differentiate once with respect to parameter i - orders[i] = 1; - for (int j = 0; j < point.length; ++j) { - partials[j] = point[j].getPartialDerivative(orders); - } - orders[i] = 0; - - // compose partial derivatives - packed[i + 1] = LinearCombination.value(dv, partials); - - } - - return new DerivativeStructure(parameters, 1, packed); - - } - - }; - - } - - /** Convert an {@link UnivariateDifferentiableFunction} to an - * {@link UnivariateFunction} computing nth order derivative. - *

- * This converter is only a convenience method. Beware computing only one derivative does - * not save any computation as the original function will really be called under the hood. - * The derivative will be extracted from the full {@link DerivativeStructure} result. - *

- * @param f original function, with value and all its derivatives - * @param order of the derivative to extract - * @return function computing the derivative at required order - * @see #derivative(MultivariateDifferentiableFunction, int[]) - * @see #toDifferentiable(UnivariateFunction, UnivariateFunction...) - */ - public static UnivariateFunction derivative(final UnivariateDifferentiableFunction f, final int order) { - return new UnivariateFunction() { - - /** {@inheritDoc} */ - @Override - public double value(final double x) { - final DerivativeStructure dsX = new DerivativeStructure(1, order, 0, x); - return f.value(dsX).getPartialDerivative(order); - } - - }; - } - - /** Convert an {@link MultivariateDifferentiableFunction} to an - * {@link MultivariateFunction} computing nth order derivative. - *

- * This converter is only a convenience method. Beware computing only one derivative does - * not save any computation as the original function will really be called under the hood. - * The derivative will be extracted from the full {@link DerivativeStructure} result. - *

- * @param f original function, with value and all its derivatives - * @param orders of the derivative to extract, for each free parameters - * @return function computing the derivative at required order - * @see #derivative(UnivariateDifferentiableFunction, int) - * @see #toDifferentiable(MultivariateFunction, MultivariateVectorFunction) - */ - public static MultivariateFunction derivative(final MultivariateDifferentiableFunction f, final int[] orders) { - return new MultivariateFunction() { - - /** {@inheritDoc} */ - @Override - public double value(final double[] point) { - - // the maximum differentiation order is the sum of all orders - int sumOrders = 0; - for (final int order : orders) { - sumOrders += order; - } - - // set up the input parameters - final DerivativeStructure[] dsPoint = new DerivativeStructure[point.length]; - for (int i = 0; i < point.length; ++i) { - dsPoint[i] = new DerivativeStructure(point.length, sumOrders, i, point[i]); - } - - return f.value(dsPoint).getPartialDerivative(orders); - - } - - }; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/MultivariateFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/MultivariateFunction.java deleted file mode 100644 index e694cdc9a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/MultivariateFunction.java +++ /dev/null @@ -1,42 +0,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. - */ - -package org.apache.commons.math4.analysis; - -/** - * An interface representing a multivariate real function. - * - * @since 2.0 - */ -public interface MultivariateFunction { - - /** - * Compute the value for the function at the given point. - * - * @param point Point at which the function must be evaluated. - * @return the function value for the given point. - * @throws org.apache.commons.math4.exception.DimensionMismatchException - * if the parameter's dimension is wrong for the function being evaluated. - * @throws org.apache.commons.math4.exception.MathIllegalArgumentException - * when the activated method itself can ascertain that preconditions, - * specified in the API expressed at the level of the activated method, - * have been violated. In the vast majority of cases where Commons Math - * throws this exception, it is the result of argument checking of actual - * parameters immediately passed to a method. - */ - double value(double[] point); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/MultivariateMatrixFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/MultivariateMatrixFunction.java deleted file mode 100644 index 1f136d7a0..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/MultivariateMatrixFunction.java +++ /dev/null @@ -1,35 +0,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. - */ - -package org.apache.commons.math4.analysis; - -/** - * An interface representing a multivariate matrix function. - * @since 2.0 - */ -public interface MultivariateMatrixFunction { - - /** - * Compute the value for the function at the given point. - * @param point point at which the function must be evaluated - * @return function value for the given point - * @exception IllegalArgumentException if point's dimension is wrong - */ - double[][] value(double[] point) - throws IllegalArgumentException; - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/MultivariateVectorFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/MultivariateVectorFunction.java deleted file mode 100644 index 14d62daab..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/MultivariateVectorFunction.java +++ /dev/null @@ -1,35 +0,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. - */ - -package org.apache.commons.math4.analysis; - -/** - * An interface representing a multivariate vectorial function. - * @since 2.0 - */ -public interface MultivariateVectorFunction { - - /** - * Compute the value for the function at the given point. - * @param point point at which the function must be evaluated - * @return function value for the given point - * @exception IllegalArgumentException if point's dimension is wrong - */ - double[] value(double[] point) - throws IllegalArgumentException; - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/ParametricUnivariateFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/ParametricUnivariateFunction.java deleted file mode 100644 index e44d72c88..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/ParametricUnivariateFunction.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis; - -/** - * An interface representing a real function that depends on one independent - * variable plus some extra parameters. - * - * @since 3.0 - */ -public interface ParametricUnivariateFunction { - /** - * Compute the value of the function. - * - * @param x Point for which the function value should be computed. - * @param parameters Function parameters. - * @return the value. - */ - double value(double x, double... parameters); - - /** - * Compute the gradient of the function with respect to its parameters. - * - * @param x Point for which the function value should be computed. - * @param parameters Function parameters. - * @return the value. - */ - double[] gradient(double x, double... parameters); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/RealFieldUnivariateFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/RealFieldUnivariateFunction.java deleted file mode 100644 index e34174c03..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/RealFieldUnivariateFunction.java +++ /dev/null @@ -1,86 +0,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. - */ -package org.apache.commons.math4.analysis; - -import org.apache.commons.math4.RealFieldElement; - -/** - * An interface representing a univariate real function. - *

- * When a user-defined function encounters an error during - * evaluation, the {@link #value(RealFieldElement) value} method should throw a - * user-defined unchecked exception.

- *

- * The following code excerpt shows the recommended way to do that using - * a root solver as an example, but the same construct is applicable to - * ODE integrators or optimizers. - * - *

- * private static class LocalException extends RuntimeException {
- *     // The x value that caused the problem.
- *     private final SomeFieldType x;
- *
- *     public LocalException(SomeFieldType x) {
- *         this.x = x;
- *     }
- *
- *     public double getX() {
- *         return x;
- *     }
- * }
- *
- * private static class MyFunction implements FieldUnivariateFunction<SomeFieldType> {
- *     public SomeFieldType value(SomeFieldType x) {
- *         SomeFieldType y = hugeFormula(x);
- *         if (somethingBadHappens) {
- *           throw new LocalException(x);
- *         }
- *         return y;
- *     }
- * }
- *
- * public void compute() {
- *     try {
- *         solver.solve(maxEval, new MyFunction(a, b, c), min, max);
- *     } catch (LocalException le) {
- *         // Retrieve the x value.
- *     }
- * }
- * 
- *

- * As shown, the exception is local to the user's code and it is guaranteed - * that Apache Commons Math will not catch it.

- * - * @param the type of the field elements - * @since 3.6 - * @see UnivariateFunction - */ -public interface RealFieldUnivariateFunction> { - /** - * Compute the value of the function. - * - * @param x Point at which the function value should be computed. - * @return the value of the function. - * @throws IllegalArgumentException when the activated method itself can - * ascertain that a precondition, specified in the API expressed at the - * level of the activated method, has been violated. - * When Commons Math throws an {@code IllegalArgumentException}, it is - * usually the consequence of checking the actual parameters passed to - * the method. - */ - T value(T x); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/TrivariateFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/TrivariateFunction.java deleted file mode 100644 index b3934a548..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/TrivariateFunction.java +++ /dev/null @@ -1,35 +0,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. - */ - -package org.apache.commons.math4.analysis; - -/** - * An interface representing a trivariate real function. - * - * @since 2.2 - */ -public interface TrivariateFunction { - /** - * Compute the value for the function. - * - * @param x x-coordinate for which the function value should be computed. - * @param y y-coordinate for which the function value should be computed. - * @param z z-coordinate for which the function value should be computed. - * @return the value. - */ - double value(double x, double y, double z); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/UnivariateFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/UnivariateFunction.java deleted file mode 100644 index cf96a29a3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/UnivariateFunction.java +++ /dev/null @@ -1,81 +0,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. - */ -package org.apache.commons.math4.analysis; - -/** - * An interface representing a univariate real function. - *

- * When a user-defined function encounters an error during - * evaluation, the {@link #value(double) value} method should throw a - * user-defined unchecked exception.

- *

- * The following code excerpt shows the recommended way to do that using - * a root solver as an example, but the same construct is applicable to - * ODE integrators or optimizers.

- * - *
- * private static class LocalException extends RuntimeException {
- *     // The x value that caused the problem.
- *     private final double x;
- *
- *     public LocalException(double x) {
- *         this.x = x;
- *     }
- *
- *     public double getX() {
- *         return x;
- *     }
- * }
- *
- * private static class MyFunction implements UnivariateFunction {
- *     public double value(double x) {
- *         double y = hugeFormula(x);
- *         if (somethingBadHappens) {
- *           throw new LocalException(x);
- *         }
- *         return y;
- *     }
- * }
- *
- * public void compute() {
- *     try {
- *         solver.solve(maxEval, new MyFunction(a, b, c), min, max);
- *     } catch (LocalException le) {
- *         // Retrieve the x value.
- *     }
- * }
- * 
- * - * As shown, the exception is local to the user's code and it is guaranteed - * that Apache Commons Math will not catch it. - * - */ -public interface UnivariateFunction { - /** - * Compute the value of the function. - * - * @param x Point at which the function value should be computed. - * @return the value of the function. - * @throws IllegalArgumentException when the activated method itself can - * ascertain that a precondition, specified in the API expressed at the - * level of the activated method, has been violated. - * When Commons Math throws an {@code IllegalArgumentException}, it is - * usually the consequence of checking the actual parameters passed to - * the method. - */ - double value(double x); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/UnivariateMatrixFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/UnivariateMatrixFunction.java deleted file mode 100644 index a364cb70c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/UnivariateMatrixFunction.java +++ /dev/null @@ -1,33 +0,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. - */ -package org.apache.commons.math4.analysis; - -/** - * An interface representing a univariate matrix function. - * - * @since 2.0 - */ -public interface UnivariateMatrixFunction { - - /** - * Compute the value for the function. - * @param x the point for which the function value should be computed - * @return the value - */ - double[][] value(double x); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/UnivariateVectorFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/UnivariateVectorFunction.java deleted file mode 100644 index c836ecb28..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/UnivariateVectorFunction.java +++ /dev/null @@ -1,33 +0,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. - */ -package org.apache.commons.math4.analysis; - -/** - * An interface representing a univariate vectorial function. - * - * @since 2.0 - */ -public interface UnivariateVectorFunction { - - /** - * Compute the value for the function. - * @param x the point for which the function value should be computed - * @return the value - */ - double[] value(double x); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/DSCompiler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/DSCompiler.java deleted file mode 100644 index 03898ac82..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/DSCompiler.java +++ /dev/null @@ -1,1834 +0,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. - */ -package org.apache.commons.math4.analysis.differentiation; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; - -import org.apache.commons.numbers.arrays.LinearCombination; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.MathInternalError; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.numbers.combinatorics.FactorialDouble; -import org.apache.commons.math4.util.FastMath; - -/** Class holding "compiled" computation rules for derivative structures. - *

This class implements the computation rules described in Dan Kalman's paper Doubly - * Recursive Multivariate Automatic Differentiation, Mathematics Magazine, vol. 75, - * no. 3, June 2002. However, in order to avoid performances bottlenecks, the recursive - * rules are "compiled" once in an unfold form. This class does this recursion unrolling - * and stores the computation rules as simple loops with pre-computed indirection arrays.

- *

- * This class maps all derivative computation into single dimension arrays that hold the - * value and partial derivatives. The class does not hold these arrays, which remains under - * the responsibility of the caller. For each combination of number of free parameters and - * derivation order, only one compiler is necessary, and this compiler will be used to - * perform computations on all arrays provided to it, which can represent hundreds or - * thousands of different parameters kept together with all their partial derivatives. - *

- *

- * The arrays on which compilers operate contain only the partial derivatives together - * with the 0th derivative, i.e. the value. The partial derivatives are stored in - * a compiler-specific order, which can be retrieved using methods {@link - * #getPartialDerivativeIndex(int...) getPartialDerivativeIndex} and {@link - * #getPartialDerivativeOrders(int)}. The value is guaranteed to be stored as the first element - * (i.e. the {@link #getPartialDerivativeIndex(int...) getPartialDerivativeIndex} method returns - * 0 when called with 0 for all derivation orders and {@link #getPartialDerivativeOrders(int) - * getPartialDerivativeOrders} returns an array filled with 0 when called with 0 as the index). - *

- *

- * Note that the ordering changes with number of parameters and derivation order. For example - * given 2 parameters x and y, df/dy is stored at index 2 when derivation order is set to 1 (in - * this case the array has three elements: f, df/dx and df/dy). If derivation order is set to - * 2, then df/dy will be stored at index 3 (in this case the array has six elements: f, df/dx, - * df/dxdx, df/dy, df/dxdy and df/dydy). - *

- *

- * Given this structure, users can perform some simple operations like adding, subtracting - * or multiplying constants and negating the elements by themselves, knowing if they want to - * mutate their array or create a new array. These simple operations are not provided by - * the compiler. The compiler provides only the more complex operations between several arrays. - *

- *

This class is mainly used as the engine for scalar variable {@link DerivativeStructure}. - * It can also be used directly to hold several variables in arrays for more complex data - * structures. User can for example store a vector of n variables depending on three x, y - * and z free parameters in one array as follows:

- *   // parameter 0 is x, parameter 1 is y, parameter 2 is z
- *   int parameters = 3;
- *   DSCompiler compiler = DSCompiler.getCompiler(parameters, order);
- *   int size = compiler.getSize();
- *
- *   // pack all elements in a single array
- *   double[] array = new double[n * size];
- *   for (int i = 0; i < n; ++i) {
- *
- *     // we know value is guaranteed to be the first element
- *     array[i * size] = v[i];
- *
- *     // we don't know where first derivatives are stored, so we ask the compiler
- *     array[i * size + compiler.getPartialDerivativeIndex(1, 0, 0) = dvOnDx[i][0];
- *     array[i * size + compiler.getPartialDerivativeIndex(0, 1, 0) = dvOnDy[i][0];
- *     array[i * size + compiler.getPartialDerivativeIndex(0, 0, 1) = dvOnDz[i][0];
- *
- *     // we let all higher order derivatives set to 0
- *
- *   }
- * 
- *

Then in another function, user can perform some operations on all elements stored - * in the single array, such as a simple product of all variables:

- *   // compute the product of all elements
- *   double[] product = new double[size];
- *   prod[0] = 1.0;
- *   for (int i = 0; i < n; ++i) {
- *     double[] tmp = product.clone();
- *     compiler.multiply(tmp, 0, array, i * size, product, 0);
- *   }
- *
- *   // value
- *   double p = product[0];
- *
- *   // first derivatives
- *   double dPdX = product[compiler.getPartialDerivativeIndex(1, 0, 0)];
- *   double dPdY = product[compiler.getPartialDerivativeIndex(0, 1, 0)];
- *   double dPdZ = product[compiler.getPartialDerivativeIndex(0, 0, 1)];
- *
- *   // cross derivatives (assuming order was at least 2)
- *   double dPdXdX = product[compiler.getPartialDerivativeIndex(2, 0, 0)];
- *   double dPdXdY = product[compiler.getPartialDerivativeIndex(1, 1, 0)];
- *   double dPdXdZ = product[compiler.getPartialDerivativeIndex(1, 0, 1)];
- *   double dPdYdY = product[compiler.getPartialDerivativeIndex(0, 2, 0)];
- *   double dPdYdZ = product[compiler.getPartialDerivativeIndex(0, 1, 1)];
- *   double dPdZdZ = product[compiler.getPartialDerivativeIndex(0, 0, 2)];
- * 
- * @see DerivativeStructure - * @since 3.1 - */ -public class DSCompiler { - /** Cache for factorials. */ - private static FactorialDouble FACTORIAL = FactorialDouble.create().withCache(30); - - /** Array of all compilers created so far. */ - private static AtomicReference compilers = - new AtomicReference<>(null); - - /** Number of free parameters. */ - private final int parameters; - - /** Derivation order. */ - private final int order; - - /** Number of partial derivatives (including the single 0 order derivative element). */ - private final int[][] sizes; - - /** Indirection array for partial derivatives. */ - private final int[][] derivativesIndirection; - - /** Indirection array of the lower derivative elements. */ - private final int[] lowerIndirection; - - /** Indirection arrays for multiplication. */ - private final int[][][] multIndirection; - - /** Indirection arrays for function composition. */ - private final int[][][] compIndirection; - - /** Private constructor, reserved for the factory method {@link #getCompiler(int, int)}. - * @param parameters number of free parameters - * @param order derivation order - * @param valueCompiler compiler for the value part - * @param derivativeCompiler compiler for the derivative part - * @throws NumberIsTooLargeException if order is too large - */ - private DSCompiler(final int parameters, final int order, - final DSCompiler valueCompiler, final DSCompiler derivativeCompiler) - throws NumberIsTooLargeException { - - this.parameters = parameters; - this.order = order; - this.sizes = compileSizes(parameters, order, valueCompiler); - this.derivativesIndirection = - compileDerivativesIndirection(parameters, order, - valueCompiler, derivativeCompiler); - this.lowerIndirection = - compileLowerIndirection(parameters, order, - valueCompiler, derivativeCompiler); - this.multIndirection = - compileMultiplicationIndirection(parameters, order, - valueCompiler, derivativeCompiler, lowerIndirection); - this.compIndirection = - compileCompositionIndirection(parameters, order, - valueCompiler, derivativeCompiler, - sizes, derivativesIndirection); - - } - - /** Get the compiler for number of free parameters and order. - * @param parameters number of free parameters - * @param order derivation order - * @return cached rules set - * @throws NumberIsTooLargeException if order is too large - */ - public static DSCompiler getCompiler(int parameters, int order) - throws NumberIsTooLargeException { - - // get the cached compilers - final DSCompiler[][] cache = compilers.get(); - if (cache != null && cache.length > parameters && - cache[parameters].length > order && cache[parameters][order] != null) { - // the compiler has already been created - return cache[parameters][order]; - } - - // we need to create more compilers - final int maxParameters = FastMath.max(parameters, cache == null ? 0 : cache.length); - final int maxOrder = FastMath.max(order, cache == null ? 0 : cache[0].length); - final DSCompiler[][] newCache = new DSCompiler[maxParameters + 1][maxOrder + 1]; - - if (cache != null) { - // preserve the already created compilers - for (int i = 0; i < cache.length; ++i) { - System.arraycopy(cache[i], 0, newCache[i], 0, cache[i].length); - } - } - - // create the array in increasing diagonal order - for (int diag = 0; diag <= parameters + order; ++diag) { - for (int o = FastMath.max(0, diag - parameters); o <= FastMath.min(order, diag); ++o) { - final int p = diag - o; - if (newCache[p][o] == null) { - final DSCompiler valueCompiler = (p == 0) ? null : newCache[p - 1][o]; - final DSCompiler derivativeCompiler = (o == 0) ? null : newCache[p][o - 1]; - newCache[p][o] = new DSCompiler(p, o, valueCompiler, derivativeCompiler); - } - } - } - - // atomically reset the cached compilers array - compilers.compareAndSet(cache, newCache); - - return newCache[parameters][order]; - - } - - /** Compile the sizes array. - * @param parameters number of free parameters - * @param order derivation order - * @param valueCompiler compiler for the value part - * @return sizes array - */ - private static int[][] compileSizes(final int parameters, final int order, - final DSCompiler valueCompiler) { - - final int[][] sizes = new int[parameters + 1][order + 1]; - if (parameters == 0) { - Arrays.fill(sizes[0], 1); - } else { - System.arraycopy(valueCompiler.sizes, 0, sizes, 0, parameters); - sizes[parameters][0] = 1; - for (int i = 0; i < order; ++i) { - sizes[parameters][i + 1] = sizes[parameters][i] + sizes[parameters - 1][i + 1]; - } - } - - return sizes; - - } - - /** Compile the derivatives indirection array. - * @param parameters number of free parameters - * @param order derivation order - * @param valueCompiler compiler for the value part - * @param derivativeCompiler compiler for the derivative part - * @return derivatives indirection array - */ - private static int[][] compileDerivativesIndirection(final int parameters, final int order, - final DSCompiler valueCompiler, - final DSCompiler derivativeCompiler) { - - if (parameters == 0 || order == 0) { - return new int[1][parameters]; - } - - final int vSize = valueCompiler.derivativesIndirection.length; - final int dSize = derivativeCompiler.derivativesIndirection.length; - final int[][] derivativesIndirection = new int[vSize + dSize][parameters]; - - // set up the indices for the value part - for (int i = 0; i < vSize; ++i) { - // copy the first indices, the last one remaining set to 0 - System.arraycopy(valueCompiler.derivativesIndirection[i], 0, - derivativesIndirection[i], 0, - parameters - 1); - } - - // set up the indices for the derivative part - for (int i = 0; i < dSize; ++i) { - - // copy the indices - System.arraycopy(derivativeCompiler.derivativesIndirection[i], 0, - derivativesIndirection[vSize + i], 0, - parameters); - - // increment the derivation order for the last parameter - derivativesIndirection[vSize + i][parameters - 1]++; - - } - - return derivativesIndirection; - - } - - /** Compile the lower derivatives indirection array. - *

- * This indirection array contains the indices of all elements - * except derivatives for last derivation order. - *

- * @param parameters number of free parameters - * @param order derivation order - * @param valueCompiler compiler for the value part - * @param derivativeCompiler compiler for the derivative part - * @return lower derivatives indirection array - */ - private static int[] compileLowerIndirection(final int parameters, final int order, - final DSCompiler valueCompiler, - final DSCompiler derivativeCompiler) { - - if (parameters == 0 || order <= 1) { - return new int[] { 0 }; - } - - // this is an implementation of definition 6 in Dan Kalman's paper. - final int vSize = valueCompiler.lowerIndirection.length; - final int dSize = derivativeCompiler.lowerIndirection.length; - final int[] lowerIndirection = new int[vSize + dSize]; - System.arraycopy(valueCompiler.lowerIndirection, 0, lowerIndirection, 0, vSize); - for (int i = 0; i < dSize; ++i) { - lowerIndirection[vSize + i] = valueCompiler.getSize() + derivativeCompiler.lowerIndirection[i]; - } - - return lowerIndirection; - - } - - /** Compile the multiplication indirection array. - *

- * This indirection array contains the indices of all pairs of elements - * involved when computing a multiplication. This allows a straightforward - * loop-based multiplication (see {@link #multiply(double[], int, double[], int, double[], int)}). - *

- * @param parameters number of free parameters - * @param order derivation order - * @param valueCompiler compiler for the value part - * @param derivativeCompiler compiler for the derivative part - * @param lowerIndirection lower derivatives indirection array - * @return multiplication indirection array - */ - private static int[][][] compileMultiplicationIndirection(final int parameters, final int order, - final DSCompiler valueCompiler, - final DSCompiler derivativeCompiler, - final int[] lowerIndirection) { - - if ((parameters == 0) || (order == 0)) { - return new int[][][] { { { 1, 0, 0 } } }; - } - - // this is an implementation of definition 3 in Dan Kalman's paper. - final int vSize = valueCompiler.multIndirection.length; - final int dSize = derivativeCompiler.multIndirection.length; - final int[][][] multIndirection = new int[vSize + dSize][][]; - - System.arraycopy(valueCompiler.multIndirection, 0, multIndirection, 0, vSize); - - for (int i = 0; i < dSize; ++i) { - final int[][] dRow = derivativeCompiler.multIndirection[i]; - List row = new ArrayList<>(dRow.length * 2); - for (int j = 0; j < dRow.length; ++j) { - row.add(new int[] { dRow[j][0], lowerIndirection[dRow[j][1]], vSize + dRow[j][2] }); - row.add(new int[] { dRow[j][0], vSize + dRow[j][1], lowerIndirection[dRow[j][2]] }); - } - - // combine terms with similar derivation orders - final List combined = new ArrayList<>(row.size()); - for (int j = 0; j < row.size(); ++j) { - final int[] termJ = row.get(j); - if (termJ[0] > 0) { - for (int k = j + 1; k < row.size(); ++k) { - final int[] termK = row.get(k); - if (termJ[1] == termK[1] && termJ[2] == termK[2]) { - // combine termJ and termK - termJ[0] += termK[0]; - // make sure we will skip termK later on in the outer loop - termK[0] = 0; - } - } - combined.add(termJ); - } - } - - multIndirection[vSize + i] = combined.toArray(new int[combined.size()][]); - - } - - return multIndirection; - - } - - /** Compile the function composition indirection array. - *

- * This indirection array contains the indices of all sets of elements - * involved when computing a composition. This allows a straightforward - * loop-based composition (see {@link #compose(double[], int, double[], double[], int)}). - *

- * @param parameters number of free parameters - * @param order derivation order - * @param valueCompiler compiler for the value part - * @param derivativeCompiler compiler for the derivative part - * @param sizes sizes array - * @param derivativesIndirection derivatives indirection array - * @return multiplication indirection array - * @throws NumberIsTooLargeException if order is too large - */ - private static int[][][] compileCompositionIndirection(final int parameters, final int order, - final DSCompiler valueCompiler, - final DSCompiler derivativeCompiler, - final int[][] sizes, - final int[][] derivativesIndirection) - throws NumberIsTooLargeException { - - if ((parameters == 0) || (order == 0)) { - return new int[][][] { { { 1, 0 } } }; - } - - final int vSize = valueCompiler.compIndirection.length; - final int dSize = derivativeCompiler.compIndirection.length; - final int[][][] compIndirection = new int[vSize + dSize][][]; - - // the composition rules from the value part can be reused as is - System.arraycopy(valueCompiler.compIndirection, 0, compIndirection, 0, vSize); - - // the composition rules for the derivative part are deduced by - // differentiation the rules from the underlying compiler once - // with respect to the parameter this compiler handles and the - // underlying one did not handle - for (int i = 0; i < dSize; ++i) { - List row = new ArrayList<>(); - for (int[] term : derivativeCompiler.compIndirection[i]) { - - // handle term p * f_k(g(x)) * g_l1(x) * g_l2(x) * ... * g_lp(x) - - // derive the first factor in the term: f_k with respect to new parameter - int[] derivedTermF = new int[term.length + 1]; - derivedTermF[0] = term[0]; // p - derivedTermF[1] = term[1] + 1; // f_(k+1) - int[] orders = new int[parameters]; - orders[parameters - 1] = 1; - derivedTermF[term.length] = getPartialDerivativeIndex(parameters, order, sizes, orders); // g_1 - for (int j = 2; j < term.length; ++j) { - // convert the indices as the mapping for the current order - // is different from the mapping with one less order - derivedTermF[j] = convertIndex(term[j], parameters, - derivativeCompiler.derivativesIndirection, - parameters, order, sizes); - } - Arrays.sort(derivedTermF, 2, derivedTermF.length); - row.add(derivedTermF); - - // derive the various g_l - for (int l = 2; l < term.length; ++l) { - int[] derivedTermG = new int[term.length]; - derivedTermG[0] = term[0]; - derivedTermG[1] = term[1]; - for (int j = 2; j < term.length; ++j) { - // convert the indices as the mapping for the current order - // is different from the mapping with one less order - derivedTermG[j] = convertIndex(term[j], parameters, - derivativeCompiler.derivativesIndirection, - parameters, order, sizes); - if (j == l) { - // derive this term - System.arraycopy(derivativesIndirection[derivedTermG[j]], 0, orders, 0, parameters); - orders[parameters - 1]++; - derivedTermG[j] = getPartialDerivativeIndex(parameters, order, sizes, orders); - } - } - Arrays.sort(derivedTermG, 2, derivedTermG.length); - row.add(derivedTermG); - } - - } - - // combine terms with similar derivation orders - final List combined = new ArrayList<>(row.size()); - for (int j = 0; j < row.size(); ++j) { - final int[] termJ = row.get(j); - if (termJ[0] > 0) { - for (int k = j + 1; k < row.size(); ++k) { - final int[] termK = row.get(k); - boolean equals = termJ.length == termK.length; - for (int l = 1; equals && l < termJ.length; ++l) { - equals &= termJ[l] == termK[l]; - } - if (equals) { - // combine termJ and termK - termJ[0] += termK[0]; - // make sure we will skip termK later on in the outer loop - termK[0] = 0; - } - } - combined.add(termJ); - } - } - - compIndirection[vSize + i] = combined.toArray(new int[combined.size()][]); - - } - - return compIndirection; - - } - - /** Get the index of a partial derivative in the array. - *

- * If all orders are set to 0, then the 0th order derivative - * is returned, which is the value of the function. - *

- *

The indices of derivatives are between 0 and {@link #getSize() getSize()} - 1. - * Their specific order is fixed for a given compiler, but otherwise not - * publicly specified. There are however some simple cases which have guaranteed - * indices: - *

- *
    - *
  • the index of 0th order derivative is always 0
  • - *
  • if there is only 1 {@link #getFreeParameters() free parameter}, then the - * derivatives are sorted in increasing derivation order (i.e. f at index 0, df/dp - * at index 1, d2f/dp2 at index 2 ... - * dkf/dpk at index k),
  • - *
  • if the {@link #getOrder() derivation order} is 1, then the derivatives - * are sorted in increasing free parameter order (i.e. f at index 0, df/dx1 - * at index 1, df/dx2 at index 2 ... df/dxk at index k),
  • - *
  • all other cases are not publicly specified
  • - *
- *

- * This method is the inverse of method {@link #getPartialDerivativeOrders(int)} - *

- * @param orders derivation orders with respect to each parameter - * @return index of the partial derivative - * @exception DimensionMismatchException if the numbers of parameters does not - * match the instance - * @exception NumberIsTooLargeException if sum of derivation orders is larger - * than the instance limits - * @see #getPartialDerivativeOrders(int) - */ - public int getPartialDerivativeIndex(final int ... orders) - throws DimensionMismatchException, NumberIsTooLargeException { - - // safety check - if (orders.length != getFreeParameters()) { - throw new DimensionMismatchException(orders.length, getFreeParameters()); - } - - return getPartialDerivativeIndex(parameters, order, sizes, orders); - - } - - /** Get the index of a partial derivative in an array. - * @param parameters number of free parameters - * @param order derivation order - * @param sizes sizes array - * @param orders derivation orders with respect to each parameter - * (the length of this array must match the number of parameters) - * @return index of the partial derivative - * @exception NumberIsTooLargeException if sum of derivation orders is larger - * than the instance limits - */ - private static int getPartialDerivativeIndex(final int parameters, final int order, - final int[][] sizes, final int ... orders) - throws NumberIsTooLargeException { - - // the value is obtained by diving into the recursive Dan Kalman's structure - // this is theorem 2 of his paper, with recursion replaced by iteration - int index = 0; - int m = order; - int ordersSum = 0; - for (int i = parameters - 1; i >= 0; --i) { - - // derivative order for current free parameter - int derivativeOrder = orders[i]; - - // safety check - ordersSum += derivativeOrder; - if (ordersSum > order) { - throw new NumberIsTooLargeException(ordersSum, order, true); - } - - while (derivativeOrder-- > 0) { - // as long as we differentiate according to current free parameter, - // we have to skip the value part and dive into the derivative part - // so we add the size of the value part to the base index - index += sizes[i][m--]; - } - - } - - return index; - - } - - /** Convert an index from one (parameters, order) structure to another. - * @param index index of a partial derivative in source derivative structure - * @param srcP number of free parameters in source derivative structure - * @param srcDerivativesIndirection derivatives indirection array for the source - * derivative structure - * @param destP number of free parameters in destination derivative structure - * @param destO derivation order in destination derivative structure - * @param destSizes sizes array for the destination derivative structure - * @return index of the partial derivative with the same characteristics - * in destination derivative structure - * @throws NumberIsTooLargeException if order is too large - */ - private static int convertIndex(final int index, - final int srcP, final int[][] srcDerivativesIndirection, - final int destP, final int destO, final int[][] destSizes) - throws NumberIsTooLargeException { - int[] orders = new int[destP]; - System.arraycopy(srcDerivativesIndirection[index], 0, orders, 0, FastMath.min(srcP, destP)); - return getPartialDerivativeIndex(destP, destO, destSizes, orders); - } - - /** Get the derivation orders for a specific index in the array. - *

- * This method is the inverse of {@link #getPartialDerivativeIndex(int...)}. - *

- * @param index of the partial derivative - * @return orders derivation orders with respect to each parameter - * @see #getPartialDerivativeIndex(int...) - */ - public int[] getPartialDerivativeOrders(final int index) { - return derivativesIndirection[index]; - } - - /** Get the number of free parameters. - * @return number of free parameters - */ - public int getFreeParameters() { - return parameters; - } - - /** Get the derivation order. - * @return derivation order - */ - public int getOrder() { - return order; - } - - /** Get the array size required for holding partial derivatives data. - *

- * This number includes the single 0 order derivative element, which is - * guaranteed to be stored in the first element of the array. - *

- * @return array size required for holding partial derivatives data - */ - public int getSize() { - return sizes[parameters][order]; - } - - /** Compute linear combination. - * The derivative structure built will be a1 * ds1 + a2 * ds2 - * @param a1 first scale factor - * @param c1 first base (unscaled) component - * @param offset1 offset of first operand in its array - * @param a2 second scale factor - * @param c2 second base (unscaled) component - * @param offset2 offset of second operand in its array - * @param result array where result must be stored (it may be - * one of the input arrays) - * @param resultOffset offset of the result in its array - */ - public void linearCombination(final double a1, final double[] c1, final int offset1, - final double a2, final double[] c2, final int offset2, - final double[] result, final int resultOffset) { - for (int i = 0; i < getSize(); ++i) { - result[resultOffset + i] = - LinearCombination.value(a1, c1[offset1 + i], a2, c2[offset2 + i]); - } - } - - /** Compute linear combination. - * The derivative structure built will be a1 * ds1 + a2 * ds2 + a3 * ds3 + a4 * ds4 - * @param a1 first scale factor - * @param c1 first base (unscaled) component - * @param offset1 offset of first operand in its array - * @param a2 second scale factor - * @param c2 second base (unscaled) component - * @param offset2 offset of second operand in its array - * @param a3 third scale factor - * @param c3 third base (unscaled) component - * @param offset3 offset of third operand in its array - * @param result array where result must be stored (it may be - * one of the input arrays) - * @param resultOffset offset of the result in its array - */ - public void linearCombination(final double a1, final double[] c1, final int offset1, - final double a2, final double[] c2, final int offset2, - final double a3, final double[] c3, final int offset3, - final double[] result, final int resultOffset) { - for (int i = 0; i < getSize(); ++i) { - result[resultOffset + i] = - LinearCombination.value(a1, c1[offset1 + i], - a2, c2[offset2 + i], - a3, c3[offset3 + i]); - } - } - - /** Compute linear combination. - * The derivative structure built will be a1 * ds1 + a2 * ds2 + a3 * ds3 + a4 * ds4 - * @param a1 first scale factor - * @param c1 first base (unscaled) component - * @param offset1 offset of first operand in its array - * @param a2 second scale factor - * @param c2 second base (unscaled) component - * @param offset2 offset of second operand in its array - * @param a3 third scale factor - * @param c3 third base (unscaled) component - * @param offset3 offset of third operand in its array - * @param a4 fourth scale factor - * @param c4 fourth base (unscaled) component - * @param offset4 offset of fourth operand in its array - * @param result array where result must be stored (it may be - * one of the input arrays) - * @param resultOffset offset of the result in its array - */ - public void linearCombination(final double a1, final double[] c1, final int offset1, - final double a2, final double[] c2, final int offset2, - final double a3, final double[] c3, final int offset3, - final double a4, final double[] c4, final int offset4, - final double[] result, final int resultOffset) { - for (int i = 0; i < getSize(); ++i) { - result[resultOffset + i] = - LinearCombination.value(a1, c1[offset1 + i], - a2, c2[offset2 + i], - a3, c3[offset3 + i], - a4, c4[offset4 + i]); - } - } - - /** Perform addition of two derivative structures. - * @param lhs array holding left hand side of addition - * @param lhsOffset offset of the left hand side in its array - * @param rhs array right hand side of addition - * @param rhsOffset offset of the right hand side in its array - * @param result array where result must be stored (it may be - * one of the input arrays) - * @param resultOffset offset of the result in its array - */ - public void add(final double[] lhs, final int lhsOffset, - final double[] rhs, final int rhsOffset, - final double[] result, final int resultOffset) { - for (int i = 0; i < getSize(); ++i) { - result[resultOffset + i] = lhs[lhsOffset + i] + rhs[rhsOffset + i]; - } - } - /** Perform subtraction of two derivative structures. - * @param lhs array holding left hand side of subtraction - * @param lhsOffset offset of the left hand side in its array - * @param rhs array right hand side of subtraction - * @param rhsOffset offset of the right hand side in its array - * @param result array where result must be stored (it may be - * one of the input arrays) - * @param resultOffset offset of the result in its array - */ - public void subtract(final double[] lhs, final int lhsOffset, - final double[] rhs, final int rhsOffset, - final double[] result, final int resultOffset) { - for (int i = 0; i < getSize(); ++i) { - result[resultOffset + i] = lhs[lhsOffset + i] - rhs[rhsOffset + i]; - } - } - - /** Perform multiplication of two derivative structures. - * @param lhs array holding left hand side of multiplication - * @param lhsOffset offset of the left hand side in its array - * @param rhs array right hand side of multiplication - * @param rhsOffset offset of the right hand side in its array - * @param result array where result must be stored (for - * multiplication the result array cannot be one of - * the input arrays) - * @param resultOffset offset of the result in its array - */ - public void multiply(final double[] lhs, final int lhsOffset, - final double[] rhs, final int rhsOffset, - final double[] result, final int resultOffset) { - for (int i = 0; i < multIndirection.length; ++i) { - final int[][] mappingI = multIndirection[i]; - double r = 0; - for (int j = 0; j < mappingI.length; ++j) { - r += mappingI[j][0] * - lhs[lhsOffset + mappingI[j][1]] * - rhs[rhsOffset + mappingI[j][2]]; - } - result[resultOffset + i] = r; - } - } - - /** Perform division of two derivative structures. - * @param lhs array holding left hand side of division - * @param lhsOffset offset of the left hand side in its array - * @param rhs array right hand side of division - * @param rhsOffset offset of the right hand side in its array - * @param result array where result must be stored (for - * division the result array cannot be one of - * the input arrays) - * @param resultOffset offset of the result in its array - */ - public void divide(final double[] lhs, final int lhsOffset, - final double[] rhs, final int rhsOffset, - final double[] result, final int resultOffset) { - final double[] reciprocal = new double[getSize()]; - pow(rhs, lhsOffset, -1, reciprocal, 0); - multiply(lhs, lhsOffset, reciprocal, 0, result, resultOffset); - } - - /** Perform remainder of two derivative structures. - * @param lhs array holding left hand side of remainder - * @param lhsOffset offset of the left hand side in its array - * @param rhs array right hand side of remainder - * @param rhsOffset offset of the right hand side in its array - * @param result array where result must be stored (it may be - * one of the input arrays) - * @param resultOffset offset of the result in its array - */ - public void remainder(final double[] lhs, final int lhsOffset, - final double[] rhs, final int rhsOffset, - final double[] result, final int resultOffset) { - - // compute k such that lhs % rhs = lhs - k rhs - final double rem = FastMath.IEEEremainder(lhs[lhsOffset], rhs[rhsOffset]); - final double k = FastMath.rint((lhs[lhsOffset] - rem) / rhs[rhsOffset]); - - // set up value - result[resultOffset] = rem; - - // set up partial derivatives - for (int i = 1; i < getSize(); ++i) { - result[resultOffset + i] = lhs[lhsOffset + i] - k * rhs[rhsOffset + i]; - } - - } - - /** Compute power of a double to a derivative structure. - * @param a number to exponentiate - * @param operand array holding the power - * @param operandOffset offset of the power in its array - * @param result array where result must be stored (for - * power the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - * @since 3.3 - */ - public void pow(final double a, - final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - // [a^x, ln(a) a^x, ln(a)^2 a^x,, ln(a)^3 a^x, ... ] - final double[] function = new double[1 + order]; - if (a == 0) { - if (operand[operandOffset] == 0) { - function[0] = 1; - double infinity = Double.POSITIVE_INFINITY; - for (int i = 1; i < function.length; ++i) { - infinity = -infinity; - function[i] = infinity; - } - } else if (operand[operandOffset] < 0) { - Arrays.fill(function, Double.NaN); - } - } else { - function[0] = FastMath.pow(a, operand[operandOffset]); - final double lnA = FastMath.log(a); - for (int i = 1; i < function.length; ++i) { - function[i] = lnA * function[i - 1]; - } - } - - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute power of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param p power to apply - * @param result array where result must be stored (for - * power the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void pow(final double[] operand, final int operandOffset, final double p, - final double[] result, final int resultOffset) { - - if (p == 0) { - // special case, x^0 = 1 for all x - result[resultOffset] = 1.0; - Arrays.fill(result, resultOffset + 1, resultOffset + getSize(), 0); - return; - } - - if (operand[operandOffset] == 0) { - // special case, 0^p = 0 for all p - Arrays.fill(result, resultOffset, resultOffset + getSize(), 0); - return; - } - - // create the function value and derivatives - // [x^p, px^(p-1), p(p-1)x^(p-2), ... ] - double[] function = new double[1 + order]; - double xk = FastMath.pow(operand[operandOffset], p - order); - for (int i = order; i > 0; --i) { - function[i] = xk; - xk *= operand[operandOffset]; - } - function[0] = xk; - double coefficient = p; - for (int i = 1; i <= order; ++i) { - function[i] *= coefficient; - coefficient *= p - i; - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute integer power of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param n power to apply - * @param result array where result must be stored (for - * power the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void pow(final double[] operand, final int operandOffset, final int n, - final double[] result, final int resultOffset) { - - if (n == 0) { - // special case, x^0 = 1 for all x - result[resultOffset] = 1.0; - Arrays.fill(result, resultOffset + 1, resultOffset + getSize(), 0); - return; - } - - // create the power function value and derivatives - // [x^n, nx^(n-1), n(n-1)x^(n-2), ... ] - double[] function = new double[1 + order]; - - if (n > 0) { - // strictly positive power - final int maxOrder = FastMath.min(order, n); - double xk = FastMath.pow(operand[operandOffset], n - maxOrder); - for (int i = maxOrder; i > 0; --i) { - function[i] = xk; - xk *= operand[operandOffset]; - } - function[0] = xk; - } else { - // strictly negative power - final double inv = 1.0 / operand[operandOffset]; - double xk = FastMath.pow(inv, -n); - for (int i = 0; i <= order; ++i) { - function[i] = xk; - xk *= inv; - } - } - - double coefficient = n; - for (int i = 1; i <= order; ++i) { - function[i] *= coefficient; - coefficient *= n - i; - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute power of a derivative structure. - * @param x array holding the base - * @param xOffset offset of the base in its array - * @param y array holding the exponent - * @param yOffset offset of the exponent in its array - * @param result array where result must be stored (for - * power the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void pow(final double[] x, final int xOffset, - final double[] y, final int yOffset, - final double[] result, final int resultOffset) { - final double[] logX = new double[getSize()]; - log(x, xOffset, logX, 0); - final double[] yLogX = new double[getSize()]; - multiply(logX, 0, y, yOffset, yLogX, 0); - exp(yLogX, 0, result, resultOffset); - } - - /** Compute nth root of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param n order of the root - * @param result array where result must be stored (for - * nth root the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void rootN(final double[] operand, final int operandOffset, final int n, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - // [x^(1/n), (1/n)x^((1/n)-1), (1-n)/n^2x^((1/n)-2), ... ] - double[] function = new double[1 + order]; - double xk; - if (n == 2) { - function[0] = FastMath.sqrt(operand[operandOffset]); - xk = 0.5 / function[0]; - } else if (n == 3) { - function[0] = FastMath.cbrt(operand[operandOffset]); - xk = 1.0 / (3.0 * function[0] * function[0]); - } else { - function[0] = FastMath.pow(operand[operandOffset], 1.0 / n); - xk = 1.0 / (n * FastMath.pow(function[0], n - 1)); - } - final double nReciprocal = 1.0 / n; - final double xReciprocal = 1.0 / operand[operandOffset]; - for (int i = 1; i <= order; ++i) { - function[i] = xk; - xk *= xReciprocal * (nReciprocal - i); - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute exponential of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param result array where result must be stored (for - * exponential the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void exp(final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - double[] function = new double[1 + order]; - Arrays.fill(function, FastMath.exp(operand[operandOffset])); - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute exp(x) - 1 of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param result array where result must be stored (for - * exponential the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void expm1(final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - double[] function = new double[1 + order]; - function[0] = FastMath.expm1(operand[operandOffset]); - Arrays.fill(function, 1, 1 + order, FastMath.exp(operand[operandOffset])); - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute natural logarithm of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param result array where result must be stored (for - * logarithm the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void log(final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - double[] function = new double[1 + order]; - function[0] = FastMath.log(operand[operandOffset]); - if (order > 0) { - double inv = 1.0 / operand[operandOffset]; - double xk = inv; - for (int i = 1; i <= order; ++i) { - function[i] = xk; - xk *= -i * inv; - } - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Computes shifted logarithm of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param result array where result must be stored (for - * shifted logarithm the result array cannot be the input array) - * @param resultOffset offset of the result in its array - */ - public void log1p(final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - double[] function = new double[1 + order]; - function[0] = FastMath.log1p(operand[operandOffset]); - if (order > 0) { - double inv = 1.0 / (1.0 + operand[operandOffset]); - double xk = inv; - for (int i = 1; i <= order; ++i) { - function[i] = xk; - xk *= -i * inv; - } - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Computes base 10 logarithm of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param result array where result must be stored (for - * base 10 logarithm the result array cannot be the input array) - * @param resultOffset offset of the result in its array - */ - public void log10(final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - double[] function = new double[1 + order]; - function[0] = FastMath.log10(operand[operandOffset]); - if (order > 0) { - double inv = 1.0 / operand[operandOffset]; - double xk = inv / FastMath.log(10.0); - for (int i = 1; i <= order; ++i) { - function[i] = xk; - xk *= -i * inv; - } - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute cosine of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param result array where result must be stored (for - * cosine the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void cos(final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - double[] function = new double[1 + order]; - function[0] = FastMath.cos(operand[operandOffset]); - if (order > 0) { - function[1] = -FastMath.sin(operand[operandOffset]); - for (int i = 2; i <= order; ++i) { - function[i] = -function[i - 2]; - } - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute sine of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param result array where result must be stored (for - * sine the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void sin(final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - double[] function = new double[1 + order]; - function[0] = FastMath.sin(operand[operandOffset]); - if (order > 0) { - function[1] = FastMath.cos(operand[operandOffset]); - for (int i = 2; i <= order; ++i) { - function[i] = -function[i - 2]; - } - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute tangent of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param result array where result must be stored (for - * tangent the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void tan(final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - final double[] function = new double[1 + order]; - final double t = FastMath.tan(operand[operandOffset]); - function[0] = t; - - if (order > 0) { - - // the nth order derivative of tan has the form: - // dn(tan(x)/dxn = P_n(tan(x)) - // where P_n(t) is a degree n+1 polynomial with same parity as n+1 - // P_0(t) = t, P_1(t) = 1 + t^2, P_2(t) = 2 t (1 + t^2) ... - // the general recurrence relation for P_n is: - // P_n(x) = (1+t^2) P_(n-1)'(t) - // as per polynomial parity, we can store coefficients of both P_(n-1) and P_n in the same array - final double[] p = new double[order + 2]; - p[1] = 1; - final double t2 = t * t; - for (int n = 1; n <= order; ++n) { - - // update and evaluate polynomial P_n(t) - double v = 0; - p[n + 1] = n * p[n]; - for (int k = n + 1; k >= 0; k -= 2) { - v = v * t2 + p[k]; - if (k > 2) { - p[k - 2] = (k - 1) * p[k - 1] + (k - 3) * p[k - 3]; - } else if (k == 2) { - p[0] = p[1]; - } - } - if ((n & 0x1) == 0) { - v *= t; - } - - function[n] = v; - - } - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute arc cosine of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param result array where result must be stored (for - * arc cosine the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void acos(final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - double[] function = new double[1 + order]; - final double x = operand[operandOffset]; - function[0] = FastMath.acos(x); - if (order > 0) { - // the nth order derivative of acos has the form: - // dn(acos(x)/dxn = P_n(x) / [1 - x^2]^((2n-1)/2) - // where P_n(x) is a degree n-1 polynomial with same parity as n-1 - // P_1(x) = -1, P_2(x) = -x, P_3(x) = -2x^2 - 1 ... - // the general recurrence relation for P_n is: - // P_n(x) = (1-x^2) P_(n-1)'(x) + (2n-3) x P_(n-1)(x) - // as per polynomial parity, we can store coefficients of both P_(n-1) and P_n in the same array - final double[] p = new double[order]; - p[0] = -1; - final double x2 = x * x; - final double f = 1.0 / (1 - x2); - double coeff = FastMath.sqrt(f); - function[1] = coeff * p[0]; - for (int n = 2; n <= order; ++n) { - - // update and evaluate polynomial P_n(x) - double v = 0; - p[n - 1] = (n - 1) * p[n - 2]; - for (int k = n - 1; k >= 0; k -= 2) { - v = v * x2 + p[k]; - if (k > 2) { - p[k - 2] = (k - 1) * p[k - 1] + (2 * n - k) * p[k - 3]; - } else if (k == 2) { - p[0] = p[1]; - } - } - if ((n & 0x1) == 0) { - v *= x; - } - - coeff *= f; - function[n] = coeff * v; - - } - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute arc sine of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param result array where result must be stored (for - * arc sine the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void asin(final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - double[] function = new double[1 + order]; - final double x = operand[operandOffset]; - function[0] = FastMath.asin(x); - if (order > 0) { - // the nth order derivative of asin has the form: - // dn(asin(x)/dxn = P_n(x) / [1 - x^2]^((2n-1)/2) - // where P_n(x) is a degree n-1 polynomial with same parity as n-1 - // P_1(x) = 1, P_2(x) = x, P_3(x) = 2x^2 + 1 ... - // the general recurrence relation for P_n is: - // P_n(x) = (1-x^2) P_(n-1)'(x) + (2n-3) x P_(n-1)(x) - // as per polynomial parity, we can store coefficients of both P_(n-1) and P_n in the same array - final double[] p = new double[order]; - p[0] = 1; - final double x2 = x * x; - final double f = 1.0 / (1 - x2); - double coeff = FastMath.sqrt(f); - function[1] = coeff * p[0]; - for (int n = 2; n <= order; ++n) { - - // update and evaluate polynomial P_n(x) - double v = 0; - p[n - 1] = (n - 1) * p[n - 2]; - for (int k = n - 1; k >= 0; k -= 2) { - v = v * x2 + p[k]; - if (k > 2) { - p[k - 2] = (k - 1) * p[k - 1] + (2 * n - k) * p[k - 3]; - } else if (k == 2) { - p[0] = p[1]; - } - } - if ((n & 0x1) == 0) { - v *= x; - } - - coeff *= f; - function[n] = coeff * v; - - } - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute arc tangent of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param result array where result must be stored (for - * arc tangent the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void atan(final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - double[] function = new double[1 + order]; - final double x = operand[operandOffset]; - function[0] = FastMath.atan(x); - if (order > 0) { - // the nth order derivative of atan has the form: - // dn(atan(x)/dxn = Q_n(x) / (1 + x^2)^n - // where Q_n(x) is a degree n-1 polynomial with same parity as n-1 - // Q_1(x) = 1, Q_2(x) = -2x, Q_3(x) = 6x^2 - 2 ... - // the general recurrence relation for Q_n is: - // Q_n(x) = (1+x^2) Q_(n-1)'(x) - 2(n-1) x Q_(n-1)(x) - // as per polynomial parity, we can store coefficients of both Q_(n-1) and Q_n in the same array - final double[] q = new double[order]; - q[0] = 1; - final double x2 = x * x; - final double f = 1.0 / (1 + x2); - double coeff = f; - function[1] = coeff * q[0]; - for (int n = 2; n <= order; ++n) { - - // update and evaluate polynomial Q_n(x) - double v = 0; - q[n - 1] = -n * q[n - 2]; - for (int k = n - 1; k >= 0; k -= 2) { - v = v * x2 + q[k]; - if (k > 2) { - q[k - 2] = (k - 1) * q[k - 1] + (k - 1 - 2 * n) * q[k - 3]; - } else if (k == 2) { - q[0] = q[1]; - } - } - if ((n & 0x1) == 0) { - v *= x; - } - - coeff *= f; - function[n] = coeff * v; - - } - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute two arguments arc tangent of a derivative structure. - * @param y array holding the first operand - * @param yOffset offset of the first operand in its array - * @param x array holding the second operand - * @param xOffset offset of the second operand in its array - * @param result array where result must be stored (for - * two arguments arc tangent the result array cannot - * be the input array) - * @param resultOffset offset of the result in its array - */ - public void atan2(final double[] y, final int yOffset, - final double[] x, final int xOffset, - final double[] result, final int resultOffset) { - - // compute r = sqrt(x^2+y^2) - double[] tmp1 = new double[getSize()]; - multiply(x, xOffset, x, xOffset, tmp1, 0); // x^2 - double[] tmp2 = new double[getSize()]; - multiply(y, yOffset, y, yOffset, tmp2, 0); // y^2 - add(tmp1, 0, tmp2, 0, tmp2, 0); // x^2 + y^2 - rootN(tmp2, 0, 2, tmp1, 0); // r = sqrt(x^2 + y^2) - - if (x[xOffset] >= 0) { - - // compute atan2(y, x) = 2 atan(y / (r + x)) - add(tmp1, 0, x, xOffset, tmp2, 0); // r + x - divide(y, yOffset, tmp2, 0, tmp1, 0); // y /(r + x) - atan(tmp1, 0, tmp2, 0); // atan(y / (r + x)) - for (int i = 0; i < tmp2.length; ++i) { - result[resultOffset + i] = 2 * tmp2[i]; // 2 * atan(y / (r + x)) - } - - } else { - - // compute atan2(y, x) = +/- pi - 2 atan(y / (r - x)) - subtract(tmp1, 0, x, xOffset, tmp2, 0); // r - x - divide(y, yOffset, tmp2, 0, tmp1, 0); // y /(r - x) - atan(tmp1, 0, tmp2, 0); // atan(y / (r - x)) - result[resultOffset] = - ((tmp2[0] <= 0) ? -FastMath.PI : FastMath.PI) - 2 * tmp2[0]; // +/-pi - 2 * atan(y / (r - x)) - for (int i = 1; i < tmp2.length; ++i) { - result[resultOffset + i] = -2 * tmp2[i]; // +/-pi - 2 * atan(y / (r - x)) - } - - } - - // fix value to take special cases (+0/+0, +0/-0, -0/+0, -0/-0, +/-infinity) correctly - result[resultOffset] = FastMath.atan2(y[yOffset], x[xOffset]); - - } - - /** Compute hyperbolic cosine of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param result array where result must be stored (for - * hyperbolic cosine the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void cosh(final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - double[] function = new double[1 + order]; - function[0] = FastMath.cosh(operand[operandOffset]); - if (order > 0) { - function[1] = FastMath.sinh(operand[operandOffset]); - for (int i = 2; i <= order; ++i) { - function[i] = function[i - 2]; - } - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute hyperbolic sine of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param result array where result must be stored (for - * hyperbolic sine the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void sinh(final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - double[] function = new double[1 + order]; - function[0] = FastMath.sinh(operand[operandOffset]); - if (order > 0) { - function[1] = FastMath.cosh(operand[operandOffset]); - for (int i = 2; i <= order; ++i) { - function[i] = function[i - 2]; - } - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute hyperbolic tangent of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param result array where result must be stored (for - * hyperbolic tangent the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void tanh(final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - final double[] function = new double[1 + order]; - final double t = FastMath.tanh(operand[operandOffset]); - function[0] = t; - - if (order > 0) { - - // the nth order derivative of tanh has the form: - // dn(tanh(x)/dxn = P_n(tanh(x)) - // where P_n(t) is a degree n+1 polynomial with same parity as n+1 - // P_0(t) = t, P_1(t) = 1 - t^2, P_2(t) = -2 t (1 - t^2) ... - // the general recurrence relation for P_n is: - // P_n(x) = (1-t^2) P_(n-1)'(t) - // as per polynomial parity, we can store coefficients of both P_(n-1) and P_n in the same array - final double[] p = new double[order + 2]; - p[1] = 1; - final double t2 = t * t; - for (int n = 1; n <= order; ++n) { - - // update and evaluate polynomial P_n(t) - double v = 0; - p[n + 1] = -n * p[n]; - for (int k = n + 1; k >= 0; k -= 2) { - v = v * t2 + p[k]; - if (k > 2) { - p[k - 2] = (k - 1) * p[k - 1] - (k - 3) * p[k - 3]; - } else if (k == 2) { - p[0] = p[1]; - } - } - if ((n & 0x1) == 0) { - v *= t; - } - - function[n] = v; - - } - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute inverse hyperbolic cosine of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param result array where result must be stored (for - * inverse hyperbolic cosine the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void acosh(final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - double[] function = new double[1 + order]; - final double x = operand[operandOffset]; - function[0] = FastMath.acosh(x); - if (order > 0) { - // the nth order derivative of acosh has the form: - // dn(acosh(x)/dxn = P_n(x) / [x^2 - 1]^((2n-1)/2) - // where P_n(x) is a degree n-1 polynomial with same parity as n-1 - // P_1(x) = 1, P_2(x) = -x, P_3(x) = 2x^2 + 1 ... - // the general recurrence relation for P_n is: - // P_n(x) = (x^2-1) P_(n-1)'(x) - (2n-3) x P_(n-1)(x) - // as per polynomial parity, we can store coefficients of both P_(n-1) and P_n in the same array - final double[] p = new double[order]; - p[0] = 1; - final double x2 = x * x; - final double f = 1.0 / (x2 - 1); - double coeff = FastMath.sqrt(f); - function[1] = coeff * p[0]; - for (int n = 2; n <= order; ++n) { - - // update and evaluate polynomial P_n(x) - double v = 0; - p[n - 1] = (1 - n) * p[n - 2]; - for (int k = n - 1; k >= 0; k -= 2) { - v = v * x2 + p[k]; - if (k > 2) { - p[k - 2] = (1 - k) * p[k - 1] + (k - 2 * n) * p[k - 3]; - } else if (k == 2) { - p[0] = -p[1]; - } - } - if ((n & 0x1) == 0) { - v *= x; - } - - coeff *= f; - function[n] = coeff * v; - - } - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute inverse hyperbolic sine of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param result array where result must be stored (for - * inverse hyperbolic sine the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void asinh(final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - double[] function = new double[1 + order]; - final double x = operand[operandOffset]; - function[0] = FastMath.asinh(x); - if (order > 0) { - // the nth order derivative of asinh has the form: - // dn(asinh(x)/dxn = P_n(x) / [x^2 + 1]^((2n-1)/2) - // where P_n(x) is a degree n-1 polynomial with same parity as n-1 - // P_1(x) = 1, P_2(x) = -x, P_3(x) = 2x^2 - 1 ... - // the general recurrence relation for P_n is: - // P_n(x) = (x^2+1) P_(n-1)'(x) - (2n-3) x P_(n-1)(x) - // as per polynomial parity, we can store coefficients of both P_(n-1) and P_n in the same array - final double[] p = new double[order]; - p[0] = 1; - final double x2 = x * x; - final double f = 1.0 / (1 + x2); - double coeff = FastMath.sqrt(f); - function[1] = coeff * p[0]; - for (int n = 2; n <= order; ++n) { - - // update and evaluate polynomial P_n(x) - double v = 0; - p[n - 1] = (1 - n) * p[n - 2]; - for (int k = n - 1; k >= 0; k -= 2) { - v = v * x2 + p[k]; - if (k > 2) { - p[k - 2] = (k - 1) * p[k - 1] + (k - 2 * n) * p[k - 3]; - } else if (k == 2) { - p[0] = p[1]; - } - } - if ((n & 0x1) == 0) { - v *= x; - } - - coeff *= f; - function[n] = coeff * v; - - } - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute inverse hyperbolic tangent of a derivative structure. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param result array where result must be stored (for - * inverse hyperbolic tangent the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void atanh(final double[] operand, final int operandOffset, - final double[] result, final int resultOffset) { - - // create the function value and derivatives - double[] function = new double[1 + order]; - final double x = operand[operandOffset]; - function[0] = FastMath.atanh(x); - if (order > 0) { - // the nth order derivative of atanh has the form: - // dn(atanh(x)/dxn = Q_n(x) / (1 - x^2)^n - // where Q_n(x) is a degree n-1 polynomial with same parity as n-1 - // Q_1(x) = 1, Q_2(x) = 2x, Q_3(x) = 6x^2 + 2 ... - // the general recurrence relation for Q_n is: - // Q_n(x) = (1-x^2) Q_(n-1)'(x) + 2(n-1) x Q_(n-1)(x) - // as per polynomial parity, we can store coefficients of both Q_(n-1) and Q_n in the same array - final double[] q = new double[order]; - q[0] = 1; - final double x2 = x * x; - final double f = 1.0 / (1 - x2); - double coeff = f; - function[1] = coeff * q[0]; - for (int n = 2; n <= order; ++n) { - - // update and evaluate polynomial Q_n(x) - double v = 0; - q[n - 1] = n * q[n - 2]; - for (int k = n - 1; k >= 0; k -= 2) { - v = v * x2 + q[k]; - if (k > 2) { - q[k - 2] = (k - 1) * q[k - 1] + (2 * n - k + 1) * q[k - 3]; - } else if (k == 2) { - q[0] = q[1]; - } - } - if ((n & 0x1) == 0) { - v *= x; - } - - coeff *= f; - function[n] = coeff * v; - - } - } - - // apply function composition - compose(operand, operandOffset, function, result, resultOffset); - - } - - /** Compute composition of a derivative structure by a function. - * @param operand array holding the operand - * @param operandOffset offset of the operand in its array - * @param f array of value and derivatives of the function at - * the current point (i.e. at {@code operand[operandOffset]}). - * @param result array where result must be stored (for - * composition the result array cannot be the input - * array) - * @param resultOffset offset of the result in its array - */ - public void compose(final double[] operand, final int operandOffset, final double[] f, - final double[] result, final int resultOffset) { - for (int i = 0; i < compIndirection.length; ++i) { - final int[][] mappingI = compIndirection[i]; - double r = 0; - for (int j = 0; j < mappingI.length; ++j) { - final int[] mappingIJ = mappingI[j]; - double product = mappingIJ[0] * f[mappingIJ[1]]; - for (int k = 2; k < mappingIJ.length; ++k) { - product *= operand[operandOffset + mappingIJ[k]]; - } - r += product; - } - result[resultOffset + i] = r; - } - } - - /** Evaluate Taylor expansion of a derivative structure. - * @param ds array holding the derivative structure - * @param dsOffset offset of the derivative structure in its array - * @param delta parameters offsets (Δx, Δy, ...) - * @return value of the Taylor expansion at x + Δx, y + Δy, ... - * @throws MathArithmeticException if factorials becomes too large - */ - public double taylor(final double[] ds, final int dsOffset, final double ... delta) - throws MathArithmeticException { - double value = 0; - for (int i = getSize() - 1; i >= 0; --i) { - final int[] orders = getPartialDerivativeOrders(i); - double term = ds[dsOffset + i]; - for (int k = 0; k < orders.length; ++k) { - if (orders[k] > 0) { - try { - term *= FastMath.pow(delta[k], orders[k]) / FACTORIAL.value(orders[k]); - } catch (NotPositiveException e) { - // this cannot happen - throw new MathInternalError(e); - } - } - } - value += term; - } - return value; - } - - /** Check rules set compatibility. - * @param compiler other compiler to check against instance - * @exception DimensionMismatchException if number of free parameters or orders are inconsistent - */ - public void checkCompatibility(final DSCompiler compiler) - throws DimensionMismatchException { - if (parameters != compiler.parameters) { - throw new DimensionMismatchException(parameters, compiler.parameters); - } - if (order != compiler.order) { - throw new DimensionMismatchException(order, compiler.order); - } - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/DerivativeStructure.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/DerivativeStructure.java deleted file mode 100644 index b99fd4385..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/DerivativeStructure.java +++ /dev/null @@ -1,1256 +0,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. - */ -package org.apache.commons.math4.analysis.differentiation; - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; -import org.apache.commons.math4.RealFieldElement; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; -import org.apache.commons.numbers.arrays.LinearCombination; - -import java.io.Serializable; - -/** Class representing both the value and the differentials of a function. - *

This class is the workhorse of the differentiation package.

- *

This class is an implementation of the extension to Rall's - * numbers described in Dan Kalman's paper Doubly - * Recursive Multivariate Automatic Differentiation, Mathematics Magazine, vol. 75, - * no. 3, June 2002. Rall's numbers are an extension to the real numbers used - * throughout mathematical expressions; they hold the derivative together with the - * value of a function. Dan Kalman's derivative structures hold all partial derivatives - * up to any specified order, with respect to any number of free parameters. Rall's - * numbers therefore can be seen as derivative structures for order one derivative and - * one free parameter, and real numbers can be seen as derivative structures with zero - * order derivative and no free parameters.

- *

{@link DerivativeStructure} instances can be used directly thanks to - * the arithmetic operators to the mathematical functions provided as - * methods by this class (+, -, *, /, %, sin, cos ...).

- *

Implementing complex expressions by hand using these classes is - * a tedious and error-prone task but has the advantage of having no limitation - * on the derivation order despite not requiring users to compute the derivatives by - * themselves. Implementing complex expression can also be done by developing computation - * code using standard primitive double values and to use {@link - * UnivariateFunctionDifferentiator differentiators} to create the {@link - * DerivativeStructure}-based instances. This method is simpler but may be limited in - * the accuracy and derivation orders and may be computationally intensive (this is - * typically the case for {@link FiniteDifferencesDifferentiator finite differences - * differentiator}.

- *

Instances of this class are guaranteed to be immutable.

- * @see DSCompiler - * @since 3.1 - */ -public class DerivativeStructure implements RealFieldElement, Serializable { - - /** Serializable UID. */ - private static final long serialVersionUID = 20120730L; - - /** Compiler for the current dimensions. */ - private transient DSCompiler compiler; - - /** Combined array holding all values. */ - private final double[] data; - - /** Build an instance with all values and derivatives set to 0. - * @param compiler compiler to use for computation - */ - private DerivativeStructure(final DSCompiler compiler) { - this.compiler = compiler; - this.data = new double[compiler.getSize()]; - } - - /** Build an instance with all values and derivatives set to 0. - * @param parameters number of free parameters - * @param order derivation order - * @throws NumberIsTooLargeException if order is too large - */ - public DerivativeStructure(final int parameters, final int order) - throws NumberIsTooLargeException { - this(DSCompiler.getCompiler(parameters, order)); - } - - /** Build an instance representing a constant value. - * @param parameters number of free parameters - * @param order derivation order - * @param value value of the constant - * @throws NumberIsTooLargeException if order is too large - * @see #DerivativeStructure(int, int, int, double) - */ - public DerivativeStructure(final int parameters, final int order, final double value) - throws NumberIsTooLargeException { - this(parameters, order); - this.data[0] = value; - } - - /** Build an instance representing a variable. - *

Instances built using this constructor are considered - * to be the free variables with respect to which differentials - * are computed. As such, their differential with respect to - * themselves is +1.

- * @param parameters number of free parameters - * @param order derivation order - * @param index index of the variable (from 0 to {@code parameters - 1}) - * @param value value of the variable - * @exception NumberIsTooLargeException if {@code index ≥ parameters}. - * @see #DerivativeStructure(int, int, double) - */ - public DerivativeStructure(final int parameters, final int order, - final int index, final double value) - throws NumberIsTooLargeException { - this(parameters, order, value); - - if (index >= parameters) { - throw new NumberIsTooLargeException(index, parameters, false); - } - - if (order > 0) { - // the derivative of the variable with respect to itself is 1. - data[DSCompiler.getCompiler(index, order).getSize()] = 1.0; - } - - } - - /** Linear combination constructor. - * The derivative structure built will be a1 * ds1 + a2 * ds2 - * @param a1 first scale factor - * @param ds1 first base (unscaled) derivative structure - * @param a2 second scale factor - * @param ds2 second base (unscaled) derivative structure - * @exception DimensionMismatchException if number of free parameters or orders are inconsistent - */ - public DerivativeStructure(final double a1, final DerivativeStructure ds1, - final double a2, final DerivativeStructure ds2) - throws DimensionMismatchException { - this(ds1.compiler); - compiler.checkCompatibility(ds2.compiler); - compiler.linearCombination(a1, ds1.data, 0, a2, ds2.data, 0, data, 0); - } - - /** Linear combination constructor. - * The derivative structure built will be a1 * ds1 + a2 * ds2 + a3 * ds3 - * @param a1 first scale factor - * @param ds1 first base (unscaled) derivative structure - * @param a2 second scale factor - * @param ds2 second base (unscaled) derivative structure - * @param a3 third scale factor - * @param ds3 third base (unscaled) derivative structure - * @exception DimensionMismatchException if number of free parameters or orders are inconsistent - */ - public DerivativeStructure(final double a1, final DerivativeStructure ds1, - final double a2, final DerivativeStructure ds2, - final double a3, final DerivativeStructure ds3) - throws DimensionMismatchException { - this(ds1.compiler); - compiler.checkCompatibility(ds2.compiler); - compiler.checkCompatibility(ds3.compiler); - compiler.linearCombination(a1, ds1.data, 0, a2, ds2.data, 0, a3, ds3.data, 0, data, 0); - } - - /** Linear combination constructor. - * The derivative structure built will be a1 * ds1 + a2 * ds2 + a3 * ds3 + a4 * ds4 - * @param a1 first scale factor - * @param ds1 first base (unscaled) derivative structure - * @param a2 second scale factor - * @param ds2 second base (unscaled) derivative structure - * @param a3 third scale factor - * @param ds3 third base (unscaled) derivative structure - * @param a4 fourth scale factor - * @param ds4 fourth base (unscaled) derivative structure - * @exception DimensionMismatchException if number of free parameters or orders are inconsistent - */ - public DerivativeStructure(final double a1, final DerivativeStructure ds1, - final double a2, final DerivativeStructure ds2, - final double a3, final DerivativeStructure ds3, - final double a4, final DerivativeStructure ds4) - throws DimensionMismatchException { - this(ds1.compiler); - compiler.checkCompatibility(ds2.compiler); - compiler.checkCompatibility(ds3.compiler); - compiler.checkCompatibility(ds4.compiler); - compiler.linearCombination(a1, ds1.data, 0, a2, ds2.data, 0, - a3, ds3.data, 0, a4, ds4.data, 0, - data, 0); - } - - /** Build an instance from all its derivatives. - * @param parameters number of free parameters - * @param order derivation order - * @param derivatives derivatives sorted according to - * {@link DSCompiler#getPartialDerivativeIndex(int...)} - * @exception DimensionMismatchException if derivatives array does not match the - * {@link DSCompiler#getSize() size} expected by the compiler - * @throws NumberIsTooLargeException if order is too large - * @see #getAllDerivatives() - */ - public DerivativeStructure(final int parameters, final int order, final double ... derivatives) - throws DimensionMismatchException, NumberIsTooLargeException { - this(parameters, order); - if (derivatives.length != data.length) { - throw new DimensionMismatchException(derivatives.length, data.length); - } - System.arraycopy(derivatives, 0, data, 0, data.length); - } - - /** Copy constructor. - * @param ds instance to copy - */ - private DerivativeStructure(final DerivativeStructure ds) { - this.compiler = ds.compiler; - this.data = ds.data.clone(); - } - - /** Get the number of free parameters. - * @return number of free parameters - */ - public int getFreeParameters() { - return compiler.getFreeParameters(); - } - - /** Get the derivation order. - * @return derivation order - */ - public int getOrder() { - return compiler.getOrder(); - } - - /** Create a constant compatible with instance order and number of parameters. - *

- * This method is a convenience factory method, it simply calls - * {@code new DerivativeStructure(getFreeParameters(), getOrder(), c)} - *

- * @param c value of the constant - * @return a constant compatible with instance order and number of parameters - * @see #DerivativeStructure(int, int, double) - * @since 3.3 - */ - public DerivativeStructure createConstant(final double c) { - return new DerivativeStructure(getFreeParameters(), getOrder(), c); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public double getReal() { - return data[0]; - } - - /** Get the value part of the derivative structure. - * @return value part of the derivative structure - * @see #getPartialDerivative(int...) - */ - public double getValue() { - return data[0]; - } - - /** Get a partial derivative. - * @param orders derivation orders with respect to each variable (if all orders are 0, - * the value is returned) - * @return partial derivative - * @see #getValue() - * @exception DimensionMismatchException if the numbers of variables does not - * match the instance - * @exception NumberIsTooLargeException if sum of derivation orders is larger - * than the instance limits - */ - public double getPartialDerivative(final int ... orders) - throws DimensionMismatchException, NumberIsTooLargeException { - return data[compiler.getPartialDerivativeIndex(orders)]; - } - - /** Get all partial derivatives. - * @return a fresh copy of partial derivatives, in an array sorted according to - * {@link DSCompiler#getPartialDerivativeIndex(int...)} - */ - public double[] getAllDerivatives() { - return data.clone(); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure add(final double a) { - final DerivativeStructure ds = new DerivativeStructure(this); - ds.data[0] += a; - return ds; - } - - /** {@inheritDoc} - * @exception DimensionMismatchException if number of free parameters - * or orders do not match - */ - @Override - public DerivativeStructure add(final DerivativeStructure a) - throws DimensionMismatchException { - compiler.checkCompatibility(a.compiler); - final DerivativeStructure ds = new DerivativeStructure(this); - compiler.add(data, 0, a.data, 0, ds.data, 0); - return ds; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure subtract(final double a) { - return add(-a); - } - - /** {@inheritDoc} - * @exception DimensionMismatchException if number of free parameters - * or orders do not match - */ - @Override - public DerivativeStructure subtract(final DerivativeStructure a) - throws DimensionMismatchException { - compiler.checkCompatibility(a.compiler); - final DerivativeStructure ds = new DerivativeStructure(this); - compiler.subtract(data, 0, a.data, 0, ds.data, 0); - return ds; - } - - /** {@inheritDoc} */ - @Override - public DerivativeStructure multiply(final int n) { - return multiply((double) n); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure multiply(final double a) { - final DerivativeStructure ds = new DerivativeStructure(this); - for (int i = 0; i < ds.data.length; ++i) { - ds.data[i] *= a; - } - return ds; - } - - /** {@inheritDoc} - * @exception DimensionMismatchException if number of free parameters - * or orders do not match - */ - @Override - public DerivativeStructure multiply(final DerivativeStructure a) - throws DimensionMismatchException { - compiler.checkCompatibility(a.compiler); - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.multiply(data, 0, a.data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure divide(final double a) { - final DerivativeStructure ds = new DerivativeStructure(this); - for (int i = 0; i < ds.data.length; ++i) { - ds.data[i] /= a; - } - return ds; - } - - /** {@inheritDoc} - * @exception DimensionMismatchException if number of free parameters - * or orders do not match - */ - @Override - public DerivativeStructure divide(final DerivativeStructure a) - throws DimensionMismatchException { - compiler.checkCompatibility(a.compiler); - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.divide(data, 0, a.data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} */ - @Override - public DerivativeStructure remainder(final double a) { - final DerivativeStructure ds = new DerivativeStructure(this); - ds.data[0] = FastMath.IEEEremainder(ds.data[0], a); - return ds; - } - - /** {@inheritDoc} - * @exception DimensionMismatchException if number of free parameters - * or orders do not match - * @since 3.2 - */ - @Override - public DerivativeStructure remainder(final DerivativeStructure a) - throws DimensionMismatchException { - compiler.checkCompatibility(a.compiler); - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.remainder(data, 0, a.data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} */ - @Override - public DerivativeStructure negate() { - final DerivativeStructure ds = new DerivativeStructure(compiler); - for (int i = 0; i < ds.data.length; ++i) { - ds.data[i] = -data[i]; - } - return ds; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure abs() { - if (Double.doubleToLongBits(data[0]) < 0) { - // we use the bits representation to also handle -0.0 - return negate(); - } else { - return this; - } - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure ceil() { - return new DerivativeStructure(compiler.getFreeParameters(), - compiler.getOrder(), - FastMath.ceil(data[0])); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure floor() { - return new DerivativeStructure(compiler.getFreeParameters(), - compiler.getOrder(), - FastMath.floor(data[0])); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure rint() { - return new DerivativeStructure(compiler.getFreeParameters(), - compiler.getOrder(), - FastMath.rint(data[0])); - } - - /** {@inheritDoc} */ - @Override - public long round() { - return FastMath.round(data[0]); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure signum() { - return new DerivativeStructure(compiler.getFreeParameters(), - compiler.getOrder(), - FastMath.signum(data[0])); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure copySign(final DerivativeStructure sign){ - long m = Double.doubleToLongBits(data[0]); - long s = Double.doubleToLongBits(sign.data[0]); - if ((m >= 0 && s >= 0) || (m < 0 && s < 0)) { // Sign is currently OK - return this; - } - return negate(); // flip sign - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure copySign(final double sign) { - long m = Double.doubleToLongBits(data[0]); - long s = Double.doubleToLongBits(sign); - if ((m >= 0 && s >= 0) || (m < 0 && s < 0)) { // Sign is currently OK - return this; - } - return negate(); // flip sign - } - - /** - * Return the exponent of the instance value, removing the bias. - *

- * For double numbers of the form 2x, the unbiased - * exponent is exactly x. - *

- * @return exponent for instance in IEEE754 representation, without bias - */ - public int getExponent() { - return FastMath.getExponent(data[0]); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure scalb(final int n) { - final DerivativeStructure ds = new DerivativeStructure(compiler); - for (int i = 0; i < ds.data.length; ++i) { - ds.data[i] = FastMath.scalb(data[i], n); - } - return ds; - } - - /** {@inheritDoc} - * @exception DimensionMismatchException if number of free parameters - * or orders do not match - * @since 3.2 - */ - @Override - public DerivativeStructure hypot(final DerivativeStructure y) - throws DimensionMismatchException { - - compiler.checkCompatibility(y.compiler); - - if (Double.isInfinite(data[0]) || Double.isInfinite(y.data[0])) { - return new DerivativeStructure(compiler.getFreeParameters(), - compiler.getFreeParameters(), - Double.POSITIVE_INFINITY); - } else if (Double.isNaN(data[0]) || Double.isNaN(y.data[0])) { - return new DerivativeStructure(compiler.getFreeParameters(), - compiler.getFreeParameters(), - Double.NaN); - } else { - - final int expX = getExponent(); - final int expY = y.getExponent(); - if (expX > expY + 27) { - // y is neglectible with respect to x - return abs(); - } else if (expY > expX + 27) { - // x is neglectible with respect to y - return y.abs(); - } else { - - // find an intermediate scale to avoid both overflow and underflow - final int middleExp = (expX + expY) / 2; - - // scale parameters without losing precision - final DerivativeStructure scaledX = scalb(-middleExp); - final DerivativeStructure scaledY = y.scalb(-middleExp); - - // compute scaled hypotenuse - final DerivativeStructure scaledH = - scaledX.multiply(scaledX).add(scaledY.multiply(scaledY)).sqrt(); - - // remove scaling - return scaledH.scalb(middleExp); - - } - - } - } - - /** - * Returns the hypotenuse of a triangle with sides {@code x} and {@code y} - * - sqrt(x2 +y2) - * avoiding intermediate overflow or underflow. - * - *
    - *
  • If either argument is infinite, then the result is positive infinity.
  • - *
  • else, if either argument is NaN then the result is NaN.
  • - *
- * - * @param x a value - * @param y a value - * @return sqrt(x2 +y2) - * @exception DimensionMismatchException if number of free parameters - * or orders do not match - * @since 3.2 - */ - public static DerivativeStructure hypot(final DerivativeStructure x, final DerivativeStructure y) - throws DimensionMismatchException { - return x.hypot(y); - } - - /** Compute composition of the instance by a univariate function. - * @param f array of value and derivatives of the function at - * the current point (i.e. [f({@link #getValue()}), - * f'({@link #getValue()}), f''({@link #getValue()})...]). - * @return f(this) - * @exception DimensionMismatchException if the number of derivatives - * in the array is not equal to {@link #getOrder() order} + 1 - */ - public DerivativeStructure compose(final double ... f) - throws DimensionMismatchException { - if (f.length != getOrder() + 1) { - throw new DimensionMismatchException(f.length, getOrder() + 1); - } - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.compose(data, 0, f, result.data, 0); - return result; - } - - /** {@inheritDoc} */ - @Override - public DerivativeStructure reciprocal() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.pow(data, 0, -1, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure sqrt() { - return rootN(2); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure cbrt() { - return rootN(3); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure rootN(final int n) { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.rootN(data, 0, n, result.data, 0); - return result; - } - - /** {@inheritDoc} */ - @Override - public Field getField() { - return new Field() { - - /** {@inheritDoc} */ - @Override - public DerivativeStructure getZero() { - return new DerivativeStructure(compiler.getFreeParameters(), compiler.getOrder(), 0.0); - } - - /** {@inheritDoc} */ - @Override - public DerivativeStructure getOne() { - return new DerivativeStructure(compiler.getFreeParameters(), compiler.getOrder(), 1.0); - } - - /** {@inheritDoc} */ - @Override - public Class> getRuntimeClass() { - return DerivativeStructure.class; - } - - }; - } - - /** Compute ax where a is a double and x a {@link DerivativeStructure} - * @param a number to exponentiate - * @param x power to apply - * @return ax - * @since 3.3 - */ - public static DerivativeStructure pow(final double a, final DerivativeStructure x) { - final DerivativeStructure result = new DerivativeStructure(x.compiler); - x.compiler.pow(a, x.data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure pow(final double p) { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.pow(data, 0, p, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure pow(final int n) { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.pow(data, 0, n, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @exception DimensionMismatchException if number of free parameters - * or orders do not match - * @since 3.2 - */ - @Override - public DerivativeStructure pow(final DerivativeStructure e) - throws DimensionMismatchException { - compiler.checkCompatibility(e.compiler); - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.pow(data, 0, e.data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure exp() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.exp(data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure expm1() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.expm1(data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure log() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.log(data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure log1p() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.log1p(data, 0, result.data, 0); - return result; - } - - /** Base 10 logarithm. - * @return base 10 logarithm of the instance - */ - @Override - public DerivativeStructure log10() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.log10(data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure cos() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.cos(data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure sin() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.sin(data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure tan() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.tan(data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure acos() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.acos(data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure asin() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.asin(data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure atan() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.atan(data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure atan2(final DerivativeStructure x) - throws DimensionMismatchException { - compiler.checkCompatibility(x.compiler); - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.atan2(data, 0, x.data, 0, result.data, 0); - return result; - } - - /** Two arguments arc tangent operation. - * @param y first argument of the arc tangent - * @param x second argument of the arc tangent - * @return atan2(y, x) - * @exception DimensionMismatchException if number of free parameters - * or orders do not match - * @since 3.2 - */ - public static DerivativeStructure atan2(final DerivativeStructure y, final DerivativeStructure x) - throws DimensionMismatchException { - return y.atan2(x); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure cosh() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.cosh(data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure sinh() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.sinh(data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure tanh() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.tanh(data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure acosh() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.acosh(data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure asinh() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.asinh(data, 0, result.data, 0); - return result; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public DerivativeStructure atanh() { - final DerivativeStructure result = new DerivativeStructure(compiler); - compiler.atanh(data, 0, result.data, 0); - return result; - } - - /** Convert radians to degrees, with error of less than 0.5 ULP - * @return instance converted into degrees - */ - public DerivativeStructure toDegrees() { - final DerivativeStructure ds = new DerivativeStructure(compiler); - for (int i = 0; i < ds.data.length; ++i) { - ds.data[i] = FastMath.toDegrees(data[i]); - } - return ds; - } - - /** Convert degrees to radians, with error of less than 0.5 ULP - * @return instance converted into radians - */ - public DerivativeStructure toRadians() { - final DerivativeStructure ds = new DerivativeStructure(compiler); - for (int i = 0; i < ds.data.length; ++i) { - ds.data[i] = FastMath.toRadians(data[i]); - } - return ds; - } - - /** Evaluate Taylor expansion a derivative structure. - * @param delta parameters offsets (Δx, Δy, ...) - * @return value of the Taylor expansion at x + Δx, y + Δy, ... - * @throws MathArithmeticException if factorials becomes too large - */ - public double taylor(final double ... delta) throws MathArithmeticException { - return compiler.taylor(data, 0, delta); - } - - /** {@inheritDoc} - * @exception DimensionMismatchException if number of free parameters - * or orders do not match - * @since 3.2 - */ - @Override - public DerivativeStructure linearCombination(final DerivativeStructure[] a, final DerivativeStructure[] b) - throws DimensionMismatchException { - - // compute an accurate value, taking care of cancellations - final double[] aDouble = new double[a.length]; - for (int i = 0; i < a.length; ++i) { - aDouble[i] = a[i].getValue(); - } - final double[] bDouble = new double[b.length]; - for (int i = 0; i < b.length; ++i) { - bDouble[i] = b[i].getValue(); - } - final double accurateValue = LinearCombination.value(aDouble, bDouble); - - // compute a simple value, with all partial derivatives - DerivativeStructure simpleValue = a[0].getField().getZero(); - for (int i = 0; i < a.length; ++i) { - simpleValue = simpleValue.add(a[i].multiply(b[i])); - } - - // create a result with accurate value and all derivatives (not necessarily as accurate as the value) - final double[] all = simpleValue.getAllDerivatives(); - all[0] = accurateValue; - return new DerivativeStructure(simpleValue.getFreeParameters(), simpleValue.getOrder(), all); - - } - - /** {@inheritDoc} - * @exception DimensionMismatchException if number of free parameters - * or orders do not match - * @since 3.2 - */ - @Override - public DerivativeStructure linearCombination(final double[] a, final DerivativeStructure[] b) - throws DimensionMismatchException { - - // compute an accurate value, taking care of cancellations - final double[] bDouble = new double[b.length]; - for (int i = 0; i < b.length; ++i) { - bDouble[i] = b[i].getValue(); - } - final double accurateValue = LinearCombination.value(a, bDouble); - - // compute a simple value, with all partial derivatives - DerivativeStructure simpleValue = b[0].getField().getZero(); - for (int i = 0; i < a.length; ++i) { - simpleValue = simpleValue.add(b[i].multiply(a[i])); - } - - // create a result with accurate value and all derivatives (not necessarily as accurate as the value) - final double[] all = simpleValue.getAllDerivatives(); - all[0] = accurateValue; - return new DerivativeStructure(simpleValue.getFreeParameters(), simpleValue.getOrder(), all); - - } - - /** {@inheritDoc} - * @exception DimensionMismatchException if number of free parameters - * or orders do not match - * @since 3.2 - */ - @Override - public DerivativeStructure linearCombination(final DerivativeStructure a1, final DerivativeStructure b1, - final DerivativeStructure a2, final DerivativeStructure b2) - throws DimensionMismatchException { - - // compute an accurate value, taking care of cancellations - final double accurateValue = LinearCombination.value(a1.getValue(), b1.getValue(), - a2.getValue(), b2.getValue()); - - // compute a simple value, with all partial derivatives - final DerivativeStructure simpleValue = a1.multiply(b1).add(a2.multiply(b2)); - - // create a result with accurate value and all derivatives (not necessarily as accurate as the value) - final double[] all = simpleValue.getAllDerivatives(); - all[0] = accurateValue; - return new DerivativeStructure(getFreeParameters(), getOrder(), all); - - } - - /** {@inheritDoc} - * @exception DimensionMismatchException if number of free parameters - * or orders do not match - * @since 3.2 - */ - @Override - public DerivativeStructure linearCombination(final double a1, final DerivativeStructure b1, - final double a2, final DerivativeStructure b2) - throws DimensionMismatchException { - - // compute an accurate value, taking care of cancellations - final double accurateValue = LinearCombination.value(a1, b1.getValue(), - a2, b2.getValue()); - - // compute a simple value, with all partial derivatives - final DerivativeStructure simpleValue = b1.multiply(a1).add(b2.multiply(a2)); - - // create a result with accurate value and all derivatives (not necessarily as accurate as the value) - final double[] all = simpleValue.getAllDerivatives(); - all[0] = accurateValue; - return new DerivativeStructure(getFreeParameters(), getOrder(), all); - - } - - /** {@inheritDoc} - * @exception DimensionMismatchException if number of free parameters - * or orders do not match - * @since 3.2 - */ - @Override - public DerivativeStructure linearCombination(final DerivativeStructure a1, final DerivativeStructure b1, - final DerivativeStructure a2, final DerivativeStructure b2, - final DerivativeStructure a3, final DerivativeStructure b3) - throws DimensionMismatchException { - - // compute an accurate value, taking care of cancellations - final double accurateValue = LinearCombination.value(a1.getValue(), b1.getValue(), - a2.getValue(), b2.getValue(), - a3.getValue(), b3.getValue()); - - // compute a simple value, with all partial derivatives - final DerivativeStructure simpleValue = a1.multiply(b1).add(a2.multiply(b2)).add(a3.multiply(b3)); - - // create a result with accurate value and all derivatives (not necessarily as accurate as the value) - final double[] all = simpleValue.getAllDerivatives(); - all[0] = accurateValue; - return new DerivativeStructure(getFreeParameters(), getOrder(), all); - - } - - /** {@inheritDoc} - * @exception DimensionMismatchException if number of free parameters - * or orders do not match - * @since 3.2 - */ - @Override - public DerivativeStructure linearCombination(final double a1, final DerivativeStructure b1, - final double a2, final DerivativeStructure b2, - final double a3, final DerivativeStructure b3) - throws DimensionMismatchException { - - // compute an accurate value, taking care of cancellations - final double accurateValue = LinearCombination.value(a1, b1.getValue(), - a2, b2.getValue(), - a3, b3.getValue()); - - // compute a simple value, with all partial derivatives - final DerivativeStructure simpleValue = b1.multiply(a1).add(b2.multiply(a2)).add(b3.multiply(a3)); - - // create a result with accurate value and all derivatives (not necessarily as accurate as the value) - final double[] all = simpleValue.getAllDerivatives(); - all[0] = accurateValue; - return new DerivativeStructure(getFreeParameters(), getOrder(), all); - - } - - /** {@inheritDoc} - * @exception DimensionMismatchException if number of free parameters - * or orders do not match - * @since 3.2 - */ - @Override - public DerivativeStructure linearCombination(final DerivativeStructure a1, final DerivativeStructure b1, - final DerivativeStructure a2, final DerivativeStructure b2, - final DerivativeStructure a3, final DerivativeStructure b3, - final DerivativeStructure a4, final DerivativeStructure b4) - throws DimensionMismatchException { - - // compute an accurate value, taking care of cancellations - final double accurateValue = LinearCombination.value(a1.getValue(), b1.getValue(), - a2.getValue(), b2.getValue(), - a3.getValue(), b3.getValue(), - a4.getValue(), b4.getValue()); - - // compute a simple value, with all partial derivatives - final DerivativeStructure simpleValue = a1.multiply(b1).add(a2.multiply(b2)).add(a3.multiply(b3)).add(a4.multiply(b4)); - - // create a result with accurate value and all derivatives (not necessarily as accurate as the value) - final double[] all = simpleValue.getAllDerivatives(); - all[0] = accurateValue; - return new DerivativeStructure(getFreeParameters(), getOrder(), all); - - } - - /** {@inheritDoc} - * @exception DimensionMismatchException if number of free parameters - * or orders do not match - * @since 3.2 - */ - @Override - public DerivativeStructure linearCombination(final double a1, final DerivativeStructure b1, - final double a2, final DerivativeStructure b2, - final double a3, final DerivativeStructure b3, - final double a4, final DerivativeStructure b4) - throws DimensionMismatchException { - - // compute an accurate value, taking care of cancellations - final double accurateValue = LinearCombination.value(a1, b1.getValue(), - a2, b2.getValue(), - a3, b3.getValue(), - a4, b4.getValue()); - - // compute a simple value, with all partial derivatives - final DerivativeStructure simpleValue = b1.multiply(a1).add(b2.multiply(a2)).add(b3.multiply(a3)).add(b4.multiply(a4)); - - // create a result with accurate value and all derivatives (not necessarily as accurate as the value) - final double[] all = simpleValue.getAllDerivatives(); - all[0] = accurateValue; - return new DerivativeStructure(getFreeParameters(), getOrder(), all); - - } - - /** - * Test for the equality of two derivative structures. - *

- * Derivative structures are considered equal if they have the same number - * of free parameters, the same derivation order, and the same derivatives. - *

- * @param other Object to test for equality to this - * @return true if two derivative structures are equal - * @since 3.2 - */ - @Override - public boolean equals(Object other) { - - if (this == other) { - return true; - } - - if (other instanceof DerivativeStructure) { - final DerivativeStructure rhs = (DerivativeStructure)other; - return (getFreeParameters() == rhs.getFreeParameters()) && - (getOrder() == rhs.getOrder()) && - MathArrays.equals(data, rhs.data); - } - - return false; - - } - - /** - * Get a hashCode for the derivative structure. - * @return a hash code value for this object - * @since 3.2 - */ - @Override - public int hashCode() { - return 227 + 229 * getFreeParameters() + 233 * getOrder() + 239 * MathUtils.hash(data); - } - - /** - * Replace the instance with a data transfer object for serialization. - * @return data transfer object that will be serialized - */ - private Object writeReplace() { - return new DataTransferObject(compiler.getFreeParameters(), compiler.getOrder(), data); - } - - /** Internal class used only for serialization. */ - private static class DataTransferObject implements Serializable { - - /** Serializable UID. */ - private static final long serialVersionUID = 20120730L; - - /** Number of variables. - * @serial - */ - private final int variables; - - /** Derivation order. - * @serial - */ - private final int order; - - /** Partial derivatives. - * @serial - */ - private final double[] data; - - /** Simple constructor. - * @param variables number of variables - * @param order derivation order - * @param data partial derivatives - */ - DataTransferObject(final int variables, final int order, final double[] data) { - this.variables = variables; - this.order = order; - this.data = data; - } - - /** Replace the deserialized data transfer object with a {@link DerivativeStructure}. - * @return replacement {@link DerivativeStructure} - */ - private Object readResolve() { - return new DerivativeStructure(variables, order, data); - } - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/FiniteDifferencesDifferentiator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/FiniteDifferencesDifferentiator.java deleted file mode 100644 index 3dfc80537..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/FiniteDifferencesDifferentiator.java +++ /dev/null @@ -1,393 +0,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. - */ -package org.apache.commons.math4.analysis.differentiation; - -import java.io.Serializable; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.analysis.UnivariateMatrixFunction; -import org.apache.commons.math4.analysis.UnivariateVectorFunction; -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.util.FastMath; - -/** Univariate functions differentiator using finite differences. - *

- * This class creates some wrapper objects around regular - * {@link UnivariateFunction univariate functions} (or {@link - * UnivariateVectorFunction univariate vector functions} or {@link - * UnivariateMatrixFunction univariate matrix functions}). These - * wrapper objects compute derivatives in addition to function - * values. - *

- *

- * The wrapper objects work by calling the underlying function on - * a sampling grid around the current point and performing polynomial - * interpolation. A finite differences scheme with n points is - * theoretically able to compute derivatives up to order n-1, but - * it is generally better to have a slight margin. The step size must - * also be small enough in order for the polynomial approximation to - * be good in the current point neighborhood, but it should not be too - * small because numerical instability appears quickly (there are several - * differences of close points). Choosing the number of points and - * the step size is highly problem dependent. - *

- *

- * As an example of good and bad settings, lets consider the quintic - * polynomial function {@code f(x) = (x-1)*(x-0.5)*x*(x+0.5)*(x+1)}. - * Since it is a polynomial, finite differences with at least 6 points - * should theoretically recover the exact same polynomial and hence - * compute accurate derivatives for any order. However, due to numerical - * errors, we get the following results for a 7 points finite differences - * for abscissae in the [-10, 10] range: - *

    - *
  • step size = 0.25, second order derivative error about 9.97e-10
  • - *
  • step size = 0.25, fourth order derivative error about 5.43e-8
  • - *
  • step size = 1.0e-6, second order derivative error about 148
  • - *
  • step size = 1.0e-6, fourth order derivative error about 6.35e+14
  • - *
- *

- * This example shows that the small step size is really bad, even simply - * for second order derivative!

- * - * @since 3.1 - */ -public class FiniteDifferencesDifferentiator - implements UnivariateFunctionDifferentiator, UnivariateVectorFunctionDifferentiator, - UnivariateMatrixFunctionDifferentiator, Serializable { - - /** Serializable UID. */ - private static final long serialVersionUID = 20120917L; - - /** Number of points to use. */ - private final int nbPoints; - - /** Step size. */ - private final double stepSize; - - /** Half sample span. */ - private final double halfSampleSpan; - - /** Lower bound for independent variable. */ - private final double tMin; - - /** Upper bound for independent variable. */ - private final double tMax; - - /** - * Build a differentiator with number of points and step size when independent variable is unbounded. - *

- * Beware that wrong settings for the finite differences differentiator - * can lead to highly unstable and inaccurate results, especially for - * high derivation orders. Using very small step sizes is often a - * bad idea. - *

- * @param nbPoints number of points to use - * @param stepSize step size (gap between each point) - * @exception NotPositiveException if {@code stepsize <= 0} (note that - * {@link NotPositiveException} extends {@link NumberIsTooSmallException}) - * @exception NumberIsTooSmallException {@code nbPoint <= 1} - */ - public FiniteDifferencesDifferentiator(final int nbPoints, final double stepSize) - throws NotPositiveException, NumberIsTooSmallException { - this(nbPoints, stepSize, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); - } - - /** - * Build a differentiator with number of points and step size when independent variable is bounded. - *

- * When the independent variable is bounded (tLower < t < tUpper), the sampling - * points used for differentiation will be adapted to ensure the constraint holds - * even near the boundaries. This means the sample will not be centered anymore in - * these cases. At an extreme case, computing derivatives exactly at the lower bound - * will lead the sample to be entirely on the right side of the derivation point. - *

- *

- * Note that the boundaries are considered to be excluded for function evaluation. - *

- *

- * Beware that wrong settings for the finite differences differentiator - * can lead to highly unstable and inaccurate results, especially for - * high derivation orders. Using very small step sizes is often a - * bad idea. - *

- * @param nbPoints number of points to use - * @param stepSize step size (gap between each point) - * @param tLower lower bound for independent variable (may be {@code Double.NEGATIVE_INFINITY} - * if there are no lower bounds) - * @param tUpper upper bound for independent variable (may be {@code Double.POSITIVE_INFINITY} - * if there are no upper bounds) - * @exception NotPositiveException if {@code stepsize <= 0} (note that - * {@link NotPositiveException} extends {@link NumberIsTooSmallException}) - * @exception NumberIsTooSmallException {@code nbPoint <= 1} - * @exception NumberIsTooLargeException {@code stepSize * (nbPoints - 1) >= tUpper - tLower} - */ - public FiniteDifferencesDifferentiator(final int nbPoints, final double stepSize, - final double tLower, final double tUpper) - throws NotPositiveException, NumberIsTooSmallException, NumberIsTooLargeException { - - if (nbPoints <= 1) { - throw new NumberIsTooSmallException(stepSize, 1, false); - } - this.nbPoints = nbPoints; - - if (stepSize <= 0) { - throw new NotPositiveException(stepSize); - } - this.stepSize = stepSize; - - halfSampleSpan = 0.5 * stepSize * (nbPoints - 1); - if (2 * halfSampleSpan >= tUpper - tLower) { - throw new NumberIsTooLargeException(2 * halfSampleSpan, tUpper - tLower, false); - } - final double safety = FastMath.ulp(halfSampleSpan); - this.tMin = tLower + halfSampleSpan + safety; - this.tMax = tUpper - halfSampleSpan - safety; - - } - - /** - * Get the number of points to use. - * @return number of points to use - */ - public int getNbPoints() { - return nbPoints; - } - - /** - * Get the step size. - * @return step size - */ - public double getStepSize() { - return stepSize; - } - - /** - * Evaluate derivatives from a sample. - *

- * Evaluation is done using divided differences. - *

- * @param t evaluation abscissa value and derivatives - * @param t0 first sample point abscissa - * @param y function values sample {@code y[i] = f(t[i]) = f(t0 + i * stepSize)} - * @return value and derivatives at {@code t} - * @exception NumberIsTooLargeException if the requested derivation order - * is larger or equal to the number of points - */ - private DerivativeStructure evaluate(final DerivativeStructure t, final double t0, - final double[] y) - throws NumberIsTooLargeException { - - // create divided differences diagonal arrays - final double[] top = new double[nbPoints]; - final double[] bottom = new double[nbPoints]; - - for (int i = 0; i < nbPoints; ++i) { - - // update the bottom diagonal of the divided differences array - bottom[i] = y[i]; - for (int j = 1; j <= i; ++j) { - bottom[i - j] = (bottom[i - j + 1] - bottom[i - j]) / (j * stepSize); - } - - // update the top diagonal of the divided differences array - top[i] = bottom[0]; - - } - - // evaluate interpolation polynomial (represented by top diagonal) at t - final int order = t.getOrder(); - final int parameters = t.getFreeParameters(); - final double[] derivatives = t.getAllDerivatives(); - final double dt0 = t.getValue() - t0; - DerivativeStructure interpolation = new DerivativeStructure(parameters, order, 0.0); - DerivativeStructure monomial = null; - for (int i = 0; i < nbPoints; ++i) { - if (i == 0) { - // start with monomial(t) = 1 - monomial = new DerivativeStructure(parameters, order, 1.0); - } else { - // monomial(t) = (t - t0) * (t - t1) * ... * (t - t(i-1)) - derivatives[0] = dt0 - (i - 1) * stepSize; - final DerivativeStructure deltaX = new DerivativeStructure(parameters, order, derivatives); - monomial = monomial.multiply(deltaX); - } - interpolation = interpolation.add(monomial.multiply(top[i])); - } - - return interpolation; - - } - - /** {@inheritDoc} - *

The returned object cannot compute derivatives to arbitrary orders. The - * value function will throw a {@link NumberIsTooLargeException} if the requested - * derivation order is larger or equal to the number of points. - *

- */ - @Override - public UnivariateDifferentiableFunction differentiate(final UnivariateFunction function) { - return new UnivariateDifferentiableFunction() { - - /** {@inheritDoc} */ - @Override - public double value(final double x) throws MathIllegalArgumentException { - return function.value(x); - } - - /** {@inheritDoc} */ - @Override - public DerivativeStructure value(final DerivativeStructure t) - throws MathIllegalArgumentException { - - // check we can achieve the requested derivation order with the sample - if (t.getOrder() >= nbPoints) { - throw new NumberIsTooLargeException(t.getOrder(), nbPoints, false); - } - - // compute sample position, trying to be centered if possible - final double t0 = FastMath.max(FastMath.min(t.getValue(), tMax), tMin) - halfSampleSpan; - - // compute sample points - final double[] y = new double[nbPoints]; - for (int i = 0; i < nbPoints; ++i) { - y[i] = function.value(t0 + i * stepSize); - } - - // evaluate derivatives - return evaluate(t, t0, y); - - } - - }; - } - - /** {@inheritDoc} - *

The returned object cannot compute derivatives to arbitrary orders. The - * value function will throw a {@link NumberIsTooLargeException} if the requested - * derivation order is larger or equal to the number of points. - *

- */ - @Override - public UnivariateDifferentiableVectorFunction differentiate(final UnivariateVectorFunction function) { - return new UnivariateDifferentiableVectorFunction() { - - /** {@inheritDoc} */ - @Override - public double[]value(final double x) throws MathIllegalArgumentException { - return function.value(x); - } - - /** {@inheritDoc} */ - @Override - public DerivativeStructure[] value(final DerivativeStructure t) - throws MathIllegalArgumentException { - - // check we can achieve the requested derivation order with the sample - if (t.getOrder() >= nbPoints) { - throw new NumberIsTooLargeException(t.getOrder(), nbPoints, false); - } - - // compute sample position, trying to be centered if possible - final double t0 = FastMath.max(FastMath.min(t.getValue(), tMax), tMin) - halfSampleSpan; - - // compute sample points - double[][] y = null; - for (int i = 0; i < nbPoints; ++i) { - final double[] v = function.value(t0 + i * stepSize); - if (i == 0) { - y = new double[v.length][nbPoints]; - } - for (int j = 0; j < v.length; ++j) { - y[j][i] = v[j]; - } - } - - // evaluate derivatives - final DerivativeStructure[] value = new DerivativeStructure[y.length]; - for (int j = 0; j < value.length; ++j) { - value[j] = evaluate(t, t0, y[j]); - } - - return value; - - } - - }; - } - - /** {@inheritDoc} - *

The returned object cannot compute derivatives to arbitrary orders. The - * value function will throw a {@link NumberIsTooLargeException} if the requested - * derivation order is larger or equal to the number of points. - *

- */ - @Override - public UnivariateDifferentiableMatrixFunction differentiate(final UnivariateMatrixFunction function) { - return new UnivariateDifferentiableMatrixFunction() { - - /** {@inheritDoc} */ - @Override - public double[][] value(final double x) throws MathIllegalArgumentException { - return function.value(x); - } - - /** {@inheritDoc} */ - @Override - public DerivativeStructure[][] value(final DerivativeStructure t) - throws MathIllegalArgumentException { - - // check we can achieve the requested derivation order with the sample - if (t.getOrder() >= nbPoints) { - throw new NumberIsTooLargeException(t.getOrder(), nbPoints, false); - } - - // compute sample position, trying to be centered if possible - final double t0 = FastMath.max(FastMath.min(t.getValue(), tMax), tMin) - halfSampleSpan; - - // compute sample points - double[][][] y = null; - for (int i = 0; i < nbPoints; ++i) { - final double[][] v = function.value(t0 + i * stepSize); - if (i == 0) { - y = new double[v.length][v[0].length][nbPoints]; - } - for (int j = 0; j < v.length; ++j) { - for (int k = 0; k < v[j].length; ++k) { - y[j][k][i] = v[j][k]; - } - } - } - - // evaluate derivatives - final DerivativeStructure[][] value = new DerivativeStructure[y.length][y[0].length]; - for (int j = 0; j < value.length; ++j) { - for (int k = 0; k < y[j].length; ++k) { - value[j][k] = evaluate(t, t0, y[j][k]); - } - } - - return value; - - } - - }; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/GradientFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/GradientFunction.java deleted file mode 100644 index 665a1f834..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/GradientFunction.java +++ /dev/null @@ -1,66 +0,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. - */ -package org.apache.commons.math4.analysis.differentiation; - -import org.apache.commons.math4.analysis.MultivariateVectorFunction; - -/** Class representing the gradient of a multivariate function. - *

- * The vectorial components of the function represent the derivatives - * with respect to each function parameters. - *

- * @since 3.1 - */ -public class GradientFunction implements MultivariateVectorFunction { - - /** Underlying real-valued function. */ - private final MultivariateDifferentiableFunction f; - - /** Simple constructor. - * @param f underlying real-valued function - */ - public GradientFunction(final MultivariateDifferentiableFunction f) { - this.f = f; - } - - /** {@inheritDoc} */ - @Override - public double[] value(double[] point) { - - // set up parameters - final DerivativeStructure[] dsX = new DerivativeStructure[point.length]; - for (int i = 0; i < point.length; ++i) { - dsX[i] = new DerivativeStructure(point.length, 1, i, point[i]); - } - - // compute the derivatives - final DerivativeStructure dsY = f.value(dsX); - - // extract the gradient - final double[] y = new double[point.length]; - final int[] orders = new int[point.length]; - for (int i = 0; i < point.length; ++i) { - orders[i] = 1; - y[i] = dsY.getPartialDerivative(orders); - orders[i] = 0; - } - - return y; - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/JacobianFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/JacobianFunction.java deleted file mode 100644 index 16e338c4b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/JacobianFunction.java +++ /dev/null @@ -1,70 +0,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. - */ -package org.apache.commons.math4.analysis.differentiation; - -import org.apache.commons.math4.analysis.MultivariateMatrixFunction; - -/** Class representing the Jacobian of a multivariate vector function. - *

- * The rows iterate on the model functions while the columns iterate on the parameters; thus, - * the numbers of rows is equal to the dimension of the underlying function vector - * value and the number of columns is equal to the number of free parameters of - * the underlying function. - *

- * @since 3.1 - */ -public class JacobianFunction implements MultivariateMatrixFunction { - - /** Underlying vector-valued function. */ - private final MultivariateDifferentiableVectorFunction f; - - /** Simple constructor. - * @param f underlying vector-valued function - */ - public JacobianFunction(final MultivariateDifferentiableVectorFunction f) { - this.f = f; - } - - /** {@inheritDoc} */ - @Override - public double[][] value(double[] point) { - - // set up parameters - final DerivativeStructure[] dsX = new DerivativeStructure[point.length]; - for (int i = 0; i < point.length; ++i) { - dsX[i] = new DerivativeStructure(point.length, 1, i, point[i]); - } - - // compute the derivatives - final DerivativeStructure[] dsY = f.value(dsX); - - // extract the Jacobian - final double[][] y = new double[dsY.length][point.length]; - final int[] orders = new int[point.length]; - for (int i = 0; i < dsY.length; ++i) { - for (int j = 0; j < point.length; ++j) { - orders[j] = 1; - y[i][j] = dsY[i].getPartialDerivative(orders); - orders[j] = 0; - } - } - - return y; - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/MultivariateDifferentiableFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/MultivariateDifferentiableFunction.java deleted file mode 100644 index 068e0538f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/MultivariateDifferentiableFunction.java +++ /dev/null @@ -1,42 +0,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. - */ - -package org.apache.commons.math4.analysis.differentiation; - -import org.apache.commons.math4.analysis.MultivariateFunction; -import org.apache.commons.math4.exception.MathIllegalArgumentException; - -/** - * Extension of {@link MultivariateFunction} representing a - * multivariate differentiable real function. - * @since 3.1 - */ -public interface MultivariateDifferentiableFunction extends MultivariateFunction { - - /** - * Compute the value for the function at the given point. - * - * @param point Point at which the function must be evaluated. - * @return the function value for the given point. - * @exception MathIllegalArgumentException if {@code point} does not - * satisfy the function's constraints (wrong dimension, argument out of bound, - * or unsupported derivative order for example) - */ - DerivativeStructure value(DerivativeStructure[] point) - throws MathIllegalArgumentException; - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/MultivariateDifferentiableVectorFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/MultivariateDifferentiableVectorFunction.java deleted file mode 100644 index fe2bd15a8..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/MultivariateDifferentiableVectorFunction.java +++ /dev/null @@ -1,43 +0,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. - */ - -package org.apache.commons.math4.analysis.differentiation; - -import org.apache.commons.math4.analysis.MultivariateVectorFunction; -import org.apache.commons.math4.exception.MathIllegalArgumentException; - - -/** - * Extension of {@link MultivariateVectorFunction} representing a - * multivariate differentiable vectorial function. - * @since 3.1 - */ -public interface MultivariateDifferentiableVectorFunction - extends MultivariateVectorFunction { - - /** - * Compute the value for the function at the given point. - * @param point point at which the function must be evaluated - * @return function value for the given point - * @exception MathIllegalArgumentException if {@code point} does not - * satisfy the function's constraints (wrong dimension, argument out of bound, - * or unsupported derivative order for example) - */ - DerivativeStructure[] value(DerivativeStructure[] point) - throws MathIllegalArgumentException; - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/SparseGradient.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/SparseGradient.java deleted file mode 100644 index 13893cd06..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/SparseGradient.java +++ /dev/null @@ -1,937 +0,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. - */ -package org.apache.commons.math4.analysis.differentiation; - -import java.io.Serializable; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.numbers.arrays.LinearCombination; -import org.apache.commons.numbers.core.Precision; -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; -import org.apache.commons.math4.RealFieldElement; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathUtils; - -/** - * First derivative computation with large number of variables. - *

- * This class plays a similar role to {@link DerivativeStructure}, with - * a focus on efficiency when dealing with large number of independent variables - * and most computation depend only on a few of them, and when only first derivative - * is desired. When these conditions are met, this class should be much faster than - * {@link DerivativeStructure} and use less memory. - *

- * - * @since 3.3 - */ -public class SparseGradient implements RealFieldElement, Serializable { - - /** Serializable UID. */ - private static final long serialVersionUID = 20131025L; - - /** Value of the calculation. */ - private double value; - - /** Stored derivative, each key representing a different independent variable. */ - private final Map derivatives; - - /** Internal constructor. - * @param value value of the function - * @param derivatives derivatives map, a deep copy will be performed, - * so the map given here will remain safe from changes in the new instance, - * may be null to create an empty derivatives map, i.e. a constant value - */ - private SparseGradient(final double value, final Map derivatives) { - this.value = value; - this.derivatives = new HashMap<>(); - if (derivatives != null) { - this.derivatives.putAll(derivatives); - } - } - - /** Internal constructor. - * @param value value of the function - * @param scale scaling factor to apply to all derivatives - * @param derivatives derivatives map, a deep copy will be performed, - * so the map given here will remain safe from changes in the new instance, - * may be null to create an empty derivatives map, i.e. a constant value - */ - private SparseGradient(final double value, final double scale, - final Map derivatives) { - this.value = value; - this.derivatives = new HashMap<>(); - if (derivatives != null) { - for (final Map.Entry entry : derivatives.entrySet()) { - this.derivatives.put(entry.getKey(), scale * entry.getValue()); - } - } - } - - /** Factory method creating a constant. - * @param value value of the constant - * @return a new instance - */ - public static SparseGradient createConstant(final double value) { - return new SparseGradient(value, Collections. emptyMap()); - } - - /** Factory method creating an independent variable. - * @param idx index of the variable - * @param value value of the variable - * @return a new instance - */ - public static SparseGradient createVariable(final int idx, final double value) { - return new SparseGradient(value, Collections.singletonMap(idx, 1.0)); - } - - /** - * Find the number of variables. - * @return number of variables - */ - public int numVars() { - return derivatives.size(); - } - - /** - * Get the derivative with respect to a particular index variable. - * - * @param index index to differentiate with. - * @return derivative with respect to a particular index variable - */ - public double getDerivative(final int index) { - final Double out = derivatives.get(index); - return (out == null) ? 0.0 : out; - } - - /** - * Get the value of the function. - * @return value of the function. - */ - public double getValue() { - return value; - } - - /** {@inheritDoc} */ - @Override - public double getReal() { - return value; - } - - /** {@inheritDoc} */ - @Override - public SparseGradient add(final SparseGradient a) { - final SparseGradient out = new SparseGradient(value + a.value, derivatives); - for (Map.Entry entry : a.derivatives.entrySet()) { - final int id = entry.getKey(); - final Double old = out.derivatives.get(id); - if (old == null) { - out.derivatives.put(id, entry.getValue()); - } else { - out.derivatives.put(id, old + entry.getValue()); - } - } - - return out; - } - - /** - * Add in place. - *

- * This method is designed to be faster when used multiple times in a loop. - *

- *

- * The instance is changed here, in order to not change the - * instance the {@link #add(SparseGradient)} method should - * be used. - *

- * @param a instance to add - */ - public void addInPlace(final SparseGradient a) { - value += a.value; - for (final Map.Entry entry : a.derivatives.entrySet()) { - final int id = entry.getKey(); - final Double old = derivatives.get(id); - if (old == null) { - derivatives.put(id, entry.getValue()); - } else { - derivatives.put(id, old + entry.getValue()); - } - } - } - - /** {@inheritDoc} */ - @Override - public SparseGradient add(final double c) { - final SparseGradient out = new SparseGradient(value + c, derivatives); - return out; - } - - /** {@inheritDoc} */ - @Override - public SparseGradient subtract(final SparseGradient a) { - final SparseGradient out = new SparseGradient(value - a.value, derivatives); - for (Map.Entry entry : a.derivatives.entrySet()) { - final int id = entry.getKey(); - final Double old = out.derivatives.get(id); - if (old == null) { - out.derivatives.put(id, -entry.getValue()); - } else { - out.derivatives.put(id, old - entry.getValue()); - } - } - return out; - } - - /** {@inheritDoc} */ - @Override - public SparseGradient subtract(double c) { - return new SparseGradient(value - c, derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient multiply(final SparseGradient a) { - final SparseGradient out = - new SparseGradient(value * a.value, Collections. emptyMap()); - - // Derivatives. - for (Map.Entry entry : derivatives.entrySet()) { - out.derivatives.put(entry.getKey(), a.value * entry.getValue()); - } - for (Map.Entry entry : a.derivatives.entrySet()) { - final int id = entry.getKey(); - final Double old = out.derivatives.get(id); - if (old == null) { - out.derivatives.put(id, value * entry.getValue()); - } else { - out.derivatives.put(id, old + value * entry.getValue()); - } - } - return out; - } - - /** - * Multiply in place. - *

- * This method is designed to be faster when used multiple times in a loop. - *

- *

- * The instance is changed here, in order to not change the - * instance the {@link #add(SparseGradient)} method should - * be used. - *

- * @param a instance to multiply - */ - public void multiplyInPlace(final SparseGradient a) { - // Derivatives. - for (Map.Entry entry : derivatives.entrySet()) { - derivatives.put(entry.getKey(), a.value * entry.getValue()); - } - for (Map.Entry entry : a.derivatives.entrySet()) { - final int id = entry.getKey(); - final Double old = derivatives.get(id); - if (old == null) { - derivatives.put(id, value * entry.getValue()); - } else { - derivatives.put(id, old + value * entry.getValue()); - } - } - value *= a.value; - } - - /** {@inheritDoc} */ - @Override - public SparseGradient multiply(final double c) { - return new SparseGradient(value * c, c, derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient multiply(final int n) { - return new SparseGradient(value * n, n, derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient divide(final SparseGradient a) { - final SparseGradient out = new SparseGradient(value / a.value, Collections. emptyMap()); - - // Derivatives. - for (Map.Entry entry : derivatives.entrySet()) { - out.derivatives.put(entry.getKey(), entry.getValue() / a.value); - } - for (Map.Entry entry : a.derivatives.entrySet()) { - final int id = entry.getKey(); - final Double old = out.derivatives.get(id); - if (old == null) { - out.derivatives.put(id, -out.value / a.value * entry.getValue()); - } else { - out.derivatives.put(id, old - out.value / a.value * entry.getValue()); - } - } - return out; - } - - /** {@inheritDoc} */ - @Override - public SparseGradient divide(final double c) { - return new SparseGradient(value / c, 1.0 / c, derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient negate() { - return new SparseGradient(-value, -1.0, derivatives); - } - - /** {@inheritDoc} */ - @Override - public Field getField() { - return new Field() { - - /** {@inheritDoc} */ - @Override - public SparseGradient getZero() { - return createConstant(0); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient getOne() { - return createConstant(1); - } - - /** {@inheritDoc} */ - @Override - public Class> getRuntimeClass() { - return SparseGradient.class; - } - - }; - } - - /** {@inheritDoc} */ - @Override - public SparseGradient remainder(final double a) { - return new SparseGradient(FastMath.IEEEremainder(value, a), derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient remainder(final SparseGradient a) { - - // compute k such that lhs % rhs = lhs - k rhs - final double rem = FastMath.IEEEremainder(value, a.value); - final double k = FastMath.rint((value - rem) / a.value); - - return subtract(a.multiply(k)); - - } - - /** {@inheritDoc} */ - @Override - public SparseGradient abs() { - if (Double.doubleToLongBits(value) < 0) { - // we use the bits representation to also handle -0.0 - return negate(); - } else { - return this; - } - } - - /** {@inheritDoc} */ - @Override - public SparseGradient ceil() { - return createConstant(FastMath.ceil(value)); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient floor() { - return createConstant(FastMath.floor(value)); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient rint() { - return createConstant(FastMath.rint(value)); - } - - /** {@inheritDoc} */ - @Override - public long round() { - return FastMath.round(value); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient signum() { - return createConstant(FastMath.signum(value)); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient copySign(final SparseGradient sign) { - final long m = Double.doubleToLongBits(value); - final long s = Double.doubleToLongBits(sign.value); - if ((m >= 0 && s >= 0) || (m < 0 && s < 0)) { // Sign is currently OK - return this; - } - return negate(); // flip sign - } - - /** {@inheritDoc} */ - @Override - public SparseGradient copySign(final double sign) { - final long m = Double.doubleToLongBits(value); - final long s = Double.doubleToLongBits(sign); - if ((m >= 0 && s >= 0) || (m < 0 && s < 0)) { // Sign is currently OK - return this; - } - return negate(); // flip sign - } - - /** {@inheritDoc} */ - @Override - public SparseGradient scalb(final int n) { - final SparseGradient out = new SparseGradient(FastMath.scalb(value, n), Collections. emptyMap()); - for (Map.Entry entry : derivatives.entrySet()) { - out.derivatives.put(entry.getKey(), FastMath.scalb(entry.getValue(), n)); - } - return out; - } - - /** {@inheritDoc} */ - @Override - public SparseGradient hypot(final SparseGradient y) { - if (Double.isInfinite(value) || Double.isInfinite(y.value)) { - return createConstant(Double.POSITIVE_INFINITY); - } else if (Double.isNaN(value) || Double.isNaN(y.value)) { - return createConstant(Double.NaN); - } else { - - final int expX = FastMath.getExponent(value); - final int expY = FastMath.getExponent(y.value); - if (expX > expY + 27) { - // y is negligible with respect to x - return abs(); - } else if (expY > expX + 27) { - // x is negligible with respect to y - return y.abs(); - } else { - - // find an intermediate scale to avoid both overflow and underflow - final int middleExp = (expX + expY) / 2; - - // scale parameters without losing precision - final SparseGradient scaledX = scalb(-middleExp); - final SparseGradient scaledY = y.scalb(-middleExp); - - // compute scaled hypotenuse - final SparseGradient scaledH = - scaledX.multiply(scaledX).add(scaledY.multiply(scaledY)).sqrt(); - - // remove scaling - return scaledH.scalb(middleExp); - - } - - } - } - - /** - * Returns the hypotenuse of a triangle with sides {@code x} and {@code y} - * - sqrt(x2 +y2) - * avoiding intermediate overflow or underflow. - * - *
    - *
  • If either argument is infinite, then the result is positive infinity.
  • - *
  • else, if either argument is NaN then the result is NaN.
  • - *
- * - * @param x a value - * @param y a value - * @return sqrt(x2 +y2) - */ - public static SparseGradient hypot(final SparseGradient x, final SparseGradient y) { - return x.hypot(y); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient reciprocal() { - return new SparseGradient(1.0 / value, -1.0 / (value * value), derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient sqrt() { - final double sqrt = FastMath.sqrt(value); - return new SparseGradient(sqrt, 0.5 / sqrt, derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient cbrt() { - final double cbrt = FastMath.cbrt(value); - return new SparseGradient(cbrt, 1.0 / (3 * cbrt * cbrt), derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient rootN(final int n) { - if (n == 2) { - return sqrt(); - } else if (n == 3) { - return cbrt(); - } else { - final double root = FastMath.pow(value, 1.0 / n); - return new SparseGradient(root, 1.0 / (n * FastMath.pow(root, n - 1)), derivatives); - } - } - - /** {@inheritDoc} */ - @Override - public SparseGradient pow(final double p) { - return new SparseGradient(FastMath.pow(value, p), p * FastMath.pow(value, p - 1), derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient pow(final int n) { - if (n == 0) { - return getField().getOne(); - } else { - final double valueNm1 = FastMath.pow(value, n - 1); - return new SparseGradient(value * valueNm1, n * valueNm1, derivatives); - } - } - - /** {@inheritDoc} */ - @Override - public SparseGradient pow(final SparseGradient e) { - return log().multiply(e).exp(); - } - - /** Compute ax where a is a double and x a {@link SparseGradient} - * @param a number to exponentiate - * @param x power to apply - * @return ax - */ - public static SparseGradient pow(final double a, final SparseGradient x) { - if (a == 0) { - if (x.value == 0) { - return x.compose(1.0, Double.NEGATIVE_INFINITY); - } else if (x.value < 0) { - return x.compose(Double.NaN, Double.NaN); - } else { - return x.getField().getZero(); - } - } else { - final double ax = FastMath.pow(a, x.value); - return new SparseGradient(ax, ax * FastMath.log(a), x.derivatives); - } - } - - /** {@inheritDoc} */ - @Override - public SparseGradient exp() { - final double e = FastMath.exp(value); - return new SparseGradient(e, e, derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient expm1() { - return new SparseGradient(FastMath.expm1(value), FastMath.exp(value), derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient log() { - return new SparseGradient(FastMath.log(value), 1.0 / value, derivatives); - } - - /** Base 10 logarithm. - * @return base 10 logarithm of the instance - */ - @Override - public SparseGradient log10() { - return new SparseGradient(FastMath.log10(value), 1.0 / (FastMath.log(10.0) * value), derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient log1p() { - return new SparseGradient(FastMath.log1p(value), 1.0 / (1.0 + value), derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient cos() { - return new SparseGradient(FastMath.cos(value), -FastMath.sin(value), derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient sin() { - return new SparseGradient(FastMath.sin(value), FastMath.cos(value), derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient tan() { - final double t = FastMath.tan(value); - return new SparseGradient(t, 1 + t * t, derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient acos() { - return new SparseGradient(FastMath.acos(value), -1.0 / FastMath.sqrt(1 - value * value), derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient asin() { - return new SparseGradient(FastMath.asin(value), 1.0 / FastMath.sqrt(1 - value * value), derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient atan() { - return new SparseGradient(FastMath.atan(value), 1.0 / (1 + value * value), derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient atan2(final SparseGradient x) { - - // compute r = sqrt(x^2+y^2) - final SparseGradient r = multiply(this).add(x.multiply(x)).sqrt(); - - final SparseGradient a; - if (x.value >= 0) { - - // compute atan2(y, x) = 2 atan(y / (r + x)) - a = divide(r.add(x)).atan().multiply(2); - - } else { - - // compute atan2(y, x) = +/- pi - 2 atan(y / (r - x)) - final SparseGradient tmp = divide(r.subtract(x)).atan().multiply(-2); - a = tmp.add(tmp.value <= 0 ? -FastMath.PI : FastMath.PI); - - } - - // fix value to take special cases (+0/+0, +0/-0, -0/+0, -0/-0, +/-infinity) correctly - a.value = FastMath.atan2(value, x.value); - - return a; - - } - - /** Two arguments arc tangent operation. - * @param y first argument of the arc tangent - * @param x second argument of the arc tangent - * @return atan2(y, x) - */ - public static SparseGradient atan2(final SparseGradient y, final SparseGradient x) { - return y.atan2(x); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient cosh() { - return new SparseGradient(FastMath.cosh(value), FastMath.sinh(value), derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient sinh() { - return new SparseGradient(FastMath.sinh(value), FastMath.cosh(value), derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient tanh() { - final double t = FastMath.tanh(value); - return new SparseGradient(t, 1 - t * t, derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient acosh() { - return new SparseGradient(FastMath.acosh(value), 1.0 / FastMath.sqrt(value * value - 1.0), derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient asinh() { - return new SparseGradient(FastMath.asinh(value), 1.0 / FastMath.sqrt(value * value + 1.0), derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient atanh() { - return new SparseGradient(FastMath.atanh(value), 1.0 / (1.0 - value * value), derivatives); - } - - /** Convert radians to degrees, with error of less than 0.5 ULP - * @return instance converted into degrees - */ - public SparseGradient toDegrees() { - return new SparseGradient(FastMath.toDegrees(value), FastMath.toDegrees(1.0), derivatives); - } - - /** Convert degrees to radians, with error of less than 0.5 ULP - * @return instance converted into radians - */ - public SparseGradient toRadians() { - return new SparseGradient(FastMath.toRadians(value), FastMath.toRadians(1.0), derivatives); - } - - /** Evaluate Taylor expansion of a sparse gradient. - * @param delta parameters offsets (Δx, Δy, ...) - * @return value of the Taylor expansion at x + Δx, y + Δy, ... - */ - public double taylor(final double ... delta) { - double y = value; - for (int i = 0; i < delta.length; ++i) { - y += delta[i] * getDerivative(i); - } - return y; - } - - /** Compute composition of the instance by a univariate function. - * @param f0 value of the function at (i.e. f({@link #getValue()})) - * @param f1 first derivative of the function at - * the current point (i.e. f'({@link #getValue()})) - * @return f(this) - */ - public SparseGradient compose(final double f0, final double f1) { - return new SparseGradient(f0, f1, derivatives); - } - - /** {@inheritDoc} */ - @Override - public SparseGradient linearCombination(final SparseGradient[] a, - final SparseGradient[] b) - throws DimensionMismatchException { - - // compute a simple value, with all partial derivatives - SparseGradient out = a[0].getField().getZero(); - for (int i = 0; i < a.length; ++i) { - out = out.add(a[i].multiply(b[i])); - } - - // recompute an accurate value, taking care of cancellations - final double[] aDouble = new double[a.length]; - for (int i = 0; i < a.length; ++i) { - aDouble[i] = a[i].getValue(); - } - final double[] bDouble = new double[b.length]; - for (int i = 0; i < b.length; ++i) { - bDouble[i] = b[i].getValue(); - } - out.value = LinearCombination.value(aDouble, bDouble); - - return out; - - } - - /** {@inheritDoc} */ - @Override - public SparseGradient linearCombination(final double[] a, final SparseGradient[] b) { - - // compute a simple value, with all partial derivatives - SparseGradient out = b[0].getField().getZero(); - for (int i = 0; i < a.length; ++i) { - out = out.add(b[i].multiply(a[i])); - } - - // recompute an accurate value, taking care of cancellations - final double[] bDouble = new double[b.length]; - for (int i = 0; i < b.length; ++i) { - bDouble[i] = b[i].getValue(); - } - out.value = LinearCombination.value(a, bDouble); - - return out; - - } - - /** {@inheritDoc} */ - @Override - public SparseGradient linearCombination(final SparseGradient a1, final SparseGradient b1, - final SparseGradient a2, final SparseGradient b2) { - - // compute a simple value, with all partial derivatives - SparseGradient out = a1.multiply(b1).add(a2.multiply(b2)); - - // recompute an accurate value, taking care of cancellations - out.value = LinearCombination.value(a1.value, b1.value, a2.value, b2.value); - - return out; - - } - - /** {@inheritDoc} */ - @Override - public SparseGradient linearCombination(final double a1, final SparseGradient b1, - final double a2, final SparseGradient b2) { - - // compute a simple value, with all partial derivatives - SparseGradient out = b1.multiply(a1).add(b2.multiply(a2)); - - // recompute an accurate value, taking care of cancellations - out.value = LinearCombination.value(a1, b1.value, a2, b2.value); - - return out; - - } - - /** {@inheritDoc} */ - @Override - public SparseGradient linearCombination(final SparseGradient a1, final SparseGradient b1, - final SparseGradient a2, final SparseGradient b2, - final SparseGradient a3, final SparseGradient b3) { - - // compute a simple value, with all partial derivatives - SparseGradient out = a1.multiply(b1).add(a2.multiply(b2)).add(a3.multiply(b3)); - - // recompute an accurate value, taking care of cancellations - out.value = LinearCombination.value(a1.value, b1.value, - a2.value, b2.value, - a3.value, b3.value); - - return out; - - } - - /** {@inheritDoc} */ - @Override - public SparseGradient linearCombination(final double a1, final SparseGradient b1, - final double a2, final SparseGradient b2, - final double a3, final SparseGradient b3) { - - // compute a simple value, with all partial derivatives - SparseGradient out = b1.multiply(a1).add(b2.multiply(a2)).add(b3.multiply(a3)); - - // recompute an accurate value, taking care of cancellations - out.value = LinearCombination.value(a1, b1.value, - a2, b2.value, - a3, b3.value); - - return out; - - } - - /** {@inheritDoc} */ - @Override - public SparseGradient linearCombination(final SparseGradient a1, final SparseGradient b1, - final SparseGradient a2, final SparseGradient b2, - final SparseGradient a3, final SparseGradient b3, - final SparseGradient a4, final SparseGradient b4) { - - // compute a simple value, with all partial derivatives - SparseGradient out = a1.multiply(b1).add(a2.multiply(b2)).add(a3.multiply(b3)).add(a4.multiply(b4)); - - // recompute an accurate value, taking care of cancellations - out.value = LinearCombination.value(a1.value, b1.value, - a2.value, b2.value, - a3.value, b3.value, - a4.value, b4.value); - - return out; - - } - - /** {@inheritDoc} */ - @Override - public SparseGradient linearCombination(final double a1, final SparseGradient b1, - final double a2, final SparseGradient b2, - final double a3, final SparseGradient b3, - final double a4, final SparseGradient b4) { - - // compute a simple value, with all partial derivatives - SparseGradient out = b1.multiply(a1).add(b2.multiply(a2)).add(b3.multiply(a3)).add(b4.multiply(a4)); - - // recompute an accurate value, taking care of cancellations - out.value = LinearCombination.value(a1, b1.value, - a2, b2.value, - a3, b3.value, - a4, b4.value); - - return out; - - } - - /** - * Test for the equality of two sparse gradients. - *

- * Sparse gradients are considered equal if they have the same value - * and the same derivatives. - *

- * @param other Object to test for equality to this - * @return true if two sparse gradients are equal - */ - @Override - public boolean equals(Object other) { - - if (this == other) { - return true; - } - - if (other instanceof SparseGradient) { - final SparseGradient rhs = (SparseGradient)other; - if (!Precision.equals(value, rhs.value, 1)) { - return false; - } - if (derivatives.size() != rhs.derivatives.size()) { - return false; - } - for (final Map.Entry entry : derivatives.entrySet()) { - if (!rhs.derivatives.containsKey(entry.getKey())) { - return false; - } - if (!Precision.equals(entry.getValue(), rhs.derivatives.get(entry.getKey()), 1)) { - return false; - } - } - return true; - } - - return false; - - } - - /** - * Get a hashCode for the derivative structure. - * @return a hash code value for this object - * @since 3.2 - */ - @Override - public int hashCode() { - return 743 + 809 * MathUtils.hash(value) + 167 * derivatives.hashCode(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateDifferentiableFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateDifferentiableFunction.java deleted file mode 100644 index 7e651e634..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateDifferentiableFunction.java +++ /dev/null @@ -1,43 +0,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. - */ -package org.apache.commons.math4.analysis.differentiation; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; - -/** Interface for univariate functions derivatives. - *

This interface represents a simple function which computes - * both the value and the first derivative of a mathematical function. - * The derivative is computed with respect to the input variable.

- * @see UnivariateDifferentiableFunction - * @see UnivariateFunctionDifferentiator - * @since 3.1 - */ -public interface UnivariateDifferentiableFunction extends UnivariateFunction { - - /** Simple mathematical function. - *

{@link UnivariateDifferentiableFunction} classes compute both the - * value and the first derivative of the function.

- * @param t function input value - * @return function result - * @exception DimensionMismatchException if t is inconsistent with the - * function's free parameters or order - */ - DerivativeStructure value(DerivativeStructure t) - throws DimensionMismatchException; - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateDifferentiableMatrixFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateDifferentiableMatrixFunction.java deleted file mode 100644 index 26e5834cc..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateDifferentiableMatrixFunction.java +++ /dev/null @@ -1,40 +0,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. - */ -package org.apache.commons.math4.analysis.differentiation; - -import org.apache.commons.math4.analysis.UnivariateMatrixFunction; -import org.apache.commons.math4.exception.MathIllegalArgumentException; - -/** - * Extension of {@link UnivariateMatrixFunction} representing a univariate differentiable matrix function. - * - * @since 3.1 - */ -public interface UnivariateDifferentiableMatrixFunction - extends UnivariateMatrixFunction { - - /** - * Compute the value for the function. - * @param x the point for which the function value should be computed - * @return the value - * @exception MathIllegalArgumentException if {@code x} does not - * satisfy the function's constraints (argument out of bound, or unsupported - * derivative order for example) - */ - DerivativeStructure[][] value(DerivativeStructure x) throws MathIllegalArgumentException; - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateDifferentiableVectorFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateDifferentiableVectorFunction.java deleted file mode 100644 index c4c2a0f8c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateDifferentiableVectorFunction.java +++ /dev/null @@ -1,40 +0,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. - */ -package org.apache.commons.math4.analysis.differentiation; - -import org.apache.commons.math4.analysis.UnivariateVectorFunction; -import org.apache.commons.math4.exception.MathIllegalArgumentException; - -/** - * Extension of {@link UnivariateVectorFunction} representing a univariate differentiable vectorial function. - * - * @since 3.1 - */ -public interface UnivariateDifferentiableVectorFunction - extends UnivariateVectorFunction { - - /** - * Compute the value for the function. - * @param x the point for which the function value should be computed - * @return the value - * @exception MathIllegalArgumentException if {@code x} does not - * satisfy the function's constraints (argument out of bound, or unsupported - * derivative order for example) - */ - DerivativeStructure[] value(DerivativeStructure x) throws MathIllegalArgumentException; - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateFunctionDifferentiator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateFunctionDifferentiator.java deleted file mode 100644 index b4ec86e2c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateFunctionDifferentiator.java +++ /dev/null @@ -1,33 +0,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. - */ -package org.apache.commons.math4.analysis.differentiation; - -import org.apache.commons.math4.analysis.UnivariateFunction; - -/** Interface defining the function differentiation operation. - * @since 3.1 - */ -public interface UnivariateFunctionDifferentiator { - - /** Create an implementation of a {@link UnivariateDifferentiableFunction - * differential} from a regular {@link UnivariateFunction function}. - * @param function function to differentiate - * @return differential function - */ - UnivariateDifferentiableFunction differentiate(UnivariateFunction function); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateMatrixFunctionDifferentiator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateMatrixFunctionDifferentiator.java deleted file mode 100644 index 2c42ee5d2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateMatrixFunctionDifferentiator.java +++ /dev/null @@ -1,33 +0,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. - */ -package org.apache.commons.math4.analysis.differentiation; - -import org.apache.commons.math4.analysis.UnivariateMatrixFunction; - -/** Interface defining the function differentiation operation. - * @since 3.1 - */ -public interface UnivariateMatrixFunctionDifferentiator { - - /** Create an implementation of a {@link UnivariateDifferentiableMatrixFunction - * differential} from a regular {@link UnivariateMatrixFunction matrix function}. - * @param function function to differentiate - * @return differential function - */ - UnivariateDifferentiableMatrixFunction differentiate(UnivariateMatrixFunction function); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateVectorFunctionDifferentiator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateVectorFunctionDifferentiator.java deleted file mode 100644 index e197525cf..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/UnivariateVectorFunctionDifferentiator.java +++ /dev/null @@ -1,33 +0,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. - */ -package org.apache.commons.math4.analysis.differentiation; - -import org.apache.commons.math4.analysis.UnivariateVectorFunction; - -/** Interface defining the function differentiation operation. - * @since 3.1 - */ -public interface UnivariateVectorFunctionDifferentiator { - - /** Create an implementation of a {@link UnivariateDifferentiableVectorFunction - * differential} from a regular {@link UnivariateVectorFunction vector function}. - * @param function function to differentiate - * @return differential function - */ - UnivariateDifferentiableVectorFunction differentiate(UnivariateVectorFunction function); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/package-info.java deleted file mode 100644 index 6b5f68ccf..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/differentiation/package-info.java +++ /dev/null @@ -1,42 +0,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. - */ -/** - * - *

- * This package holds the main interfaces and basic building block classes - * dealing with differentiation. - * The core class is {@link org.apache.commons.math4.analysis.differentiation.DerivativeStructure - * DerivativeStructure} which holds the value and the differentials of a function. This class - * handles some arbitrary number of free parameters and arbitrary differentiation order. It is used - * both as the input and the output type for the {@link - * org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction - * UnivariateDifferentiableFunction} interface. Any differentiable function should implement this - * interface. - *

- *

- * The {@link org.apache.commons.math4.analysis.differentiation.UnivariateFunctionDifferentiator - * UnivariateFunctionDifferentiator} interface defines a way to differentiate a simple {@link - * org.apache.commons.math4.analysis.UnivariateFunction UnivariateFunction} and get a {@link - * org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction - * UnivariateDifferentiableFunction}. - *

- *

- * Similar interfaces also exist for multivariate functions and for vector or matrix valued functions. - *

- * - */ -package org.apache.commons.math4.analysis.differentiation; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Abs.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Abs.java deleted file mode 100644 index 9f52e5a2a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Abs.java +++ /dev/null @@ -1,34 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Absolute value function. - * - * @since 3.0 - */ -public class Abs implements UnivariateFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.abs(x); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Acos.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Acos.java deleted file mode 100644 index 2d9a3dd12..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Acos.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Arc-cosine function. - * - * @since 3.0 - */ -public class Acos implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.acos(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.acos(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Acosh.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Acosh.java deleted file mode 100644 index 29c325da8..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Acosh.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Hyperbolic arc-cosine function. - * - * @since 3.0 - */ -public class Acosh implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.acosh(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.acosh(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Add.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Add.java deleted file mode 100644 index e66804ca2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Add.java +++ /dev/null @@ -1,33 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.BivariateFunction; - -/** - * Add the two operands. - * - * @since 3.0 - */ -public class Add implements BivariateFunction { - /** {@inheritDoc} */ - @Override - public double value(double x, double y) { - return x + y; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Asin.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Asin.java deleted file mode 100644 index 56c1b93f0..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Asin.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Arc-sine function. - * - * @since 3.0 - */ -public class Asin implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.asin(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.asin(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Asinh.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Asinh.java deleted file mode 100644 index a4e5d3fab..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Asinh.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Hyperbolic arc-sine function. - * - * @since 3.0 - */ -public class Asinh implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.asinh(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.asinh(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Atan.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Atan.java deleted file mode 100644 index 25f8208e0..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Atan.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Arc-tangent function. - * - * @since 3.0 - */ -public class Atan implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.atan(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.atan(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Atan2.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Atan2.java deleted file mode 100644 index 9fef4f193..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Atan2.java +++ /dev/null @@ -1,34 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.BivariateFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Arc-tangent function. - * - * @since 3.0 - */ -public class Atan2 implements BivariateFunction { - /** {@inheritDoc} */ - @Override - public double value(double x, double y) { - return FastMath.atan2(x, y); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Atanh.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Atanh.java deleted file mode 100644 index ea284bda7..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Atanh.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Hyperbolic arc-tangent function. - * - * @since 3.0 - */ -public class Atanh implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.atanh(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.atanh(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Cbrt.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Cbrt.java deleted file mode 100644 index 6d08743d0..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Cbrt.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Cube root function. - * - * @since 3.0 - */ -public class Cbrt implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.cbrt(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.cbrt(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Ceil.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Ceil.java deleted file mode 100644 index 161f73d04..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Ceil.java +++ /dev/null @@ -1,34 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * {@code ceil} function. - * - * @since 3.0 - */ -public class Ceil implements UnivariateFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.ceil(x); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Constant.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Constant.java deleted file mode 100644 index 5b612f5e8..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Constant.java +++ /dev/null @@ -1,53 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; - -/** - * Constant function. - * - * @since 3.0 - */ -public class Constant implements UnivariateDifferentiableFunction { - /** Constant. */ - private final double c; - - /** - * @param c Constant. - */ - public Constant(double c) { - this.c = c; - } - - /** {@inheritDoc} */ - @Override - public double value(double x) { - return c; - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return new DerivativeStructure(t.getFreeParameters(), t.getOrder(), c); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Cos.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Cos.java deleted file mode 100644 index 3f992c24d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Cos.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Cosine function. - * - * @since 3.0 - */ -public class Cos implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.cos(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.cos(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Cosh.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Cosh.java deleted file mode 100644 index 5678612c8..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Cosh.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Hyperbolic cosine function. - * - * @since 3.0 - */ -public class Cosh implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.cosh(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.cosh(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Divide.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Divide.java deleted file mode 100644 index a49769248..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Divide.java +++ /dev/null @@ -1,33 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.BivariateFunction; - -/** - * Divide the first operand by the second. - * - * @since 3.0 - */ -public class Divide implements BivariateFunction { - /** {@inheritDoc} */ - @Override - public double value(double x, double y) { - return x / y; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Exp.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Exp.java deleted file mode 100644 index abee43e57..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Exp.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Exponential function. - * - * @since 3.0 - */ -public class Exp implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.exp(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.exp(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Expm1.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Expm1.java deleted file mode 100644 index aba08f11d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Expm1.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * ex-1 function. - * - * @since 3.0 - */ -public class Expm1 implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.expm1(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.expm1(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Floor.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Floor.java deleted file mode 100644 index 1ecd5d72a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Floor.java +++ /dev/null @@ -1,34 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * {@code floor} function. - * - * @since 3.0 - */ -public class Floor implements UnivariateFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.floor(x); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Gaussian.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Gaussian.java deleted file mode 100644 index 08dcac0d4..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Gaussian.java +++ /dev/null @@ -1,252 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import java.util.Arrays; - -import org.apache.commons.math4.analysis.ParametricUnivariateFunction; -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.numbers.core.Precision; - -/** - * - * Gaussian function. - * - * @since 3.0 - */ -public class Gaussian implements UnivariateDifferentiableFunction { - /** Mean. */ - private final double mean; - /** Inverse of the standard deviation. */ - private final double is; - /** Inverse of twice the square of the standard deviation. */ - private final double i2s2; - /** Normalization factor. */ - private final double norm; - - /** - * Gaussian with given normalization factor, mean and standard deviation. - * - * @param norm Normalization factor. - * @param mean Mean. - * @param sigma Standard deviation. - * @throws NotStrictlyPositiveException if {@code sigma <= 0}. - */ - public Gaussian(double norm, - double mean, - double sigma) - throws NotStrictlyPositiveException { - if (sigma <= 0) { - throw new NotStrictlyPositiveException(sigma); - } - - this.norm = norm; - this.mean = mean; - this.is = 1 / sigma; - this.i2s2 = 0.5 * is * is; - } - - /** - * Normalized gaussian with given mean and standard deviation. - * - * @param mean Mean. - * @param sigma Standard deviation. - * @throws NotStrictlyPositiveException if {@code sigma <= 0}. - */ - public Gaussian(double mean, - double sigma) - throws NotStrictlyPositiveException { - this(1 / (sigma * FastMath.sqrt(2 * Math.PI)), mean, sigma); - } - - /** - * Normalized gaussian with zero mean and unit standard deviation. - */ - public Gaussian() { - this(0, 1); - } - - /** {@inheritDoc} */ - @Override - public double value(double x) { - return value(x - mean, norm, i2s2); - } - - /** - * Parametric function where the input array contains the parameters of - * the Gaussian, ordered as follows: - *
    - *
  • Norm
  • - *
  • Mean
  • - *
  • Standard deviation
  • - *
- */ - public static class Parametric implements ParametricUnivariateFunction { - /** - * Computes the value of the Gaussian at {@code x}. - * - * @param x Value for which the function must be computed. - * @param param Values of norm, mean and standard deviation. - * @return the value of the function. - * @throws NullArgumentException if {@code param} is {@code null}. - * @throws DimensionMismatchException if the size of {@code param} is - * not 3. - * @throws NotStrictlyPositiveException if {@code param[2]} is negative. - */ - @Override - public double value(double x, double ... param) - throws NullArgumentException, - DimensionMismatchException, - NotStrictlyPositiveException { - validateParameters(param); - - final double diff = x - param[1]; - final double i2s2 = 1 / (2 * param[2] * param[2]); - return Gaussian.value(diff, param[0], i2s2); - } - - /** - * Computes the value of the gradient at {@code x}. - * The components of the gradient vector are the partial - * derivatives of the function with respect to each of the - * parameters (norm, mean and standard deviation). - * - * @param x Value at which the gradient must be computed. - * @param param Values of norm, mean and standard deviation. - * @return the gradient vector at {@code x}. - * @throws NullArgumentException if {@code param} is {@code null}. - * @throws DimensionMismatchException if the size of {@code param} is - * not 3. - * @throws NotStrictlyPositiveException if {@code param[2]} is negative. - */ - @Override - public double[] gradient(double x, double ... param) - throws NullArgumentException, - DimensionMismatchException, - NotStrictlyPositiveException { - validateParameters(param); - - final double norm = param[0]; - final double diff = x - param[1]; - final double sigma = param[2]; - final double i2s2 = 1 / (2 * sigma * sigma); - - final double n = Gaussian.value(diff, 1, i2s2); - final double m = norm * n * 2 * i2s2 * diff; - final double s = m * diff / sigma; - - return new double[] { n, m, s }; - } - - /** - * Validates parameters to ensure they are appropriate for the evaluation of - * the {@link #value(double,double[])} and {@link #gradient(double,double[])} - * methods. - * - * @param param Values of norm, mean and standard deviation. - * @throws NullArgumentException if {@code param} is {@code null}. - * @throws DimensionMismatchException if the size of {@code param} is - * not 3. - * @throws NotStrictlyPositiveException if {@code param[2]} is negative. - */ - private void validateParameters(double[] param) - throws NullArgumentException, - DimensionMismatchException, - NotStrictlyPositiveException { - if (param == null) { - throw new NullArgumentException(); - } - if (param.length != 3) { - throw new DimensionMismatchException(param.length, 3); - } - if (param[2] <= 0) { - throw new NotStrictlyPositiveException(param[2]); - } - } - } - - /** - * @param xMinusMean {@code x - mean}. - * @param norm Normalization factor. - * @param i2s2 Inverse of twice the square of the standard deviation. - * @return the value of the Gaussian at {@code x}. - */ - private static double value(double xMinusMean, - double norm, - double i2s2) { - return norm * FastMath.exp(-xMinusMean * xMinusMean * i2s2); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) - throws DimensionMismatchException { - - final double u = is * (t.getValue() - mean); - double[] f = new double[t.getOrder() + 1]; - - // the nth order derivative of the Gaussian has the form: - // dn(g(x)/dxn = (norm / s^n) P_n(u) exp(-u^2/2) with u=(x-m)/s - // where P_n(u) is a degree n polynomial with same parity as n - // P_0(u) = 1, P_1(u) = -u, P_2(u) = u^2 - 1, P_3(u) = -u^3 + 3 u... - // the general recurrence relation for P_n is: - // P_n(u) = P_(n-1)'(u) - u P_(n-1)(u) - // as per polynomial parity, we can store coefficients of both P_(n-1) and P_n in the same array - final double[] p = new double[f.length]; - p[0] = 1; - final double u2 = u * u; - double coeff = norm * FastMath.exp(-0.5 * u2); - if (coeff <= Precision.SAFE_MIN) { - Arrays.fill(f, 0.0); - } else { - f[0] = coeff; - for (int n = 1; n < f.length; ++n) { - - // update and evaluate polynomial P_n(x) - double v = 0; - p[n] = -p[n - 1]; - for (int k = n; k >= 0; k -= 2) { - v = v * u2 + p[k]; - if (k > 2) { - p[k - 2] = (k - 1) * p[k - 1] - p[k - 3]; - } else if (k == 2) { - p[0] = p[1]; - } - } - if ((n & 0x1) == 1) { - v *= u; - } - - coeff *= is; - f[n] = coeff * v; - - } - } - - return t.compose(f); - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/HarmonicOscillator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/HarmonicOscillator.java deleted file mode 100644 index 6207d007a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/HarmonicOscillator.java +++ /dev/null @@ -1,176 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.ParametricUnivariateFunction; -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.util.FastMath; - -/** - * - * simple harmonic oscillator function. - * - * @since 3.0 - */ -public class HarmonicOscillator implements UnivariateDifferentiableFunction { - /** Amplitude. */ - private final double amplitude; - /** Angular frequency. */ - private final double omega; - /** Phase. */ - private final double phase; - - /** - * Harmonic oscillator function. - * - * @param amplitude Amplitude. - * @param omega Angular frequency. - * @param phase Phase. - */ - public HarmonicOscillator(double amplitude, - double omega, - double phase) { - this.amplitude = amplitude; - this.omega = omega; - this.phase = phase; - } - - /** {@inheritDoc} */ - @Override - public double value(double x) { - return value(omega * x + phase, amplitude); - } - - /** - * Parametric function where the input array contains the parameters of - * the harmonic oscillator function, ordered as follows: - *
    - *
  • Amplitude
  • - *
  • Angular frequency
  • - *
  • Phase
  • - *
- */ - public static class Parametric implements ParametricUnivariateFunction { - /** - * Computes the value of the harmonic oscillator at {@code x}. - * - * @param x Value for which the function must be computed. - * @param param Values of norm, mean and standard deviation. - * @return the value of the function. - * @throws NullArgumentException if {@code param} is {@code null}. - * @throws DimensionMismatchException if the size of {@code param} is - * not 3. - */ - @Override - public double value(double x, double ... param) - throws NullArgumentException, - DimensionMismatchException { - validateParameters(param); - return HarmonicOscillator.value(x * param[1] + param[2], param[0]); - } - - /** - * Computes the value of the gradient at {@code x}. - * The components of the gradient vector are the partial - * derivatives of the function with respect to each of the - * parameters (amplitude, angular frequency and phase). - * - * @param x Value at which the gradient must be computed. - * @param param Values of amplitude, angular frequency and phase. - * @return the gradient vector at {@code x}. - * @throws NullArgumentException if {@code param} is {@code null}. - * @throws DimensionMismatchException if the size of {@code param} is - * not 3. - */ - @Override - public double[] gradient(double x, double ... param) - throws NullArgumentException, - DimensionMismatchException { - validateParameters(param); - - final double amplitude = param[0]; - final double omega = param[1]; - final double phase = param[2]; - - final double xTimesOmegaPlusPhase = omega * x + phase; - final double a = HarmonicOscillator.value(xTimesOmegaPlusPhase, 1); - final double p = -amplitude * FastMath.sin(xTimesOmegaPlusPhase); - final double w = p * x; - - return new double[] { a, w, p }; - } - - /** - * Validates parameters to ensure they are appropriate for the evaluation of - * the {@link #value(double,double[])} and {@link #gradient(double,double[])} - * methods. - * - * @param param Values of norm, mean and standard deviation. - * @throws NullArgumentException if {@code param} is {@code null}. - * @throws DimensionMismatchException if the size of {@code param} is - * not 3. - */ - private void validateParameters(double[] param) - throws NullArgumentException, - DimensionMismatchException { - if (param == null) { - throw new NullArgumentException(); - } - if (param.length != 3) { - throw new DimensionMismatchException(param.length, 3); - } - } - } - - /** - * @param xTimesOmegaPlusPhase {@code omega * x + phase}. - * @param amplitude Amplitude. - * @return the value of the harmonic oscillator function at {@code x}. - */ - private static double value(double xTimesOmegaPlusPhase, - double amplitude) { - return amplitude * FastMath.cos(xTimesOmegaPlusPhase); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) - throws DimensionMismatchException { - final double x = t.getValue(); - double[] f = new double[t.getOrder() + 1]; - - final double alpha = omega * x + phase; - f[0] = amplitude * FastMath.cos(alpha); - if (f.length > 1) { - f[1] = -amplitude * omega * FastMath.sin(alpha); - final double mo2 = - omega * omega; - for (int i = 2; i < f.length; ++i) { - f[i] = mo2 * f[i - 2]; - } - } - - return t.compose(f); - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Identity.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Identity.java deleted file mode 100644 index 56567d464..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Identity.java +++ /dev/null @@ -1,43 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; - -/** - * Identity function. - * - * @since 3.0 - */ -public class Identity implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return x; - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Inverse.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Inverse.java deleted file mode 100644 index 500496265..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Inverse.java +++ /dev/null @@ -1,43 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; - -/** - * Inverse function. - * - * @since 3.0 - */ -public class Inverse implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return 1 / x; - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.reciprocal(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Log.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Log.java deleted file mode 100644 index 5f114669a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Log.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Natural logarithm function. - * - * @since 3.0 - */ -public class Log implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.log(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.log(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Log10.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Log10.java deleted file mode 100644 index e0ad0b421..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Log10.java +++ /dev/null @@ -1,45 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Base 10 logarithm function. - * - * @since 3.0 - */ -public class Log10 implements UnivariateDifferentiableFunction { - - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.log10(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.log10(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Log1p.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Log1p.java deleted file mode 100644 index f95c97058..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Log1p.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * log(1 + p) function. - * - * @since 3.0 - */ -public class Log1p implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.log1p(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.log1p(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Logistic.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Logistic.java deleted file mode 100644 index c5ff5e0ec..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Logistic.java +++ /dev/null @@ -1,221 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.ParametricUnivariateFunction; -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.util.FastMath; - -/** - * - * Generalised logistic function. - * - * @since 3.0 - */ -public class Logistic implements UnivariateDifferentiableFunction { - /** Lower asymptote. */ - private final double a; - /** Upper asymptote. */ - private final double k; - /** Growth rate. */ - private final double b; - /** Parameter that affects near which asymptote maximum growth occurs. */ - private final double oneOverN; - /** Parameter that affects the position of the curve along the ordinate axis. */ - private final double q; - /** Abscissa of maximum growth. */ - private final double m; - - /** - * @param k If {@code b > 0}, value of the function for x going towards +∞. - * If {@code b < 0}, value of the function for x going towards -∞. - * @param m Abscissa of maximum growth. - * @param b Growth rate. - * @param q Parameter that affects the position of the curve along the - * ordinate axis. - * @param a If {@code b > 0}, value of the function for x going towards -∞. - * If {@code b < 0}, value of the function for x going towards +∞. - * @param n Parameter that affects near which asymptote the maximum - * growth occurs. - * @throws NotStrictlyPositiveException if {@code n <= 0}. - */ - public Logistic(double k, - double m, - double b, - double q, - double a, - double n) - throws NotStrictlyPositiveException { - if (n <= 0) { - throw new NotStrictlyPositiveException(n); - } - - this.k = k; - this.m = m; - this.b = b; - this.q = q; - this.a = a; - oneOverN = 1 / n; - } - - /** {@inheritDoc} */ - @Override - public double value(double x) { - return value(m - x, k, b, q, a, oneOverN); - } - - /** - * Parametric function where the input array contains the parameters of - * the {@link Logistic#Logistic(double,double,double,double,double,double) - * logistic function}, ordered as follows: - *
    - *
  • k
  • - *
  • m
  • - *
  • b
  • - *
  • q
  • - *
  • a
  • - *
  • n
  • - *
- */ - public static class Parametric implements ParametricUnivariateFunction { - /** - * Computes the value of the sigmoid at {@code x}. - * - * @param x Value for which the function must be computed. - * @param param Values for {@code k}, {@code m}, {@code b}, {@code q}, - * {@code a} and {@code n}. - * @return the value of the function. - * @throws NullArgumentException if {@code param} is {@code null}. - * @throws DimensionMismatchException if the size of {@code param} is - * not 6. - * @throws NotStrictlyPositiveException if {@code param[5] <= 0}. - */ - @Override - public double value(double x, double ... param) - throws NullArgumentException, - DimensionMismatchException, - NotStrictlyPositiveException { - validateParameters(param); - return Logistic.value(param[1] - x, param[0], - param[2], param[3], - param[4], 1 / param[5]); - } - - /** - * Computes the value of the gradient at {@code x}. - * The components of the gradient vector are the partial - * derivatives of the function with respect to each of the - * parameters. - * - * @param x Value at which the gradient must be computed. - * @param param Values for {@code k}, {@code m}, {@code b}, {@code q}, - * {@code a} and {@code n}. - * @return the gradient vector at {@code x}. - * @throws NullArgumentException if {@code param} is {@code null}. - * @throws DimensionMismatchException if the size of {@code param} is - * not 6. - * @throws NotStrictlyPositiveException if {@code param[5] <= 0}. - */ - @Override - public double[] gradient(double x, double ... param) - throws NullArgumentException, - DimensionMismatchException, - NotStrictlyPositiveException { - validateParameters(param); - - final double b = param[2]; - final double q = param[3]; - - final double mMinusX = param[1] - x; - final double oneOverN = 1 / param[5]; - final double exp = FastMath.exp(b * mMinusX); - final double qExp = q * exp; - final double qExp1 = qExp + 1; - final double factor1 = (param[0] - param[4]) * oneOverN / FastMath.pow(qExp1, oneOverN); - final double factor2 = -factor1 / qExp1; - - // Components of the gradient. - final double gk = Logistic.value(mMinusX, 1, b, q, 0, oneOverN); - final double gm = factor2 * b * qExp; - final double gb = factor2 * mMinusX * qExp; - final double gq = factor2 * exp; - final double ga = Logistic.value(mMinusX, 0, b, q, 1, oneOverN); - final double gn = factor1 * FastMath.log(qExp1) * oneOverN; - - return new double[] { gk, gm, gb, gq, ga, gn }; - } - - /** - * Validates parameters to ensure they are appropriate for the evaluation of - * the {@link #value(double,double[])} and {@link #gradient(double,double[])} - * methods. - * - * @param param Values for {@code k}, {@code m}, {@code b}, {@code q}, - * {@code a} and {@code n}. - * @throws NullArgumentException if {@code param} is {@code null}. - * @throws DimensionMismatchException if the size of {@code param} is - * not 6. - * @throws NotStrictlyPositiveException if {@code param[5] <= 0}. - */ - private void validateParameters(double[] param) - throws NullArgumentException, - DimensionMismatchException, - NotStrictlyPositiveException { - if (param == null) { - throw new NullArgumentException(); - } - if (param.length != 6) { - throw new DimensionMismatchException(param.length, 6); - } - if (param[5] <= 0) { - throw new NotStrictlyPositiveException(param[5]); - } - } - } - - /** - * @param mMinusX {@code m - x}. - * @param k {@code k}. - * @param b {@code b}. - * @param q {@code q}. - * @param a {@code a}. - * @param oneOverN {@code 1 / n}. - * @return the value of the function. - */ - private static double value(double mMinusX, - double k, - double b, - double q, - double a, - double oneOverN) { - return a + (k - a) / FastMath.pow(1 + q * FastMath.exp(b * mMinusX), oneOverN); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.negate().add(m).multiply(b).exp().multiply(q).add(1).pow(oneOverN).reciprocal().multiply(k - a).add(a); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Logit.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Logit.java deleted file mode 100644 index 55b1fd9a8..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Logit.java +++ /dev/null @@ -1,205 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.ParametricUnivariateFunction; -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.util.FastMath; - -/** - * - * Logit function. - * It is the inverse of the {@link Sigmoid sigmoid} function. - * - * @since 3.0 - */ -public class Logit implements UnivariateDifferentiableFunction { - /** Lower bound. */ - private final double lo; - /** Higher bound. */ - private final double hi; - - /** - * Usual logit function, where the lower bound is 0 and the higher - * bound is 1. - */ - public Logit() { - this(0, 1); - } - - /** - * Logit function. - * - * @param lo Lower bound of the function domain. - * @param hi Higher bound of the function domain. - */ - public Logit(double lo, - double hi) { - this.lo = lo; - this.hi = hi; - } - - /** {@inheritDoc} */ - @Override - public double value(double x) - throws OutOfRangeException { - return value(x, lo, hi); - } - - /** - * Parametric function where the input array contains the parameters of - * the logit function, ordered as follows: - *
    - *
  • Lower bound
  • - *
  • Higher bound
  • - *
- */ - public static class Parametric implements ParametricUnivariateFunction { - /** - * Computes the value of the logit at {@code x}. - * - * @param x Value for which the function must be computed. - * @param param Values of lower bound and higher bounds. - * @return the value of the function. - * @throws NullArgumentException if {@code param} is {@code null}. - * @throws DimensionMismatchException if the size of {@code param} is - * not 2. - */ - @Override - public double value(double x, double ... param) - throws NullArgumentException, - DimensionMismatchException { - validateParameters(param); - return Logit.value(x, param[0], param[1]); - } - - /** - * Computes the value of the gradient at {@code x}. - * The components of the gradient vector are the partial - * derivatives of the function with respect to each of the - * parameters (lower bound and higher bound). - * - * @param x Value at which the gradient must be computed. - * @param param Values for lower and higher bounds. - * @return the gradient vector at {@code x}. - * @throws NullArgumentException if {@code param} is {@code null}. - * @throws DimensionMismatchException if the size of {@code param} is - * not 2. - */ - @Override - public double[] gradient(double x, double ... param) - throws NullArgumentException, - DimensionMismatchException { - validateParameters(param); - - final double lo = param[0]; - final double hi = param[1]; - - return new double[] { 1 / (lo - x), 1 / (hi - x) }; - } - - /** - * Validates parameters to ensure they are appropriate for the evaluation of - * the {@link #value(double,double[])} and {@link #gradient(double,double[])} - * methods. - * - * @param param Values for lower and higher bounds. - * @throws NullArgumentException if {@code param} is {@code null}. - * @throws DimensionMismatchException if the size of {@code param} is - * not 2. - */ - private void validateParameters(double[] param) - throws NullArgumentException, - DimensionMismatchException { - if (param == null) { - throw new NullArgumentException(); - } - if (param.length != 2) { - throw new DimensionMismatchException(param.length, 2); - } - } - } - - /** - * @param x Value at which to compute the logit. - * @param lo Lower bound. - * @param hi Higher bound. - * @return the value of the logit function at {@code x}. - * @throws OutOfRangeException if {@code x < lo} or {@code x > hi}. - */ - private static double value(double x, - double lo, - double hi) - throws OutOfRangeException { - if (x < lo || x > hi) { - throw new OutOfRangeException(x, lo, hi); - } - return FastMath.log((x - lo) / (hi - x)); - } - - /** {@inheritDoc} - * @since 3.1 - * @exception OutOfRangeException if parameter is outside of function domain - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) - throws OutOfRangeException { - final double x = t.getValue(); - if (x < lo || x > hi) { - throw new OutOfRangeException(x, lo, hi); - } - double[] f = new double[t.getOrder() + 1]; - - // function value - f[0] = FastMath.log((x - lo) / (hi - x)); - - if (Double.isInfinite(f[0])) { - - if (f.length > 1) { - f[1] = Double.POSITIVE_INFINITY; - } - // fill the array with infinities - // (for x close to lo the signs will flip between -inf and +inf, - // for x close to hi the signs will always be +inf) - // this is probably overkill, since the call to compose at the end - // of the method will transform most infinities into NaN ... - for (int i = 2; i < f.length; ++i) { - f[i] = f[i - 2]; - } - - } else { - - // function derivatives - final double invL = 1.0 / (x - lo); - double xL = invL; - final double invH = 1.0 / (hi - x); - double xH = invH; - for (int i = 1; i < f.length; ++i) { - f[i] = xL + xH; - xL *= -i * invL; - xH *= i * invH; - } - } - - return t.compose(f); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Max.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Max.java deleted file mode 100644 index cf6a3e351..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Max.java +++ /dev/null @@ -1,34 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.BivariateFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Maximum function. - * - * @since 3.0 - */ -public class Max implements BivariateFunction { - /** {@inheritDoc} */ - @Override - public double value(double x, double y) { - return FastMath.max(x, y); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Min.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Min.java deleted file mode 100644 index 0866dde53..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Min.java +++ /dev/null @@ -1,34 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.BivariateFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Minimum function. - * - * @since 3.0 - */ -public class Min implements BivariateFunction { - /** {@inheritDoc} */ - @Override - public double value(double x, double y) { - return FastMath.min(x, y); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Minus.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Minus.java deleted file mode 100644 index 714de04b2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Minus.java +++ /dev/null @@ -1,43 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; - -/** - * Minus function. - * - * @since 3.0 - */ -public class Minus implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return -x; - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.negate(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Multiply.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Multiply.java deleted file mode 100644 index df3bb50c9..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Multiply.java +++ /dev/null @@ -1,33 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.BivariateFunction; - -/** - * Multiply the two operands. - * - * @since 3.0 - */ -public class Multiply implements BivariateFunction { - /** {@inheritDoc} */ - @Override - public double value(double x, double y) { - return x * y; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Pow.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Pow.java deleted file mode 100644 index 52df284cc..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Pow.java +++ /dev/null @@ -1,34 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.BivariateFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Power function. - * - * @since 3.0 - */ -public class Pow implements BivariateFunction { - /** {@inheritDoc} */ - @Override - public double value(double x, double y) { - return FastMath.pow(x, y); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Power.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Power.java deleted file mode 100644 index f605c9351..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Power.java +++ /dev/null @@ -1,54 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Power function. - * - * @since 3.0 - */ -public class Power implements UnivariateDifferentiableFunction { - /** Power. */ - private final double p; - - /** - * @param p Power. - */ - public Power(double p) { - this.p = p; - } - - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.pow(x, p); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.pow(p); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Rint.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Rint.java deleted file mode 100644 index 31312237e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Rint.java +++ /dev/null @@ -1,34 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * {@code rint} function. - * - * @since 3.0 - */ -public class Rint implements UnivariateFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.rint(x); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Sigmoid.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Sigmoid.java deleted file mode 100644 index 52d582523..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Sigmoid.java +++ /dev/null @@ -1,211 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import java.util.Arrays; - -import org.apache.commons.math4.analysis.ParametricUnivariateFunction; -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.util.FastMath; - -/** - * - * Sigmoid function. - * It is the inverse of the {@link Logit logit} function. - * A more flexible version, the generalised logistic, is implemented - * by the {@link Logistic} class. - * - * @since 3.0 - */ -public class Sigmoid implements UnivariateDifferentiableFunction { - /** Lower asymptote. */ - private final double lo; - /** Higher asymptote. */ - private final double hi; - - /** - * Usual sigmoid function, where the lower asymptote is 0 and the higher - * asymptote is 1. - */ - public Sigmoid() { - this(0, 1); - } - - /** - * Sigmoid function. - * - * @param lo Lower asymptote. - * @param hi Higher asymptote. - */ - public Sigmoid(double lo, - double hi) { - this.lo = lo; - this.hi = hi; - } - - /** {@inheritDoc} */ - @Override - public double value(double x) { - return value(x, lo, hi); - } - - /** - * Parametric function where the input array contains the parameters of - * the {@link Sigmoid#Sigmoid(double,double) sigmoid function}, ordered - * as follows: - *
    - *
  • Lower asymptote
  • - *
  • Higher asymptote
  • - *
- */ - public static class Parametric implements ParametricUnivariateFunction { - /** - * Computes the value of the sigmoid at {@code x}. - * - * @param x Value for which the function must be computed. - * @param param Values of lower asymptote and higher asymptote. - * @return the value of the function. - * @throws NullArgumentException if {@code param} is {@code null}. - * @throws DimensionMismatchException if the size of {@code param} is - * not 2. - */ - @Override - public double value(double x, double ... param) - throws NullArgumentException, - DimensionMismatchException { - validateParameters(param); - return Sigmoid.value(x, param[0], param[1]); - } - - /** - * Computes the value of the gradient at {@code x}. - * The components of the gradient vector are the partial - * derivatives of the function with respect to each of the - * parameters (lower asymptote and higher asymptote). - * - * @param x Value at which the gradient must be computed. - * @param param Values for lower asymptote and higher asymptote. - * @return the gradient vector at {@code x}. - * @throws NullArgumentException if {@code param} is {@code null}. - * @throws DimensionMismatchException if the size of {@code param} is - * not 2. - */ - @Override - public double[] gradient(double x, double ... param) - throws NullArgumentException, - DimensionMismatchException { - validateParameters(param); - - final double invExp1 = 1 / (1 + FastMath.exp(-x)); - - return new double[] { 1 - invExp1, invExp1 }; - } - - /** - * Validates parameters to ensure they are appropriate for the evaluation of - * the {@link #value(double,double[])} and {@link #gradient(double,double[])} - * methods. - * - * @param param Values for lower and higher asymptotes. - * @throws NullArgumentException if {@code param} is {@code null}. - * @throws DimensionMismatchException if the size of {@code param} is - * not 2. - */ - private void validateParameters(double[] param) - throws NullArgumentException, - DimensionMismatchException { - if (param == null) { - throw new NullArgumentException(); - } - if (param.length != 2) { - throw new DimensionMismatchException(param.length, 2); - } - } - } - - /** - * @param x Value at which to compute the sigmoid. - * @param lo Lower asymptote. - * @param hi Higher asymptote. - * @return the value of the sigmoid function at {@code x}. - */ - private static double value(double x, - double lo, - double hi) { - return lo + (hi - lo) / (1 + FastMath.exp(-x)); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) - throws DimensionMismatchException { - - double[] f = new double[t.getOrder() + 1]; - final double exp = FastMath.exp(-t.getValue()); - if (Double.isInfinite(exp)) { - - // special handling near lower boundary, to avoid NaN - f[0] = lo; - Arrays.fill(f, 1, f.length, 0.0); - - } else { - - // the nth order derivative of sigmoid has the form: - // dn(sigmoid(x)/dxn = P_n(exp(-x)) / (1+exp(-x))^(n+1) - // where P_n(t) is a degree n polynomial with normalized higher term - // P_0(t) = 1, P_1(t) = t, P_2(t) = t^2 - t, P_3(t) = t^3 - 4 t^2 + t... - // the general recurrence relation for P_n is: - // P_n(x) = n t P_(n-1)(t) - t (1 + t) P_(n-1)'(t) - final double[] p = new double[f.length]; - - final double inv = 1 / (1 + exp); - double coeff = hi - lo; - for (int n = 0; n < f.length; ++n) { - - // update and evaluate polynomial P_n(t) - double v = 0; - p[n] = 1; - for (int k = n; k >= 0; --k) { - v = v * exp + p[k]; - if (k > 1) { - p[k - 1] = (n - k + 2) * p[k - 2] - (k - 1) * p[k - 1]; - } else { - p[0] = 0; - } - } - - coeff *= inv; - f[n] = coeff * v; - - } - - // fix function value - f[0] += lo; - - } - - return t.compose(f); - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Signum.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Signum.java deleted file mode 100644 index 45fbc47c0..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Signum.java +++ /dev/null @@ -1,34 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * {@code signum} function. - * - * @since 3.0 - */ -public class Signum implements UnivariateFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.signum(x); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Sin.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Sin.java deleted file mode 100644 index 08e958112..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Sin.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Sine function. - * - * @since 3.0 - */ -public class Sin implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.sin(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.sin(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Sinc.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Sinc.java deleted file mode 100644 index b6207fcac..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Sinc.java +++ /dev/null @@ -1,196 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.util.FastMath; - -/** - * Sinc function, - * defined by - *

- *   sinc(x) = 1            if x = 0,
- *             sin(x) / x   otherwise.
- * 
- * - * @since 3.0 - */ -public class Sinc implements UnivariateDifferentiableFunction { - /** - * Value below which the computations are done using Taylor series. - *

- * The Taylor series for sinc even order derivatives are: - *

-     * d^(2n)sinc/dx^(2n)     = Sum_(k>=0) (-1)^(n+k) / ((2k)!(2n+2k+1)) x^(2k)
-     *                        = (-1)^n     [ 1/(2n+1) - x^2/(4n+6) + x^4/(48n+120) - x^6/(1440n+5040) + O(x^8) ]
-     * 
- *

- *

- * The Taylor series for sinc odd order derivatives are: - *

-     * d^(2n+1)sinc/dx^(2n+1) = Sum_(k>=0) (-1)^(n+k+1) / ((2k+1)!(2n+2k+3)) x^(2k+1)
-     *                        = (-1)^(n+1) [ x/(2n+3) - x^3/(12n+30) + x^5/(240n+840) - x^7/(10080n+45360) + O(x^9) ]
-     * 
- *

- *

- * So the ratio of the fourth term with respect to the first term - * is always smaller than x^6/720, for all derivative orders. - * This implies that neglecting this term and using only the first three terms induces - * a relative error bounded by x^6/720. The SHORTCUT value is chosen such that this - * relative error is below double precision accuracy when |x| <= SHORTCUT. - *

- */ - private static final double SHORTCUT = 6.0e-3; - /** For normalized sinc function. */ - private final boolean normalized; - - /** - * The sinc function, {@code sin(x) / x}. - */ - public Sinc() { - this(false); - } - - /** - * Instantiates the sinc function. - * - * @param normalized If {@code true}, the function is - * sin(πx) / πx, otherwise {@code sin(x) / x}. - */ - public Sinc(boolean normalized) { - this.normalized = normalized; - } - - /** {@inheritDoc} */ - @Override - public double value(final double x) { - final double scaledX = normalized ? FastMath.PI * x : x; - if (FastMath.abs(scaledX) <= SHORTCUT) { - // use Taylor series - final double scaledX2 = scaledX * scaledX; - return ((scaledX2 - 20) * scaledX2 + 120) / 120; - } else { - // use definition expression - return FastMath.sin(scaledX) / scaledX; - } - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) - throws DimensionMismatchException { - - final double scaledX = (normalized ? FastMath.PI : 1) * t.getValue(); - final double scaledX2 = scaledX * scaledX; - - double[] f = new double[t.getOrder() + 1]; - - if (FastMath.abs(scaledX) <= SHORTCUT) { - - for (int i = 0; i < f.length; ++i) { - final int k = i / 2; - if ((i & 0x1) == 0) { - // even derivation order - f[i] = (((k & 0x1) == 0) ? 1 : -1) * - (1.0 / (i + 1) - scaledX2 * (1.0 / (2 * i + 6) - scaledX2 / (24 * i + 120))); - } else { - // odd derivation order - f[i] = (((k & 0x1) == 0) ? -scaledX : scaledX) * - (1.0 / (i + 2) - scaledX2 * (1.0 / (6 * i + 24) - scaledX2 / (120 * i + 720))); - } - } - - } else { - - final double inv = 1 / scaledX; - final double cos = FastMath.cos(scaledX); - final double sin = FastMath.sin(scaledX); - - f[0] = inv * sin; - - // the nth order derivative of sinc has the form: - // dn(sinc(x)/dxn = [S_n(x) sin(x) + C_n(x) cos(x)] / x^(n+1) - // where S_n(x) is an even polynomial with degree n-1 or n (depending on parity) - // and C_n(x) is an odd polynomial with degree n-1 or n (depending on parity) - // S_0(x) = 1, S_1(x) = -1, S_2(x) = -x^2 + 2, S_3(x) = 3x^2 - 6... - // C_0(x) = 0, C_1(x) = x, C_2(x) = -2x, C_3(x) = -x^3 + 6x... - // the general recurrence relations for S_n and C_n are: - // S_n(x) = x S_(n-1)'(x) - n S_(n-1)(x) - x C_(n-1)(x) - // C_n(x) = x C_(n-1)'(x) - n C_(n-1)(x) + x S_(n-1)(x) - // as per polynomials parity, we can store both S_n and C_n in the same array - final double[] sc = new double[f.length]; - sc[0] = 1; - - double coeff = inv; - for (int n = 1; n < f.length; ++n) { - - double s = 0; - double c = 0; - - // update and evaluate polynomials S_n(x) and C_n(x) - final int kStart; - if ((n & 0x1) == 0) { - // even derivation order, S_n is degree n and C_n is degree n-1 - sc[n] = 0; - kStart = n; - } else { - // odd derivation order, S_n is degree n-1 and C_n is degree n - sc[n] = sc[n - 1]; - c = sc[n]; - kStart = n - 1; - } - - // in this loop, k is always even - for (int k = kStart; k > 1; k -= 2) { - - // sine part - sc[k] = (k - n) * sc[k] - sc[k - 1]; - s = s * scaledX2 + sc[k]; - - // cosine part - sc[k - 1] = (k - 1 - n) * sc[k - 1] + sc[k -2]; - c = c * scaledX2 + sc[k - 1]; - - } - sc[0] *= -n; - s = s * scaledX2 + sc[0]; - - coeff *= inv; - f[n] = coeff * (s * sin + c * scaledX * cos); - - } - - } - - if (normalized) { - double scale = FastMath.PI; - for (int i = 1; i < f.length; ++i) { - f[i] *= scale; - scale *= FastMath.PI; - } - } - - return t.compose(f); - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Sinh.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Sinh.java deleted file mode 100644 index 617f9a46d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Sinh.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Hyperbolic sine function. - * - * @since 3.0 - */ -public class Sinh implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.sinh(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.sinh(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Sqrt.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Sqrt.java deleted file mode 100644 index 979e67d7c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Sqrt.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Square-root function. - * - * @since 3.0 - */ -public class Sqrt implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.sqrt(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.sqrt(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/StepFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/StepFunction.java deleted file mode 100644 index 08461cb2c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/StepFunction.java +++ /dev/null @@ -1,102 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import java.util.Arrays; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.util.MathArrays; - -/** - * - * Step function. - * - * @since 3.0 - */ -public class StepFunction implements UnivariateFunction { - /** Abscissae. */ - private final double[] abscissa; - /** Ordinates. */ - private final double[] ordinate; - - /** - * Builds a step function from a list of arguments and the corresponding - * values. Specifically, returns the function h(x) defined by

-     * h(x) = y[0] for all x < x[1]
-     *        y[1] for x[1] ≤ x < x[2]
-     *        ...
-     *        y[y.length - 1] for x ≥ x[x.length - 1]
-     * 
- * The value of {@code x[0]} is ignored, but it must be strictly less than - * {@code x[1]}. - * - * @param x Domain values where the function changes value. - * @param y Values of the function. - * @throws NonMonotonicSequenceException - * if the {@code x} array is not sorted in strictly increasing order. - * @throws NullArgumentException if {@code x} or {@code y} are {@code null}. - * @throws NoDataException if {@code x} or {@code y} are zero-length. - * @throws DimensionMismatchException if {@code x} and {@code y} do not - * have the same length. - */ - public StepFunction(double[] x, - double[] y) - throws NullArgumentException, NoDataException, - DimensionMismatchException, NonMonotonicSequenceException { - if (x == null || - y == null) { - throw new NullArgumentException(); - } - if (x.length == 0 || - y.length == 0) { - throw new NoDataException(); - } - if (y.length != x.length) { - throw new DimensionMismatchException(y.length, x.length); - } - MathArrays.checkOrder(x); - - abscissa = MathArrays.copyOf(x); - ordinate = MathArrays.copyOf(y); - } - - /** {@inheritDoc} */ - @Override - public double value(double x) { - int index = Arrays.binarySearch(abscissa, x); - double fx = 0; - - if (index < -1) { - // "x" is between "abscissa[-index-2]" and "abscissa[-index-1]". - fx = ordinate[-index-2]; - } else if (index >= 0) { - // "x" is exactly "abscissa[index]". - fx = ordinate[index]; - } else { - // Otherwise, "x" is smaller than the first value in "abscissa" - // (hence the returned value should be "ordinate[0]"). - fx = ordinate[0]; - } - - return fx; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Subtract.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Subtract.java deleted file mode 100644 index 1ce5e95a4..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Subtract.java +++ /dev/null @@ -1,33 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.BivariateFunction; - -/** - * Subtract the second operand from the first. - * - * @since 3.0 - */ -public class Subtract implements BivariateFunction { - /** {@inheritDoc} */ - @Override - public double value(double x, double y) { - return x - y; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Tan.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Tan.java deleted file mode 100644 index dc205892e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Tan.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Tangent function. - * - * @since 3.0 - */ -public class Tan implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.tan(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.tan(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Tanh.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Tanh.java deleted file mode 100644 index 2769ca537..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Tanh.java +++ /dev/null @@ -1,44 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * Hyperbolic tangent function. - * - * @since 3.0 - */ -public class Tanh implements UnivariateDifferentiableFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.tanh(x); - } - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - return t.tanh(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Ulp.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Ulp.java deleted file mode 100644 index 543a7d46a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/Ulp.java +++ /dev/null @@ -1,34 +0,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. - */ - -package org.apache.commons.math4.analysis.function; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.util.FastMath; - -/** - * {@code ulp} function. - * - * @since 3.0 - */ -public class Ulp implements UnivariateFunction { - /** {@inheritDoc} */ - @Override - public double value(double x) { - return FastMath.ulp(x); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/package-info.java deleted file mode 100644 index 695f68985..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/function/package-info.java +++ /dev/null @@ -1,26 +0,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. - */ -/** - * - *

- * The {@code function} package contains function objects that wrap the - * methods contained in {@link java.lang.Math}, as well as common - * mathematical functions such as the gaussian and sinc functions. - *

- * - */ -package org.apache.commons.math4.analysis.function; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/BaseAbstractUnivariateIntegrator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/BaseAbstractUnivariateIntegrator.java deleted file mode 100644 index 595f18f3d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/BaseAbstractUnivariateIntegrator.java +++ /dev/null @@ -1,287 +0,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. - */ -package org.apache.commons.math4.analysis.integration; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.analysis.solvers.UnivariateSolverUtils; -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.TooManyEvaluationsException; -import org.apache.commons.math4.util.Incrementor; -import org.apache.commons.math4.util.MathUtils; - -/** - * Provide a default implementation for several generic functions. - * - * @since 1.2 - */ -public abstract class BaseAbstractUnivariateIntegrator implements UnivariateIntegrator { - - /** Default absolute accuracy. */ - public static final double DEFAULT_ABSOLUTE_ACCURACY = 1.0e-15; - - /** Default relative accuracy. */ - public static final double DEFAULT_RELATIVE_ACCURACY = 1.0e-6; - - /** Default minimal iteration count. */ - public static final int DEFAULT_MIN_ITERATIONS_COUNT = 3; - - /** Default maximal iteration count. */ - public static final int DEFAULT_MAX_ITERATIONS_COUNT = Integer.MAX_VALUE; - - /** The iteration count. */ - protected final Incrementor iterations; - - /** Maximum absolute error. */ - private final double absoluteAccuracy; - - /** Maximum relative error. */ - private final double relativeAccuracy; - - /** minimum number of iterations */ - private final int minimalIterationCount; - - /** The functions evaluation count. */ - private final Incrementor evaluations; - - /** Function to integrate. */ - private UnivariateFunction function; - - /** Lower bound for the interval. */ - private double min; - - /** Upper bound for the interval. */ - private double max; - - /** - * Construct an integrator with given accuracies and iteration counts. - *

- * The meanings of the various parameters are: - *

    - *
  • relative accuracy: - * this is used to stop iterations if the absolute accuracy can't be - * achieved due to large values or short mantissa length. If this - * should be the primary criterion for convergence rather then a - * safety measure, set the absolute accuracy to a ridiculously small value, - * like {@link org.apache.commons.numbers.core.Precision#SAFE_MIN Precision.SAFE_MIN}.
  • - *
  • absolute accuracy: - * The default is usually chosen so that results in the interval - * -10..-0.1 and +0.1..+10 can be found with a reasonable accuracy. If the - * expected absolute value of your results is of much smaller magnitude, set - * this to a smaller value.
  • - *
  • minimum number of iterations: - * minimal iteration is needed to avoid false early convergence, e.g. - * the sample points happen to be zeroes of the function. Users can - * use the default value or choose one that they see as appropriate.
  • - *
  • maximum number of iterations: - * usually a high iteration count indicates convergence problems. However, - * the "reasonable value" varies widely for different algorithms. Users are - * advised to use the default value supplied by the algorithm.
  • - *
- * - * @param relativeAccuracy relative accuracy of the result - * @param absoluteAccuracy absolute accuracy of the result - * @param minimalIterationCount minimum number of iterations - * @param maximalIterationCount maximum number of iterations - * @exception NotStrictlyPositiveException if minimal number of iterations - * is not strictly positive - * @exception NumberIsTooSmallException if maximal number of iterations - * is lesser than or equal to the minimal number of iterations - */ - protected BaseAbstractUnivariateIntegrator(final double relativeAccuracy, - final double absoluteAccuracy, - final int minimalIterationCount, - final int maximalIterationCount) - throws NotStrictlyPositiveException, NumberIsTooSmallException { - - // accuracy settings - this.relativeAccuracy = relativeAccuracy; - this.absoluteAccuracy = absoluteAccuracy; - - // iterations count settings - if (minimalIterationCount <= 0) { - throw new NotStrictlyPositiveException(minimalIterationCount); - } - if (maximalIterationCount <= minimalIterationCount) { - throw new NumberIsTooSmallException(maximalIterationCount, minimalIterationCount, false); - } - this.minimalIterationCount = minimalIterationCount; - this.iterations = new Incrementor(); - iterations.setMaximalCount(maximalIterationCount); - - // prepare evaluations counter, but do not set it yet - evaluations = new Incrementor(); - - } - - /** - * Construct an integrator with given accuracies. - * @param relativeAccuracy relative accuracy of the result - * @param absoluteAccuracy absolute accuracy of the result - */ - protected BaseAbstractUnivariateIntegrator(final double relativeAccuracy, - final double absoluteAccuracy) { - this(relativeAccuracy, absoluteAccuracy, - DEFAULT_MIN_ITERATIONS_COUNT, DEFAULT_MAX_ITERATIONS_COUNT); - } - - /** - * Construct an integrator with given iteration counts. - * @param minimalIterationCount minimum number of iterations - * @param maximalIterationCount maximum number of iterations - * @exception NotStrictlyPositiveException if minimal number of iterations - * is not strictly positive - * @exception NumberIsTooSmallException if maximal number of iterations - * is lesser than or equal to the minimal number of iterations - */ - protected BaseAbstractUnivariateIntegrator(final int minimalIterationCount, - final int maximalIterationCount) - throws NotStrictlyPositiveException, NumberIsTooSmallException { - this(DEFAULT_RELATIVE_ACCURACY, DEFAULT_ABSOLUTE_ACCURACY, - minimalIterationCount, maximalIterationCount); - } - - /** {@inheritDoc} */ - @Override - public double getRelativeAccuracy() { - return relativeAccuracy; - } - - /** {@inheritDoc} */ - @Override - public double getAbsoluteAccuracy() { - return absoluteAccuracy; - } - - /** {@inheritDoc} */ - @Override - public int getMinimalIterationCount() { - return minimalIterationCount; - } - - /** {@inheritDoc} */ - @Override - public int getMaximalIterationCount() { - return iterations.getMaximalCount(); - } - - /** {@inheritDoc} */ - @Override - public int getEvaluations() { - return evaluations.getCount(); - } - - /** {@inheritDoc} */ - @Override - public int getIterations() { - return iterations.getCount(); - } - - /** - * @return the lower bound. - */ - protected double getMin() { - return min; - } - /** - * @return the upper bound. - */ - protected double getMax() { - return max; - } - - /** - * Compute the objective function value. - * - * @param point Point at which the objective function must be evaluated. - * @return the objective function value at specified point. - * @throws TooManyEvaluationsException if the maximal number of function - * evaluations is exceeded. - */ - protected double computeObjectiveValue(final double point) - throws TooManyEvaluationsException { - try { - evaluations.incrementCount(); - } catch (MaxCountExceededException e) { - throw new TooManyEvaluationsException(e.getMax()); - } - return function.value(point); - } - - /** - * Prepare for computation. - * Subclasses must call this method if they override any of the - * {@code solve} methods. - * - * @param maxEval Maximum number of evaluations. - * @param f the integrand function - * @param lower the min bound for the interval - * @param upper the upper bound for the interval - * @throws NullArgumentException if {@code f} is {@code null}. - * @throws MathIllegalArgumentException if {@code min >= max}. - */ - protected void setup(final int maxEval, - final UnivariateFunction f, - final double lower, final double upper) - throws NullArgumentException, MathIllegalArgumentException { - - // Checks. - MathUtils.checkNotNull(f); - UnivariateSolverUtils.verifyInterval(lower, upper); - - // Reset. - min = lower; - max = upper; - function = f; - evaluations.setMaximalCount(maxEval); - evaluations.resetCount(); - iterations.resetCount(); - - } - - /** {@inheritDoc} */ - @Override - public double integrate(final int maxEval, final UnivariateFunction f, - final double lower, final double upper) - throws TooManyEvaluationsException, MaxCountExceededException, - MathIllegalArgumentException, NullArgumentException { - - // Initialization. - setup(maxEval, f, lower, upper); - - // Perform computation. - return doIntegrate(); - - } - - /** - * Method for implementing actual integration algorithms in derived - * classes. - * - * @return the root. - * @throws TooManyEvaluationsException if the maximal number of evaluations - * is exceeded. - * @throws MaxCountExceededException if the maximum iteration count is exceeded - * or the integrator detects convergence problems otherwise - */ - protected abstract double doIntegrate() - throws TooManyEvaluationsException, MaxCountExceededException; - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/IterativeLegendreGaussIntegrator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/IterativeLegendreGaussIntegrator.java deleted file mode 100644 index f65334c9f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/IterativeLegendreGaussIntegrator.java +++ /dev/null @@ -1,184 +0,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. - */ -package org.apache.commons.math4.analysis.integration; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.analysis.integration.gauss.GaussIntegrator; -import org.apache.commons.math4.analysis.integration.gauss.GaussIntegratorFactory; -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.TooManyEvaluationsException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; - -/** - * This algorithm divides the integration interval into equally-sized - * sub-interval and on each of them performs a - * - * Legendre-Gauss quadrature. - * Because of its non-adaptive nature, this algorithm can - * converge to a wrong value for the integral (for example, if the - * function is significantly different from zero toward the ends of the - * integration interval). - * In particular, a change of variables aimed at estimating integrals - * over infinite intervals as proposed - * - * here should be avoided when using this class. - * - * @since 3.1 - */ - -public class IterativeLegendreGaussIntegrator - extends BaseAbstractUnivariateIntegrator { - /** Factory that computes the points and weights. */ - private static final GaussIntegratorFactory FACTORY - = new GaussIntegratorFactory(); - /** Number of integration points (per interval). */ - private final int numberOfPoints; - - /** - * Builds an integrator with given accuracies and iterations counts. - * - * @param n Number of integration points. - * @param relativeAccuracy Relative accuracy of the result. - * @param absoluteAccuracy Absolute accuracy of the result. - * @param minimalIterationCount Minimum number of iterations. - * @param maximalIterationCount Maximum number of iterations. - * @throws NotStrictlyPositiveException if minimal number of iterations - * or number of points are not strictly positive. - * @throws NumberIsTooSmallException if maximal number of iterations - * is smaller than or equal to the minimal number of iterations. - */ - public IterativeLegendreGaussIntegrator(final int n, - final double relativeAccuracy, - final double absoluteAccuracy, - final int minimalIterationCount, - final int maximalIterationCount) - throws NotStrictlyPositiveException, NumberIsTooSmallException { - super(relativeAccuracy, absoluteAccuracy, minimalIterationCount, maximalIterationCount); - if (n <= 0) { - throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_POINTS, n); - } - numberOfPoints = n; - } - - /** - * Builds an integrator with given accuracies. - * - * @param n Number of integration points. - * @param relativeAccuracy Relative accuracy of the result. - * @param absoluteAccuracy Absolute accuracy of the result. - * @throws NotStrictlyPositiveException if {@code n < 1}. - */ - public IterativeLegendreGaussIntegrator(final int n, - final double relativeAccuracy, - final double absoluteAccuracy) - throws NotStrictlyPositiveException { - this(n, relativeAccuracy, absoluteAccuracy, - DEFAULT_MIN_ITERATIONS_COUNT, DEFAULT_MAX_ITERATIONS_COUNT); - } - - /** - * Builds an integrator with given iteration counts. - * - * @param n Number of integration points. - * @param minimalIterationCount Minimum number of iterations. - * @param maximalIterationCount Maximum number of iterations. - * @throws NotStrictlyPositiveException if minimal number of iterations - * is not strictly positive. - * @throws NumberIsTooSmallException if maximal number of iterations - * is smaller than or equal to the minimal number of iterations. - * @throws NotStrictlyPositiveException if {@code n < 1}. - */ - public IterativeLegendreGaussIntegrator(final int n, - final int minimalIterationCount, - final int maximalIterationCount) - throws NotStrictlyPositiveException, NumberIsTooSmallException { - this(n, DEFAULT_RELATIVE_ACCURACY, DEFAULT_ABSOLUTE_ACCURACY, - minimalIterationCount, maximalIterationCount); - } - - /** {@inheritDoc} */ - @Override - protected double doIntegrate() - throws MathIllegalArgumentException, TooManyEvaluationsException, MaxCountExceededException { - // Compute first estimate with a single step. - double oldt = stage(1); - - int n = 2; - while (true) { - // Improve integral with a larger number of steps. - final double t = stage(n); - - // Estimate the error. - final double delta = FastMath.abs(t - oldt); - final double limit = - FastMath.max(getAbsoluteAccuracy(), - getRelativeAccuracy() * (FastMath.abs(oldt) + FastMath.abs(t)) * 0.5); - - // check convergence - if (iterations.getCount() + 1 >= getMinimalIterationCount() && - delta <= limit) { - return t; - } - - // Prepare next iteration. - final double ratio = FastMath.min(4, FastMath.pow(delta / limit, 0.5 / numberOfPoints)); - n = FastMath.max((int) (ratio * n), n + 1); - oldt = t; - iterations.incrementCount(); - } - } - - /** - * Compute the n-th stage integral. - * - * @param n Number of steps. - * @return the value of n-th stage integral. - * @throws TooManyEvaluationsException if the maximum number of evaluations - * is exceeded. - */ - private double stage(final int n) - throws TooManyEvaluationsException { - // Function to be integrated is stored in the base class. - final UnivariateFunction f = new UnivariateFunction() { - /** {@inheritDoc} */ - @Override - public double value(double x) - throws MathIllegalArgumentException, TooManyEvaluationsException { - return computeObjectiveValue(x); - } - }; - - final double min = getMin(); - final double max = getMax(); - final double step = (max - min) / n; - - double sum = 0; - for (int i = 0; i < n; i++) { - // Integrate over each sub-interval [a, b]. - final double a = min + i * step; - final double b = a + step; - final GaussIntegrator g = FACTORY.legendreHighPrecision(numberOfPoints, a, b); - sum += g.integrate(f); - } - - return sum; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/MidPointIntegrator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/MidPointIntegrator.java deleted file mode 100644 index edcb3007c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/MidPointIntegrator.java +++ /dev/null @@ -1,169 +0,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. - */ -package org.apache.commons.math4.analysis.integration; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.TooManyEvaluationsException; -import org.apache.commons.math4.util.FastMath; - -/** - * Implements the - * Midpoint Rule for integration of real univariate functions. For - * reference, see Numerical Mathematics, ISBN 0387989595, - * chapter 9.2. - *

- * The function should be integrable.

- * - * @since 3.3 - */ -public class MidPointIntegrator extends BaseAbstractUnivariateIntegrator { - - /** Maximum number of iterations for midpoint. */ - public static final int MIDPOINT_MAX_ITERATIONS_COUNT = 64; - - /** - * Build a midpoint integrator with given accuracies and iterations counts. - * @param relativeAccuracy relative accuracy of the result - * @param absoluteAccuracy absolute accuracy of the result - * @param minimalIterationCount minimum number of iterations - * @param maximalIterationCount maximum number of iterations - * (must be less than or equal to {@link #MIDPOINT_MAX_ITERATIONS_COUNT} - * @exception NotStrictlyPositiveException if minimal number of iterations - * is not strictly positive - * @exception NumberIsTooSmallException if maximal number of iterations - * is lesser than or equal to the minimal number of iterations - * @exception NumberIsTooLargeException if maximal number of iterations - * is greater than {@link #MIDPOINT_MAX_ITERATIONS_COUNT} - */ - public MidPointIntegrator(final double relativeAccuracy, - final double absoluteAccuracy, - final int minimalIterationCount, - final int maximalIterationCount) - throws NotStrictlyPositiveException, NumberIsTooSmallException, NumberIsTooLargeException { - super(relativeAccuracy, absoluteAccuracy, minimalIterationCount, maximalIterationCount); - if (maximalIterationCount > MIDPOINT_MAX_ITERATIONS_COUNT) { - throw new NumberIsTooLargeException(maximalIterationCount, - MIDPOINT_MAX_ITERATIONS_COUNT, false); - } - } - - /** - * Build a midpoint integrator with given iteration counts. - * @param minimalIterationCount minimum number of iterations - * @param maximalIterationCount maximum number of iterations - * (must be less than or equal to {@link #MIDPOINT_MAX_ITERATIONS_COUNT} - * @exception NotStrictlyPositiveException if minimal number of iterations - * is not strictly positive - * @exception NumberIsTooSmallException if maximal number of iterations - * is lesser than or equal to the minimal number of iterations - * @exception NumberIsTooLargeException if maximal number of iterations - * is greater than {@link #MIDPOINT_MAX_ITERATIONS_COUNT} - */ - public MidPointIntegrator(final int minimalIterationCount, - final int maximalIterationCount) - throws NotStrictlyPositiveException, NumberIsTooSmallException, NumberIsTooLargeException { - super(minimalIterationCount, maximalIterationCount); - if (maximalIterationCount > MIDPOINT_MAX_ITERATIONS_COUNT) { - throw new NumberIsTooLargeException(maximalIterationCount, - MIDPOINT_MAX_ITERATIONS_COUNT, false); - } - } - - /** - * Construct a midpoint integrator with default settings. - * (max iteration count set to {@link #MIDPOINT_MAX_ITERATIONS_COUNT}) - */ - public MidPointIntegrator() { - super(DEFAULT_MIN_ITERATIONS_COUNT, MIDPOINT_MAX_ITERATIONS_COUNT); - } - - /** - * Compute the n-th stage integral of midpoint rule. - * This function should only be called by API integrate() in the package. - * To save time it does not verify arguments - caller does. - *

- * The interval is divided equally into 2^n sections rather than an - * arbitrary m sections because this configuration can best utilize the - * already computed values.

- * - * @param n the stage of 1/2 refinement. Must be larger than 0. - * @param previousStageResult Result from the previous call to the - * {@code stage} method. - * @param min Lower bound of the integration interval. - * @param diffMaxMin Difference between the lower bound and upper bound - * of the integration interval. - * @return the value of n-th stage integral - * @throws TooManyEvaluationsException if the maximal number of evaluations - * is exceeded. - */ - private double stage(final int n, - double previousStageResult, - double min, - double diffMaxMin) - throws TooManyEvaluationsException { - - // number of new points in this stage - final long np = 1L << (n - 1); - double sum = 0; - - // spacing between adjacent new points - final double spacing = diffMaxMin / np; - - // the first new point - double x = min + 0.5 * spacing; - for (long i = 0; i < np; i++) { - sum += computeObjectiveValue(x); - x += spacing; - } - // add the new sum to previously calculated result - return 0.5 * (previousStageResult + sum * spacing); - } - - - /** {@inheritDoc} */ - @Override - protected double doIntegrate() - throws MathIllegalArgumentException, TooManyEvaluationsException, MaxCountExceededException { - - final double min = getMin(); - final double diff = getMax() - min; - final double midPoint = min + 0.5 * diff; - - double oldt = diff * computeObjectiveValue(midPoint); - - while (true) { - iterations.incrementCount(); - final int i = iterations.getCount(); - final double t = stage(i, oldt, min, diff); - if (i >= getMinimalIterationCount()) { - final double delta = FastMath.abs(t - oldt); - final double rLimit = - getRelativeAccuracy() * (FastMath.abs(oldt) + FastMath.abs(t)) * 0.5; - if ((delta <= rLimit) || (delta <= getAbsoluteAccuracy())) { - return t; - } - } - oldt = t; - } - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/RombergIntegrator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/RombergIntegrator.java deleted file mode 100644 index 923de73f7..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/RombergIntegrator.java +++ /dev/null @@ -1,142 +0,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. - */ -package org.apache.commons.math4.analysis.integration; - -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.TooManyEvaluationsException; -import org.apache.commons.math4.util.FastMath; - -/** - * Implements the - * Romberg Algorithm for integration of real univariate functions. For - * reference, see Introduction to Numerical Analysis, ISBN 038795452X, - * chapter 3. - *

- * Romberg integration employs k successive refinements of the trapezoid - * rule to remove error terms less than order O(N^(-2k)). Simpson's rule - * is a special case of k = 2.

- * - * @since 1.2 - */ -public class RombergIntegrator extends BaseAbstractUnivariateIntegrator { - - /** Maximal number of iterations for Romberg. */ - public static final int ROMBERG_MAX_ITERATIONS_COUNT = 32; - - /** - * Build a Romberg integrator with given accuracies and iterations counts. - * @param relativeAccuracy relative accuracy of the result - * @param absoluteAccuracy absolute accuracy of the result - * @param minimalIterationCount minimum number of iterations - * @param maximalIterationCount maximum number of iterations - * (must be less than or equal to {@link #ROMBERG_MAX_ITERATIONS_COUNT}) - * @exception NotStrictlyPositiveException if minimal number of iterations - * is not strictly positive - * @exception NumberIsTooSmallException if maximal number of iterations - * is lesser than or equal to the minimal number of iterations - * @exception NumberIsTooLargeException if maximal number of iterations - * is greater than {@link #ROMBERG_MAX_ITERATIONS_COUNT} - */ - public RombergIntegrator(final double relativeAccuracy, - final double absoluteAccuracy, - final int minimalIterationCount, - final int maximalIterationCount) - throws NotStrictlyPositiveException, NumberIsTooSmallException, NumberIsTooLargeException { - super(relativeAccuracy, absoluteAccuracy, minimalIterationCount, maximalIterationCount); - if (maximalIterationCount > ROMBERG_MAX_ITERATIONS_COUNT) { - throw new NumberIsTooLargeException(maximalIterationCount, - ROMBERG_MAX_ITERATIONS_COUNT, false); - } - } - - /** - * Build a Romberg integrator with given iteration counts. - * @param minimalIterationCount minimum number of iterations - * @param maximalIterationCount maximum number of iterations - * (must be less than or equal to {@link #ROMBERG_MAX_ITERATIONS_COUNT}) - * @exception NotStrictlyPositiveException if minimal number of iterations - * is not strictly positive - * @exception NumberIsTooSmallException if maximal number of iterations - * is lesser than or equal to the minimal number of iterations - * @exception NumberIsTooLargeException if maximal number of iterations - * is greater than {@link #ROMBERG_MAX_ITERATIONS_COUNT} - */ - public RombergIntegrator(final int minimalIterationCount, - final int maximalIterationCount) - throws NotStrictlyPositiveException, NumberIsTooSmallException, NumberIsTooLargeException { - super(minimalIterationCount, maximalIterationCount); - if (maximalIterationCount > ROMBERG_MAX_ITERATIONS_COUNT) { - throw new NumberIsTooLargeException(maximalIterationCount, - ROMBERG_MAX_ITERATIONS_COUNT, false); - } - } - - /** - * Construct a Romberg integrator with default settings - * (max iteration count set to {@link #ROMBERG_MAX_ITERATIONS_COUNT}) - */ - public RombergIntegrator() { - super(DEFAULT_MIN_ITERATIONS_COUNT, ROMBERG_MAX_ITERATIONS_COUNT); - } - - /** {@inheritDoc} */ - @Override - protected double doIntegrate() - throws TooManyEvaluationsException, MaxCountExceededException { - - final int m = iterations.getMaximalCount() + 1; - double previousRow[] = new double[m]; - double currentRow[] = new double[m]; - - TrapezoidIntegrator qtrap = new TrapezoidIntegrator(); - currentRow[0] = qtrap.stage(this, 0); - iterations.incrementCount(); - double olds = currentRow[0]; - while (true) { - - final int i = iterations.getCount(); - - // switch rows - final double[] tmpRow = previousRow; - previousRow = currentRow; - currentRow = tmpRow; - - currentRow[0] = qtrap.stage(this, i); - iterations.incrementCount(); - for (int j = 1; j <= i; j++) { - // Richardson extrapolation coefficient - final double r = (1L << (2 * j)) - 1; - final double tIJm1 = currentRow[j - 1]; - currentRow[j] = tIJm1 + (tIJm1 - previousRow[j - 1]) / r; - } - final double s = currentRow[i]; - if (i >= getMinimalIterationCount()) { - final double delta = FastMath.abs(s - olds); - final double rLimit = getRelativeAccuracy() * (FastMath.abs(olds) + FastMath.abs(s)) * 0.5; - if ((delta <= rLimit) || (delta <= getAbsoluteAccuracy())) { - return s; - } - } - olds = s; - } - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/SimpsonIntegrator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/SimpsonIntegrator.java deleted file mode 100644 index 0ede25e94..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/SimpsonIntegrator.java +++ /dev/null @@ -1,124 +0,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. - */ -package org.apache.commons.math4.analysis.integration; - -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.util.FastMath; - -/** - * Implements - * Simpson's Rule for integration of real univariate functions. For - * reference, see Introduction to Numerical Analysis, ISBN 038795452X, - * chapter 3. - *

- * This implementation employs the basic trapezoid rule to calculate Simpson's - * rule.

- * - * @since 1.2 - */ -public class SimpsonIntegrator extends BaseAbstractUnivariateIntegrator { - - /** Maximal number of iterations for Simpson. */ - public static final int SIMPSON_MAX_ITERATIONS_COUNT = 63; - - /** - * Build a Simpson integrator with given accuracies and iterations counts. - * @param relativeAccuracy relative accuracy of the result - * @param absoluteAccuracy absolute accuracy of the result - * @param minimalIterationCount minimum number of iterations - * @param maximalIterationCount maximum number of iterations - * (must be less than or equal to {@link #SIMPSON_MAX_ITERATIONS_COUNT}) - * @exception NotStrictlyPositiveException if minimal number of iterations - * is not strictly positive - * @exception NumberIsTooSmallException if maximal number of iterations - * is lesser than or equal to the minimal number of iterations - * @exception NumberIsTooLargeException if maximal number of iterations - * is greater than {@link #SIMPSON_MAX_ITERATIONS_COUNT} - */ - public SimpsonIntegrator(final double relativeAccuracy, - final double absoluteAccuracy, - final int minimalIterationCount, - final int maximalIterationCount) - throws NotStrictlyPositiveException, NumberIsTooSmallException, NumberIsTooLargeException { - super(relativeAccuracy, absoluteAccuracy, minimalIterationCount, maximalIterationCount); - if (maximalIterationCount > SIMPSON_MAX_ITERATIONS_COUNT) { - throw new NumberIsTooLargeException(maximalIterationCount, - SIMPSON_MAX_ITERATIONS_COUNT, false); - } - } - - /** - * Build a Simpson integrator with given iteration counts. - * @param minimalIterationCount minimum number of iterations - * @param maximalIterationCount maximum number of iterations - * (must be less than or equal to {@link #SIMPSON_MAX_ITERATIONS_COUNT}) - * @exception NotStrictlyPositiveException if minimal number of iterations - * is not strictly positive - * @exception NumberIsTooSmallException if maximal number of iterations - * is lesser than or equal to the minimal number of iterations - * @exception NumberIsTooLargeException if maximal number of iterations - * is greater than {@link #SIMPSON_MAX_ITERATIONS_COUNT} - */ - public SimpsonIntegrator(final int minimalIterationCount, - final int maximalIterationCount) - throws NotStrictlyPositiveException, NumberIsTooSmallException, NumberIsTooLargeException { - super(minimalIterationCount, maximalIterationCount); - if (maximalIterationCount > SIMPSON_MAX_ITERATIONS_COUNT) { - throw new NumberIsTooLargeException(maximalIterationCount, - SIMPSON_MAX_ITERATIONS_COUNT, false); - } - } - - /** - * Construct an integrator with default settings. - * (max iteration count set to {@link #SIMPSON_MAX_ITERATIONS_COUNT}) - */ - public SimpsonIntegrator() { - super(DEFAULT_MIN_ITERATIONS_COUNT, SIMPSON_MAX_ITERATIONS_COUNT); - } - - /** {@inheritDoc} */ - @Override - protected double doIntegrate() { - // Simpson's rule requires at least two trapezoid stages. - // So we set the first sum using two trapezoid stages. - final TrapezoidIntegrator qtrap = new TrapezoidIntegrator(); - - final double s0 = qtrap.stage(this, 0); - double oldt = qtrap.stage(this, 1); - double olds = (4 * oldt - s0) / 3.0; - while (true) { - // The first iteration is the first refinement of the sum. - iterations.incrementCount(); - final int i = getIterations(); - final double t = qtrap.stage(this, i + 1); // 1-stage ahead of the iteration - final double s = (4 * t - oldt) / 3.0; - if (i >= getMinimalIterationCount()) { - final double delta = FastMath.abs(s - olds); - final double rLimit = getRelativeAccuracy() * (FastMath.abs(olds) + FastMath.abs(s)) * 0.5; - if (delta <= rLimit || - delta <= getAbsoluteAccuracy()) { - return s; - } - } - olds = s; - oldt = t; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/TrapezoidIntegrator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/TrapezoidIntegrator.java deleted file mode 100644 index 893d602d0..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/TrapezoidIntegrator.java +++ /dev/null @@ -1,168 +0,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. - */ -package org.apache.commons.math4.analysis.integration; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.TooManyEvaluationsException; -import org.apache.commons.math4.util.FastMath; - -/** - * Implements the - * Trapezoid Rule for integration of real univariate functions. For - * reference, see Introduction to Numerical Analysis, ISBN 038795452X, - * chapter 3. - *

- * The function should be integrable.

- * - * @since 1.2 - */ -public class TrapezoidIntegrator extends BaseAbstractUnivariateIntegrator { - - /** Maximum number of iterations for trapezoid. */ - public static final int TRAPEZOID_MAX_ITERATIONS_COUNT = 64; - - /** Intermediate result. */ - private double s; - - /** - * Build a trapezoid integrator with given accuracies and iterations counts. - * @param relativeAccuracy relative accuracy of the result - * @param absoluteAccuracy absolute accuracy of the result - * @param minimalIterationCount minimum number of iterations - * @param maximalIterationCount maximum number of iterations - * (must be less than or equal to {@link #TRAPEZOID_MAX_ITERATIONS_COUNT} - * @exception NotStrictlyPositiveException if minimal number of iterations - * is not strictly positive - * @exception NumberIsTooSmallException if maximal number of iterations - * is lesser than or equal to the minimal number of iterations - * @exception NumberIsTooLargeException if maximal number of iterations - * is greater than {@link #TRAPEZOID_MAX_ITERATIONS_COUNT} - */ - public TrapezoidIntegrator(final double relativeAccuracy, - final double absoluteAccuracy, - final int minimalIterationCount, - final int maximalIterationCount) - throws NotStrictlyPositiveException, NumberIsTooSmallException, NumberIsTooLargeException { - super(relativeAccuracy, absoluteAccuracy, minimalIterationCount, maximalIterationCount); - if (maximalIterationCount > TRAPEZOID_MAX_ITERATIONS_COUNT) { - throw new NumberIsTooLargeException(maximalIterationCount, - TRAPEZOID_MAX_ITERATIONS_COUNT, false); - } - } - - /** - * Build a trapezoid integrator with given iteration counts. - * @param minimalIterationCount minimum number of iterations - * @param maximalIterationCount maximum number of iterations - * (must be less than or equal to {@link #TRAPEZOID_MAX_ITERATIONS_COUNT} - * @exception NotStrictlyPositiveException if minimal number of iterations - * is not strictly positive - * @exception NumberIsTooSmallException if maximal number of iterations - * is lesser than or equal to the minimal number of iterations - * @exception NumberIsTooLargeException if maximal number of iterations - * is greater than {@link #TRAPEZOID_MAX_ITERATIONS_COUNT} - */ - public TrapezoidIntegrator(final int minimalIterationCount, - final int maximalIterationCount) - throws NotStrictlyPositiveException, NumberIsTooSmallException, NumberIsTooLargeException { - super(minimalIterationCount, maximalIterationCount); - if (maximalIterationCount > TRAPEZOID_MAX_ITERATIONS_COUNT) { - throw new NumberIsTooLargeException(maximalIterationCount, - TRAPEZOID_MAX_ITERATIONS_COUNT, false); - } - } - - /** - * Construct a trapezoid integrator with default settings. - * (max iteration count set to {@link #TRAPEZOID_MAX_ITERATIONS_COUNT}) - */ - public TrapezoidIntegrator() { - super(DEFAULT_MIN_ITERATIONS_COUNT, TRAPEZOID_MAX_ITERATIONS_COUNT); - } - - /** - * Compute the n-th stage integral of trapezoid rule. This function - * should only be called by API integrate() in the package. - * To save time it does not verify arguments - caller does. - *

- * The interval is divided equally into 2^n sections rather than an - * arbitrary m sections because this configuration can best utilize the - * already computed values.

- * - * @param baseIntegrator integrator holding integration parameters - * @param n the stage of 1/2 refinement, n = 0 is no refinement - * @return the value of n-th stage integral - * @throws TooManyEvaluationsException if the maximal number of evaluations - * is exceeded. - */ - double stage(final BaseAbstractUnivariateIntegrator baseIntegrator, final int n) - throws TooManyEvaluationsException { - - if (n == 0) { - final double max = baseIntegrator.getMax(); - final double min = baseIntegrator.getMin(); - s = 0.5 * (max - min) * - (baseIntegrator.computeObjectiveValue(min) + - baseIntegrator.computeObjectiveValue(max)); - return s; - } else { - final long np = 1L << (n-1); // number of new points in this stage - double sum = 0; - final double max = baseIntegrator.getMax(); - final double min = baseIntegrator.getMin(); - // spacing between adjacent new points - final double spacing = (max - min) / np; - double x = min + 0.5 * spacing; // the first new point - for (long i = 0; i < np; i++) { - sum += baseIntegrator.computeObjectiveValue(x); - x += spacing; - } - // add the new sum to previously calculated result - s = 0.5 * (s + sum * spacing); - return s; - } - } - - /** {@inheritDoc} */ - @Override - protected double doIntegrate() - throws MathIllegalArgumentException, TooManyEvaluationsException, MaxCountExceededException { - - double oldt = stage(this, 0); - iterations.incrementCount(); - while (true) { - final int i = iterations.getCount(); - final double t = stage(this, i); - if (i >= getMinimalIterationCount()) { - final double delta = FastMath.abs(t - oldt); - final double rLimit = - getRelativeAccuracy() * (FastMath.abs(oldt) + FastMath.abs(t)) * 0.5; - if ((delta <= rLimit) || (delta <= getAbsoluteAccuracy())) { - return t; - } - } - oldt = t; - iterations.incrementCount(); - } - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/UnivariateIntegrator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/UnivariateIntegrator.java deleted file mode 100644 index 60b8a444f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/UnivariateIntegrator.java +++ /dev/null @@ -1,95 +0,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. - */ -package org.apache.commons.math4.analysis.integration; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.TooManyEvaluationsException; - -/** - * Interface for univariate real integration algorithms. - * - * @since 1.2 - */ -public interface UnivariateIntegrator { - - /** - * Get the relative accuracy. - * - * @return the accuracy - */ - double getRelativeAccuracy(); - - /** - * Get the absolute accuracy. - * - * @return the accuracy - */ - double getAbsoluteAccuracy(); - - /** - * Get the min limit for the number of iterations. - * - * @return the actual min limit - */ - int getMinimalIterationCount(); - - /** - * Get the upper limit for the number of iterations. - * - * @return the actual upper limit - */ - int getMaximalIterationCount(); - - /** - * Integrate the function in the given interval. - * - * @param maxEval Maximum number of evaluations. - * @param f the integrand function - * @param min the lower bound for the interval - * @param max the upper bound for the interval - * @return the value of integral - * @throws TooManyEvaluationsException if the maximum number of function - * evaluations is exceeded - * @throws MaxCountExceededException if the maximum iteration count is exceeded - * or the integrator detects convergence problems otherwise - * @throws MathIllegalArgumentException if {@code min > max} or the endpoints do not - * satisfy the requirements specified by the integrator - * @throws NullArgumentException if {@code f} is {@code null}. - */ - double integrate(int maxEval, UnivariateFunction f, double min, - double max) - throws TooManyEvaluationsException, MaxCountExceededException, - MathIllegalArgumentException, NullArgumentException; - - /** - * Get the number of function evaluations of the last run of the integrator. - * - * @return number of function evaluations - */ - int getEvaluations(); - - /** - * Get the number of iterations of the last run of the integrator. - * - * @return number of iterations - */ - int getIterations(); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/BaseRuleFactory.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/BaseRuleFactory.java deleted file mode 100644 index bd05c5e68..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/BaseRuleFactory.java +++ /dev/null @@ -1,154 +0,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. - */ -package org.apache.commons.math4.analysis.integration.gauss; - -import java.util.Map; -import java.util.TreeMap; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.Pair; - -/** - * Base class for rules that determines the integration nodes and their - * weights. - * Subclasses must implement the {@link #computeRule(int) computeRule} method. - * - * @param Type of the number used to represent the points and weights of - * the quadrature rules. - * - * @since 3.1 - */ -public abstract class BaseRuleFactory { - /** List of points and weights, indexed by the order of the rule. */ - private final Map> pointsAndWeights - = new TreeMap<>(); - /** Cache for double-precision rules. */ - private final Map> pointsAndWeightsDouble - = new TreeMap<>(); - - /** - * Gets a copy of the quadrature rule with the given number of integration - * points. - * - * @param numberOfPoints Number of integration points. - * @return a copy of the integration rule. - * @throws NotStrictlyPositiveException if {@code numberOfPoints < 1}. - * @throws DimensionMismatchException if the elements of the rule pair do not - * have the same length. - */ - public Pair getRule(int numberOfPoints) - throws NotStrictlyPositiveException, DimensionMismatchException { - - if (numberOfPoints <= 0) { - throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_POINTS, - numberOfPoints); - } - - // Try to obtain the rule from the cache. - Pair cached = pointsAndWeightsDouble.get(numberOfPoints); - - if (cached == null) { - // Rule not computed yet. - - // Compute the rule. - final Pair rule = getRuleInternal(numberOfPoints); - cached = convertToDouble(rule); - - // Cache it. - pointsAndWeightsDouble.put(numberOfPoints, cached); - } - - // Return a copy. - return new Pair<>(cached.getFirst().clone(), - cached.getSecond().clone()); - } - - /** - * Gets a rule. - * Synchronization ensures that rules will be computed and added to the - * cache at most once. - * The returned rule is a reference into the cache. - * - * @param numberOfPoints Order of the rule to be retrieved. - * @return the points and weights corresponding to the given order. - * @throws DimensionMismatchException if the elements of the rule pair do not - * have the same length. - */ - protected synchronized Pair getRuleInternal(int numberOfPoints) - throws DimensionMismatchException { - final Pair rule = pointsAndWeights.get(numberOfPoints); - if (rule == null) { - addRule(computeRule(numberOfPoints)); - // The rule should be available now. - return getRuleInternal(numberOfPoints); - } - return rule; - } - - /** - * Stores a rule. - * - * @param rule Rule to be stored. - * @throws DimensionMismatchException if the elements of the pair do not - * have the same length. - */ - protected void addRule(Pair rule) throws DimensionMismatchException { - if (rule.getFirst().length != rule.getSecond().length) { - throw new DimensionMismatchException(rule.getFirst().length, - rule.getSecond().length); - } - - pointsAndWeights.put(rule.getFirst().length, rule); - } - - /** - * Computes the rule for the given order. - * - * @param numberOfPoints Order of the rule to be computed. - * @return the computed rule. - * @throws DimensionMismatchException if the elements of the pair do not - * have the same length. - */ - protected abstract Pair computeRule(int numberOfPoints) - throws DimensionMismatchException; - - /** - * Converts the from the actual {@code Number} type to {@code double} - * - * @param Type of the number used to represent the points and - * weights of the quadrature rules. - * @param rule Points and weights. - * @return points and weights as {@code double}s. - */ - private static Pair convertToDouble(Pair rule) { - final T[] pT = rule.getFirst(); - final T[] wT = rule.getSecond(); - - final int len = pT.length; - final double[] pD = new double[len]; - final double[] wD = new double[len]; - - for (int i = 0; i < len; i++) { - pD[i] = pT[i].doubleValue(); - wD[i] = wT[i].doubleValue(); - } - - return new Pair<>(pD, wD); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/GaussIntegrator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/GaussIntegrator.java deleted file mode 100644 index f934ce60f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/GaussIntegrator.java +++ /dev/null @@ -1,129 +0,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. - */ -package org.apache.commons.math4.analysis.integration.gauss; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.Pair; - -/** - * Class that implements the Gaussian rule for - * {@link #integrate(UnivariateFunction) integrating} a weighted - * function. - * - * @since 3.1 - */ -public class GaussIntegrator { - /** Nodes. */ - private final double[] points; - /** Nodes weights. */ - private final double[] weights; - - /** - * Creates an integrator from the given {@code points} and {@code weights}. - * The integration interval is defined by the first and last value of - * {@code points} which must be sorted in increasing order. - * - * @param points Integration points. - * @param weights Weights of the corresponding integration nodes. - * @throws NonMonotonicSequenceException if the {@code points} are not - * sorted in increasing order. - * @throws DimensionMismatchException if points and weights don't have the same length - */ - public GaussIntegrator(double[] points, - double[] weights) - throws NonMonotonicSequenceException, DimensionMismatchException { - if (points.length != weights.length) { - throw new DimensionMismatchException(points.length, - weights.length); - } - - MathArrays.checkOrder(points, MathArrays.OrderDirection.INCREASING, true, true); - - this.points = points.clone(); - this.weights = weights.clone(); - } - - /** - * Creates an integrator from the given pair of points (first element of - * the pair) and weights (second element of the pair. - * - * @param pointsAndWeights Integration points and corresponding weights. - * @throws NonMonotonicSequenceException if the {@code points} are not - * sorted in increasing order. - * - * @see #GaussIntegrator(double[], double[]) - */ - public GaussIntegrator(Pair pointsAndWeights) - throws NonMonotonicSequenceException { - this(pointsAndWeights.getFirst(), pointsAndWeights.getSecond()); - } - - /** - * Returns an estimate of the integral of {@code f(x) * w(x)}, - * where {@code w} is a weight function that depends on the actual - * flavor of the Gauss integration scheme. - * The algorithm uses the points and associated weights, as passed - * to the {@link #GaussIntegrator(double[],double[]) constructor}. - * - * @param f Function to integrate. - * @return the integral of the weighted function. - */ - public double integrate(UnivariateFunction f) { - double s = 0; - double c = 0; - for (int i = 0; i < points.length; i++) { - final double x = points[i]; - final double w = weights[i]; - final double y = w * f.value(x) - c; - final double t = s + y; - c = (t - s) - y; - s = t; - } - return s; - } - - /** - * @return the order of the integration rule (the number of integration - * points). - */ - public int getNumberOfPoints() { - return points.length; - } - - /** - * Gets the integration point at the given index. - * The index must be in the valid range but no check is performed. - * @param index index of the integration point - * @return the integration point. - */ - public double getPoint(int index) { - return points[index]; - } - - /** - * Gets the weight of the integration point at the given index. - * The index must be in the valid range but no check is performed. - * @param index index of the integration point - * @return the weight. - */ - public double getWeight(int index) { - return weights[index]; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/GaussIntegratorFactory.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/GaussIntegratorFactory.java deleted file mode 100644 index 25046921b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/GaussIntegratorFactory.java +++ /dev/null @@ -1,188 +0,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. - */ -package org.apache.commons.math4.analysis.integration.gauss; - -import java.math.BigDecimal; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.util.Pair; - -/** - * Class that provides different ways to compute the nodes and weights to be - * used by the {@link GaussIntegrator Gaussian integration rule}. - * - * @since 3.1 - */ -public class GaussIntegratorFactory { - /** Generator of Gauss-Legendre integrators. */ - private final BaseRuleFactory legendre = new LegendreRuleFactory(); - /** Generator of Gauss-Legendre integrators. */ - private final BaseRuleFactory legendreHighPrecision = new LegendreHighPrecisionRuleFactory(); - /** Generator of Gauss-Hermite integrators. */ - private final BaseRuleFactory hermite = new HermiteRuleFactory(); - /** Generator of Gauss-Laguerre integrators. */ - private final BaseRuleFactory laguerre = new LaguerreRuleFactory(); - - /** - * Creates a Gauss-Laguerre integrator of the given order. - * The call to the - * {@link GaussIntegrator#integrate(org.apache.commons.math4.analysis.UnivariateFunction) - * integrate} method will perform an integration on the interval - * \([0, +\infty)\): the computed value is the improper integral of - * \(e^{-x} f(x)\) - * where \(f(x)\) is the function passed to the - * {@link SymmetricGaussIntegrator#integrate(org.apache.commons.math4.analysis.UnivariateFunction) - * integrate} method. - * - * @param numberOfPoints Order of the integration rule. - * @return a Gauss-Legendre integrator. - * @since 4.0 - */ - public GaussIntegrator laguerre(int numberOfPoints) { - return new GaussIntegrator(getRule(laguerre, numberOfPoints)); - } - - /** - * Creates a Gauss-Legendre integrator of the given order. - * The call to the - * {@link GaussIntegrator#integrate(org.apache.commons.math4.analysis.UnivariateFunction) - * integrate} method will perform an integration on the natural interval - * {@code [-1 , 1]}. - * - * @param numberOfPoints Order of the integration rule. - * @return a Gauss-Legendre integrator. - */ - public GaussIntegrator legendre(int numberOfPoints) { - return new GaussIntegrator(getRule(legendre, numberOfPoints)); - } - - /** - * Creates a Gauss-Legendre integrator of the given order. - * The call to the - * {@link GaussIntegrator#integrate(org.apache.commons.math4.analysis.UnivariateFunction) - * integrate} method will perform an integration on the given interval. - * - * @param numberOfPoints Order of the integration rule. - * @param lowerBound Lower bound of the integration interval. - * @param upperBound Upper bound of the integration interval. - * @return a Gauss-Legendre integrator. - * @throws NotStrictlyPositiveException if number of points is not positive - */ - public GaussIntegrator legendre(int numberOfPoints, - double lowerBound, - double upperBound) - throws NotStrictlyPositiveException { - return new GaussIntegrator(transform(getRule(legendre, numberOfPoints), - lowerBound, upperBound)); - } - - /** - * Creates a Gauss-Legendre integrator of the given order. - * The call to the - * {@link GaussIntegrator#integrate(org.apache.commons.math4.analysis.UnivariateFunction) - * integrate} method will perform an integration on the natural interval - * {@code [-1 , 1]}. - * - * @param numberOfPoints Order of the integration rule. - * @return a Gauss-Legendre integrator. - * @throws NotStrictlyPositiveException if number of points is not positive - */ - public GaussIntegrator legendreHighPrecision(int numberOfPoints) - throws NotStrictlyPositiveException { - return new GaussIntegrator(getRule(legendreHighPrecision, numberOfPoints)); - } - - /** - * Creates an integrator of the given order, and whose call to the - * {@link GaussIntegrator#integrate(org.apache.commons.math4.analysis.UnivariateFunction) - * integrate} method will perform an integration on the given interval. - * - * @param numberOfPoints Order of the integration rule. - * @param lowerBound Lower bound of the integration interval. - * @param upperBound Upper bound of the integration interval. - * @return a Gauss-Legendre integrator. - * @throws NotStrictlyPositiveException if number of points is not positive - */ - public GaussIntegrator legendreHighPrecision(int numberOfPoints, - double lowerBound, - double upperBound) - throws NotStrictlyPositiveException { - return new GaussIntegrator(transform(getRule(legendreHighPrecision, numberOfPoints), - lowerBound, upperBound)); - } - - /** - * Creates a Gauss-Hermite integrator of the given order. - * The call to the - * {@link SymmetricGaussIntegrator#integrate(org.apache.commons.math4.analysis.UnivariateFunction) - * integrate} method will perform a weighted integration on the interval - * \([-\infty, +\infty]\): the computed value is the improper integral of - * \(e^{-x^2}f(x)\) - * where \(f(x)\) is the function passed to the - * {@link SymmetricGaussIntegrator#integrate(org.apache.commons.math4.analysis.UnivariateFunction) - * integrate} method. - * - * @param numberOfPoints Order of the integration rule. - * @return a Gauss-Hermite integrator. - */ - public SymmetricGaussIntegrator hermite(int numberOfPoints) { - return new SymmetricGaussIntegrator(getRule(hermite, numberOfPoints)); - } - - /** - * @param factory Integration rule factory. - * @param numberOfPoints Order of the integration rule. - * @return the integration nodes and weights. - * @throws NotStrictlyPositiveException if number of points is not positive - * @throws DimensionMismatchException if the elements of the rule pair do not - * have the same length. - */ - private static Pair getRule(BaseRuleFactory factory, - int numberOfPoints) - throws NotStrictlyPositiveException, DimensionMismatchException { - return factory.getRule(numberOfPoints); - } - - /** - * Performs a change of variable so that the integration can be performed - * on an arbitrary interval {@code [a, b]}. - * It is assumed that the natural interval is {@code [-1, 1]}. - * - * @param rule Original points and weights. - * @param a Lower bound of the integration interval. - * @param b Lower bound of the integration interval. - * @return the points and weights adapted to the new interval. - */ - private static Pair transform(Pair rule, - double a, - double b) { - final double[] points = rule.getFirst(); - final double[] weights = rule.getSecond(); - - // Scaling - final double scale = (b - a) / 2; - final double shift = a + scale; - - for (int i = 0; i < points.length; i++) { - points[i] = points[i] * scale + shift; - weights[i] *= scale; - } - - return new Pair<>(points, weights); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/HermiteRuleFactory.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/HermiteRuleFactory.java deleted file mode 100644 index e65f5bdeb..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/HermiteRuleFactory.java +++ /dev/null @@ -1,177 +0,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. - */ -package org.apache.commons.math4.analysis.integration.gauss; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.Pair; - -/** - * Factory that creates a - * - * Gauss-type quadrature rule using Hermite polynomials - * of the first kind. - * Such a quadrature rule allows the calculation of improper integrals - * of a function - *

- * \(f(x) e^{-x^2}\) - *

- * Recurrence relation and weights computation follow - * - * Abramowitz and Stegun, 1964. - *

- * The coefficients of the standard Hermite polynomials grow very rapidly. - * In order to avoid overflows, each Hermite polynomial is normalized with - * respect to the underlying scalar product. - * The initial interval for the application of the bisection method is - * based on the roots of the previous Hermite polynomial (interlacing). - * Upper and lower bounds of these roots are provided by

- *
- * I. Krasikov, - * Nonnegative quadratic forms and bounds on orthogonal polynomials, - * Journal of Approximation theory 111, 31-49 - *
- * - * @since 3.3 - */ -public class HermiteRuleFactory extends BaseRuleFactory { - /** π1/2 */ - private static final double SQRT_PI = 1.77245385090551602729; - /** π-1/4 */ - private static final double H0 = 7.5112554446494248286e-1; - /** π-1/4 √2 */ - private static final double H1 = 1.0622519320271969145; - - /** {@inheritDoc} */ - @Override - protected Pair computeRule(int numberOfPoints) - throws DimensionMismatchException { - - if (numberOfPoints == 1) { - // Break recursion. - return new Pair<>(new Double[] { 0d }, - new Double[] { SQRT_PI }); - } - - // Get previous rule. - // If it has not been computed yet it will trigger a recursive call - // to this method. - final int lastNumPoints = numberOfPoints - 1; - final Double[] previousPoints = getRuleInternal(lastNumPoints).getFirst(); - - // Compute next rule. - final Double[] points = new Double[numberOfPoints]; - final Double[] weights = new Double[numberOfPoints]; - - final double sqrtTwoTimesLastNumPoints = FastMath.sqrt(2 * lastNumPoints); - final double sqrtTwoTimesNumPoints = FastMath.sqrt(2 * numberOfPoints); - - // Find i-th root of H[n+1] by bracketing. - final int iMax = numberOfPoints / 2; - for (int i = 0; i < iMax; i++) { - // Lower-bound of the interval. - double a = (i == 0) ? -sqrtTwoTimesLastNumPoints : previousPoints[i - 1].doubleValue(); - // Upper-bound of the interval. - double b = (iMax == 1) ? -0.5 : previousPoints[i].doubleValue(); - - // H[j-1](a) - double hma = H0; - // H[j](a) - double ha = H1 * a; - // H[j-1](b) - double hmb = H0; - // H[j](b) - double hb = H1 * b; - for (int j = 1; j < numberOfPoints; j++) { - // Compute H[j+1](a) and H[j+1](b) - final double jp1 = j + 1; - final double s = FastMath.sqrt(2 / jp1); - final double sm = FastMath.sqrt(j / jp1); - final double hpa = s * a * ha - sm * hma; - final double hpb = s * b * hb - sm * hmb; - hma = ha; - ha = hpa; - hmb = hb; - hb = hpb; - } - - // Now ha = H[n+1](a), and hma = H[n](a) (same holds for b). - // Middle of the interval. - double c = 0.5 * (a + b); - // P[j-1](c) - double hmc = H0; - // P[j](c) - double hc = H1 * c; - boolean done = false; - while (!done) { - done = b - a <= Math.ulp(c); - hmc = H0; - hc = H1 * c; - for (int j = 1; j < numberOfPoints; j++) { - // Compute H[j+1](c) - final double jp1 = j + 1; - final double s = FastMath.sqrt(2 / jp1); - final double sm = FastMath.sqrt(j / jp1); - final double hpc = s * c * hc - sm * hmc; - hmc = hc; - hc = hpc; - } - // Now h = H[n+1](c) and hm = H[n](c). - if (!done) { - if (ha * hc < 0) { - b = c; - hmb = hmc; - hb = hc; - } else { - a = c; - hma = hmc; - ha = hc; - } - c = 0.5 * (a + b); - } - } - final double d = sqrtTwoTimesNumPoints * hmc; - final double w = 2 / (d * d); - - points[i] = c; - weights[i] = w; - - final int idx = lastNumPoints - i; - points[idx] = -c; - weights[idx] = w; - } - - // If "numberOfPoints" is odd, 0 is a root. - // Note: as written, the test for oddness will work for negative - // integers too (although it is not necessary here), preventing - // a FindBugs warning. - if (numberOfPoints % 2 != 0) { - double hm = H0; - for (int j = 1; j < numberOfPoints; j += 2) { - final double jp1 = j + 1; - hm = -FastMath.sqrt(j / jp1) * hm; - } - final double d = sqrtTwoTimesNumPoints * hm; - final double w = 2 / (d * d); - - points[iMax] = 0d; - weights[iMax] = w; - } - - return new Pair<>(points, weights); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/LaguerreRuleFactory.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/LaguerreRuleFactory.java deleted file mode 100644 index 25031e87f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/LaguerreRuleFactory.java +++ /dev/null @@ -1,84 +0,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. - */ -package org.apache.commons.math4.analysis.integration.gauss; - -import java.util.Arrays; - -import org.apache.commons.math4.analysis.polynomials.PolynomialFunction; -import org.apache.commons.math4.analysis.polynomials.PolynomialsUtils; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.linear.EigenDecomposition; -import org.apache.commons.math4.linear.MatrixUtils; -import org.apache.commons.math4.linear.RealMatrix; -import org.apache.commons.math4.util.Pair; - -/** - * Factory that creates Gauss-type quadrature rule using Laguerre polynomials. - * - * @see Gauss-Laguerre quadrature (Wikipedia) - * @since 4.0 - */ -public class LaguerreRuleFactory extends BaseRuleFactory { - /** {@inheritDoc} */ - @Override - protected Pair computeRule(int numberOfPoints) - throws DimensionMismatchException { - - final RealMatrix companionMatrix = companionMatrix(numberOfPoints); - final EigenDecomposition eigen = new EigenDecomposition(companionMatrix); - final double[] roots = eigen.getRealEigenvalues(); - Arrays.sort(roots); - - final Double[] points = new Double[numberOfPoints]; - final Double[] weights = new Double[numberOfPoints]; - - final int n1 = numberOfPoints + 1; - final long n1Squared = n1 * (long) n1; - final PolynomialFunction laguerreN1 = PolynomialsUtils.createLaguerrePolynomial(n1); - for (int i = 0; i < numberOfPoints; i++) { - final double xi = roots[i]; - points[i] = xi; - - final double val = laguerreN1.value(xi); - weights[i] = xi / n1Squared / (val * val); - } - - return new Pair<>(points, weights); - } - - /** - * @param degree Matrix dimension. - * @return a square matrix. - */ - private RealMatrix companionMatrix(final int degree) { - final RealMatrix c = MatrixUtils.createRealMatrix(degree, degree); - - for (int i = 0; i < degree; i++) { - c.setEntry(i, i, 2 * i + 1); - if (i + 1 < degree) { - // subdiagonal - c.setEntry(i+1, i, -(i + 1)); - } - if (i - 1 >= 0) { - // superdiagonal - c.setEntry(i-1, i, -i); - } - } - - return c; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/LegendreHighPrecisionRuleFactory.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/LegendreHighPrecisionRuleFactory.java deleted file mode 100644 index 1790c725a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/LegendreHighPrecisionRuleFactory.java +++ /dev/null @@ -1,215 +0,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. - */ -package org.apache.commons.math4.analysis.integration.gauss; - -import java.math.BigDecimal; -import java.math.MathContext; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.util.Pair; - -/** - * Factory that creates Gauss-type quadrature rule using Legendre polynomials. - * In this implementation, the lower and upper bounds of the natural interval - * of integration are -1 and 1, respectively. - * The Legendre polynomials are evaluated using the recurrence relation - * presented in - * Abramowitz and Stegun, 1964. - * - * @since 3.1 - */ -public class LegendreHighPrecisionRuleFactory extends BaseRuleFactory { - /** Settings for enhanced precision computations. */ - private final MathContext mContext; - /** The number {@code 2}. */ - private final BigDecimal two; - /** The number {@code -1}. */ - private final BigDecimal minusOne; - /** The number {@code 0.5}. */ - private final BigDecimal oneHalf; - - /** - * Default precision is {@link MathContext#DECIMAL128 DECIMAL128}. - */ - public LegendreHighPrecisionRuleFactory() { - this(MathContext.DECIMAL128); - } - - /** - * @param mContext Precision setting for computing the quadrature rules. - */ - public LegendreHighPrecisionRuleFactory(MathContext mContext) { - this.mContext = mContext; - two = new BigDecimal("2", mContext); - minusOne = new BigDecimal("-1", mContext); - oneHalf = new BigDecimal("0.5", mContext); - } - - /** {@inheritDoc} */ - @Override - protected Pair computeRule(int numberOfPoints) - throws DimensionMismatchException { - - if (numberOfPoints == 1) { - // Break recursion. - return new Pair<>(new BigDecimal[] { BigDecimal.ZERO }, - new BigDecimal[] { two }); - } - - // Get previous rule. - // If it has not been computed yet it will trigger a recursive call - // to this method. - final BigDecimal[] previousPoints = getRuleInternal(numberOfPoints - 1).getFirst(); - - // Compute next rule. - final BigDecimal[] points = new BigDecimal[numberOfPoints]; - final BigDecimal[] weights = new BigDecimal[numberOfPoints]; - - // Find i-th root of P[n+1] by bracketing. - final int iMax = numberOfPoints / 2; - for (int i = 0; i < iMax; i++) { - // Lower-bound of the interval. - BigDecimal a = (i == 0) ? minusOne : previousPoints[i - 1]; - // Upper-bound of the interval. - BigDecimal b = (iMax == 1) ? BigDecimal.ONE : previousPoints[i]; - // P[j-1](a) - BigDecimal pma = BigDecimal.ONE; - // P[j](a) - BigDecimal pa = a; - // P[j-1](b) - BigDecimal pmb = BigDecimal.ONE; - // P[j](b) - BigDecimal pb = b; - for (int j = 1; j < numberOfPoints; j++) { - final BigDecimal b_two_j_p_1 = new BigDecimal(2 * j + 1, mContext); - final BigDecimal b_j = new BigDecimal(j, mContext); - final BigDecimal b_j_p_1 = new BigDecimal(j + 1, mContext); - - // Compute P[j+1](a) - // ppa = ((2 * j + 1) * a * pa - j * pma) / (j + 1); - - BigDecimal tmp1 = a.multiply(b_two_j_p_1, mContext); - tmp1 = pa.multiply(tmp1, mContext); - BigDecimal tmp2 = pma.multiply(b_j, mContext); - // P[j+1](a) - BigDecimal ppa = tmp1.subtract(tmp2, mContext); - ppa = ppa.divide(b_j_p_1, mContext); - - // Compute P[j+1](b) - // ppb = ((2 * j + 1) * b * pb - j * pmb) / (j + 1); - - tmp1 = b.multiply(b_two_j_p_1, mContext); - tmp1 = pb.multiply(tmp1, mContext); - tmp2 = pmb.multiply(b_j, mContext); - // P[j+1](b) - BigDecimal ppb = tmp1.subtract(tmp2, mContext); - ppb = ppb.divide(b_j_p_1, mContext); - - pma = pa; - pa = ppa; - pmb = pb; - pb = ppb; - } - // Now pa = P[n+1](a), and pma = P[n](a). Same holds for b. - // Middle of the interval. - BigDecimal c = a.add(b, mContext).multiply(oneHalf, mContext); - // P[j-1](c) - BigDecimal pmc = BigDecimal.ONE; - // P[j](c) - BigDecimal pc = c; - boolean done = false; - while (!done) { - BigDecimal tmp1 = b.subtract(a, mContext); - BigDecimal tmp2 = c.ulp().multiply(BigDecimal.TEN, mContext); - done = tmp1.compareTo(tmp2) <= 0; - pmc = BigDecimal.ONE; - pc = c; - for (int j = 1; j < numberOfPoints; j++) { - final BigDecimal b_two_j_p_1 = new BigDecimal(2 * j + 1, mContext); - final BigDecimal b_j = new BigDecimal(j, mContext); - final BigDecimal b_j_p_1 = new BigDecimal(j + 1, mContext); - - // Compute P[j+1](c) - tmp1 = c.multiply(b_two_j_p_1, mContext); - tmp1 = pc.multiply(tmp1, mContext); - tmp2 = pmc.multiply(b_j, mContext); - // P[j+1](c) - BigDecimal ppc = tmp1.subtract(tmp2, mContext); - ppc = ppc.divide(b_j_p_1, mContext); - - pmc = pc; - pc = ppc; - } - // Now pc = P[n+1](c) and pmc = P[n](c). - if (!done) { - if (pa.signum() * pc.signum() <= 0) { - b = c; - pmb = pmc; - pb = pc; - } else { - a = c; - pma = pmc; - pa = pc; - } - c = a.add(b, mContext).multiply(oneHalf, mContext); - } - } - final BigDecimal nP = new BigDecimal(numberOfPoints, mContext); - BigDecimal tmp1 = pmc.subtract(c.multiply(pc, mContext), mContext); - tmp1 = tmp1.multiply(nP); - tmp1 = tmp1.pow(2, mContext); - BigDecimal tmp2 = c.pow(2, mContext); - tmp2 = BigDecimal.ONE.subtract(tmp2, mContext); - tmp2 = tmp2.multiply(two, mContext); - tmp2 = tmp2.divide(tmp1, mContext); - - points[i] = c; - weights[i] = tmp2; - - final int idx = numberOfPoints - i - 1; - points[idx] = c.negate(mContext); - weights[idx] = tmp2; - } - // If "numberOfPoints" is odd, 0 is a root. - // Note: as written, the test for oddness will work for negative - // integers too (although it is not necessary here), preventing - // a FindBugs warning. - if (numberOfPoints % 2 != 0) { - BigDecimal pmc = BigDecimal.ONE; - for (int j = 1; j < numberOfPoints; j += 2) { - final BigDecimal b_j = new BigDecimal(j, mContext); - final BigDecimal b_j_p_1 = new BigDecimal(j + 1, mContext); - - // pmc = -j * pmc / (j + 1); - pmc = pmc.multiply(b_j, mContext); - pmc = pmc.divide(b_j_p_1, mContext); - pmc = pmc.negate(mContext); - } - - // 2 / pow(numberOfPoints * pmc, 2); - final BigDecimal nP = new BigDecimal(numberOfPoints, mContext); - BigDecimal tmp1 = pmc.multiply(nP, mContext); - tmp1 = tmp1.pow(2, mContext); - BigDecimal tmp2 = two.divide(tmp1, mContext); - - points[iMax] = BigDecimal.ZERO; - weights[iMax] = tmp2; - } - - return new Pair<>(points, weights); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/LegendreRuleFactory.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/LegendreRuleFactory.java deleted file mode 100644 index 29684bffa..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/LegendreRuleFactory.java +++ /dev/null @@ -1,140 +0,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. - */ -package org.apache.commons.math4.analysis.integration.gauss; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.util.Pair; - -/** - * Factory that creates Gauss-type quadrature rule using Legendre polynomials. - * In this implementation, the lower and upper bounds of the natural interval - * of integration are -1 and 1, respectively. - * The Legendre polynomials are evaluated using the recurrence relation - * presented in - * Abramowitz and Stegun, 1964. - * - * @since 3.1 - */ -public class LegendreRuleFactory extends BaseRuleFactory { - /** {@inheritDoc} */ - @Override - protected Pair computeRule(int numberOfPoints) - throws DimensionMismatchException { - - if (numberOfPoints == 1) { - // Break recursion. - return new Pair<>(new Double[] { 0d }, - new Double[] { 2d }); - } - - // Get previous rule. - // If it has not been computed yet it will trigger a recursive call - // to this method. - final Double[] previousPoints = getRuleInternal(numberOfPoints - 1).getFirst(); - - // Compute next rule. - final Double[] points = new Double[numberOfPoints]; - final Double[] weights = new Double[numberOfPoints]; - - // Find i-th root of P[n+1] by bracketing. - final int iMax = numberOfPoints / 2; - for (int i = 0; i < iMax; i++) { - // Lower-bound of the interval. - double a = (i == 0) ? -1 : previousPoints[i - 1].doubleValue(); - // Upper-bound of the interval. - double b = (iMax == 1) ? 1 : previousPoints[i].doubleValue(); - // P[j-1](a) - double pma = 1; - // P[j](a) - double pa = a; - // P[j-1](b) - double pmb = 1; - // P[j](b) - double pb = b; - for (int j = 1; j < numberOfPoints; j++) { - final int two_j_p_1 = 2 * j + 1; - final int j_p_1 = j + 1; - // P[j+1](a) - final double ppa = (two_j_p_1 * a * pa - j * pma) / j_p_1; - // P[j+1](b) - final double ppb = (two_j_p_1 * b * pb - j * pmb) / j_p_1; - pma = pa; - pa = ppa; - pmb = pb; - pb = ppb; - } - // Now pa = P[n+1](a), and pma = P[n](a) (same holds for b). - // Middle of the interval. - double c = 0.5 * (a + b); - // P[j-1](c) - double pmc = 1; - // P[j](c) - double pc = c; - boolean done = false; - while (!done) { - done = b - a <= Math.ulp(c); - pmc = 1; - pc = c; - for (int j = 1; j < numberOfPoints; j++) { - // P[j+1](c) - final double ppc = ((2 * j + 1) * c * pc - j * pmc) / (j + 1); - pmc = pc; - pc = ppc; - } - // Now pc = P[n+1](c) and pmc = P[n](c). - if (!done) { - if (pa * pc <= 0) { - b = c; - pmb = pmc; - pb = pc; - } else { - a = c; - pma = pmc; - pa = pc; - } - c = 0.5 * (a + b); - } - } - final double d = numberOfPoints * (pmc - c * pc); - final double w = 2 * (1 - c * c) / (d * d); - - points[i] = c; - weights[i] = w; - - final int idx = numberOfPoints - i - 1; - points[idx] = -c; - weights[idx] = w; - } - // If "numberOfPoints" is odd, 0 is a root. - // Note: as written, the test for oddness will work for negative - // integers too (although it is not necessary here), preventing - // a FindBugs warning. - if (numberOfPoints % 2 != 0) { - double pmc = 1; - for (int j = 1; j < numberOfPoints; j += 2) { - pmc = -j * pmc / (j + 1); - } - final double d = numberOfPoints * pmc; - final double w = 2 / (d * d); - - points[iMax] = 0d; - weights[iMax] = w; - } - - return new Pair<>(points, weights); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/SymmetricGaussIntegrator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/SymmetricGaussIntegrator.java deleted file mode 100644 index ee3a466ad..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/SymmetricGaussIntegrator.java +++ /dev/null @@ -1,103 +0,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. - */ -package org.apache.commons.math4.analysis.integration.gauss; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.util.Pair; - -/** - * This class's implements {@link #integrate(UnivariateFunction) integrate} - * method assuming that the integral is symmetric about 0. - * This allows to reduce numerical errors. - * - * @since 3.3 - */ -public class SymmetricGaussIntegrator extends GaussIntegrator { - /** - * Creates an integrator from the given {@code points} and {@code weights}. - * The integration interval is defined by the first and last value of - * {@code points} which must be sorted in increasing order. - * - * @param points Integration points. - * @param weights Weights of the corresponding integration nodes. - * @throws NonMonotonicSequenceException if the {@code points} are not - * sorted in increasing order. - * @throws DimensionMismatchException if points and weights don't have the same length - */ - public SymmetricGaussIntegrator(double[] points, - double[] weights) - throws NonMonotonicSequenceException, DimensionMismatchException { - super(points, weights); - } - - /** - * Creates an integrator from the given pair of points (first element of - * the pair) and weights (second element of the pair. - * - * @param pointsAndWeights Integration points and corresponding weights. - * @throws NonMonotonicSequenceException if the {@code points} are not - * sorted in increasing order. - * - * @see #SymmetricGaussIntegrator(double[], double[]) - */ - public SymmetricGaussIntegrator(Pair pointsAndWeights) - throws NonMonotonicSequenceException { - this(pointsAndWeights.getFirst(), pointsAndWeights.getSecond()); - } - - /** - * {@inheritDoc} - */ - @Override - public double integrate(UnivariateFunction f) { - final int ruleLength = getNumberOfPoints(); - - if (ruleLength == 1) { - return getWeight(0) * f.value(0d); - } - - final int iMax = ruleLength / 2; - double s = 0; - double c = 0; - for (int i = 0; i < iMax; i++) { - final double p = getPoint(i); - final double w = getWeight(i); - - final double f1 = f.value(p); - final double f2 = f.value(-p); - - final double y = w * (f1 + f2) - c; - final double t = s + y; - - c = (t - s) - y; - s = t; - } - - if (ruleLength % 2 != 0) { - final double w = getWeight(iMax); - - final double y = w * f.value(0d) - c; - final double t = s + y; - - s = t; - } - - return s; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/package-info.java deleted file mode 100644 index 9fd1bc888..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/gauss/package-info.java +++ /dev/null @@ -1,22 +0,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. - */ -/** - * - * Gauss family of quadrature schemes. - * - */ -package org.apache.commons.math4.analysis.integration.gauss; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/package-info.java deleted file mode 100644 index 4afe6b0ba..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/integration/package-info.java +++ /dev/null @@ -1,22 +0,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. - */ -/** - * - * Numerical integration (quadrature) algorithms for univariate real functions. - * - */ -package org.apache.commons.math4.analysis.integration; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/AkimaSplineInterpolator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/AkimaSplineInterpolator.java deleted file mode 100644 index 089a7acf4..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/AkimaSplineInterpolator.java +++ /dev/null @@ -1,216 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import org.apache.commons.math4.analysis.polynomials.PolynomialFunction; -import org.apache.commons.math4.analysis.polynomials.PolynomialSplineFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.numbers.core.Precision; - -/** - * Computes a cubic spline interpolation for the data set using the Akima - * algorithm, as originally formulated by Hiroshi Akima in his 1970 paper - * "A New Method of Interpolation and Smooth Curve Fitting Based on Local Procedures." - * J. ACM 17, 4 (October 1970), 589-602. DOI=10.1145/321607.321609 - * http://doi.acm.org/10.1145/321607.321609 - *

- * This implementation is based on the Akima implementation in the CubicSpline - * class in the Math.NET Numerics library. The method referenced is - * CubicSpline.InterpolateAkimaSorted - *

- *

- * The {@link #interpolate(double[], double[]) interpolate} method returns a - * {@link PolynomialSplineFunction} consisting of n cubic polynomials, defined - * over the subintervals determined by the x values, {@code x[0] < x[i] ... < x[n]}. - * The Akima algorithm requires that {@code n >= 5}. - *

- */ -public class AkimaSplineInterpolator - implements UnivariateInterpolator { - /** The minimum number of points that are needed to compute the function. */ - private static final int MINIMUM_NUMBER_POINTS = 5; - - /** - * Computes an interpolating function for the data set. - * - * @param xvals the arguments for the interpolation points - * @param yvals the values for the interpolation points - * @return a function which interpolates the data set - * @throws DimensionMismatchException if {@code xvals} and {@code yvals} have - * different sizes. - * @throws NonMonotonicSequenceException if {@code xvals} is not sorted in - * strict increasing order. - * @throws NumberIsTooSmallException if the size of {@code xvals} is smaller - * than 5. - */ - @Override - public PolynomialSplineFunction interpolate(double[] xvals, - double[] yvals) - throws DimensionMismatchException, - NumberIsTooSmallException, - NonMonotonicSequenceException { - if (xvals == null || - yvals == null) { - throw new NullArgumentException(); - } - - if (xvals.length != yvals.length) { - throw new DimensionMismatchException(xvals.length, yvals.length); - } - - if (xvals.length < MINIMUM_NUMBER_POINTS) { - throw new NumberIsTooSmallException(LocalizedFormats.NUMBER_OF_POINTS, - xvals.length, - MINIMUM_NUMBER_POINTS, true); - } - - MathArrays.checkOrder(xvals); - - final int numberOfDiffAndWeightElements = xvals.length - 1; - - final double[] differences = new double[numberOfDiffAndWeightElements]; - final double[] weights = new double[numberOfDiffAndWeightElements]; - - for (int i = 0; i < differences.length; i++) { - differences[i] = (yvals[i + 1] - yvals[i]) / (xvals[i + 1] - xvals[i]); - } - - for (int i = 1; i < weights.length; i++) { - weights[i] = FastMath.abs(differences[i] - differences[i - 1]); - } - - // Prepare Hermite interpolation scheme. - final double[] firstDerivatives = new double[xvals.length]; - - for (int i = 2; i < firstDerivatives.length - 2; i++) { - final double wP = weights[i + 1]; - final double wM = weights[i - 1]; - if (Precision.equals(wP, 0.0) && - Precision.equals(wM, 0.0)) { - final double xv = xvals[i]; - final double xvP = xvals[i + 1]; - final double xvM = xvals[i - 1]; - firstDerivatives[i] = (((xvP - xv) * differences[i - 1]) + ((xv - xvM) * differences[i])) / (xvP - xvM); - } else { - firstDerivatives[i] = ((wP * differences[i - 1]) + (wM * differences[i])) / (wP + wM); - } - } - - firstDerivatives[0] = differentiateThreePoint(xvals, yvals, 0, 0, 1, 2); - firstDerivatives[1] = differentiateThreePoint(xvals, yvals, 1, 0, 1, 2); - firstDerivatives[xvals.length - 2] = differentiateThreePoint(xvals, yvals, xvals.length - 2, - xvals.length - 3, xvals.length - 2, - xvals.length - 1); - firstDerivatives[xvals.length - 1] = differentiateThreePoint(xvals, yvals, xvals.length - 1, - xvals.length - 3, xvals.length - 2, - xvals.length - 1); - - return interpolateHermiteSorted(xvals, yvals, firstDerivatives); - } - - /** - * Three point differentiation helper, modeled off of the same method in the - * Math.NET CubicSpline class. This is used by both the Apache Math and the - * Math.NET Akima Cubic Spline algorithms - * - * @param xvals x values to calculate the numerical derivative with - * @param yvals y values to calculate the numerical derivative with - * @param indexOfDifferentiation index of the elemnt we are calculating the derivative around - * @param indexOfFirstSample index of the first element to sample for the three point method - * @param indexOfSecondsample index of the second element to sample for the three point method - * @param indexOfThirdSample index of the third element to sample for the three point method - * @return the derivative - */ - private double differentiateThreePoint(double[] xvals, double[] yvals, - int indexOfDifferentiation, - int indexOfFirstSample, - int indexOfSecondsample, - int indexOfThirdSample) { - final double x0 = yvals[indexOfFirstSample]; - final double x1 = yvals[indexOfSecondsample]; - final double x2 = yvals[indexOfThirdSample]; - - final double t = xvals[indexOfDifferentiation] - xvals[indexOfFirstSample]; - final double t1 = xvals[indexOfSecondsample] - xvals[indexOfFirstSample]; - final double t2 = xvals[indexOfThirdSample] - xvals[indexOfFirstSample]; - - final double a = (x2 - x0 - (t2 / t1 * (x1 - x0))) / (t2 * t2 - t1 * t2); - final double b = (x1 - x0 - a * t1 * t1) / t1; - - return (2 * a * t) + b; - } - - /** - * Creates a Hermite cubic spline interpolation from the set of (x,y) value - * pairs and their derivatives. This is modeled off of the - * InterpolateHermiteSorted method in the Math.NET CubicSpline class. - * - * @param xvals x values for interpolation - * @param yvals y values for interpolation - * @param firstDerivatives first derivative values of the function - * @return polynomial that fits the function - */ - private PolynomialSplineFunction interpolateHermiteSorted(double[] xvals, - double[] yvals, - double[] firstDerivatives) { - if (xvals.length != yvals.length) { - throw new DimensionMismatchException(xvals.length, yvals.length); - } - - if (xvals.length != firstDerivatives.length) { - throw new DimensionMismatchException(xvals.length, - firstDerivatives.length); - } - - final int minimumLength = 2; - if (xvals.length < minimumLength) { - throw new NumberIsTooSmallException(LocalizedFormats.NUMBER_OF_POINTS, - xvals.length, minimumLength, - true); - } - - final int size = xvals.length - 1; - final PolynomialFunction[] polynomials = new PolynomialFunction[size]; - final double[] coefficients = new double[4]; - - for (int i = 0; i < polynomials.length; i++) { - final double w = xvals[i + 1] - xvals[i]; - final double w2 = w * w; - - final double yv = yvals[i]; - final double yvP = yvals[i + 1]; - - final double fd = firstDerivatives[i]; - final double fdP = firstDerivatives[i + 1]; - - coefficients[0] = yv; - coefficients[1] = firstDerivatives[i]; - coefficients[2] = (3 * (yvP - yv) / w - 2 * fd - fdP) / w; - coefficients[3] = (2 * (yv - yvP) / w + fd + fdP) / w2; - polynomials[i] = new PolynomialFunction(coefficients); - } - - return new PolynomialSplineFunction(xvals, polynomials); - - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/BicubicInterpolatingFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/BicubicInterpolatingFunction.java deleted file mode 100644 index aa2350274..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/BicubicInterpolatingFunction.java +++ /dev/null @@ -1,329 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import java.util.Arrays; - -import org.apache.commons.numbers.arrays.LinearCombination; -import org.apache.commons.math4.analysis.BivariateFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.util.MathArrays; - -/** - * Function that implements the - * - * bicubic spline interpolation. - * - * @since 3.4 - */ -public class BicubicInterpolatingFunction - implements BivariateFunction { - /** Number of coefficients. */ - private static final int NUM_COEFF = 16; - /** - * Matrix to compute the spline coefficients from the function values - * and function derivatives values - */ - private static final double[][] AINV = { - { 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0 }, - { -3,3,0,0,-2,-1,0,0,0,0,0,0,0,0,0,0 }, - { 2,-2,0,0,1,1,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0 }, - { 0,0,0,0,0,0,0,0,-3,3,0,0,-2,-1,0,0 }, - { 0,0,0,0,0,0,0,0,2,-2,0,0,1,1,0,0 }, - { -3,0,3,0,0,0,0,0,-2,0,-1,0,0,0,0,0 }, - { 0,0,0,0,-3,0,3,0,0,0,0,0,-2,0,-1,0 }, - { 9,-9,-9,9,6,3,-6,-3,6,-6,3,-3,4,2,2,1 }, - { -6,6,6,-6,-3,-3,3,3,-4,4,-2,2,-2,-2,-1,-1 }, - { 2,0,-2,0,0,0,0,0,1,0,1,0,0,0,0,0 }, - { 0,0,0,0,2,0,-2,0,0,0,0,0,1,0,1,0 }, - { -6,6,6,-6,-4,-2,4,2,-3,3,-3,3,-2,-1,-2,-1 }, - { 4,-4,-4,4,2,2,-2,-2,2,-2,2,-2,1,1,1,1 } - }; - - /** Samples x-coordinates */ - private final double[] xval; - /** Samples y-coordinates */ - private final double[] yval; - /** Set of cubic splines patching the whole data grid */ - private final BicubicFunction[][] splines; - - /** - * @param x Sample values of the x-coordinate, in increasing order. - * @param y Sample values of the y-coordinate, in increasing order. - * @param f Values of the function on every grid point. - * @param dFdX Values of the partial derivative of function with respect - * to x on every grid point. - * @param dFdY Values of the partial derivative of function with respect - * to y on every grid point. - * @param d2FdXdY Values of the cross partial derivative of function on - * every grid point. - * @throws DimensionMismatchException if the various arrays do not contain - * the expected number of elements. - * @throws NonMonotonicSequenceException if {@code x} or {@code y} are - * not strictly increasing. - * @throws NoDataException if any of the arrays has zero length. - */ - public BicubicInterpolatingFunction(double[] x, - double[] y, - double[][] f, - double[][] dFdX, - double[][] dFdY, - double[][] d2FdXdY) - throws DimensionMismatchException, - NoDataException, - NonMonotonicSequenceException { - final int xLen = x.length; - final int yLen = y.length; - - if (xLen == 0 || yLen == 0 || f.length == 0 || f[0].length == 0) { - throw new NoDataException(); - } - if (xLen != f.length) { - throw new DimensionMismatchException(xLen, f.length); - } - if (xLen != dFdX.length) { - throw new DimensionMismatchException(xLen, dFdX.length); - } - if (xLen != dFdY.length) { - throw new DimensionMismatchException(xLen, dFdY.length); - } - if (xLen != d2FdXdY.length) { - throw new DimensionMismatchException(xLen, d2FdXdY.length); - } - - MathArrays.checkOrder(x); - MathArrays.checkOrder(y); - - xval = x.clone(); - yval = y.clone(); - - final int lastI = xLen - 1; - final int lastJ = yLen - 1; - splines = new BicubicFunction[lastI][lastJ]; - - for (int i = 0; i < lastI; i++) { - if (f[i].length != yLen) { - throw new DimensionMismatchException(f[i].length, yLen); - } - if (dFdX[i].length != yLen) { - throw new DimensionMismatchException(dFdX[i].length, yLen); - } - if (dFdY[i].length != yLen) { - throw new DimensionMismatchException(dFdY[i].length, yLen); - } - if (d2FdXdY[i].length != yLen) { - throw new DimensionMismatchException(d2FdXdY[i].length, yLen); - } - final int ip1 = i + 1; - final double xR = xval[ip1] - xval[i]; - for (int j = 0; j < lastJ; j++) { - final int jp1 = j + 1; - final double yR = yval[jp1] - yval[j]; - final double xRyR = xR * yR; - final double[] beta = new double[] { - f[i][j], f[ip1][j], f[i][jp1], f[ip1][jp1], - dFdX[i][j] * xR, dFdX[ip1][j] * xR, dFdX[i][jp1] * xR, dFdX[ip1][jp1] * xR, - dFdY[i][j] * yR, dFdY[ip1][j] * yR, dFdY[i][jp1] * yR, dFdY[ip1][jp1] * yR, - d2FdXdY[i][j] * xRyR, d2FdXdY[ip1][j] * xRyR, d2FdXdY[i][jp1] * xRyR, d2FdXdY[ip1][jp1] * xRyR - }; - - splines[i][j] = new BicubicFunction(computeSplineCoefficients(beta)); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public double value(double x, double y) - throws OutOfRangeException { - final int i = searchIndex(x, xval); - final int j = searchIndex(y, yval); - - final double xN = (x - xval[i]) / (xval[i + 1] - xval[i]); - final double yN = (y - yval[j]) / (yval[j + 1] - yval[j]); - - return splines[i][j].value(xN, yN); - } - - /** - * Indicates whether a point is within the interpolation range. - * - * @param x First coordinate. - * @param y Second coordinate. - * @return {@code true} if (x, y) is a valid point. - */ - public boolean isValidPoint(double x, double y) { - if (x < xval[0] || - x > xval[xval.length - 1] || - y < yval[0] || - y > yval[yval.length - 1]) { - return false; - } else { - return true; - } - } - - /** - * @param c Coordinate. - * @param val Coordinate samples. - * @return the index in {@code val} corresponding to the interval - * containing {@code c}. - * @throws OutOfRangeException if {@code c} is out of the - * range defined by the boundary values of {@code val}. - */ - private int searchIndex(double c, double[] val) { - final int r = Arrays.binarySearch(val, c); - - if (r == -1 || - r == -val.length - 1) { - throw new OutOfRangeException(c, val[0], val[val.length - 1]); - } - - if (r < 0) { - // "c" in within an interpolation sub-interval: Return the - // index of the sample at the lower end of the sub-interval. - return -r - 2; - } - final int last = val.length - 1; - if (r == last) { - // "c" is the last sample of the range: Return the index - // of the sample at the lower end of the last sub-interval. - return last - 1; - } - - // "c" is another sample point. - return r; - } - - /** - * Compute the spline coefficients from the list of function values and - * function partial derivatives values at the four corners of a grid - * element. They must be specified in the following order: - *
    - *
  • f(0,0)
  • - *
  • f(1,0)
  • - *
  • f(0,1)
  • - *
  • f(1,1)
  • - *
  • fx(0,0)
  • - *
  • fx(1,0)
  • - *
  • fx(0,1)
  • - *
  • fx(1,1)
  • - *
  • fy(0,0)
  • - *
  • fy(1,0)
  • - *
  • fy(0,1)
  • - *
  • fy(1,1)
  • - *
  • fxy(0,0)
  • - *
  • fxy(1,0)
  • - *
  • fxy(0,1)
  • - *
  • fxy(1,1)
  • - *
- * where the subscripts indicate the partial derivative with respect to - * the corresponding variable(s). - * - * @param beta List of function values and function partial derivatives - * values. - * @return the spline coefficients. - */ - private double[] computeSplineCoefficients(double[] beta) { - final double[] a = new double[NUM_COEFF]; - - for (int i = 0; i < NUM_COEFF; i++) { - double result = 0; - final double[] row = AINV[i]; - for (int j = 0; j < NUM_COEFF; j++) { - result += row[j] * beta[j]; - } - a[i] = result; - } - - return a; - } -} - -/** - * Bicubic function. - */ -class BicubicFunction implements BivariateFunction { - /** Number of points. */ - private static final short N = 4; - /** Coefficients */ - private final double[][] a; - - /** - * Simple constructor. - * - * @param coeff Spline coefficients. - */ - BicubicFunction(double[] coeff) { - a = new double[N][N]; - for (int j = 0; j < N; j++) { - final double[] aJ = a[j]; - for (int i = 0; i < N; i++) { - aJ[i] = coeff[i * N + j]; - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public double value(double x, double y) { - if (x < 0 || x > 1) { - throw new OutOfRangeException(x, 0, 1); - } - if (y < 0 || y > 1) { - throw new OutOfRangeException(y, 0, 1); - } - - final double x2 = x * x; - final double x3 = x2 * x; - final double[] pX = {1, x, x2, x3}; - - final double y2 = y * y; - final double y3 = y2 * y; - final double[] pY = {1, y, y2, y3}; - - return apply(pX, pY, a); - } - - /** - * Compute the value of the bicubic polynomial. - * - * @param pX Powers of the x-coordinate. - * @param pY Powers of the y-coordinate. - * @param coeff Spline coefficients. - * @return the interpolated value. - */ - private double apply(double[] pX, double[] pY, double[][] coeff) { - double result = 0; - for (int i = 0; i < N; i++) { - final double r = LinearCombination.value(coeff[i], pY); - result += r * pX[i]; - } - - return result; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/BicubicInterpolator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/BicubicInterpolator.java deleted file mode 100644 index 62d16029b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/BicubicInterpolator.java +++ /dev/null @@ -1,114 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.util.MathArrays; - -/** - * Generates a {@link BicubicInterpolatingFunction bicubic interpolating - * function}. - *

- * Caveat: Because the interpolation scheme requires that derivatives be - * specified at the sample points, those are approximated with finite - * differences (using the 2-points symmetric formulae). - * Since their values are undefined at the borders of the provided - * interpolation ranges, the interpolated values will be wrong at the - * edges of the patch. - * The {@code interpolate} method will return a function that overrides - * {@link BicubicInterpolatingFunction#isValidPoint(double,double)} to - * indicate points where the interpolation will be inaccurate. - *

- * - * @since 3.4 - */ -public class BicubicInterpolator - implements BivariateGridInterpolator { - /** - * {@inheritDoc} - */ - @Override - public BicubicInterpolatingFunction interpolate(final double[] xval, - final double[] yval, - final double[][] fval) - throws NoDataException, DimensionMismatchException, - NonMonotonicSequenceException, NumberIsTooSmallException { - if (xval.length == 0 || yval.length == 0 || fval.length == 0) { - throw new NoDataException(); - } - if (xval.length != fval.length) { - throw new DimensionMismatchException(xval.length, fval.length); - } - - MathArrays.checkOrder(xval); - MathArrays.checkOrder(yval); - - final int xLen = xval.length; - final int yLen = yval.length; - - // Approximation to the partial derivatives using finite differences. - final double[][] dFdX = new double[xLen][yLen]; - final double[][] dFdY = new double[xLen][yLen]; - final double[][] d2FdXdY = new double[xLen][yLen]; - for (int i = 1; i < xLen - 1; i++) { - final int nI = i + 1; - final int pI = i - 1; - - final double nX = xval[nI]; - final double pX = xval[pI]; - - final double deltaX = nX - pX; - - for (int j = 1; j < yLen - 1; j++) { - final int nJ = j + 1; - final int pJ = j - 1; - - final double nY = yval[nJ]; - final double pY = yval[pJ]; - - final double deltaY = nY - pY; - - dFdX[i][j] = (fval[nI][j] - fval[pI][j]) / deltaX; - dFdY[i][j] = (fval[i][nJ] - fval[i][pJ]) / deltaY; - - final double deltaXY = deltaX * deltaY; - - d2FdXdY[i][j] = (fval[nI][nJ] - fval[nI][pJ] - fval[pI][nJ] + fval[pI][pJ]) / deltaXY; - } - } - - // Create the interpolating function. - return new BicubicInterpolatingFunction(xval, yval, fval, - dFdX, dFdY, d2FdXdY) { - /** {@inheritDoc} */ - @Override - public boolean isValidPoint(double x, double y) { - if (x < xval[1] || - x > xval[xval.length - 2] || - y < yval[1] || - y > yval[yval.length - 2]) { - return false; - } else { - return true; - } - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/BivariateGridInterpolator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/BivariateGridInterpolator.java deleted file mode 100644 index 97ed9698d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/BivariateGridInterpolator.java +++ /dev/null @@ -1,51 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import org.apache.commons.math4.analysis.BivariateFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; - -/** - * Interface representing a bivariate real interpolating function where the - * sample points must be specified on a regular grid. - * - */ -public interface BivariateGridInterpolator { - /** - * Compute an interpolating function for the dataset. - * - * @param xval All the x-coordinates of the interpolation points, sorted - * in increasing order. - * @param yval All the y-coordinates of the interpolation points, sorted - * in increasing order. - * @param fval The values of the interpolation points on all the grid knots: - * {@code fval[i][j] = f(xval[i], yval[j])}. - * @return a function which interpolates the dataset. - * @throws NoDataException if any of the arrays has zero length. - * @throws DimensionMismatchException if the array lengths are inconsistent. - * @throws NonMonotonicSequenceException if the array is not sorted. - * @throws NumberIsTooSmallException if the number of points is too small for - * the order of the interpolation - */ - BivariateFunction interpolate(double[] xval, double[] yval, - double[][] fval) - throws NoDataException, DimensionMismatchException, - NonMonotonicSequenceException, NumberIsTooSmallException; -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/DividedDifferenceInterpolator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/DividedDifferenceInterpolator.java deleted file mode 100644 index e6ea96683..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/DividedDifferenceInterpolator.java +++ /dev/null @@ -1,122 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import java.io.Serializable; - -import org.apache.commons.math4.analysis.polynomials.PolynomialFunctionLagrangeForm; -import org.apache.commons.math4.analysis.polynomials.PolynomialFunctionNewtonForm; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; - -/** - * Implements the - * Divided Difference Algorithm for interpolation of real univariate - * functions. For reference, see Introduction to Numerical Analysis, - * ISBN 038795452X, chapter 2. - *

- * The actual code of Neville's evaluation is in PolynomialFunctionLagrangeForm, - * this class provides an easy-to-use interface to it.

- * - * @since 1.2 - */ -public class DividedDifferenceInterpolator - implements UnivariateInterpolator, Serializable { - /** serializable version identifier */ - private static final long serialVersionUID = 107049519551235069L; - - /** - * Compute an interpolating function for the dataset. - * - * @param x Interpolating points array. - * @param y Interpolating values array. - * @return a function which interpolates the dataset. - * @throws DimensionMismatchException if the array lengths are different. - * @throws NumberIsTooSmallException if the number of points is less than 2. - * @throws NonMonotonicSequenceException if {@code x} is not sorted in - * strictly increasing order. - */ - @Override - public PolynomialFunctionNewtonForm interpolate(double x[], double y[]) - throws DimensionMismatchException, - NumberIsTooSmallException, - NonMonotonicSequenceException { - /** - * a[] and c[] are defined in the general formula of Newton form: - * p(x) = a[0] + a[1](x-c[0]) + a[2](x-c[0])(x-c[1]) + ... + - * a[n](x-c[0])(x-c[1])...(x-c[n-1]) - */ - PolynomialFunctionLagrangeForm.verifyInterpolationArray(x, y, true); - - /** - * When used for interpolation, the Newton form formula becomes - * p(x) = f[x0] + f[x0,x1](x-x0) + f[x0,x1,x2](x-x0)(x-x1) + ... + - * f[x0,x1,...,x[n-1]](x-x0)(x-x1)...(x-x[n-2]) - * Therefore, a[k] = f[x0,x1,...,xk], c[k] = x[k]. - *

- * Note x[], y[], a[] have the same length but c[]'s size is one less.

- */ - final double[] c = new double[x.length-1]; - System.arraycopy(x, 0, c, 0, c.length); - - final double[] a = computeDividedDifference(x, y); - return new PolynomialFunctionNewtonForm(a, c); - } - - /** - * Return a copy of the divided difference array. - *

- * The divided difference array is defined recursively by

-     * f[x0] = f(x0)
-     * f[x0,x1,...,xk] = (f[x1,...,xk] - f[x0,...,x[k-1]]) / (xk - x0)
-     * 
- *

- * The computational complexity is \(O(n^2)\) where \(n\) is the common - * length of {@code x} and {@code y}.

- * - * @param x Interpolating points array. - * @param y Interpolating values array. - * @return a fresh copy of the divided difference array. - * @throws DimensionMismatchException if the array lengths are different. - * @throws NumberIsTooSmallException if the number of points is less than 2. - * @throws NonMonotonicSequenceException - * if {@code x} is not sorted in strictly increasing order. - */ - protected static double[] computeDividedDifference(final double x[], final double y[]) - throws DimensionMismatchException, - NumberIsTooSmallException, - NonMonotonicSequenceException { - PolynomialFunctionLagrangeForm.verifyInterpolationArray(x, y, true); - - final double[] divdiff = y.clone(); // initialization - - final int n = x.length; - final double[] a = new double [n]; - a[0] = divdiff[0]; - for (int i = 1; i < n; i++) { - for (int j = 0; j < n-i; j++) { - final double denominator = x[j+i] - x[j]; - divdiff[j] = (divdiff[j+1] - divdiff[j]) / denominator; - } - a[i] = divdiff[0]; - } - - return a; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/FieldHermiteInterpolator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/FieldHermiteInterpolator.java deleted file mode 100644 index 3241ddf38..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/FieldHermiteInterpolator.java +++ /dev/null @@ -1,210 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.math4.FieldElement; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.ZeroException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - -/** Polynomial interpolator using both sample values and sample derivatives. - *

- * The interpolation polynomials match all sample points, including both values - * and provided derivatives. There is one polynomial for each component of - * the values vector. All polynomials have the same degree. The degree of the - * polynomials depends on the number of points and number of derivatives at each - * point. For example the interpolation polynomials for n sample points without - * any derivatives all have degree n-1. The interpolation polynomials for n - * sample points with the two extreme points having value and first derivative - * and the remaining points having value only all have degree n+1. The - * interpolation polynomial for n sample points with value, first and second - * derivative for all points all have degree 3n-1. - *

- * - * @param Type of the field elements. - * - * @since 3.2 - */ -public class FieldHermiteInterpolator> { - - /** Sample abscissae. */ - private final List abscissae; - - /** Top diagonal of the divided differences array. */ - private final List topDiagonal; - - /** Bottom diagonal of the divided differences array. */ - private final List bottomDiagonal; - - /** Create an empty interpolator. - */ - public FieldHermiteInterpolator() { - this.abscissae = new ArrayList<>(); - this.topDiagonal = new ArrayList<>(); - this.bottomDiagonal = new ArrayList<>(); - } - - /** Add a sample point. - *

- * This method must be called once for each sample point. It is allowed to - * mix some calls with values only with calls with values and first - * derivatives. - *

- *

- * The point abscissae for all calls must be different. - *

- * @param x abscissa of the sample point - * @param value value and derivatives of the sample point - * (if only one row is passed, it is the value, if two rows are - * passed the first one is the value and the second the derivative - * and so on) - * @exception ZeroException if the abscissa difference between added point - * and a previous point is zero (i.e. the two points are at same abscissa) - * @exception MathArithmeticException if the number of derivatives is larger - * than 20, which prevents computation of a factorial - * @throws DimensionMismatchException if derivative structures are inconsistent - * @throws NullArgumentException if x is null - */ - @SafeVarargs - public final void addSamplePoint(final T x, final T[] ... value) - throws ZeroException, MathArithmeticException, - DimensionMismatchException, NullArgumentException { - - MathUtils.checkNotNull(x); - T factorial = x.getField().getOne(); - for (int i = 0; i < value.length; ++i) { - - final T[] y = value[i].clone(); - if (i > 1) { - factorial = factorial.multiply(i); - final T inv = factorial.reciprocal(); - for (int j = 0; j < y.length; ++j) { - y[j] = y[j].multiply(inv); - } - } - - // update the bottom diagonal of the divided differences array - final int n = abscissae.size(); - bottomDiagonal.add(n - i, y); - T[] bottom0 = y; - for (int j = i; j < n; ++j) { - final T[] bottom1 = bottomDiagonal.get(n - (j + 1)); - if (x.equals(abscissae.get(n - (j + 1)))) { - throw new ZeroException(LocalizedFormats.DUPLICATED_ABSCISSA_DIVISION_BY_ZERO, x); - } - final T inv = x.subtract(abscissae.get(n - (j + 1))).reciprocal(); - for (int k = 0; k < y.length; ++k) { - bottom1[k] = inv.multiply(bottom0[k].subtract(bottom1[k])); - } - bottom0 = bottom1; - } - - // update the top diagonal of the divided differences array - topDiagonal.add(bottom0.clone()); - - // update the abscissae array - abscissae.add(x); - - } - - } - - /** Interpolate value at a specified abscissa. - * @param x interpolation abscissa - * @return interpolated value - * @exception NoDataException if sample is empty - * @throws NullArgumentException if x is null - */ - public T[] value(T x) throws NoDataException, NullArgumentException { - - // safety check - MathUtils.checkNotNull(x); - if (abscissae.isEmpty()) { - throw new NoDataException(LocalizedFormats.EMPTY_INTERPOLATION_SAMPLE); - } - - final T[] value = MathArrays.buildArray(x.getField(), topDiagonal.get(0).length); - T valueCoeff = x.getField().getOne(); - for (int i = 0; i < topDiagonal.size(); ++i) { - T[] dividedDifference = topDiagonal.get(i); - for (int k = 0; k < value.length; ++k) { - value[k] = value[k].add(dividedDifference[k].multiply(valueCoeff)); - } - final T deltaX = x.subtract(abscissae.get(i)); - valueCoeff = valueCoeff.multiply(deltaX); - } - - return value; - - } - - /** Interpolate value and first derivatives at a specified abscissa. - * @param x interpolation abscissa - * @param order maximum derivation order - * @return interpolated value and derivatives (value in row 0, - * 1st derivative in row 1, ... nth derivative in row n) - * @exception NoDataException if sample is empty - * @throws NullArgumentException if x is null - */ - public T[][] derivatives(T x, int order) throws NoDataException, NullArgumentException { - - // safety check - MathUtils.checkNotNull(x); - if (abscissae.isEmpty()) { - throw new NoDataException(LocalizedFormats.EMPTY_INTERPOLATION_SAMPLE); - } - - final T zero = x.getField().getZero(); - final T one = x.getField().getOne(); - final T[] tj = MathArrays.buildArray(x.getField(), order + 1); - tj[0] = zero; - for (int i = 0; i < order; ++i) { - tj[i + 1] = tj[i].add(one); - } - - final T[][] derivatives = - MathArrays.buildArray(x.getField(), order + 1, topDiagonal.get(0).length); - final T[] valueCoeff = MathArrays.buildArray(x.getField(), order + 1); - valueCoeff[0] = x.getField().getOne(); - for (int i = 0; i < topDiagonal.size(); ++i) { - T[] dividedDifference = topDiagonal.get(i); - final T deltaX = x.subtract(abscissae.get(i)); - for (int j = order; j >= 0; --j) { - for (int k = 0; k < derivatives[j].length; ++k) { - derivatives[j][k] = - derivatives[j][k].add(dividedDifference[k].multiply(valueCoeff[j])); - } - valueCoeff[j] = valueCoeff[j].multiply(deltaX); - if (j > 0) { - valueCoeff[j] = valueCoeff[j].add(tj[j].multiply(valueCoeff[j - 1])); - } - } - } - - return derivatives; - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/HermiteInterpolator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/HermiteInterpolator.java deleted file mode 100644 index 439eb1cc6..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/HermiteInterpolator.java +++ /dev/null @@ -1,242 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableVectorFunction; -import org.apache.commons.math4.analysis.polynomials.PolynomialFunction; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.ZeroException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.numbers.combinatorics.Factorial; - -/** Polynomial interpolator using both sample values and sample derivatives. - *

- * The interpolation polynomials match all sample points, including both values - * and provided derivatives. There is one polynomial for each component of - * the values vector. All polynomials have the same degree. The degree of the - * polynomials depends on the number of points and number of derivatives at each - * point. For example the interpolation polynomials for n sample points without - * any derivatives all have degree n-1. The interpolation polynomials for n - * sample points with the two extreme points having value and first derivative - * and the remaining points having value only all have degree n+1. The - * interpolation polynomial for n sample points with value, first and second - * derivative for all points all have degree 3n-1. - *

- * - * @since 3.1 - */ -public class HermiteInterpolator implements UnivariateDifferentiableVectorFunction { - - /** Sample abscissae. */ - private final List abscissae; - - /** Top diagonal of the divided differences array. */ - private final List topDiagonal; - - /** Bottom diagonal of the divided differences array. */ - private final List bottomDiagonal; - - /** Create an empty interpolator. - */ - public HermiteInterpolator() { - this.abscissae = new ArrayList<>(); - this.topDiagonal = new ArrayList<>(); - this.bottomDiagonal = new ArrayList<>(); - } - - /** Add a sample point. - *

- * This method must be called once for each sample point. It is allowed to - * mix some calls with values only with calls with values and first - * derivatives. - *

- *

- * The point abscissae for all calls must be different. - *

- * @param x abscissa of the sample point - * @param value value and derivatives of the sample point - * (if only one row is passed, it is the value, if two rows are - * passed the first one is the value and the second the derivative - * and so on) - * @exception ZeroException if the abscissa difference between added point - * and a previous point is zero (i.e. the two points are at same abscissa) - * @exception MathArithmeticException if the number of derivatives is larger - * than 20, which prevents computation of a factorial - */ - public void addSamplePoint(final double x, final double[] ... value) - throws ZeroException, MathArithmeticException { - - if (value.length > 20) { - throw new MathArithmeticException(LocalizedFormats.NUMBER_TOO_LARGE, value.length, 20); - } - for (int i = 0; i < value.length; ++i) { - final double[] y = value[i].clone(); - if (i > 1) { - double inv = 1.0 / Factorial.value(i); - for (int j = 0; j < y.length; ++j) { - y[j] *= inv; - } - } - - // update the bottom diagonal of the divided differences array - final int n = abscissae.size(); - bottomDiagonal.add(n - i, y); - double[] bottom0 = y; - for (int j = i; j < n; ++j) { - final double[] bottom1 = bottomDiagonal.get(n - (j + 1)); - final double inv = 1.0 / (x - abscissae.get(n - (j + 1))); - if (Double.isInfinite(inv)) { - throw new ZeroException(LocalizedFormats.DUPLICATED_ABSCISSA_DIVISION_BY_ZERO, x); - } - for (int k = 0; k < y.length; ++k) { - bottom1[k] = inv * (bottom0[k] - bottom1[k]); - } - bottom0 = bottom1; - } - - // update the top diagonal of the divided differences array - topDiagonal.add(bottom0.clone()); - - // update the abscissae array - abscissae.add(x); - - } - - } - - /** Compute the interpolation polynomials. - * @return interpolation polynomials array - * @exception NoDataException if sample is empty - */ - public PolynomialFunction[] getPolynomials() - throws NoDataException { - - // safety check - checkInterpolation(); - - // iteration initialization - final PolynomialFunction zero = polynomial(0); - PolynomialFunction[] polynomials = new PolynomialFunction[topDiagonal.get(0).length]; - for (int i = 0; i < polynomials.length; ++i) { - polynomials[i] = zero; - } - PolynomialFunction coeff = polynomial(1); - - // build the polynomials by iterating on the top diagonal of the divided differences array - for (int i = 0; i < topDiagonal.size(); ++i) { - double[] tdi = topDiagonal.get(i); - for (int k = 0; k < polynomials.length; ++k) { - polynomials[k] = polynomials[k].add(coeff.multiply(polynomial(tdi[k]))); - } - coeff = coeff.multiply(polynomial(-abscissae.get(i), 1.0)); - } - - return polynomials; - - } - - /** Interpolate value at a specified abscissa. - *

- * Calling this method is equivalent to call the {@link PolynomialFunction#value(double) - * value} methods of all polynomials returned by {@link #getPolynomials() getPolynomials}, - * except it does not build the intermediate polynomials, so this method is faster and - * numerically more stable. - *

- * @param x interpolation abscissa - * @return interpolated value - * @exception NoDataException if sample is empty - */ - @Override - public double[] value(double x) throws NoDataException { - - // safety check - checkInterpolation(); - - final double[] value = new double[topDiagonal.get(0).length]; - double valueCoeff = 1; - for (int i = 0; i < topDiagonal.size(); ++i) { - double[] dividedDifference = topDiagonal.get(i); - for (int k = 0; k < value.length; ++k) { - value[k] += dividedDifference[k] * valueCoeff; - } - final double deltaX = x - abscissae.get(i); - valueCoeff *= deltaX; - } - - return value; - - } - - /** Interpolate value at a specified abscissa. - *

- * Calling this method is equivalent to call the {@link - * PolynomialFunction#value(DerivativeStructure) value} methods of all polynomials - * returned by {@link #getPolynomials() getPolynomials}, except it does not build the - * intermediate polynomials, so this method is faster and numerically more stable. - *

- * @param x interpolation abscissa - * @return interpolated value - * @exception NoDataException if sample is empty - */ - @Override - public DerivativeStructure[] value(final DerivativeStructure x) - throws NoDataException { - - // safety check - checkInterpolation(); - - final DerivativeStructure[] value = new DerivativeStructure[topDiagonal.get(0).length]; - Arrays.fill(value, x.getField().getZero()); - DerivativeStructure valueCoeff = x.getField().getOne(); - for (int i = 0; i < topDiagonal.size(); ++i) { - double[] dividedDifference = topDiagonal.get(i); - for (int k = 0; k < value.length; ++k) { - value[k] = value[k].add(valueCoeff.multiply(dividedDifference[k])); - } - final DerivativeStructure deltaX = x.subtract(abscissae.get(i)); - valueCoeff = valueCoeff.multiply(deltaX); - } - - return value; - - } - - /** Check interpolation can be performed. - * @exception NoDataException if interpolation cannot be performed - * because sample is empty - */ - private void checkInterpolation() throws NoDataException { - if (abscissae.isEmpty()) { - throw new NoDataException(LocalizedFormats.EMPTY_INTERPOLATION_SAMPLE); - } - } - - /** Create a polynomial from its coefficients. - * @param c polynomials coefficients - * @return polynomial - */ - private PolynomialFunction polynomial(double ... c) { - return new PolynomialFunction(c); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/InterpolatingMicrosphere.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/InterpolatingMicrosphere.java deleted file mode 100644 index e40d2025a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/InterpolatingMicrosphere.java +++ /dev/null @@ -1,387 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import java.util.List; -import java.util.ArrayList; -import org.apache.commons.numbers.arrays.CosAngle; -import org.apache.commons.numbers.arrays.SafeNorm; -import org.apache.commons.rng.sampling.UnitSphereSampler; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; - -/** - * Utility class for the {@link MicrosphereProjectionInterpolator} algorithm. - * - * @since 3.6 - */ -public class InterpolatingMicrosphere { - /** Microsphere. */ - private final List microsphere; - /** Microsphere data. */ - private final List microsphereData; - /** Space dimension. */ - private final int dimension; - /** Number of surface elements. */ - private final int size; - /** Maximum fraction of the facets that can be dark. */ - private final double maxDarkFraction; - /** Lowest non-zero illumination. */ - private final double darkThreshold; - /** Background value. */ - private final double background; - - /** - * Create an unitialiazed sphere. - * Sub-classes are responsible for calling the {@code add(double[]) add} - * method in order to initialize all the sphere's facets. - * - * @param dimension Dimension of the data space. - * @param size Number of surface elements of the sphere. - * @param maxDarkFraction Maximum fraction of the facets that can be dark. - * If the fraction of "non-illuminated" facets is larger, no estimation - * of the value will be performed, and the {@code background} value will - * be returned instead. - * @param darkThreshold Value of the illumination below which a facet is - * considered dark. - * @param background Value returned when the {@code maxDarkFraction} - * threshold is exceeded. - * @throws NotStrictlyPositiveException if {@code dimension <= 0} - * or {@code size <= 0}. - * @throws NotPositiveException if {@code darkThreshold < 0}. - * @throws OutOfRangeException if {@code maxDarkFraction} does not - * belong to the interval {@code [0, 1]}. - */ - protected InterpolatingMicrosphere(int dimension, - int size, - double maxDarkFraction, - double darkThreshold, - double background) { - if (dimension <= 0) { - throw new NotStrictlyPositiveException(dimension); - } - if (size <= 0) { - throw new NotStrictlyPositiveException(size); - } - if (maxDarkFraction < 0 || - maxDarkFraction > 1) { - throw new OutOfRangeException(maxDarkFraction, 0, 1); - } - if (darkThreshold < 0) { - throw new NotPositiveException(darkThreshold); - } - - this.dimension = dimension; - this.size = size; - this.maxDarkFraction = maxDarkFraction; - this.darkThreshold = darkThreshold; - this.background = background; - microsphere = new ArrayList<>(size); - microsphereData = new ArrayList<>(size); - } - - /** - * Create a sphere from randomly sampled vectors. - * - * @param dimension Dimension of the data space. - * @param size Number of surface elements of the sphere. - * @param rand Unit vector generator for creating the microsphere. - * @param maxDarkFraction Maximum fraction of the facets that can be dark. - * If the fraction of "non-illuminated" facets is larger, no estimation - * of the value will be performed, and the {@code background} value will - * be returned instead. - * @param darkThreshold Value of the illumination below which a facet - * is considered dark. - * @param background Value returned when the {@code maxDarkFraction} - * threshold is exceeded. - * @throws DimensionMismatchException if the size of the generated - * vectors does not match the dimension set in the constructor. - * @throws NotStrictlyPositiveException if {@code dimension <= 0} - * or {@code size <= 0}. - * @throws NotPositiveException if {@code darkThreshold < 0}. - * @throws OutOfRangeException if {@code maxDarkFraction} does not - * belong to the interval {@code [0, 1]}. - */ - public InterpolatingMicrosphere(int dimension, - int size, - double maxDarkFraction, - double darkThreshold, - double background, - UnitSphereSampler rand) { - this(dimension, size, maxDarkFraction, darkThreshold, background); - - // Generate the microsphere normals, assuming that a number of - // randomly generated normals will represent a sphere. - for (int i = 0; i < size; i++) { - add(rand.nextVector(), false); - } - } - - /** - * Copy constructor. - * - * @param other Instance to copy. - */ - protected InterpolatingMicrosphere(InterpolatingMicrosphere other) { - dimension = other.dimension; - size = other.size; - maxDarkFraction = other.maxDarkFraction; - darkThreshold = other.darkThreshold; - background = other.background; - - // Field can be shared. - microsphere = other.microsphere; - - // Field must be copied. - microsphereData = new ArrayList<>(size); - for (FacetData fd : other.microsphereData) { - microsphereData.add(new FacetData(fd.illumination(), fd.sample())); - } - } - - /** - * Perform a copy. - * - * @return a copy of this instance. - */ - public InterpolatingMicrosphere copy() { - return new InterpolatingMicrosphere(this); - } - - /** - * Get the space dimensionality. - * - * @return the number of space dimensions. - */ - public int getDimension() { - return dimension; - } - - /** - * Get the size of the sphere. - * - * @return the number of surface elements of the microspshere. - */ - public int getSize() { - return size; - } - - /** - * Estimate the value at the requested location. - * This microsphere is placed at the given {@code point}, contribution - * of the given {@code samplePoints} to each sphere facet is computed - * (illumination) and the interpolation is performed (integration of - * the illumination). - * - * @param point Interpolation point. - * @param samplePoints Sampling data points. - * @param sampleValues Sampling data values at the corresponding - * {@code samplePoints}. - * @param exponent Exponent used in the power law that computes - * the weights (distance dimming factor) of the sample data. - * @param noInterpolationTolerance When the distance between the - * {@code point} and one of the {@code samplePoints} is less than - * this value, no interpolation will be performed, and the value - * of the sample will just be returned. - * @return the estimated value at the given {@code point}. - * @throws NotPositiveException if {@code exponent < 0}. - */ - public double value(double[] point, - double[][] samplePoints, - double[] sampleValues, - double exponent, - double noInterpolationTolerance) { - if (exponent < 0) { - throw new NotPositiveException(exponent); - } - - clear(); - - // Contribution of each sample point to the illumination of the - // microsphere's facets. - final int numSamples = samplePoints.length; - for (int i = 0; i < numSamples; i++) { - // Vector between interpolation point and current sample point. - final double[] diff = MathArrays.ebeSubtract(samplePoints[i], point); - final double diffNorm = SafeNorm.value(diff); - - if (FastMath.abs(diffNorm) < noInterpolationTolerance) { - // No need to interpolate, as the interpolation point is - // actually (very close to) one of the sampled points. - return sampleValues[i]; - } - - final double weight = FastMath.pow(diffNorm, -exponent); - illuminate(diff, sampleValues[i], weight); - } - - return interpolate(); - } - - /** - * Replace {@code i}-th facet of the microsphere. - * Method for initializing the microsphere facets. - * - * @param normal Facet's normal vector. - * @param copy Whether to copy the given array. - * @throws DimensionMismatchException if the length of {@code n} - * does not match the space dimension. - * @throws MaxCountExceededException if the method has been called - * more times than the size of the sphere. - */ - protected void add(double[] normal, - boolean copy) { - if (microsphere.size() >= size) { - throw new MaxCountExceededException(size); - } - if (normal.length > dimension) { - throw new DimensionMismatchException(normal.length, dimension); - } - - microsphere.add(new Facet(copy ? normal.clone() : normal)); - microsphereData.add(new FacetData(0d, 0d)); - } - - /** - * Interpolation. - * - * @return the value estimated from the current illumination of the - * microsphere. - */ - private double interpolate() { - // Number of non-illuminated facets. - int darkCount = 0; - - double value = 0; - double totalWeight = 0; - for (FacetData fd : microsphereData) { - final double iV = fd.illumination(); - if (iV != 0d) { - value += iV * fd.sample(); - totalWeight += iV; - } else { - ++darkCount; - } - } - - final double darkFraction = darkCount / (double) size; - - return darkFraction <= maxDarkFraction ? - value / totalWeight : - background; - } - - /** - * Illumination. - * - * @param sampleDirection Vector whose origin is at the interpolation - * point and tail is at the sample location. - * @param sampleValue Data value of the sample. - * @param weight Weight. - */ - private void illuminate(double[] sampleDirection, - double sampleValue, - double weight) { - for (int i = 0; i < size; i++) { - final double[] n = microsphere.get(i).getNormal(); - final double cos = CosAngle.value(n, sampleDirection); - - if (cos > 0) { - final double illumination = cos * weight; - - if (illumination > darkThreshold && - illumination > microsphereData.get(i).illumination()) { - microsphereData.set(i, new FacetData(illumination, sampleValue)); - } - } - } - } - - /** - * Reset the all the {@link Facet facets} data to zero. - */ - private void clear() { - for (int i = 0; i < size; i++) { - microsphereData.set(i, new FacetData(0d, 0d)); - } - } - - /** - * Microsphere "facet" (surface element). - */ - private static class Facet { - /** Normal vector characterizing a surface element. */ - private final double[] normal; - - /** - * @param n Normal vector characterizing a surface element - * of the microsphere. No copy is made. - */ - Facet(double[] n) { - normal = n; - } - - /** - * Return a reference to the vector normal to this facet. - * - * @return the normal vector. - */ - public double[] getNormal() { - return normal; - } - } - - /** - * Data associated with each {@link Facet}. - */ - private static class FacetData { - /** Illumination received from the sample. */ - private final double illumination; - /** Data value of the sample. */ - private final double sample; - - /** - * @param illumination Illumination. - * @param sample Data value. - */ - FacetData(double illumination, double sample) { - this.illumination = illumination; - this.sample = sample; - } - - /** - * Get the illumination. - * @return the illumination. - */ - public double illumination() { - return illumination; - } - - /** - * Get the data value. - * @return the data value. - */ - public double sample() { - return sample; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/InterpolatingMicrosphere2D.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/InterpolatingMicrosphere2D.java deleted file mode 100644 index 0f275b5a2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/InterpolatingMicrosphere2D.java +++ /dev/null @@ -1,87 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathUtils; - -/** - * Utility class for the {@link MicrosphereProjectionInterpolator} algorithm. - * For 2D interpolation, this class constructs the microsphere as a series of - * evenly spaced facets (rather than generating random normals as in the - * base implementation). - * - * @since 4.0 - */ -public class InterpolatingMicrosphere2D extends InterpolatingMicrosphere { - /** Space dimension. */ - private static final int DIMENSION = 2; - - /** - * Create a sphere from vectors regularly sampled around a circle. - * - * @param size Number of surface elements of the sphere. - * @param maxDarkFraction Maximum fraction of the facets that can be dark. - * If the fraction of "non-illuminated" facets is larger, no estimation - * of the value will be performed, and the {@code background} value will - * be returned instead. - * @param darkThreshold Value of the illumination below which a facet is - * considered dark. - * @param background Value returned when the {@code maxDarkFraction} - * threshold is exceeded. - * @throws org.apache.commons.math4.exception.NotStrictlyPositiveException - * if {@code size <= 0}. - * @throws org.apache.commons.math4.exception.NotPositiveException if - * {@code darkThreshold < 0}. - * @throws org.apache.commons.math4.exception.OutOfRangeException if - * {@code maxDarkFraction} does not belong to the interval {@code [0, 1]}. - */ - public InterpolatingMicrosphere2D(int size, - double maxDarkFraction, - double darkThreshold, - double background) { - super(DIMENSION, size, maxDarkFraction, darkThreshold, background); - - // Generate the microsphere normals. - for (int i = 0; i < size; i++) { - final double angle = i * MathUtils.TWO_PI / size; - - add(new double[] { FastMath.cos(angle), - FastMath.sin(angle) }, - false); - } - } - - /** - * Copy constructor. - * - * @param other Instance to copy. - */ - protected InterpolatingMicrosphere2D(InterpolatingMicrosphere2D other) { - super(other); - } - - /** - * Perform a copy. - * - * @return a copy of this instance. - */ - @Override - public InterpolatingMicrosphere2D copy() { - return new InterpolatingMicrosphere2D(this); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/LinearInterpolator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/LinearInterpolator.java deleted file mode 100644 index eb9d07872..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/LinearInterpolator.java +++ /dev/null @@ -1,80 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import org.apache.commons.math4.analysis.polynomials.PolynomialFunction; -import org.apache.commons.math4.analysis.polynomials.PolynomialSplineFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.MathArrays; - -/** - * Implements a linear function for interpolation of real univariate functions. - * - */ -public class LinearInterpolator implements UnivariateInterpolator { - /** - * Computes a linear interpolating function for the data set. - * - * @param x the arguments for the interpolation points - * @param y the values for the interpolation points - * @return a function which interpolates the data set - * @throws DimensionMismatchException if {@code x} and {@code y} - * have different sizes. - * @throws NonMonotonicSequenceException if {@code x} is not sorted in - * strict increasing order. - * @throws NumberIsTooSmallException if the size of {@code x} is smaller - * than 2. - */ - @Override - public PolynomialSplineFunction interpolate(double x[], double y[]) - throws DimensionMismatchException, - NumberIsTooSmallException, - NonMonotonicSequenceException { - if (x.length != y.length) { - throw new DimensionMismatchException(x.length, y.length); - } - - if (x.length < 2) { - throw new NumberIsTooSmallException(LocalizedFormats.NUMBER_OF_POINTS, - x.length, 2, true); - } - - // Number of intervals. The number of data points is n + 1. - int n = x.length - 1; - - MathArrays.checkOrder(x); - - // Slope of the lines between the datapoints. - final double m[] = new double[n]; - for (int i = 0; i < n; i++) { - m[i] = (y[i + 1] - y[i]) / (x[i + 1] - x[i]); - } - - final PolynomialFunction polynomials[] = new PolynomialFunction[n]; - final double coefficients[] = new double[2]; - for (int i = 0; i < n; i++) { - coefficients[0] = y[i]; - coefficients[1] = m[i]; - polynomials[i] = new PolynomialFunction(coefficients); - } - - return new PolynomialSplineFunction(x, polynomials); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/LoessInterpolator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/LoessInterpolator.java deleted file mode 100644 index 598032b12..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/LoessInterpolator.java +++ /dev/null @@ -1,474 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import java.io.Serializable; -import java.util.Arrays; - -import org.apache.commons.math4.analysis.polynomials.PolynomialSplineFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.NotFiniteNumberException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - -/** - * Implements the - * Local Regression Algorithm (also Loess, Lowess) for interpolation of - * real univariate functions. - *

- * For reference, see - * - * William S. Cleveland - Robust Locally Weighted Regression and Smoothing - * Scatterplots

- *

- * This class implements both the loess method and serves as an interpolation - * adapter to it, allowing one to build a spline on the obtained loess fit.

- * - * @since 2.0 - */ -public class LoessInterpolator - implements UnivariateInterpolator, Serializable { - /** Default value of the bandwidth parameter. */ - public static final double DEFAULT_BANDWIDTH = 0.3; - /** Default value of the number of robustness iterations. */ - public static final int DEFAULT_ROBUSTNESS_ITERS = 2; - /** - * Default value for accuracy. - * @since 2.1 - */ - public static final double DEFAULT_ACCURACY = 1e-12; - /** serializable version identifier. */ - private static final long serialVersionUID = 5204927143605193821L; - /** - * The bandwidth parameter: when computing the loess fit at - * a particular point, this fraction of source points closest - * to the current point is taken into account for computing - * a least-squares regression. - *

- * A sensible value is usually 0.25 to 0.5.

- */ - private final double bandwidth; - /** - * The number of robustness iterations parameter: this many - * robustness iterations are done. - *

- * A sensible value is usually 0 (just the initial fit without any - * robustness iterations) to 4.

- */ - private final int robustnessIters; - /** - * If the median residual at a certain robustness iteration - * is less than this amount, no more iterations are done. - */ - private final double accuracy; - - /** - * Constructs a new {@link LoessInterpolator} - * with a bandwidth of {@link #DEFAULT_BANDWIDTH}, - * {@link #DEFAULT_ROBUSTNESS_ITERS} robustness iterations - * and an accuracy of {#link #DEFAULT_ACCURACY}. - * See {@link #LoessInterpolator(double, int, double)} for an explanation of - * the parameters. - */ - public LoessInterpolator() { - this.bandwidth = DEFAULT_BANDWIDTH; - this.robustnessIters = DEFAULT_ROBUSTNESS_ITERS; - this.accuracy = DEFAULT_ACCURACY; - } - - /** - * Construct a new {@link LoessInterpolator} - * with given bandwidth and number of robustness iterations. - *

- * Calling this constructor is equivalent to calling {link {@link - * #LoessInterpolator(double, int, double) LoessInterpolator(bandwidth, - * robustnessIters, LoessInterpolator.DEFAULT_ACCURACY)} - *

- * - * @param bandwidth when computing the loess fit at - * a particular point, this fraction of source points closest - * to the current point is taken into account for computing - * a least-squares regression. - * A sensible value is usually 0.25 to 0.5, the default value is - * {@link #DEFAULT_BANDWIDTH}. - * @param robustnessIters This many robustness iterations are done. - * A sensible value is usually 0 (just the initial fit without any - * robustness iterations) to 4, the default value is - * {@link #DEFAULT_ROBUSTNESS_ITERS}. - - * @see #LoessInterpolator(double, int, double) - */ - public LoessInterpolator(double bandwidth, int robustnessIters) { - this(bandwidth, robustnessIters, DEFAULT_ACCURACY); - } - - /** - * Construct a new {@link LoessInterpolator} - * with given bandwidth, number of robustness iterations and accuracy. - * - * @param bandwidth when computing the loess fit at - * a particular point, this fraction of source points closest - * to the current point is taken into account for computing - * a least-squares regression. - * A sensible value is usually 0.25 to 0.5, the default value is - * {@link #DEFAULT_BANDWIDTH}. - * @param robustnessIters This many robustness iterations are done. - * A sensible value is usually 0 (just the initial fit without any - * robustness iterations) to 4, the default value is - * {@link #DEFAULT_ROBUSTNESS_ITERS}. - * @param accuracy If the median residual at a certain robustness iteration - * is less than this amount, no more iterations are done. - * @throws OutOfRangeException if bandwidth does not lie in the interval [0,1]. - * @throws NotPositiveException if {@code robustnessIters} is negative. - * @see #LoessInterpolator(double, int) - * @since 2.1 - */ - public LoessInterpolator(double bandwidth, int robustnessIters, double accuracy) - throws OutOfRangeException, - NotPositiveException { - if (bandwidth < 0 || - bandwidth > 1) { - throw new OutOfRangeException(LocalizedFormats.BANDWIDTH, bandwidth, 0, 1); - } - this.bandwidth = bandwidth; - if (robustnessIters < 0) { - throw new NotPositiveException(LocalizedFormats.ROBUSTNESS_ITERATIONS, robustnessIters); - } - this.robustnessIters = robustnessIters; - this.accuracy = accuracy; - } - - /** - * Compute an interpolating function by performing a loess fit - * on the data at the original abscissae and then building a cubic spline - * with a - * {@link org.apache.commons.math4.analysis.interpolation.SplineInterpolator} - * on the resulting fit. - * - * @param xval the arguments for the interpolation points - * @param yval the values for the interpolation points - * @return A cubic spline built upon a loess fit to the data at the original abscissae - * @throws NonMonotonicSequenceException if {@code xval} not sorted in - * strictly increasing order. - * @throws DimensionMismatchException if {@code xval} and {@code yval} have - * different sizes. - * @throws NoDataException if {@code xval} or {@code yval} has zero size. - * @throws NotFiniteNumberException if any of the arguments and values are - * not finite real numbers. - * @throws NumberIsTooSmallException if the bandwidth is too small to - * accomodate the size of the input data (i.e. the bandwidth must be - * larger than 2/n). - */ - @Override - public final PolynomialSplineFunction interpolate(final double[] xval, - final double[] yval) - throws NonMonotonicSequenceException, - DimensionMismatchException, - NoDataException, - NotFiniteNumberException, - NumberIsTooSmallException { - return new SplineInterpolator().interpolate(xval, smooth(xval, yval)); - } - - /** - * Compute a weighted loess fit on the data at the original abscissae. - * - * @param xval Arguments for the interpolation points. - * @param yval Values for the interpolation points. - * @param weights point weights: coefficients by which the robustness weight - * of a point is multiplied. - * @return the values of the loess fit at corresponding original abscissae. - * @throws NonMonotonicSequenceException if {@code xval} not sorted in - * strictly increasing order. - * @throws DimensionMismatchException if {@code xval} and {@code yval} have - * different sizes. - * @throws NoDataException if {@code xval} or {@code yval} has zero size. - * @throws NotFiniteNumberException if any of the arguments and values are - not finite real numbers. - * @throws NumberIsTooSmallException if the bandwidth is too small to - * accomodate the size of the input data (i.e. the bandwidth must be - * larger than 2/n). - * @since 2.1 - */ - public final double[] smooth(final double[] xval, final double[] yval, - final double[] weights) - throws NonMonotonicSequenceException, - DimensionMismatchException, - NoDataException, - NotFiniteNumberException, - NumberIsTooSmallException { - if (xval.length != yval.length) { - throw new DimensionMismatchException(xval.length, yval.length); - } - - final int n = xval.length; - - if (n == 0) { - throw new NoDataException(); - } - - checkAllFiniteReal(xval); - checkAllFiniteReal(yval); - checkAllFiniteReal(weights); - - MathArrays.checkOrder(xval); - - if (n == 1) { - return new double[]{yval[0]}; - } - - if (n == 2) { - return new double[]{yval[0], yval[1]}; - } - - int bandwidthInPoints = (int) (bandwidth * n); - - if (bandwidthInPoints < 2) { - throw new NumberIsTooSmallException(LocalizedFormats.BANDWIDTH, - bandwidthInPoints, 2, true); - } - - final double[] res = new double[n]; - - final double[] residuals = new double[n]; - final double[] sortedResiduals = new double[n]; - - final double[] robustnessWeights = new double[n]; - - // Do an initial fit and 'robustnessIters' robustness iterations. - // This is equivalent to doing 'robustnessIters+1' robustness iterations - // starting with all robustness weights set to 1. - Arrays.fill(robustnessWeights, 1); - - for (int iter = 0; iter <= robustnessIters; ++iter) { - final int[] bandwidthInterval = {0, bandwidthInPoints - 1}; - // At each x, compute a local weighted linear regression - for (int i = 0; i < n; ++i) { - final double x = xval[i]; - - // Find out the interval of source points on which - // a regression is to be made. - if (i > 0) { - updateBandwidthInterval(xval, weights, i, bandwidthInterval); - } - - final int ileft = bandwidthInterval[0]; - final int iright = bandwidthInterval[1]; - - // Compute the point of the bandwidth interval that is - // farthest from x - final int edge; - if (xval[i] - xval[ileft] > xval[iright] - xval[i]) { - edge = ileft; - } else { - edge = iright; - } - - // Compute a least-squares linear fit weighted by - // the product of robustness weights and the tricube - // weight function. - // See http://en.wikipedia.org/wiki/Linear_regression - // (section "Univariate linear case") - // and http://en.wikipedia.org/wiki/Weighted_least_squares - // (section "Weighted least squares") - double sumWeights = 0; - double sumX = 0; - double sumXSquared = 0; - double sumY = 0; - double sumXY = 0; - double denom = FastMath.abs(1.0 / (xval[edge] - x)); - for (int k = ileft; k <= iright; ++k) { - final double xk = xval[k]; - final double yk = yval[k]; - final double dist = (k < i) ? x - xk : xk - x; - final double w = tricube(dist * denom) * robustnessWeights[k] * weights[k]; - final double xkw = xk * w; - sumWeights += w; - sumX += xkw; - sumXSquared += xk * xkw; - sumY += yk * w; - sumXY += yk * xkw; - } - - final double meanX = sumX / sumWeights; - final double meanY = sumY / sumWeights; - final double meanXY = sumXY / sumWeights; - final double meanXSquared = sumXSquared / sumWeights; - - final double beta; - if (FastMath.sqrt(FastMath.abs(meanXSquared - meanX * meanX)) < accuracy) { - beta = 0; - } else { - beta = (meanXY - meanX * meanY) / (meanXSquared - meanX * meanX); - } - - final double alpha = meanY - beta * meanX; - - res[i] = beta * x + alpha; - residuals[i] = FastMath.abs(yval[i] - res[i]); - } - - // No need to recompute the robustness weights at the last - // iteration, they won't be needed anymore - if (iter == robustnessIters) { - break; - } - - // Recompute the robustness weights. - - // Find the median residual. - // An arraycopy and a sort are completely tractable here, - // because the preceding loop is a lot more expensive - System.arraycopy(residuals, 0, sortedResiduals, 0, n); - Arrays.sort(sortedResiduals); - final double medianResidual = sortedResiduals[n / 2]; - - if (FastMath.abs(medianResidual) < accuracy) { - break; - } - - for (int i = 0; i < n; ++i) { - final double arg = residuals[i] / (6 * medianResidual); - if (arg >= 1) { - robustnessWeights[i] = 0; - } else { - final double w = 1 - arg * arg; - robustnessWeights[i] = w * w; - } - } - } - - return res; - } - - /** - * Compute a loess fit on the data at the original abscissae. - * - * @param xval the arguments for the interpolation points - * @param yval the values for the interpolation points - * @return values of the loess fit at corresponding original abscissae - * @throws NonMonotonicSequenceException if {@code xval} not sorted in - * strictly increasing order. - * @throws DimensionMismatchException if {@code xval} and {@code yval} have - * different sizes. - * @throws NoDataException if {@code xval} or {@code yval} has zero size. - * @throws NotFiniteNumberException if any of the arguments and values are - * not finite real numbers. - * @throws NumberIsTooSmallException if the bandwidth is too small to - * accomodate the size of the input data (i.e. the bandwidth must be - * larger than 2/n). - */ - public final double[] smooth(final double[] xval, final double[] yval) - throws NonMonotonicSequenceException, - DimensionMismatchException, - NoDataException, - NotFiniteNumberException, - NumberIsTooSmallException { - if (xval.length != yval.length) { - throw new DimensionMismatchException(xval.length, yval.length); - } - - final double[] unitWeights = new double[xval.length]; - Arrays.fill(unitWeights, 1.0); - - return smooth(xval, yval, unitWeights); - } - - /** - * Given an index interval into xval that embraces a certain number of - * points closest to {@code xval[i-1]}, update the interval so that it - * embraces the same number of points closest to {@code xval[i]}, - * ignoring zero weights. - * - * @param xval Arguments array. - * @param weights Weights array. - * @param i Index around which the new interval should be computed. - * @param bandwidthInterval a two-element array {left, right} such that: - * {@code (left==0 or xval[i] - xval[left-1] > xval[right] - xval[i])} - * and - * {@code (right==xval.length-1 or xval[right+1] - xval[i] > xval[i] - xval[left])}. - * The array will be updated. - */ - private static void updateBandwidthInterval(final double[] xval, final double[] weights, - final int i, - final int[] bandwidthInterval) { - final int left = bandwidthInterval[0]; - final int right = bandwidthInterval[1]; - - // The right edge should be adjusted if the next point to the right - // is closer to xval[i] than the leftmost point of the current interval - int nextRight = nextNonzero(weights, right); - if (nextRight < xval.length && xval[nextRight] - xval[i] < xval[i] - xval[left]) { - int nextLeft = nextNonzero(weights, bandwidthInterval[0]); - bandwidthInterval[0] = nextLeft; - bandwidthInterval[1] = nextRight; - } - } - - /** - * Return the smallest index {@code j} such that - * {@code j > i && (j == weights.length || weights[j] != 0)}. - * - * @param weights Weights array. - * @param i Index from which to start search. - * @return the smallest compliant index. - */ - private static int nextNonzero(final double[] weights, final int i) { - int j = i + 1; - while(j < weights.length && weights[j] == 0) { - ++j; - } - return j; - } - - /** - * Compute the - * tricube - * weight function - * - * @param x Argument. - * @return (1 - |x|3)3 for |x| < 1, 0 otherwise. - */ - private static double tricube(final double x) { - final double absX = FastMath.abs(x); - if (absX >= 1.0) { - return 0.0; - } - final double tmp = 1 - absX * absX * absX; - return tmp * tmp * tmp; - } - - /** - * Check that all elements of an array are finite real numbers. - * - * @param values Values array. - * @throws NotFiniteNumberException - * if one of the values is not a finite real number. - */ - private static void checkAllFiniteReal(final double[] values) { - for (int i = 0; i < values.length; i++) { - MathUtils.checkFinite(values[i]); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/MicrosphereProjectionInterpolator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/MicrosphereProjectionInterpolator.java deleted file mode 100644 index 49cbf2e83..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/MicrosphereProjectionInterpolator.java +++ /dev/null @@ -1,168 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import org.apache.commons.rng.simple.RandomSource; -import org.apache.commons.rng.sampling.UnitSphereSampler; -import org.apache.commons.math4.analysis.MultivariateFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; - -/** - * Interpolator that implements the algorithm described in - * William Dudziak's - * MS thesis. - * - * @since 3.6 - */ -public class MicrosphereProjectionInterpolator - implements MultivariateInterpolator { - /** Brightness exponent. */ - private final double exponent; - /** Microsphere. */ - private final InterpolatingMicrosphere microsphere; - /** Whether to share the sphere. */ - private final boolean sharedSphere; - /** Tolerance value below which no interpolation is necessary. */ - private final double noInterpolationTolerance; - - /** - * Create a microsphere interpolator. - * - * @param dimension Space dimension. - * @param elements Number of surface elements of the microsphere. - * @param exponent Exponent used in the power law that computes the - * @param maxDarkFraction Maximum fraction of the facets that can be dark. - * If the fraction of "non-illuminated" facets is larger, no estimation - * of the value will be performed, and the {@code background} value will - * be returned instead. - * @param darkThreshold Value of the illumination below which a facet is - * considered dark. - * @param background Value returned when the {@code maxDarkFraction} - * threshold is exceeded. - * @param sharedSphere Whether the sphere can be shared among the - * interpolating function instances. If {@code true}, the instances - * will share the same data, and thus will not be thread-safe. - * @param noInterpolationTolerance When the distance between an - * interpolated point and one of the sample points is less than this - * value, no interpolation will be performed (the value of the sample - * will be returned). - * @throws org.apache.commons.math4.exception.NotStrictlyPositiveException - * if {@code dimension <= 0} or {@code elements <= 0}. - * @throws NotPositiveException if {@code exponent < 0}. - * @throws NotPositiveException if {@code darkThreshold < 0}. - * @throws org.apache.commons.math4.exception.OutOfRangeException if - * {@code maxDarkFraction} does not belong to the interval {@code [0, 1]}. - */ - public MicrosphereProjectionInterpolator(int dimension, - int elements, - double maxDarkFraction, - double darkThreshold, - double background, - double exponent, - boolean sharedSphere, - double noInterpolationTolerance) { - this(new InterpolatingMicrosphere(dimension, - elements, - maxDarkFraction, - darkThreshold, - background, - new UnitSphereSampler(dimension, - RandomSource.create(RandomSource.MT_64))), - exponent, - sharedSphere, - noInterpolationTolerance); - } - - /** - * Create a microsphere interpolator. - * - * @param microsphere Microsphere. - * @param exponent Exponent used in the power law that computes the - * weights (distance dimming factor) of the sample data. - * @param sharedSphere Whether the sphere can be shared among the - * interpolating function instances. If {@code true}, the instances - * will share the same data, and thus will not be thread-safe. - * @param noInterpolationTolerance When the distance between an - * interpolated point and one of the sample points is less than this - * value, no interpolation will be performed (the value of the sample - * will be returned). - * @throws NotPositiveException if {@code exponent < 0}. - */ - public MicrosphereProjectionInterpolator(InterpolatingMicrosphere microsphere, - double exponent, - boolean sharedSphere, - double noInterpolationTolerance) - throws NotPositiveException { - if (exponent < 0) { - throw new NotPositiveException(exponent); - } - - this.microsphere = microsphere; - this.exponent = exponent; - this.sharedSphere = sharedSphere; - this.noInterpolationTolerance = noInterpolationTolerance; - } - - /** - * {@inheritDoc} - * - * @throws DimensionMismatchException if the space dimension of the - * given samples does not match the space dimension of the microsphere. - */ - @Override - public MultivariateFunction interpolate(final double[][] xval, - final double[] yval) - throws DimensionMismatchException, - NoDataException, - NullArgumentException { - if (xval == null || - yval == null) { - throw new NullArgumentException(); - } - if (xval.length == 0) { - throw new NoDataException(); - } - if (xval.length != yval.length) { - throw new DimensionMismatchException(xval.length, yval.length); - } - if (xval[0] == null) { - throw new NullArgumentException(); - } - final int dimension = microsphere.getDimension(); - if (dimension != xval[0].length) { - throw new DimensionMismatchException(xval[0].length, dimension); - } - - // Microsphere copy. - final InterpolatingMicrosphere m = sharedSphere ? microsphere : microsphere.copy(); - - return new MultivariateFunction() { - /** {inheritDoc} */ - @Override - public double value(double[] point) { - return m.value(point, - xval, - yval, - exponent, - noInterpolationTolerance); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/MultivariateInterpolator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/MultivariateInterpolator.java deleted file mode 100644 index 97ae5b642..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/MultivariateInterpolator.java +++ /dev/null @@ -1,51 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import org.apache.commons.math4.analysis.MultivariateFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NullArgumentException; - -/** - * Interface representing a univariate real interpolating function. - * - * @since 2.1 - */ -public interface MultivariateInterpolator { - - /** - * Computes an interpolating function for the data set. - * - * @param xval the arguments for the interpolation points. - * {@code xval[i][0]} is the first component of interpolation point - * {@code i}, {@code xval[i][1]} is the second component, and so on - * until {@code xval[i][d-1]}, the last component of that interpolation - * point (where {@code d} is thus the dimension of the space). - * @param yval the values for the interpolation points - * @return a function which interpolates the data set - * @throws MathIllegalArgumentException if the arguments violate assumptions - * made by the interpolation algorithm. - * @throws DimensionMismatchException when the array dimensions are not consistent. - * @throws NoDataException if an array has zero-length. - * @throws NullArgumentException if the arguments are {@code null}. - */ - MultivariateFunction interpolate(double[][] xval, double[] yval) - throws MathIllegalArgumentException, DimensionMismatchException, - NoDataException, NullArgumentException; -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/NevilleInterpolator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/NevilleInterpolator.java deleted file mode 100644 index d214cc87c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/NevilleInterpolator.java +++ /dev/null @@ -1,61 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import java.io.Serializable; - -import org.apache.commons.math4.analysis.polynomials.PolynomialFunctionLagrangeForm; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; - -/** - * Implements the - * Neville's Algorithm for interpolation of real univariate functions. For - * reference, see Introduction to Numerical Analysis, ISBN 038795452X, - * chapter 2. - *

- * The actual code of Neville's algorithm is in PolynomialFunctionLagrangeForm, - * this class provides an easy-to-use interface to it.

- * - * @since 1.2 - */ -public class NevilleInterpolator implements UnivariateInterpolator, - Serializable { - - /** serializable version identifier */ - static final long serialVersionUID = 3003707660147873733L; - - /** - * Computes an interpolating function for the data set. - * - * @param x Interpolating points. - * @param y Interpolating values. - * @return a function which interpolates the data set - * @throws DimensionMismatchException if the array lengths are different. - * @throws NumberIsTooSmallException if the number of points is less than 2. - * @throws NonMonotonicSequenceException if two abscissae have the same - * value. - */ - @Override - public PolynomialFunctionLagrangeForm interpolate(double x[], double y[]) - throws DimensionMismatchException, - NumberIsTooSmallException, - NonMonotonicSequenceException { - return new PolynomialFunctionLagrangeForm(x, y); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/PiecewiseBicubicSplineInterpolatingFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/PiecewiseBicubicSplineInterpolatingFunction.java deleted file mode 100644 index f547a1f3b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/PiecewiseBicubicSplineInterpolatingFunction.java +++ /dev/null @@ -1,212 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import java.util.Arrays; - -import org.apache.commons.math4.analysis.BivariateFunction; -import org.apache.commons.math4.analysis.polynomials.PolynomialSplineFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.InsufficientDataException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.util.MathArrays; - -/** - * Function that implements the - * bicubic spline - * interpolation. - * This implementation currently uses {@link AkimaSplineInterpolator} as the - * underlying one-dimensional interpolator, which requires 5 sample points; - * insufficient data will raise an exception when the - * {@link #value(double,double) value} method is called. - * - * @since 3.4 - */ -public class PiecewiseBicubicSplineInterpolatingFunction - implements BivariateFunction { - /** The minimum number of points that are needed to compute the function. */ - private static final int MIN_NUM_POINTS = 5; - /** Samples x-coordinates */ - private final double[] xval; - /** Samples y-coordinates */ - private final double[] yval; - /** Set of cubic splines patching the whole data grid */ - private final double[][] fval; - - /** - * @param x Sample values of the x-coordinate, in increasing order. - * @param y Sample values of the y-coordinate, in increasing order. - * @param f Values of the function on every grid point. the expected number - * of elements. - * @throws NonMonotonicSequenceException if {@code x} or {@code y} are not - * strictly increasing. - * @throws NullArgumentException if any of the arguments are null - * @throws NoDataException if any of the arrays has zero length. - * @throws DimensionMismatchException if the length of x and y don't match the row, column - * height of f - */ - public PiecewiseBicubicSplineInterpolatingFunction(double[] x, - double[] y, - double[][] f) - throws DimensionMismatchException, - NullArgumentException, - NoDataException, - NonMonotonicSequenceException { - if (x == null || - y == null || - f == null || - f[0] == null) { - throw new NullArgumentException(); - } - - final int xLen = x.length; - final int yLen = y.length; - - if (xLen == 0 || - yLen == 0 || - f.length == 0 || - f[0].length == 0) { - throw new NoDataException(); - } - - if (xLen < MIN_NUM_POINTS || - yLen < MIN_NUM_POINTS || - f.length < MIN_NUM_POINTS || - f[0].length < MIN_NUM_POINTS) { - throw new InsufficientDataException(); - } - - if (xLen != f.length) { - throw new DimensionMismatchException(xLen, f.length); - } - - if (yLen != f[0].length) { - throw new DimensionMismatchException(yLen, f[0].length); - } - - MathArrays.checkOrder(x); - MathArrays.checkOrder(y); - - xval = x.clone(); - yval = y.clone(); - fval = f.clone(); - } - - /** - * {@inheritDoc} - */ - @Override - public double value(double x, - double y) - throws OutOfRangeException { - final AkimaSplineInterpolator interpolator = new AkimaSplineInterpolator(); - final int offset = 2; - final int count = offset + 3; - final int i = searchIndex(x, xval, offset, count); - final int j = searchIndex(y, yval, offset, count); - - final double xArray[] = new double[count]; - final double yArray[] = new double[count]; - final double zArray[] = new double[count]; - final double interpArray[] = new double[count]; - - for (int index = 0; index < count; index++) { - xArray[index] = xval[i + index]; - yArray[index] = yval[j + index]; - } - - for (int zIndex = 0; zIndex < count; zIndex++) { - for (int index = 0; index < count; index++) { - zArray[index] = fval[i + index][j + zIndex]; - } - final PolynomialSplineFunction spline = interpolator.interpolate(xArray, zArray); - interpArray[zIndex] = spline.value(x); - } - - final PolynomialSplineFunction spline = interpolator.interpolate(yArray, interpArray); - - double returnValue = spline.value(y); - - return returnValue; - } - - /** - * Indicates whether a point is within the interpolation range. - * - * @param x First coordinate. - * @param y Second coordinate. - * @return {@code true} if (x, y) is a valid point. - * @since 3.3 - */ - public boolean isValidPoint(double x, - double y) { - if (x < xval[0] || - x > xval[xval.length - 1] || - y < yval[0] || - y > yval[yval.length - 1]) { - return false; - } else { - return true; - } - } - - /** - * @param c Coordinate. - * @param val Coordinate samples. - * @param offset how far back from found value to offset for querying - * @param count total number of elements forward from beginning that will be - * queried - * @return the index in {@code val} corresponding to the interval containing - * {@code c}. - * @throws OutOfRangeException if {@code c} is out of the range defined by - * the boundary values of {@code val}. - */ - private int searchIndex(double c, - double[] val, - int offset, - int count) { - int r = Arrays.binarySearch(val, c); - - if (r == -1 || r == -val.length - 1) { - throw new OutOfRangeException(c, val[0], val[val.length - 1]); - } - - if (r < 0) { - // "c" in within an interpolation sub-interval, which returns - // negative - // need to remove the negative sign for consistency - r = -r - offset - 1; - } else { - r -= offset; - } - - if (r < 0) { - r = 0; - } - - if ((r + count) >= val.length) { - // "c" is the last sample of the range: Return the index - // of the sample at the lower end of the last sub-interval. - r = val.length - count; - } - - return r; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/PiecewiseBicubicSplineInterpolator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/PiecewiseBicubicSplineInterpolator.java deleted file mode 100644 index 7d16b2c2f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/PiecewiseBicubicSplineInterpolator.java +++ /dev/null @@ -1,62 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.util.MathArrays; - -/** - * Generates a piecewise-bicubic interpolating function. - * - * @since 2.2 - */ -public class PiecewiseBicubicSplineInterpolator - implements BivariateGridInterpolator { - - /** - * {@inheritDoc} - */ - @Override - public PiecewiseBicubicSplineInterpolatingFunction interpolate( final double[] xval, - final double[] yval, - final double[][] fval) - throws DimensionMismatchException, - NullArgumentException, - NoDataException, - NonMonotonicSequenceException { - if ( xval == null || - yval == null || - fval == null || - fval[0] == null ) { - throw new NullArgumentException(); - } - - if ( xval.length == 0 || - yval.length == 0 || - fval.length == 0 ) { - throw new NoDataException(); - } - - MathArrays.checkOrder(xval); - MathArrays.checkOrder(yval); - - return new PiecewiseBicubicSplineInterpolatingFunction( xval, yval, fval ); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/SplineInterpolator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/SplineInterpolator.java deleted file mode 100644 index 9515dde87..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/SplineInterpolator.java +++ /dev/null @@ -1,128 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import org.apache.commons.math4.analysis.polynomials.PolynomialFunction; -import org.apache.commons.math4.analysis.polynomials.PolynomialSplineFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.MathArrays; - -/** - * Computes a natural (also known as "free", "unclamped") cubic spline interpolation for the data set. - *

- * The {@link #interpolate(double[], double[])} method returns a {@link PolynomialSplineFunction} - * consisting of n cubic polynomials, defined over the subintervals determined by the x values, - * {@code x[0] < x[i] ... < x[n].} The x values are referred to as "knot points."

- *

- * The value of the PolynomialSplineFunction at a point x that is greater than or equal to the smallest - * knot point and strictly less than the largest knot point is computed by finding the subinterval to which - * x belongs and computing the value of the corresponding polynomial at x - x[i] where - * i is the index of the subinterval. See {@link PolynomialSplineFunction} for more details. - *

- *

- * The interpolating polynomials satisfy:

    - *
  1. The value of the PolynomialSplineFunction at each of the input x values equals the - * corresponding y value.
  2. - *
  3. Adjacent polynomials are equal through two derivatives at the knot points (i.e., adjacent polynomials - * "match up" at the knot points, as do their first and second derivatives).
  4. - *
- *

- * The cubic spline interpolation algorithm implemented is as described in R.L. Burden, J.D. Faires, - * Numerical Analysis, 4th Ed., 1989, PWS-Kent, ISBN 0-53491-585-X, pp 126-131. - *

- * - */ -public class SplineInterpolator implements UnivariateInterpolator { - /** - * Computes an interpolating function for the data set. - * @param x the arguments for the interpolation points - * @param y the values for the interpolation points - * @return a function which interpolates the data set - * @throws DimensionMismatchException if {@code x} and {@code y} - * have different sizes. - * @throws NonMonotonicSequenceException if {@code x} is not sorted in - * strict increasing order. - * @throws NumberIsTooSmallException if the size of {@code x} is smaller - * than 3. - */ - @Override - public PolynomialSplineFunction interpolate(double x[], double y[]) - throws DimensionMismatchException, - NumberIsTooSmallException, - NonMonotonicSequenceException { - if (x.length != y.length) { - throw new DimensionMismatchException(x.length, y.length); - } - - if (x.length < 3) { - throw new NumberIsTooSmallException(LocalizedFormats.NUMBER_OF_POINTS, - x.length, 3, true); - } - - // Number of intervals. The number of data points is n + 1. - final int n = x.length - 1; - - MathArrays.checkOrder(x); - - // Differences between knot points - final double h[] = new double[n]; - for (int i = 0; i < n; i++) { - h[i] = x[i + 1] - x[i]; - } - - final double mu[] = new double[n]; - final double z[] = new double[n + 1]; - mu[0] = 0d; - z[0] = 0d; - double g = 0; - for (int i = 1; i < n; i++) { - g = 2d * (x[i+1] - x[i - 1]) - h[i - 1] * mu[i -1]; - mu[i] = h[i] / g; - z[i] = (3d * (y[i + 1] * h[i - 1] - y[i] * (x[i + 1] - x[i - 1])+ y[i - 1] * h[i]) / - (h[i - 1] * h[i]) - h[i - 1] * z[i - 1]) / g; - } - - // cubic spline coefficients -- b is linear, c quadratic, d is cubic (original y's are constants) - final double b[] = new double[n]; - final double c[] = new double[n + 1]; - final double d[] = new double[n]; - - z[n] = 0d; - c[n] = 0d; - - for (int j = n -1; j >=0; j--) { - c[j] = z[j] - mu[j] * c[j + 1]; - b[j] = (y[j + 1] - y[j]) / h[j] - h[j] * (c[j + 1] + 2d * c[j]) / 3d; - d[j] = (c[j + 1] - c[j]) / (3d * h[j]); - } - - final PolynomialFunction polynomials[] = new PolynomialFunction[n]; - final double coefficients[] = new double[4]; - for (int i = 0; i < n; i++) { - coefficients[0] = y[i]; - coefficients[1] = b[i]; - coefficients[2] = c[i]; - coefficients[3] = d[i]; - polynomials[i] = new PolynomialFunction(coefficients); - } - - return new PolynomialSplineFunction(x, polynomials); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/TricubicInterpolatingFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/TricubicInterpolatingFunction.java deleted file mode 100644 index d81b6642d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/TricubicInterpolatingFunction.java +++ /dev/null @@ -1,509 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import org.apache.commons.math4.analysis.TrivariateFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.util.MathArrays; - -/** - * Function that implements the - * - * tricubic spline interpolation, as proposed in - *
- * Tricubic interpolation in three dimensions
- * F. Lekien and J. Marsden
- * Int. J. Numer. Meth. Eng 2005; 63:455-471
- *
- * - * @since 3.4. - */ -public class TricubicInterpolatingFunction - implements TrivariateFunction { - /** - * Matrix to compute the spline coefficients from the function values - * and function derivatives values - */ - private static final double[][] AINV = { - { 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { -3,3,0,0,0,0,0,0,-2,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 2,-2,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-2,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { -3,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,-2,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,-3,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-2,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 9,-9,-9,9,0,0,0,0,6,3,-6,-3,0,0,0,0,6,-6,3,-3,0,0,0,0,0,0,0,0,0,0,0,0,4,2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { -6,6,6,-6,0,0,0,0,-3,-3,3,3,0,0,0,0,-4,4,-2,2,0,0,0,0,0,0,0,0,0,0,0,0,-2,-2,-1,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 2,0,-2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,2,0,-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { -6,6,6,-6,0,0,0,0,-4,-2,4,2,0,0,0,0,-3,3,-3,3,0,0,0,0,0,0,0,0,0,0,0,0,-2,-1,-2,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 4,-4,-4,4,0,0,0,0,2,2,-2,-2,0,0,0,0,2,-2,2,-2,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-2,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-3,3,0,0,0,0,0,0,-2,-1,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,-2,0,0,0,0,0,0,1,1,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-3,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-2,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-3,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,-2,0,-1,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,-9,-9,9,0,0,0,0,0,0,0,0,0,0,0,0,6,3,-6,-3,0,0,0,0,6,-6,3,-3,0,0,0,0,4,2,2,1,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-6,6,6,-6,0,0,0,0,0,0,0,0,0,0,0,0,-3,-3,3,3,0,0,0,0,-4,4,-2,2,0,0,0,0,-2,-2,-1,-1,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,-2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-6,6,6,-6,0,0,0,0,0,0,0,0,0,0,0,0,-4,-2,4,2,0,0,0,0,-3,3,-3,3,0,0,0,0,-2,-1,-2,-1,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,-4,-4,4,0,0,0,0,0,0,0,0,0,0,0,0,2,2,-2,-2,0,0,0,0,2,-2,2,-2,0,0,0,0,1,1,1,1,0,0,0,0 }, - {-3,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-2,0,0,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,-3,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-2,0,0,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 9,-9,0,0,-9,9,0,0,6,3,0,0,-6,-3,0,0,0,0,0,0,0,0,0,0,6,-6,0,0,3,-3,0,0,0,0,0,0,0,0,0,0,4,2,0,0,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { -6,6,0,0,6,-6,0,0,-3,-3,0,0,3,3,0,0,0,0,0,0,0,0,0,0,-4,4,0,0,-2,2,0,0,0,0,0,0,0,0,0,0,-2,-2,0,0,-1,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-3,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-2,0,0,0,-1,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-3,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-2,0,0,0,-1,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,-9,0,0,-9,9,0,0,0,0,0,0,0,0,0,0,6,3,0,0,-6,-3,0,0,0,0,0,0,0,0,0,0,6,-6,0,0,3,-3,0,0,4,2,0,0,2,1,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-6,6,0,0,6,-6,0,0,0,0,0,0,0,0,0,0,-3,-3,0,0,3,3,0,0,0,0,0,0,0,0,0,0,-4,4,0,0,-2,2,0,0,-2,-2,0,0,-1,-1,0,0 }, - { 9,0,-9,0,-9,0,9,0,0,0,0,0,0,0,0,0,6,0,3,0,-6,0,-3,0,6,0,-6,0,3,0,-3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,0,2,0,2,0,1,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,9,0,-9,0,-9,0,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,0,3,0,-6,0,-3,0,6,0,-6,0,3,0,-3,0,0,0,0,0,0,0,0,0,4,0,2,0,2,0,1,0 }, - { -27,27,27,-27,27,-27,-27,27,-18,-9,18,9,18,9,-18,-9,-18,18,-9,9,18,-18,9,-9,-18,18,18,-18,-9,9,9,-9,-12,-6,-6,-3,12,6,6,3,-12,-6,12,6,-6,-3,6,3,-12,12,-6,6,-6,6,-3,3,-8,-4,-4,-2,-4,-2,-2,-1 }, - { 18,-18,-18,18,-18,18,18,-18,9,9,-9,-9,-9,-9,9,9,12,-12,6,-6,-12,12,-6,6,12,-12,-12,12,6,-6,-6,6,6,6,3,3,-6,-6,-3,-3,6,6,-6,-6,3,3,-3,-3,8,-8,4,-4,4,-4,2,-2,4,4,2,2,2,2,1,1 }, - { -6,0,6,0,6,0,-6,0,0,0,0,0,0,0,0,0,-3,0,-3,0,3,0,3,0,-4,0,4,0,-2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-2,0,-2,0,-1,0,-1,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,-6,0,6,0,6,0,-6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-3,0,-3,0,3,0,3,0,-4,0,4,0,-2,0,2,0,0,0,0,0,0,0,0,0,-2,0,-2,0,-1,0,-1,0 }, - { 18,-18,-18,18,-18,18,18,-18,12,6,-12,-6,-12,-6,12,6,9,-9,9,-9,-9,9,-9,9,12,-12,-12,12,6,-6,-6,6,6,3,6,3,-6,-3,-6,-3,8,4,-8,-4,4,2,-4,-2,6,-6,6,-6,3,-3,3,-3,4,2,4,2,2,1,2,1 }, - { -12,12,12,-12,12,-12,-12,12,-6,-6,6,6,6,6,-6,-6,-6,6,-6,6,6,-6,6,-6,-8,8,8,-8,-4,4,4,-4,-3,-3,-3,-3,3,3,3,3,-4,-4,4,4,-2,-2,2,2,-4,4,-4,4,-2,2,-2,2,-2,-2,-2,-2,-1,-1,-1,-1 }, - { 2,0,0,0,-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,2,0,0,0,-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { -6,6,0,0,6,-6,0,0,-4,-2,0,0,4,2,0,0,0,0,0,0,0,0,0,0,-3,3,0,0,-3,3,0,0,0,0,0,0,0,0,0,0,-2,-1,0,0,-2,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 4,-4,0,0,-4,4,0,0,2,2,0,0,-2,-2,0,0,0,0,0,0,0,0,0,0,2,-2,0,0,2,-2,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-6,6,0,0,6,-6,0,0,0,0,0,0,0,0,0,0,-4,-2,0,0,4,2,0,0,0,0,0,0,0,0,0,0,-3,3,0,0,-3,3,0,0,-2,-1,0,0,-2,-1,0,0 }, - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,-4,0,0,-4,4,0,0,0,0,0,0,0,0,0,0,2,2,0,0,-2,-2,0,0,0,0,0,0,0,0,0,0,2,-2,0,0,2,-2,0,0,1,1,0,0,1,1,0,0 }, - { -6,0,6,0,6,0,-6,0,0,0,0,0,0,0,0,0,-4,0,-2,0,4,0,2,0,-3,0,3,0,-3,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-2,0,-1,0,-2,0,-1,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,-6,0,6,0,6,0,-6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-4,0,-2,0,4,0,2,0,-3,0,3,0,-3,0,3,0,0,0,0,0,0,0,0,0,-2,0,-1,0,-2,0,-1,0 }, - { 18,-18,-18,18,-18,18,18,-18,12,6,-12,-6,-12,-6,12,6,12,-12,6,-6,-12,12,-6,6,9,-9,-9,9,9,-9,-9,9,8,4,4,2,-8,-4,-4,-2,6,3,-6,-3,6,3,-6,-3,6,-6,3,-3,6,-6,3,-3,4,2,2,1,4,2,2,1 }, - { -12,12,12,-12,12,-12,-12,12,-6,-6,6,6,6,6,-6,-6,-8,8,-4,4,8,-8,4,-4,-6,6,6,-6,-6,6,6,-6,-4,-4,-2,-2,4,4,2,2,-3,-3,3,3,-3,-3,3,3,-4,4,-2,2,-4,4,-2,2,-2,-2,-1,-1,-2,-2,-1,-1 }, - { 4,0,-4,0,-4,0,4,0,0,0,0,0,0,0,0,0,2,0,2,0,-2,0,-2,0,2,0,-2,0,2,0,-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0 }, - { 0,0,0,0,0,0,0,0,4,0,-4,0,-4,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,-2,0,-2,0,2,0,-2,0,2,0,-2,0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,1,0 }, - { -12,12,12,-12,12,-12,-12,12,-8,-4,8,4,8,4,-8,-4,-6,6,-6,6,6,-6,6,-6,-6,6,6,-6,-6,6,6,-6,-4,-2,-4,-2,4,2,4,2,-4,-2,4,2,-4,-2,4,2,-3,3,-3,3,-3,3,-3,3,-2,-1,-2,-1,-2,-1,-2,-1 }, - { 8,-8,-8,8,-8,8,8,-8,4,4,-4,-4,-4,-4,4,4,4,-4,4,-4,-4,4,-4,4,4,-4,-4,4,4,-4,-4,4,2,2,2,2,-2,-2,-2,-2,2,2,-2,-2,2,2,-2,-2,2,-2,2,-2,2,-2,2,-2,1,1,1,1,1,1,1,1 } - }; - - /** Samples x-coordinates */ - private final double[] xval; - /** Samples y-coordinates */ - private final double[] yval; - /** Samples z-coordinates */ - private final double[] zval; - /** Set of cubic splines pacthing the whole data grid */ - private final TricubicFunction[][][] splines; - - /** - * @param x Sample values of the x-coordinate, in increasing order. - * @param y Sample values of the y-coordinate, in increasing order. - * @param z Sample values of the y-coordinate, in increasing order. - * @param f Values of the function on every grid point. - * @param dFdX Values of the partial derivative of function with respect to x on every grid point. - * @param dFdY Values of the partial derivative of function with respect to y on every grid point. - * @param dFdZ Values of the partial derivative of function with respect to z on every grid point. - * @param d2FdXdY Values of the cross partial derivative of function on every grid point. - * @param d2FdXdZ Values of the cross partial derivative of function on every grid point. - * @param d2FdYdZ Values of the cross partial derivative of function on every grid point. - * @param d3FdXdYdZ Values of the cross partial derivative of function on every grid point. - * @throws NoDataException if any of the arrays has zero length. - * @throws DimensionMismatchException if the various arrays do not contain the expected number of elements. - * @throws NonMonotonicSequenceException if {@code x}, {@code y} or {@code z} are not strictly increasing. - */ - public TricubicInterpolatingFunction(double[] x, - double[] y, - double[] z, - double[][][] f, - double[][][] dFdX, - double[][][] dFdY, - double[][][] dFdZ, - double[][][] d2FdXdY, - double[][][] d2FdXdZ, - double[][][] d2FdYdZ, - double[][][] d3FdXdYdZ) - throws NoDataException, - DimensionMismatchException, - NonMonotonicSequenceException { - final int xLen = x.length; - final int yLen = y.length; - final int zLen = z.length; - - if (xLen == 0 || yLen == 0 || z.length == 0 || f.length == 0 || f[0].length == 0) { - throw new NoDataException(); - } - if (xLen != f.length) { - throw new DimensionMismatchException(xLen, f.length); - } - if (xLen != dFdX.length) { - throw new DimensionMismatchException(xLen, dFdX.length); - } - if (xLen != dFdY.length) { - throw new DimensionMismatchException(xLen, dFdY.length); - } - if (xLen != dFdZ.length) { - throw new DimensionMismatchException(xLen, dFdZ.length); - } - if (xLen != d2FdXdY.length) { - throw new DimensionMismatchException(xLen, d2FdXdY.length); - } - if (xLen != d2FdXdZ.length) { - throw new DimensionMismatchException(xLen, d2FdXdZ.length); - } - if (xLen != d2FdYdZ.length) { - throw new DimensionMismatchException(xLen, d2FdYdZ.length); - } - if (xLen != d3FdXdYdZ.length) { - throw new DimensionMismatchException(xLen, d3FdXdYdZ.length); - } - - MathArrays.checkOrder(x); - MathArrays.checkOrder(y); - MathArrays.checkOrder(z); - - xval = x.clone(); - yval = y.clone(); - zval = z.clone(); - - final int lastI = xLen - 1; - final int lastJ = yLen - 1; - final int lastK = zLen - 1; - splines = new TricubicFunction[lastI][lastJ][lastK]; - - for (int i = 0; i < lastI; i++) { - if (f[i].length != yLen) { - throw new DimensionMismatchException(f[i].length, yLen); - } - if (dFdX[i].length != yLen) { - throw new DimensionMismatchException(dFdX[i].length, yLen); - } - if (dFdY[i].length != yLen) { - throw new DimensionMismatchException(dFdY[i].length, yLen); - } - if (dFdZ[i].length != yLen) { - throw new DimensionMismatchException(dFdZ[i].length, yLen); - } - if (d2FdXdY[i].length != yLen) { - throw new DimensionMismatchException(d2FdXdY[i].length, yLen); - } - if (d2FdXdZ[i].length != yLen) { - throw new DimensionMismatchException(d2FdXdZ[i].length, yLen); - } - if (d2FdYdZ[i].length != yLen) { - throw new DimensionMismatchException(d2FdYdZ[i].length, yLen); - } - if (d3FdXdYdZ[i].length != yLen) { - throw new DimensionMismatchException(d3FdXdYdZ[i].length, yLen); - } - - final int ip1 = i + 1; - final double xR = xval[ip1] - xval[i]; - for (int j = 0; j < lastJ; j++) { - if (f[i][j].length != zLen) { - throw new DimensionMismatchException(f[i][j].length, zLen); - } - if (dFdX[i][j].length != zLen) { - throw new DimensionMismatchException(dFdX[i][j].length, zLen); - } - if (dFdY[i][j].length != zLen) { - throw new DimensionMismatchException(dFdY[i][j].length, zLen); - } - if (dFdZ[i][j].length != zLen) { - throw new DimensionMismatchException(dFdZ[i][j].length, zLen); - } - if (d2FdXdY[i][j].length != zLen) { - throw new DimensionMismatchException(d2FdXdY[i][j].length, zLen); - } - if (d2FdXdZ[i][j].length != zLen) { - throw new DimensionMismatchException(d2FdXdZ[i][j].length, zLen); - } - if (d2FdYdZ[i][j].length != zLen) { - throw new DimensionMismatchException(d2FdYdZ[i][j].length, zLen); - } - if (d3FdXdYdZ[i][j].length != zLen) { - throw new DimensionMismatchException(d3FdXdYdZ[i][j].length, zLen); - } - - final int jp1 = j + 1; - final double yR = yval[jp1] - yval[j]; - final double xRyR = xR * yR; - for (int k = 0; k < lastK; k++) { - final int kp1 = k + 1; - final double zR = zval[kp1] - zval[k]; - final double xRzR = xR * zR; - final double yRzR = yR * zR; - final double xRyRzR = xR * yRzR; - - final double[] beta = new double[] { - f[i][j][k], f[ip1][j][k], - f[i][jp1][k], f[ip1][jp1][k], - f[i][j][kp1], f[ip1][j][kp1], - f[i][jp1][kp1], f[ip1][jp1][kp1], - - dFdX[i][j][k] * xR, dFdX[ip1][j][k] * xR, - dFdX[i][jp1][k] * xR, dFdX[ip1][jp1][k] * xR, - dFdX[i][j][kp1] * xR, dFdX[ip1][j][kp1] * xR, - dFdX[i][jp1][kp1] * xR, dFdX[ip1][jp1][kp1] * xR, - - dFdY[i][j][k] * yR, dFdY[ip1][j][k] * yR, - dFdY[i][jp1][k] * yR, dFdY[ip1][jp1][k] * yR, - dFdY[i][j][kp1] * yR, dFdY[ip1][j][kp1] * yR, - dFdY[i][jp1][kp1] * yR, dFdY[ip1][jp1][kp1] * yR, - - dFdZ[i][j][k] * zR, dFdZ[ip1][j][k] * zR, - dFdZ[i][jp1][k] * zR, dFdZ[ip1][jp1][k] * zR, - dFdZ[i][j][kp1] * zR, dFdZ[ip1][j][kp1] * zR, - dFdZ[i][jp1][kp1] * zR, dFdZ[ip1][jp1][kp1] * zR, - - d2FdXdY[i][j][k] * xRyR, d2FdXdY[ip1][j][k] * xRyR, - d2FdXdY[i][jp1][k] * xRyR, d2FdXdY[ip1][jp1][k] * xRyR, - d2FdXdY[i][j][kp1] * xRyR, d2FdXdY[ip1][j][kp1] * xRyR, - d2FdXdY[i][jp1][kp1] * xRyR, d2FdXdY[ip1][jp1][kp1] * xRyR, - - d2FdXdZ[i][j][k] * xRzR, d2FdXdZ[ip1][j][k] * xRzR, - d2FdXdZ[i][jp1][k] * xRzR, d2FdXdZ[ip1][jp1][k] * xRzR, - d2FdXdZ[i][j][kp1] * xRzR, d2FdXdZ[ip1][j][kp1] * xRzR, - d2FdXdZ[i][jp1][kp1] * xRzR, d2FdXdZ[ip1][jp1][kp1] * xRzR, - - d2FdYdZ[i][j][k] * yRzR, d2FdYdZ[ip1][j][k] * yRzR, - d2FdYdZ[i][jp1][k] * yRzR, d2FdYdZ[ip1][jp1][k] * yRzR, - d2FdYdZ[i][j][kp1] * yRzR, d2FdYdZ[ip1][j][kp1] * yRzR, - d2FdYdZ[i][jp1][kp1] * yRzR, d2FdYdZ[ip1][jp1][kp1] * yRzR, - - d3FdXdYdZ[i][j][k] * xRyRzR, d3FdXdYdZ[ip1][j][k] * xRyRzR, - d3FdXdYdZ[i][jp1][k] * xRyRzR, d3FdXdYdZ[ip1][jp1][k] * xRyRzR, - d3FdXdYdZ[i][j][kp1] * xRyRzR, d3FdXdYdZ[ip1][j][kp1] * xRyRzR, - d3FdXdYdZ[i][jp1][kp1] * xRyRzR, d3FdXdYdZ[ip1][jp1][kp1] * xRyRzR, - }; - - splines[i][j][k] = new TricubicFunction(computeCoefficients(beta)); - } - } - } - } - - /** - * {@inheritDoc} - * - * @throws OutOfRangeException if any of the variables is outside its interpolation range. - */ - @Override - public double value(double x, double y, double z) - throws OutOfRangeException { - final int i = searchIndex(x, xval); - if (i == -1) { - throw new OutOfRangeException(x, xval[0], xval[xval.length - 1]); - } - final int j = searchIndex(y, yval); - if (j == -1) { - throw new OutOfRangeException(y, yval[0], yval[yval.length - 1]); - } - final int k = searchIndex(z, zval); - if (k == -1) { - throw new OutOfRangeException(z, zval[0], zval[zval.length - 1]); - } - - final double xN = (x - xval[i]) / (xval[i + 1] - xval[i]); - final double yN = (y - yval[j]) / (yval[j + 1] - yval[j]); - final double zN = (z - zval[k]) / (zval[k + 1] - zval[k]); - - return splines[i][j][k].value(xN, yN, zN); - } - - /** - * Indicates whether a point is within the interpolation range. - * - * @param x First coordinate. - * @param y Second coordinate. - * @param z Third coordinate. - * @return {@code true} if (x, y, z) is a valid point. - */ - public boolean isValidPoint(double x, double y, double z) { - if (x < xval[0] || - x > xval[xval.length - 1] || - y < yval[0] || - y > yval[yval.length - 1] || - z < zval[0] || - z > zval[zval.length - 1]) { - return false; - } else { - return true; - } - } - - /** - * @param c Coordinate. - * @param val Coordinate samples. - * @return the index in {@code val} corresponding to the interval containing {@code c}, or {@code -1} - * if {@code c} is out of the range defined by the end values of {@code val}. - */ - private int searchIndex(double c, double[] val) { - if (c < val[0]) { - return -1; - } - - final int max = val.length; - for (int i = 1; i < max; i++) { - if (c <= val[i]) { - return i - 1; - } - } - - return -1; - } - - /** - * Compute the spline coefficients from the list of function values and - * function partial derivatives values at the four corners of a grid - * element. They must be specified in the following order: - *
    - *
  • f(0,0,0)
  • - *
  • f(1,0,0)
  • - *
  • f(0,1,0)
  • - *
  • f(1,1,0)
  • - *
  • f(0,0,1)
  • - *
  • f(1,0,1)
  • - *
  • f(0,1,1)
  • - *
  • f(1,1,1)
  • - * - *
  • fx(0,0,0)
  • - *
  • ... (same order as above)
  • - *
  • fx(1,1,1)
  • - * - *
  • fy(0,0,0)
  • - *
  • ... (same order as above)
  • - *
  • fy(1,1,1)
  • - * - *
  • fz(0,0,0)
  • - *
  • ... (same order as above)
  • - *
  • fz(1,1,1)
  • - * - *
  • fxy(0,0,0)
  • - *
  • ... (same order as above)
  • - *
  • fxy(1,1,1)
  • - * - *
  • fxz(0,0,0)
  • - *
  • ... (same order as above)
  • - *
  • fxz(1,1,1)
  • - * - *
  • fyz(0,0,0)
  • - *
  • ... (same order as above)
  • - *
  • fyz(1,1,1)
  • - * - *
  • fxyz(0,0,0)
  • - *
  • ... (same order as above)
  • - *
  • fxyz(1,1,1)
  • - *
- * where the subscripts indicate the partial derivative with respect to - * the corresponding variable(s). - * - * @param beta List of function values and function partial derivatives values. - * @return the spline coefficients. - */ - private double[] computeCoefficients(double[] beta) { - final int sz = 64; - final double[] a = new double[sz]; - - for (int i = 0; i < sz; i++) { - double result = 0; - final double[] row = AINV[i]; - for (int j = 0; j < sz; j++) { - result += row[j] * beta[j]; - } - a[i] = result; - } - - return a; - } -} - -/** - * 3D-spline function. - * - */ -class TricubicFunction - implements TrivariateFunction { - /** Number of points. */ - private static final short N = 4; - /** Coefficients */ - private final double[][][] a = new double[N][N][N]; - - /** - * @param aV List of spline coefficients. - */ - TricubicFunction(double[] aV) { - for (int i = 0; i < N; i++) { - for (int j = 0; j < N; j++) { - for (int k = 0; k < N; k++) { - a[i][j][k] = aV[i + N * (j + N * k)]; - } - } - } - } - - /** - * @param x x-coordinate of the interpolation point. - * @param y y-coordinate of the interpolation point. - * @param z z-coordinate of the interpolation point. - * @return the interpolated value. - * @throws OutOfRangeException if {@code x}, {@code y} or - * {@code z} are not in the interval {@code [0, 1]}. - */ - @Override - public double value(double x, double y, double z) throws OutOfRangeException { - if (x < 0 || x > 1) { - throw new OutOfRangeException(x, 0, 1); - } - if (y < 0 || y > 1) { - throw new OutOfRangeException(y, 0, 1); - } - if (z < 0 || z > 1) { - throw new OutOfRangeException(z, 0, 1); - } - - final double x2 = x * x; - final double x3 = x2 * x; - final double[] pX = { 1, x, x2, x3 }; - - final double y2 = y * y; - final double y3 = y2 * y; - final double[] pY = { 1, y, y2, y3 }; - - final double z2 = z * z; - final double z3 = z2 * z; - final double[] pZ = { 1, z, z2, z3 }; - - double result = 0; - for (int i = 0; i < N; i++) { - for (int j = 0; j < N; j++) { - for (int k = 0; k < N; k++) { - result += a[i][j][k] * pX[i] * pY[j] * pZ[k]; - } - } - } - - return result; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/TricubicInterpolator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/TricubicInterpolator.java deleted file mode 100644 index bdc7f201b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/TricubicInterpolator.java +++ /dev/null @@ -1,144 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.util.MathArrays; - -/** - * Generates a tricubic interpolating function. - * - * @since 3.4 - */ -public class TricubicInterpolator - implements TrivariateGridInterpolator { - /** - * {@inheritDoc} - */ - @Override - public TricubicInterpolatingFunction interpolate(final double[] xval, - final double[] yval, - final double[] zval, - final double[][][] fval) - throws NoDataException, NumberIsTooSmallException, - DimensionMismatchException, NonMonotonicSequenceException { - if (xval.length == 0 || yval.length == 0 || zval.length == 0 || fval.length == 0) { - throw new NoDataException(); - } - if (xval.length != fval.length) { - throw new DimensionMismatchException(xval.length, fval.length); - } - - MathArrays.checkOrder(xval); - MathArrays.checkOrder(yval); - MathArrays.checkOrder(zval); - - final int xLen = xval.length; - final int yLen = yval.length; - final int zLen = zval.length; - - // Approximation to the partial derivatives using finite differences. - final double[][][] dFdX = new double[xLen][yLen][zLen]; - final double[][][] dFdY = new double[xLen][yLen][zLen]; - final double[][][] dFdZ = new double[xLen][yLen][zLen]; - final double[][][] d2FdXdY = new double[xLen][yLen][zLen]; - final double[][][] d2FdXdZ = new double[xLen][yLen][zLen]; - final double[][][] d2FdYdZ = new double[xLen][yLen][zLen]; - final double[][][] d3FdXdYdZ = new double[xLen][yLen][zLen]; - - for (int i = 1; i < xLen - 1; i++) { - if (yval.length != fval[i].length) { - throw new DimensionMismatchException(yval.length, fval[i].length); - } - - final int nI = i + 1; - final int pI = i - 1; - - final double nX = xval[nI]; - final double pX = xval[pI]; - - final double deltaX = nX - pX; - - for (int j = 1; j < yLen - 1; j++) { - if (zval.length != fval[i][j].length) { - throw new DimensionMismatchException(zval.length, fval[i][j].length); - } - - final int nJ = j + 1; - final int pJ = j - 1; - - final double nY = yval[nJ]; - final double pY = yval[pJ]; - - final double deltaY = nY - pY; - final double deltaXY = deltaX * deltaY; - - for (int k = 1; k < zLen - 1; k++) { - final int nK = k + 1; - final int pK = k - 1; - - final double nZ = zval[nK]; - final double pZ = zval[pK]; - - final double deltaZ = nZ - pZ; - - dFdX[i][j][k] = (fval[nI][j][k] - fval[pI][j][k]) / deltaX; - dFdY[i][j][k] = (fval[i][nJ][k] - fval[i][pJ][k]) / deltaY; - dFdZ[i][j][k] = (fval[i][j][nK] - fval[i][j][pK]) / deltaZ; - - final double deltaXZ = deltaX * deltaZ; - final double deltaYZ = deltaY * deltaZ; - - d2FdXdY[i][j][k] = (fval[nI][nJ][k] - fval[nI][pJ][k] - fval[pI][nJ][k] + fval[pI][pJ][k]) / deltaXY; - d2FdXdZ[i][j][k] = (fval[nI][j][nK] - fval[nI][j][pK] - fval[pI][j][nK] + fval[pI][j][pK]) / deltaXZ; - d2FdYdZ[i][j][k] = (fval[i][nJ][nK] - fval[i][nJ][pK] - fval[i][pJ][nK] + fval[i][pJ][pK]) / deltaYZ; - - final double deltaXYZ = deltaXY * deltaZ; - - d3FdXdYdZ[i][j][k] = (fval[nI][nJ][nK] - fval[nI][pJ][nK] - - fval[pI][nJ][nK] + fval[pI][pJ][nK] - - fval[nI][nJ][pK] + fval[nI][pJ][pK] + - fval[pI][nJ][pK] - fval[pI][pJ][pK]) / deltaXYZ; - } - } - } - - // Create the interpolating function. - return new TricubicInterpolatingFunction(xval, yval, zval, fval, - dFdX, dFdY, dFdZ, - d2FdXdY, d2FdXdZ, d2FdYdZ, - d3FdXdYdZ) { - /** {@inheritDoc} */ - @Override - public boolean isValidPoint(double x, double y, double z) { - if (x < xval[1] || - x > xval[xval.length - 2] || - y < yval[1] || - y > yval[yval.length - 2] || - z < zval[1] || - z > zval[zval.length - 2]) { - return false; - } else { - return true; - } - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/TrivariateGridInterpolator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/TrivariateGridInterpolator.java deleted file mode 100644 index 18e264dbe..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/TrivariateGridInterpolator.java +++ /dev/null @@ -1,54 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import org.apache.commons.math4.analysis.TrivariateFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; - -/** - * Interface representing a trivariate real interpolating function where the - * sample points must be specified on a regular grid. - * - * @since 2.2 - */ -public interface TrivariateGridInterpolator { - /** - * Compute an interpolating function for the dataset. - * - * @param xval All the x-coordinates of the interpolation points, sorted - * in increasing order. - * @param yval All the y-coordinates of the interpolation points, sorted - * in increasing order. - * @param zval All the z-coordinates of the interpolation points, sorted - * in increasing order. - * @param fval the values of the interpolation points on all the grid knots: - * {@code fval[i][j][k] = f(xval[i], yval[j], zval[k])}. - * @return a function that interpolates the data set. - * @throws NoDataException if any of the arrays has zero length. - * @throws DimensionMismatchException if the array lengths are inconsistent. - * @throws NonMonotonicSequenceException if arrays are not sorted - * @throws NumberIsTooSmallException if the number of points is too small for - * the order of the interpolation - */ - TrivariateFunction interpolate(double[] xval, double[] yval, double[] zval, - double[][][] fval) - throws NoDataException, NumberIsTooSmallException, - DimensionMismatchException, NonMonotonicSequenceException; -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/UnivariateInterpolator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/UnivariateInterpolator.java deleted file mode 100644 index 349d22d3d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/UnivariateInterpolator.java +++ /dev/null @@ -1,41 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathIllegalArgumentException; - -/** - * Interface representing a univariate real interpolating function. - * - */ -public interface UnivariateInterpolator { - /** - * Compute an interpolating function for the dataset. - * - * @param xval Arguments for the interpolation points. - * @param yval Values for the interpolation points. - * @return a function which interpolates the dataset. - * @throws MathIllegalArgumentException - * if the arguments violate assumptions made by the interpolation - * algorithm. - * @throws DimensionMismatchException if arrays lengthes do not match - */ - UnivariateFunction interpolate(double xval[], double yval[]) - throws MathIllegalArgumentException, DimensionMismatchException; -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/UnivariatePeriodicInterpolator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/UnivariatePeriodicInterpolator.java deleted file mode 100644 index 5665f8ae9..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/UnivariatePeriodicInterpolator.java +++ /dev/null @@ -1,126 +0,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. - */ -package org.apache.commons.math4.analysis.interpolation; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - -/** - * Adapter for classes implementing the {@link UnivariateInterpolator} - * interface. - * The data to be interpolated is assumed to be periodic. Thus values that are - * outside of the range can be passed to the interpolation function: They will - * be wrapped into the initial range before being passed to the class that - * actually computes the interpolation. - * - */ -public class UnivariatePeriodicInterpolator - implements UnivariateInterpolator { - /** Default number of extension points of the samples array. */ - public static final int DEFAULT_EXTEND = 5; - /** Interpolator. */ - private final UnivariateInterpolator interpolator; - /** Period. */ - private final double period; - /** Number of extension points. */ - private final int extend; - - /** - * Builds an interpolator. - * - * @param interpolator Interpolator. - * @param period Period. - * @param extend Number of points to be appended at the beginning and - * end of the sample arrays in order to avoid interpolation failure at - * the (periodic) boundaries of the orginal interval. The value is the - * number of sample points which the original {@code interpolator} needs - * on each side of the interpolated point. - */ - public UnivariatePeriodicInterpolator(UnivariateInterpolator interpolator, - double period, - int extend) { - this.interpolator = interpolator; - this.period = period; - this.extend = extend; - } - - /** - * Builds an interpolator. - * Uses {@link #DEFAULT_EXTEND} as the number of extension points on each side - * of the original abscissae range. - * - * @param interpolator Interpolator. - * @param period Period. - */ - public UnivariatePeriodicInterpolator(UnivariateInterpolator interpolator, - double period) { - this(interpolator, period, DEFAULT_EXTEND); - } - - /** - * {@inheritDoc} - * - * @throws NumberIsTooSmallException if the number of extension points - * is larger than the size of {@code xval}. - */ - @Override - public UnivariateFunction interpolate(double[] xval, - double[] yval) - throws NumberIsTooSmallException, NonMonotonicSequenceException { - if (xval.length < extend) { - throw new NumberIsTooSmallException(xval.length, extend, true); - } - - MathArrays.checkOrder(xval); - final double offset = xval[0]; - - final int len = xval.length + extend * 2; - final double[] x = new double[len]; - final double[] y = new double[len]; - for (int i = 0; i < xval.length; i++) { - final int index = i + extend; - x[index] = MathUtils.reduce(xval[i], period, offset); - y[index] = yval[i]; - } - - // Wrap to enable interpolation at the boundaries. - for (int i = 0; i < extend; i++) { - int index = xval.length - extend + i; - x[i] = MathUtils.reduce(xval[index], period, offset) - period; - y[i] = yval[index]; - - index = len - extend + i; - x[index] = MathUtils.reduce(xval[i], period, offset) + period; - y[index] = yval[i]; - } - - MathArrays.sortInPlace(x, y); - - final UnivariateFunction f = interpolator.interpolate(x, y); - return new UnivariateFunction() { - /** {@inheritDoc} */ - @Override - public double value(final double x) throws MathIllegalArgumentException { - return f.value(MathUtils.reduce(x, period, offset)); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/package-info.java deleted file mode 100644 index 231da357a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/interpolation/package-info.java +++ /dev/null @@ -1,22 +0,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. - */ -/** - * - * Univariate real functions interpolation algorithms. - * - */ -package org.apache.commons.math4.analysis.interpolation; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/package-info.java deleted file mode 100644 index 472dcb06b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/package-info.java +++ /dev/null @@ -1,32 +0,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. - */ -/** - * - *

- * Parent package for common numerical analysis procedures, including root finding, - * function interpolation and integration. Note that optimization (i.e. minimization - * and maximization) is a separate top-level package. - *

- *

- * Function interfaces are intended to be implemented by user code to represent - * domain problems. The algorithms provided by the library operate on these - * functions to find their roots, or integrate them, or ... Functions can be multivariate - * or univariate, real vectorial or matrix-valued, and they can be differentiable or not. - *

- * - */ -package org.apache.commons.math4.analysis; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/PolynomialFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/PolynomialFunction.java deleted file mode 100644 index 9333c1eb3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/PolynomialFunction.java +++ /dev/null @@ -1,406 +0,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. - */ -package org.apache.commons.math4.analysis.polynomials; - -import java.io.Serializable; -import java.util.Arrays; - -import org.apache.commons.math4.analysis.ParametricUnivariateFunction; -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathUtils; - -/** - * Immutable representation of a real polynomial function with real coefficients. - *

- * Horner's Method - * is used to evaluate the function.

- * - */ -public class PolynomialFunction implements UnivariateDifferentiableFunction, Serializable { - /** - * Serialization identifier - */ - private static final long serialVersionUID = -7726511984200295583L; - /** - * The coefficients of the polynomial, ordered by degree -- i.e., - * coefficients[0] is the constant term and coefficients[n] is the - * coefficient of x^n where n is the degree of the polynomial. - */ - private final double coefficients[]; - - /** - * Construct a polynomial with the given coefficients. The first element - * of the coefficients array is the constant term. Higher degree - * coefficients follow in sequence. The degree of the resulting polynomial - * is the index of the last non-null element of the array, or 0 if all elements - * are null. - *

- * The constructor makes a copy of the input array and assigns the copy to - * the coefficients property.

- * - * @param c Polynomial coefficients. - * @throws NullArgumentException if {@code c} is {@code null}. - * @throws NoDataException if {@code c} is empty. - */ - public PolynomialFunction(double c[]) - throws NullArgumentException, NoDataException { - super(); - MathUtils.checkNotNull(c); - int n = c.length; - if (n == 0) { - throw new NoDataException(LocalizedFormats.EMPTY_POLYNOMIALS_COEFFICIENTS_ARRAY); - } - while ((n > 1) && (c[n - 1] == 0)) { - --n; - } - this.coefficients = new double[n]; - System.arraycopy(c, 0, this.coefficients, 0, n); - } - - /** - * Compute the value of the function for the given argument. - *

- * The value returned is

- * {@code coefficients[n] * x^n + ... + coefficients[1] * x + coefficients[0]} - *

- * - * @param x Argument for which the function value should be computed. - * @return the value of the polynomial at the given point. - * - * @see org.apache.commons.math4.analysis.UnivariateFunction#value(double) - */ - @Override - public double value(double x) { - return evaluate(coefficients, x); - } - - /** - * Returns the degree of the polynomial. - * - * @return the degree of the polynomial. - */ - public int degree() { - return coefficients.length - 1; - } - - /** - * Returns a copy of the coefficients array. - *

- * Changes made to the returned copy will not affect the coefficients of - * the polynomial.

- * - * @return a fresh copy of the coefficients array. - */ - public double[] getCoefficients() { - return coefficients.clone(); - } - - /** - * Uses Horner's Method to evaluate the polynomial with the given coefficients at - * the argument. - * - * @param coefficients Coefficients of the polynomial to evaluate. - * @param argument Input value. - * @return the value of the polynomial. - * @throws NoDataException if {@code coefficients} is empty. - * @throws NullArgumentException if {@code coefficients} is {@code null}. - */ - protected static double evaluate(double[] coefficients, double argument) - throws NullArgumentException, NoDataException { - MathUtils.checkNotNull(coefficients); - int n = coefficients.length; - if (n == 0) { - throw new NoDataException(LocalizedFormats.EMPTY_POLYNOMIALS_COEFFICIENTS_ARRAY); - } - double result = coefficients[n - 1]; - for (int j = n - 2; j >= 0; j--) { - result = argument * result + coefficients[j]; - } - return result; - } - - - /** {@inheritDoc} - * @since 3.1 - * @throws NoDataException if {@code coefficients} is empty. - * @throws NullArgumentException if {@code coefficients} is {@code null}. - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) - throws NullArgumentException, NoDataException { - MathUtils.checkNotNull(coefficients); - int n = coefficients.length; - if (n == 0) { - throw new NoDataException(LocalizedFormats.EMPTY_POLYNOMIALS_COEFFICIENTS_ARRAY); - } - DerivativeStructure result = - new DerivativeStructure(t.getFreeParameters(), t.getOrder(), coefficients[n - 1]); - for (int j = n - 2; j >= 0; j--) { - result = result.multiply(t).add(coefficients[j]); - } - return result; - } - - /** - * Add a polynomial to the instance. - * - * @param p Polynomial to add. - * @return a new polynomial which is the sum of the instance and {@code p}. - */ - public PolynomialFunction add(final PolynomialFunction p) { - // identify the lowest degree polynomial - final int lowLength = FastMath.min(coefficients.length, p.coefficients.length); - final int highLength = FastMath.max(coefficients.length, p.coefficients.length); - - // build the coefficients array - double[] newCoefficients = new double[highLength]; - for (int i = 0; i < lowLength; ++i) { - newCoefficients[i] = coefficients[i] + p.coefficients[i]; - } - System.arraycopy((coefficients.length < p.coefficients.length) ? - p.coefficients : coefficients, - lowLength, - newCoefficients, lowLength, - highLength - lowLength); - - return new PolynomialFunction(newCoefficients); - } - - /** - * Subtract a polynomial from the instance. - * - * @param p Polynomial to subtract. - * @return a new polynomial which is the instance minus {@code p}. - */ - public PolynomialFunction subtract(final PolynomialFunction p) { - // identify the lowest degree polynomial - int lowLength = FastMath.min(coefficients.length, p.coefficients.length); - int highLength = FastMath.max(coefficients.length, p.coefficients.length); - - // build the coefficients array - double[] newCoefficients = new double[highLength]; - for (int i = 0; i < lowLength; ++i) { - newCoefficients[i] = coefficients[i] - p.coefficients[i]; - } - if (coefficients.length < p.coefficients.length) { - for (int i = lowLength; i < highLength; ++i) { - newCoefficients[i] = -p.coefficients[i]; - } - } else { - System.arraycopy(coefficients, lowLength, newCoefficients, lowLength, - highLength - lowLength); - } - - return new PolynomialFunction(newCoefficients); - } - - /** - * Negate the instance. - * - * @return a new polynomial with all coefficients negated - */ - public PolynomialFunction negate() { - double[] newCoefficients = new double[coefficients.length]; - for (int i = 0; i < coefficients.length; ++i) { - newCoefficients[i] = -coefficients[i]; - } - return new PolynomialFunction(newCoefficients); - } - - /** - * Multiply the instance by a polynomial. - * - * @param p Polynomial to multiply by. - * @return a new polynomial equal to this times {@code p} - */ - public PolynomialFunction multiply(final PolynomialFunction p) { - double[] newCoefficients = new double[coefficients.length + p.coefficients.length - 1]; - - for (int i = 0; i < newCoefficients.length; ++i) { - newCoefficients[i] = 0.0; - for (int j = FastMath.max(0, i + 1 - p.coefficients.length); - j < FastMath.min(coefficients.length, i + 1); - ++j) { - newCoefficients[i] += coefficients[j] * p.coefficients[i-j]; - } - } - - return new PolynomialFunction(newCoefficients); - } - - /** - * Returns the coefficients of the derivative of the polynomial with the given coefficients. - * - * @param coefficients Coefficients of the polynomial to differentiate. - * @return the coefficients of the derivative or {@code null} if coefficients has length 1. - * @throws NoDataException if {@code coefficients} is empty. - * @throws NullArgumentException if {@code coefficients} is {@code null}. - */ - protected static double[] differentiate(double[] coefficients) - throws NullArgumentException, NoDataException { - MathUtils.checkNotNull(coefficients); - int n = coefficients.length; - if (n == 0) { - throw new NoDataException(LocalizedFormats.EMPTY_POLYNOMIALS_COEFFICIENTS_ARRAY); - } - if (n == 1) { - return new double[]{0}; - } - double[] result = new double[n - 1]; - for (int i = n - 1; i > 0; i--) { - result[i - 1] = i * coefficients[i]; - } - return result; - } - - /** - * Returns the derivative as a {@link PolynomialFunction}. - * - * @return the derivative polynomial. - */ - public PolynomialFunction polynomialDerivative() { - return new PolynomialFunction(differentiate(coefficients)); - } - - /** - * Returns a string representation of the polynomial. - * - *

The representation is user oriented. Terms are displayed lowest - * degrees first. The multiplications signs, coefficients equals to - * one and null terms are not displayed (except if the polynomial is 0, - * in which case the 0 constant term is displayed). Addition of terms - * with negative coefficients are replaced by subtraction of terms - * with positive coefficients except for the first displayed term - * (i.e. we display -3 for a constant negative polynomial, - * but 1 - 3 x + x^2 if the negative coefficient is not - * the first one displayed).

- * - * @return a string representation of the polynomial. - */ - @Override - public String toString() { - StringBuilder s = new StringBuilder(); - if (coefficients[0] == 0.0) { - if (coefficients.length == 1) { - return "0"; - } - } else { - s.append(toString(coefficients[0])); - } - - for (int i = 1; i < coefficients.length; ++i) { - if (coefficients[i] != 0) { - if (s.length() > 0) { - if (coefficients[i] < 0) { - s.append(" - "); - } else { - s.append(" + "); - } - } else { - if (coefficients[i] < 0) { - s.append("-"); - } - } - - double absAi = FastMath.abs(coefficients[i]); - if ((absAi - 1) != 0) { - s.append(toString(absAi)); - s.append(' '); - } - - s.append("x"); - if (i > 1) { - s.append('^'); - s.append(Integer.toString(i)); - } - } - } - - return s.toString(); - } - - /** - * Creates a string representing a coefficient, removing ".0" endings. - * - * @param coeff Coefficient. - * @return a string representation of {@code coeff}. - */ - private static String toString(double coeff) { - final String c = Double.toString(coeff); - if (c.endsWith(".0")) { - return c.substring(0, c.length() - 2); - } else { - return c; - } - } - - /** {@inheritDoc} */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + Arrays.hashCode(coefficients); - return result; - } - - /** {@inheritDoc} */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof PolynomialFunction)) { - return false; - } - PolynomialFunction other = (PolynomialFunction) obj; - if (!Arrays.equals(coefficients, other.coefficients)) { - return false; - } - return true; - } - - /** - * Dedicated parametric polynomial class. - * - * @since 3.0 - */ - public static class Parametric implements ParametricUnivariateFunction { - /** {@inheritDoc} */ - @Override - public double[] gradient(double x, double ... parameters) { - final double[] gradient = new double[parameters.length]; - double xn = 1.0; - for (int i = 0; i < parameters.length; ++i) { - gradient[i] = xn; - xn *= x; - } - return gradient; - } - - /** {@inheritDoc} */ - @Override - public double value(final double x, final double ... parameters) - throws NoDataException { - return PolynomialFunction.evaluate(parameters, x); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/PolynomialFunctionLagrangeForm.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/PolynomialFunctionLagrangeForm.java deleted file mode 100644 index 7e0a0745f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/PolynomialFunctionLagrangeForm.java +++ /dev/null @@ -1,327 +0,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. - */ -package org.apache.commons.math4.analysis.polynomials; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; - -/** - * Implements the representation of a real polynomial function in - * - * Lagrange Form. For reference, see Introduction to Numerical - * Analysis, ISBN 038795452X, chapter 2. - *

- * The approximated function should be smooth enough for Lagrange polynomial - * to work well. Otherwise, consider using splines instead.

- * - * @since 1.2 - */ -public class PolynomialFunctionLagrangeForm implements UnivariateFunction { - /** - * The coefficients of the polynomial, ordered by degree -- i.e. - * coefficients[0] is the constant term and coefficients[n] is the - * coefficient of x^n where n is the degree of the polynomial. - */ - private double coefficients[]; - /** - * Interpolating points (abscissas). - */ - private final double x[]; - /** - * Function values at interpolating points. - */ - private final double y[]; - /** - * Whether the polynomial coefficients are available. - */ - private boolean coefficientsComputed; - - /** - * Construct a Lagrange polynomial with the given abscissas and function - * values. The order of interpolating points are not important. - *

- * The constructor makes copy of the input arrays and assigns them.

- * - * @param x interpolating points - * @param y function values at interpolating points - * @throws DimensionMismatchException if the array lengths are different. - * @throws NumberIsTooSmallException if the number of points is less than 2. - * @throws NonMonotonicSequenceException - * if two abscissae have the same value. - */ - public PolynomialFunctionLagrangeForm(double x[], double y[]) - throws DimensionMismatchException, NumberIsTooSmallException, NonMonotonicSequenceException { - this.x = new double[x.length]; - this.y = new double[y.length]; - System.arraycopy(x, 0, this.x, 0, x.length); - System.arraycopy(y, 0, this.y, 0, y.length); - coefficientsComputed = false; - - if (!verifyInterpolationArray(x, y, false)) { - MathArrays.sortInPlace(this.x, this.y); - // Second check in case some abscissa is duplicated. - verifyInterpolationArray(this.x, this.y, true); - } - } - - /** - * Calculate the function value at the given point. - * - * @param z Point at which the function value is to be computed. - * @return the function value. - * @throws DimensionMismatchException if {@code x} and {@code y} have - * different lengths. - * @throws NonMonotonicSequenceException - * if {@code x} is not sorted in strictly increasing order. - * @throws NumberIsTooSmallException if the size of {@code x} is less - * than 2. - */ - @Override - public double value(double z) { - return evaluateInternal(x, y, z); - } - - /** - * Returns the degree of the polynomial. - * - * @return the degree of the polynomial - */ - public int degree() { - return x.length - 1; - } - - /** - * Returns a copy of the interpolating points array. - *

- * Changes made to the returned copy will not affect the polynomial.

- * - * @return a fresh copy of the interpolating points array - */ - public double[] getInterpolatingPoints() { - double[] out = new double[x.length]; - System.arraycopy(x, 0, out, 0, x.length); - return out; - } - - /** - * Returns a copy of the interpolating values array. - *

- * Changes made to the returned copy will not affect the polynomial.

- * - * @return a fresh copy of the interpolating values array - */ - public double[] getInterpolatingValues() { - double[] out = new double[y.length]; - System.arraycopy(y, 0, out, 0, y.length); - return out; - } - - /** - * Returns a copy of the coefficients array. - *

- * Changes made to the returned copy will not affect the polynomial.

- *

- * Note that coefficients computation can be ill-conditioned. Use with caution - * and only when it is necessary.

- * - * @return a fresh copy of the coefficients array - */ - public double[] getCoefficients() { - if (!coefficientsComputed) { - computeCoefficients(); - } - double[] out = new double[coefficients.length]; - System.arraycopy(coefficients, 0, out, 0, coefficients.length); - return out; - } - - /** - * Evaluate the Lagrange polynomial using - * - * Neville's Algorithm. It takes O(n^2) time. - * - * @param x Interpolating points array. - * @param y Interpolating values array. - * @param z Point at which the function value is to be computed. - * @return the function value. - * @throws DimensionMismatchException if {@code x} and {@code y} have - * different lengths. - * @throws NonMonotonicSequenceException - * if {@code x} is not sorted in strictly increasing order. - * @throws NumberIsTooSmallException if the size of {@code x} is less - * than 2. - */ - public static double evaluate(double x[], double y[], double z) - throws DimensionMismatchException, NumberIsTooSmallException, NonMonotonicSequenceException { - if (verifyInterpolationArray(x, y, false)) { - return evaluateInternal(x, y, z); - } - - // Array is not sorted. - final double[] xNew = new double[x.length]; - final double[] yNew = new double[y.length]; - System.arraycopy(x, 0, xNew, 0, x.length); - System.arraycopy(y, 0, yNew, 0, y.length); - - MathArrays.sortInPlace(xNew, yNew); - // Second check in case some abscissa is duplicated. - verifyInterpolationArray(xNew, yNew, true); - return evaluateInternal(xNew, yNew, z); - } - - /** - * Evaluate the Lagrange polynomial using - * - * Neville's Algorithm. It takes O(n^2) time. - * - * @param x Interpolating points array. - * @param y Interpolating values array. - * @param z Point at which the function value is to be computed. - * @return the function value. - * @throws DimensionMismatchException if {@code x} and {@code y} have - * different lengths. - * @throws NonMonotonicSequenceException - * if {@code x} is not sorted in strictly increasing order. - * @throws NumberIsTooSmallException if the size of {@code x} is less - * than 2. - */ - private static double evaluateInternal(double x[], double y[], double z) { - int nearest = 0; - final int n = x.length; - final double[] c = new double[n]; - final double[] d = new double[n]; - double min_dist = Double.POSITIVE_INFINITY; - for (int i = 0; i < n; i++) { - // initialize the difference arrays - c[i] = y[i]; - d[i] = y[i]; - // find out the abscissa closest to z - final double dist = FastMath.abs(z - x[i]); - if (dist < min_dist) { - nearest = i; - min_dist = dist; - } - } - - // initial approximation to the function value at z - double value = y[nearest]; - - for (int i = 1; i < n; i++) { - for (int j = 0; j < n-i; j++) { - final double tc = x[j] - z; - final double td = x[i+j] - z; - final double divider = x[j] - x[i+j]; - // update the difference arrays - final double w = (c[j+1] - d[j]) / divider; - c[j] = tc * w; - d[j] = td * w; - } - // sum up the difference terms to get the final value - if (nearest < 0.5*(n-i+1)) { - value += c[nearest]; // fork down - } else { - nearest--; - value += d[nearest]; // fork up - } - } - - return value; - } - - /** - * Calculate the coefficients of Lagrange polynomial from the - * interpolation data. It takes O(n^2) time. - * Note that this computation can be ill-conditioned: Use with caution - * and only when it is necessary. - */ - protected void computeCoefficients() { - final int n = degree() + 1; - coefficients = new double[n]; - for (int i = 0; i < n; i++) { - coefficients[i] = 0.0; - } - - // c[] are the coefficients of P(x) = (x-x[0])(x-x[1])...(x-x[n-1]) - final double[] c = new double[n+1]; - c[0] = 1.0; - for (int i = 0; i < n; i++) { - for (int j = i; j > 0; j--) { - c[j] = c[j-1] - c[j] * x[i]; - } - c[0] *= -x[i]; - c[i+1] = 1; - } - - final double[] tc = new double[n]; - for (int i = 0; i < n; i++) { - // d = (x[i]-x[0])...(x[i]-x[i-1])(x[i]-x[i+1])...(x[i]-x[n-1]) - double d = 1; - for (int j = 0; j < n; j++) { - if (i != j) { - d *= x[i] - x[j]; - } - } - final double t = y[i] / d; - // Lagrange polynomial is the sum of n terms, each of which is a - // polynomial of degree n-1. tc[] are the coefficients of the i-th - // numerator Pi(x) = (x-x[0])...(x-x[i-1])(x-x[i+1])...(x-x[n-1]). - tc[n-1] = c[n]; // actually c[n] = 1 - coefficients[n-1] += t * tc[n-1]; - for (int j = n-2; j >= 0; j--) { - tc[j] = c[j+1] + tc[j+1] * x[i]; - coefficients[j] += t * tc[j]; - } - } - - coefficientsComputed = true; - } - - /** - * Check that the interpolation arrays are valid. - * The arrays features checked by this method are that both arrays have the - * same length and this length is at least 2. - * - * @param x Interpolating points array. - * @param y Interpolating values array. - * @param abort Whether to throw an exception if {@code x} is not sorted. - * @throws DimensionMismatchException if the array lengths are different. - * @throws NumberIsTooSmallException if the number of points is less than 2. - * @throws NonMonotonicSequenceException - * if {@code x} is not sorted in strictly increasing order and {@code abort} - * is {@code true}. - * @return {@code false} if the {@code x} is not sorted in increasing order, - * {@code true} otherwise. - * @see #evaluate(double[], double[], double) - * @see #computeCoefficients() - */ - public static boolean verifyInterpolationArray(double x[], double y[], boolean abort) - throws DimensionMismatchException, NumberIsTooSmallException, NonMonotonicSequenceException { - if (x.length != y.length) { - throw new DimensionMismatchException(x.length, y.length); - } - if (x.length < 2) { - throw new NumberIsTooSmallException(LocalizedFormats.WRONG_NUMBER_OF_POINTS, 2, x.length, true); - } - - return MathArrays.checkOrder(x, MathArrays.OrderDirection.INCREASING, true, abort); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/PolynomialFunctionNewtonForm.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/PolynomialFunctionNewtonForm.java deleted file mode 100644 index 09fa2b009..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/PolynomialFunctionNewtonForm.java +++ /dev/null @@ -1,247 +0,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. - */ -package org.apache.commons.math4.analysis.polynomials; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.MathUtils; - -/** - * Implements the representation of a real polynomial function in - * Newton Form. For reference, see Elementary Numerical Analysis, - * ISBN 0070124477, chapter 2. - *

- * The formula of polynomial in Newton form is - * p(x) = a[0] + a[1](x-c[0]) + a[2](x-c[0])(x-c[1]) + ... + - * a[n](x-c[0])(x-c[1])...(x-c[n-1]) - * Note that the length of a[] is one more than the length of c[]

- * - * @since 1.2 - */ -public class PolynomialFunctionNewtonForm implements UnivariateDifferentiableFunction { - - /** - * The coefficients of the polynomial, ordered by degree -- i.e. - * coefficients[0] is the constant term and coefficients[n] is the - * coefficient of x^n where n is the degree of the polynomial. - */ - private double coefficients[]; - - /** - * Centers of the Newton polynomial. - */ - private final double c[]; - - /** - * When all c[i] = 0, a[] becomes normal polynomial coefficients, - * i.e. a[i] = coefficients[i]. - */ - private final double a[]; - - /** - * Whether the polynomial coefficients are available. - */ - private boolean coefficientsComputed; - - /** - * Construct a Newton polynomial with the given a[] and c[]. The order of - * centers are important in that if c[] shuffle, then values of a[] would - * completely change, not just a permutation of old a[]. - *

- * The constructor makes copy of the input arrays and assigns them.

- * - * @param a Coefficients in Newton form formula. - * @param c Centers. - * @throws NullArgumentException if any argument is {@code null}. - * @throws NoDataException if any array has zero length. - * @throws DimensionMismatchException if the size difference between - * {@code a} and {@code c} is not equal to 1. - */ - public PolynomialFunctionNewtonForm(double a[], double c[]) - throws NullArgumentException, NoDataException, DimensionMismatchException { - - verifyInputArray(a, c); - this.a = new double[a.length]; - this.c = new double[c.length]; - System.arraycopy(a, 0, this.a, 0, a.length); - System.arraycopy(c, 0, this.c, 0, c.length); - coefficientsComputed = false; - } - - /** - * Calculate the function value at the given point. - * - * @param z Point at which the function value is to be computed. - * @return the function value. - */ - @Override - public double value(double z) { - return evaluate(a, c, z); - } - - /** - * {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - verifyInputArray(a, c); - - final int n = c.length; - DerivativeStructure value = new DerivativeStructure(t.getFreeParameters(), t.getOrder(), a[n]); - for (int i = n - 1; i >= 0; i--) { - value = t.subtract(c[i]).multiply(value).add(a[i]); - } - - return value; - - } - - /** - * Returns the degree of the polynomial. - * - * @return the degree of the polynomial - */ - public int degree() { - return c.length; - } - - /** - * Returns a copy of coefficients in Newton form formula. - *

- * Changes made to the returned copy will not affect the polynomial.

- * - * @return a fresh copy of coefficients in Newton form formula - */ - public double[] getNewtonCoefficients() { - double[] out = new double[a.length]; - System.arraycopy(a, 0, out, 0, a.length); - return out; - } - - /** - * Returns a copy of the centers array. - *

- * Changes made to the returned copy will not affect the polynomial.

- * - * @return a fresh copy of the centers array. - */ - public double[] getCenters() { - double[] out = new double[c.length]; - System.arraycopy(c, 0, out, 0, c.length); - return out; - } - - /** - * Returns a copy of the coefficients array. - *

- * Changes made to the returned copy will not affect the polynomial.

- * - * @return a fresh copy of the coefficients array. - */ - public double[] getCoefficients() { - if (!coefficientsComputed) { - computeCoefficients(); - } - double[] out = new double[coefficients.length]; - System.arraycopy(coefficients, 0, out, 0, coefficients.length); - return out; - } - - /** - * Evaluate the Newton polynomial using nested multiplication. It is - * also called - * Horner's Rule and takes O(N) time. - * - * @param a Coefficients in Newton form formula. - * @param c Centers. - * @param z Point at which the function value is to be computed. - * @return the function value. - * @throws NullArgumentException if any argument is {@code null}. - * @throws NoDataException if any array has zero length. - * @throws DimensionMismatchException if the size difference between - * {@code a} and {@code c} is not equal to 1. - */ - public static double evaluate(double a[], double c[], double z) - throws NullArgumentException, DimensionMismatchException, NoDataException { - verifyInputArray(a, c); - - final int n = c.length; - double value = a[n]; - for (int i = n - 1; i >= 0; i--) { - value = a[i] + (z - c[i]) * value; - } - - return value; - } - - /** - * Calculate the normal polynomial coefficients given the Newton form. - * It also uses nested multiplication but takes O(N^2) time. - */ - protected void computeCoefficients() { - final int n = degree(); - - coefficients = new double[n+1]; - for (int i = 0; i <= n; i++) { - coefficients[i] = 0.0; - } - - coefficients[0] = a[n]; - for (int i = n-1; i >= 0; i--) { - for (int j = n-i; j > 0; j--) { - coefficients[j] = coefficients[j-1] - c[i] * coefficients[j]; - } - coefficients[0] = a[i] - c[i] * coefficients[0]; - } - - coefficientsComputed = true; - } - - /** - * Verifies that the input arrays are valid. - *

- * The centers must be distinct for interpolation purposes, but not - * for general use. Thus it is not verified here.

- * - * @param a the coefficients in Newton form formula - * @param c the centers - * @throws NullArgumentException if any argument is {@code null}. - * @throws NoDataException if any array has zero length. - * @throws DimensionMismatchException if the size difference between - * {@code a} and {@code c} is not equal to 1. - * @see org.apache.commons.math4.analysis.interpolation.DividedDifferenceInterpolator#computeDividedDifference(double[], - * double[]) - */ - protected static void verifyInputArray(double a[], double c[]) - throws NullArgumentException, NoDataException, DimensionMismatchException { - MathUtils.checkNotNull(a); - MathUtils.checkNotNull(c); - if (a.length == 0 || c.length == 0) { - throw new NoDataException(LocalizedFormats.EMPTY_POLYNOMIALS_COEFFICIENTS_ARRAY); - } - if (a.length != c.length + 1) { - throw new DimensionMismatchException(LocalizedFormats.ARRAY_SIZES_SHOULD_HAVE_DIFFERENCE_1, - a.length, c.length); - } - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/PolynomialSplineFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/PolynomialSplineFunction.java deleted file mode 100644 index d7263c2fd..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/PolynomialSplineFunction.java +++ /dev/null @@ -1,237 +0,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. - */ -package org.apache.commons.math4.analysis.polynomials; - -import java.util.Arrays; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.MathArrays; - -/** - * Represents a polynomial spline function. - *

- * A polynomial spline function consists of a set of - * interpolating polynomials and an ascending array of domain - * knot points, determining the intervals over which the spline function - * is defined by the constituent polynomials. The polynomials are assumed to - * have been computed to match the values of another function at the knot - * points. The value consistency constraints are not currently enforced by - * PolynomialSplineFunction itself, but are assumed to hold among - * the polynomials and knot points passed to the constructor.

- *

- * N.B.: The polynomials in the polynomials property must be - * centered on the knot points to compute the spline function values. - * See below.

- *

- * The domain of the polynomial spline function is - * [smallest knot, largest knot]. Attempts to evaluate the - * function at values outside of this range generate IllegalArgumentExceptions. - *

- *

- * The value of the polynomial spline function for an argument x - * is computed as follows: - *

    - *
  1. The knot array is searched to find the segment to which x - * belongs. If x is less than the smallest knot point or greater - * than the largest one, an IllegalArgumentException - * is thrown.
  2. - *
  3. Let j be the index of the largest knot point that is less - * than or equal to x. The value returned is - * {@code polynomials[j](x - knot[j])}
- * - */ -public class PolynomialSplineFunction implements UnivariateDifferentiableFunction { - /** - * Spline segment interval delimiters (knots). - * Size is n + 1 for n segments. - */ - private final double knots[]; - /** - * The polynomial functions that make up the spline. The first element - * determines the value of the spline over the first subinterval, the - * second over the second, etc. Spline function values are determined by - * evaluating these functions at {@code (x - knot[i])} where i is the - * knot segment to which x belongs. - */ - private final PolynomialFunction polynomials[]; - /** - * Number of spline segments. It is equal to the number of polynomials and - * to the number of partition points - 1. - */ - private final int n; - - - /** - * Construct a polynomial spline function with the given segment delimiters - * and interpolating polynomials. - * The constructor copies both arrays and assigns the copies to the knots - * and polynomials properties, respectively. - * - * @param knots Spline segment interval delimiters. - * @param polynomials Polynomial functions that make up the spline. - * @throws NullArgumentException if either of the input arrays is {@code null}. - * @throws NumberIsTooSmallException if knots has length less than 2. - * @throws DimensionMismatchException if {@code polynomials.length != knots.length - 1}. - * @throws NonMonotonicSequenceException if the {@code knots} array is not strictly increasing. - * - */ - public PolynomialSplineFunction(double knots[], PolynomialFunction polynomials[]) - throws NullArgumentException, NumberIsTooSmallException, - DimensionMismatchException, NonMonotonicSequenceException{ - if (knots == null || - polynomials == null) { - throw new NullArgumentException(); - } - if (knots.length < 2) { - throw new NumberIsTooSmallException(LocalizedFormats.NOT_ENOUGH_POINTS_IN_SPLINE_PARTITION, - knots.length, 2, true); - } - if (knots.length - 1 != polynomials.length) { - throw new DimensionMismatchException(polynomials.length, knots.length); - } - MathArrays.checkOrder(knots); - - this.n = knots.length -1; - this.knots = new double[n + 1]; - System.arraycopy(knots, 0, this.knots, 0, n + 1); - this.polynomials = new PolynomialFunction[n]; - System.arraycopy(polynomials, 0, this.polynomials, 0, n); - } - - /** - * Compute the value for the function. - * See {@link PolynomialSplineFunction} for details on the algorithm for - * computing the value of the function. - * - * @param v Point for which the function value should be computed. - * @return the value. - * @throws OutOfRangeException if {@code v} is outside of the domain of the - * spline function (smaller than the smallest knot point or larger than the - * largest knot point). - */ - @Override - public double value(double v) { - if (v < knots[0] || v > knots[n]) { - throw new OutOfRangeException(v, knots[0], knots[n]); - } - int i = Arrays.binarySearch(knots, v); - if (i < 0) { - i = -i - 2; - } - // This will handle the case where v is the last knot value - // There are only n-1 polynomials, so if v is the last knot - // then we will use the last polynomial to calculate the value. - if ( i >= polynomials.length ) { - i--; - } - return polynomials[i].value(v - knots[i]); - } - - /** - * Get the derivative of the polynomial spline function. - * - * @return the derivative function. - */ - public PolynomialSplineFunction polynomialSplineDerivative() { - PolynomialFunction derivativePolynomials[] = new PolynomialFunction[n]; - for (int i = 0; i < n; i++) { - derivativePolynomials[i] = polynomials[i].polynomialDerivative(); - } - return new PolynomialSplineFunction(knots, derivativePolynomials); - } - - - /** {@inheritDoc} - * @since 3.1 - */ - @Override - public DerivativeStructure value(final DerivativeStructure t) { - final double t0 = t.getValue(); - if (t0 < knots[0] || t0 > knots[n]) { - throw new OutOfRangeException(t0, knots[0], knots[n]); - } - int i = Arrays.binarySearch(knots, t0); - if (i < 0) { - i = -i - 2; - } - // This will handle the case where t is the last knot value - // There are only n-1 polynomials, so if t is the last knot - // then we will use the last polynomial to calculate the value. - if ( i >= polynomials.length ) { - i--; - } - return polynomials[i].value(t.subtract(knots[i])); - } - - /** - * Get the number of spline segments. - * It is also the number of polynomials and the number of knot points - 1. - * - * @return the number of spline segments. - */ - public int getN() { - return n; - } - - /** - * Get a copy of the interpolating polynomials array. - * It returns a fresh copy of the array. Changes made to the copy will - * not affect the polynomials property. - * - * @return the interpolating polynomials. - */ - public PolynomialFunction[] getPolynomials() { - PolynomialFunction p[] = new PolynomialFunction[n]; - System.arraycopy(polynomials, 0, p, 0, n); - return p; - } - - /** - * Get an array copy of the knot points. - * It returns a fresh copy of the array. Changes made to the copy - * will not affect the knots property. - * - * @return the knot points. - */ - public double[] getKnots() { - double out[] = new double[n + 1]; - System.arraycopy(knots, 0, out, 0, n + 1); - return out; - } - - /** - * Indicates whether a point is within the interpolation range. - * - * @param x Point. - * @return {@code true} if {@code x} is a valid point. - */ - public boolean isValidPoint(double x) { - if (x < knots[0] || - x > knots[n]) { - return false; - } else { - return true; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/PolynomialsUtils.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/PolynomialsUtils.java deleted file mode 100644 index 018df8126..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/PolynomialsUtils.java +++ /dev/null @@ -1,450 +0,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. - */ -package org.apache.commons.math4.analysis.polynomials; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.math4.fraction.BigFraction; -import org.apache.commons.numbers.combinatorics.BinomialCoefficient; -import org.apache.commons.math4.util.FastMath; - -/** - * A collection of static methods that operate on or return polynomials. - * - * @since 2.0 - */ -public class PolynomialsUtils { - - /** Coefficients for Chebyshev polynomials. */ - private static final List CHEBYSHEV_COEFFICIENTS; - - /** Coefficients for Hermite polynomials. */ - private static final List HERMITE_COEFFICIENTS; - - /** Coefficients for Laguerre polynomials. */ - private static final List LAGUERRE_COEFFICIENTS; - - /** Coefficients for Legendre polynomials. */ - private static final List LEGENDRE_COEFFICIENTS; - - /** Coefficients for Jacobi polynomials. */ - private static final Map> JACOBI_COEFFICIENTS; - - static { - - // initialize recurrence for Chebyshev polynomials - // T0(X) = 1, T1(X) = 0 + 1 * X - CHEBYSHEV_COEFFICIENTS = new ArrayList<>(); - CHEBYSHEV_COEFFICIENTS.add(BigFraction.ONE); - CHEBYSHEV_COEFFICIENTS.add(BigFraction.ZERO); - CHEBYSHEV_COEFFICIENTS.add(BigFraction.ONE); - - // initialize recurrence for Hermite polynomials - // H0(X) = 1, H1(X) = 0 + 2 * X - HERMITE_COEFFICIENTS = new ArrayList<>(); - HERMITE_COEFFICIENTS.add(BigFraction.ONE); - HERMITE_COEFFICIENTS.add(BigFraction.ZERO); - HERMITE_COEFFICIENTS.add(BigFraction.TWO); - - // initialize recurrence for Laguerre polynomials - // L0(X) = 1, L1(X) = 1 - 1 * X - LAGUERRE_COEFFICIENTS = new ArrayList<>(); - LAGUERRE_COEFFICIENTS.add(BigFraction.ONE); - LAGUERRE_COEFFICIENTS.add(BigFraction.ONE); - LAGUERRE_COEFFICIENTS.add(BigFraction.MINUS_ONE); - - // initialize recurrence for Legendre polynomials - // P0(X) = 1, P1(X) = 0 + 1 * X - LEGENDRE_COEFFICIENTS = new ArrayList<>(); - LEGENDRE_COEFFICIENTS.add(BigFraction.ONE); - LEGENDRE_COEFFICIENTS.add(BigFraction.ZERO); - LEGENDRE_COEFFICIENTS.add(BigFraction.ONE); - - // initialize map for Jacobi polynomials - JACOBI_COEFFICIENTS = new HashMap<>(); - - } - - /** - * Private constructor, to prevent instantiation. - */ - private PolynomialsUtils() { - } - - /** - * Create a Chebyshev polynomial of the first kind. - *

Chebyshev - * polynomials of the first kind are orthogonal polynomials. - * They can be defined by the following recurrence relations:

- * \( - * T_0(x) = 1 \\ - * T_1(x) = x \\ - * T_{k+1}(x) = 2x T_k(x) - T_{k-1}(x) - * \) - *

- * @param degree degree of the polynomial - * @return Chebyshev polynomial of specified degree - */ - public static PolynomialFunction createChebyshevPolynomial(final int degree) { - return buildPolynomial(degree, CHEBYSHEV_COEFFICIENTS, - new RecurrenceCoefficientsGenerator() { - /** Fixed recurrence coefficients. */ - private final BigFraction[] coeffs = { BigFraction.ZERO, BigFraction.TWO, BigFraction.ONE }; - /** {@inheritDoc} */ - @Override - public BigFraction[] generate(int k) { - return coeffs; - } - }); - } - - /** - * Create a Hermite polynomial. - *

Hermite - * polynomials are orthogonal polynomials. - * They can be defined by the following recurrence relations:

- * \( - * H_0(x) = 1 \\ - * H_1(x) = 2x \\ - * H_{k+1}(x) = 2x H_k(X) - 2k H_{k-1}(x) - * \) - *

- - * @param degree degree of the polynomial - * @return Hermite polynomial of specified degree - */ - public static PolynomialFunction createHermitePolynomial(final int degree) { - return buildPolynomial(degree, HERMITE_COEFFICIENTS, - new RecurrenceCoefficientsGenerator() { - /** {@inheritDoc} */ - @Override - public BigFraction[] generate(int k) { - return new BigFraction[] { - BigFraction.ZERO, - BigFraction.TWO, - new BigFraction(2 * k)}; - } - }); - } - - /** - * Create a Laguerre polynomial. - *

Laguerre - * polynomials are orthogonal polynomials. - * They can be defined by the following recurrence relations:

- * \( - * L_0(x) = 1 \\ - * L_1(x) = 1 - x \\ - * (k+1) L_{k+1}(x) = (2k + 1 - x) L_k(x) - k L_{k-1}(x) - * \) - *

- * @param degree degree of the polynomial - * @return Laguerre polynomial of specified degree - */ - public static PolynomialFunction createLaguerrePolynomial(final int degree) { - return buildPolynomial(degree, LAGUERRE_COEFFICIENTS, - new RecurrenceCoefficientsGenerator() { - /** {@inheritDoc} */ - @Override - public BigFraction[] generate(int k) { - final int kP1 = k + 1; - return new BigFraction[] { - new BigFraction(2 * k + 1, kP1), - new BigFraction(-1, kP1), - new BigFraction(k, kP1)}; - } - }); - } - - /** - * Create a Legendre polynomial. - *

Legendre - * polynomials are orthogonal polynomials. - * They can be defined by the following recurrence relations:

- * \( - * P_0(x) = 1 \\ - * P_1(x) = x \\ - * (k+1) P_{k+1}(x) = (2k+1) x P_k(x) - k P_{k-1}(x) - * \) - *

- * @param degree degree of the polynomial - * @return Legendre polynomial of specified degree - */ - public static PolynomialFunction createLegendrePolynomial(final int degree) { - return buildPolynomial(degree, LEGENDRE_COEFFICIENTS, - new RecurrenceCoefficientsGenerator() { - /** {@inheritDoc} */ - @Override - public BigFraction[] generate(int k) { - final int kP1 = k + 1; - return new BigFraction[] { - BigFraction.ZERO, - new BigFraction(k + kP1, kP1), - new BigFraction(k, kP1)}; - } - }); - } - - /** - * Create a Jacobi polynomial. - *

Jacobi - * polynomials are orthogonal polynomials. - * They can be defined by the following recurrence relations:

- * \( - * P_0^{vw}(x) = 1 \\ - * P_{-1}^{vw}(x) = 0 \\ - * 2k(k + v + w)(2k + v + w - 2) P_k^{vw}(x) = \\ - * (2k + v + w - 1)[(2k + v + w)(2k + v + w - 2) x + v^2 - w^2] P_{k-1}^{vw}(x) \\ - * - 2(k + v - 1)(k + w - 1)(2k + v + w) P_{k-2}^{vw}(x) - * \) - *

- * @param degree degree of the polynomial - * @param v first exponent - * @param w second exponent - * @return Jacobi polynomial of specified degree - */ - public static PolynomialFunction createJacobiPolynomial(final int degree, final int v, final int w) { - - // select the appropriate list - final JacobiKey key = new JacobiKey(v, w); - - if (!JACOBI_COEFFICIENTS.containsKey(key)) { - - // allocate a new list for v, w - final List list = new ArrayList<>(); - JACOBI_COEFFICIENTS.put(key, list); - - // Pv,w,0(x) = 1; - list.add(BigFraction.ONE); - - // P1(x) = (v - w) / 2 + (2 + v + w) * X / 2 - list.add(new BigFraction(v - w, 2)); - list.add(new BigFraction(2 + v + w, 2)); - - } - - return buildPolynomial(degree, JACOBI_COEFFICIENTS.get(key), - new RecurrenceCoefficientsGenerator() { - /** {@inheritDoc} */ - @Override - public BigFraction[] generate(int k) { - k++; - final int kvw = k + v + w; - final int twoKvw = kvw + k; - final int twoKvwM1 = twoKvw - 1; - final int twoKvwM2 = twoKvw - 2; - final int den = 2 * k * kvw * twoKvwM2; - - return new BigFraction[] { - new BigFraction(twoKvwM1 * (v * v - w * w), den), - new BigFraction(twoKvwM1 * twoKvw * twoKvwM2, den), - new BigFraction(2 * (k + v - 1) * (k + w - 1) * twoKvw, den) - }; - } - }); - - } - - /** Inner class for Jacobi polynomials keys. */ - private static class JacobiKey { - - /** First exponent. */ - private final int v; - - /** Second exponent. */ - private final int w; - - /** Simple constructor. - * @param v first exponent - * @param w second exponent - */ - JacobiKey(final int v, final int w) { - this.v = v; - this.w = w; - } - - /** Get hash code. - * @return hash code - */ - @Override - public int hashCode() { - return (v << 16) ^ w; - } - - /** Check if the instance represent the same key as another instance. - * @param key other key - * @return true if the instance and the other key refer to the same polynomial - */ - @Override - public boolean equals(final Object key) { - - if ((key == null) || !(key instanceof JacobiKey)) { - return false; - } - - final JacobiKey otherK = (JacobiKey) key; - return (v == otherK.v) && (w == otherK.w); - - } - } - - /** - * Compute the coefficients of the polynomial \(P_s(x)\) - * whose values at point {@code x} will be the same as the those from the - * original polynomial \(P(x)\) when computed at {@code x + shift}. - *

- * More precisely, let \(\Delta = \) {@code shift} and let - * \(P_s(x) = P(x + \Delta)\). The returned array - * consists of the coefficients of \(P_s\). So if \(a_0, ..., a_{n-1}\) - * are the coefficients of \(P\), then the returned array - * \(b_0, ..., b_{n-1}\) satisfies the identity - * \(\sum_{i=0}^{n-1} b_i x^i = \sum_{i=0}^{n-1} a_i (x + \Delta)^i\) for all \(x\). - * - * @param coefficients Coefficients of the original polynomial. - * @param shift Shift value. - * @return the coefficients \(b_i\) of the shifted - * polynomial. - */ - public static double[] shift(final double[] coefficients, - final double shift) { - final int dp1 = coefficients.length; - final double[] newCoefficients = new double[dp1]; - - // Pascal triangle. - final int[][] coeff = new int[dp1][dp1]; - for (int i = 0; i < dp1; i++){ - for(int j = 0; j <= i; j++){ - coeff[i][j] = (int) BinomialCoefficient.value(i, j); - } - } - - // First polynomial coefficient. - for (int i = 0; i < dp1; i++){ - newCoefficients[0] += coefficients[i] * FastMath.pow(shift, i); - } - - // Superior order. - final int d = dp1 - 1; - for (int i = 0; i < d; i++) { - for (int j = i; j < d; j++){ - newCoefficients[i + 1] += coeff[j + 1][j - i] * - coefficients[j + 1] * FastMath.pow(shift, j - i); - } - } - - return newCoefficients; - } - - - /** Get the coefficients array for a given degree. - * @param degree degree of the polynomial - * @param coefficients list where the computed coefficients are stored - * @param generator recurrence coefficients generator - * @return coefficients array - */ - private static PolynomialFunction buildPolynomial(final int degree, - final List coefficients, - final RecurrenceCoefficientsGenerator generator) { - - synchronized (coefficients) { - final int maxDegree = (int) FastMath.floor(FastMath.sqrt(2 * coefficients.size())) - 1; - if (degree > maxDegree) { - computeUpToDegree(degree, maxDegree, generator, coefficients); - } - } - - // coefficient for polynomial 0 is l [0] - // coefficients for polynomial 1 are l [1] ... l [2] (degrees 0 ... 1) - // coefficients for polynomial 2 are l [3] ... l [5] (degrees 0 ... 2) - // coefficients for polynomial 3 are l [6] ... l [9] (degrees 0 ... 3) - // coefficients for polynomial 4 are l[10] ... l[14] (degrees 0 ... 4) - // coefficients for polynomial 5 are l[15] ... l[20] (degrees 0 ... 5) - // coefficients for polynomial 6 are l[21] ... l[27] (degrees 0 ... 6) - // ... - final int start = degree * (degree + 1) / 2; - - final double[] a = new double[degree + 1]; - for (int i = 0; i <= degree; ++i) { - a[i] = coefficients.get(start + i).doubleValue(); - } - - // build the polynomial - return new PolynomialFunction(a); - - } - - /** Compute polynomial coefficients up to a given degree. - * @param degree maximal degree - * @param maxDegree current maximal degree - * @param generator recurrence coefficients generator - * @param coefficients list where the computed coefficients should be appended - */ - private static void computeUpToDegree(final int degree, final int maxDegree, - final RecurrenceCoefficientsGenerator generator, - final List coefficients) { - - int startK = (maxDegree - 1) * maxDegree / 2; - for (int k = maxDegree; k < degree; ++k) { - - // start indices of two previous polynomials Pk(X) and Pk-1(X) - int startKm1 = startK; - startK += k; - - // Pk+1(X) = (a[0] + a[1] X) Pk(X) - a[2] Pk-1(X) - BigFraction[] ai = generator.generate(k); - - BigFraction ck = coefficients.get(startK); - BigFraction ckm1 = coefficients.get(startKm1); - - // degree 0 coefficient - coefficients.add(ck.multiply(ai[0]).subtract(ckm1.multiply(ai[2]))); - - // degree 1 to degree k-1 coefficients - for (int i = 1; i < k; ++i) { - final BigFraction ckPrev = ck; - ck = coefficients.get(startK + i); - ckm1 = coefficients.get(startKm1 + i); - coefficients.add(ck.multiply(ai[0]).add(ckPrev.multiply(ai[1])).subtract(ckm1.multiply(ai[2]))); - } - - // degree k coefficient - final BigFraction ckPrev = ck; - ck = coefficients.get(startK + k); - coefficients.add(ck.multiply(ai[0]).add(ckPrev.multiply(ai[1]))); - - // degree k+1 coefficient - coefficients.add(ck.multiply(ai[1])); - - } - - } - - /** Interface for recurrence coefficients generation. */ - private interface RecurrenceCoefficientsGenerator { - /** - * Generate recurrence coefficients. - * @param k highest degree of the polynomials used in the recurrence - * @return an array of three coefficients such that - * \( P_{k+1}(x) = (a[0] + a[1] x) P_k(x) - a[2] P_{k-1}(x) \) - */ - BigFraction[] generate(int k); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/package-info.java deleted file mode 100644 index 8c8232c07..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/polynomials/package-info.java +++ /dev/null @@ -1,23 +0,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. - */ -/** - * - * Univariate real polynomials implementations, seen as differentiable - * univariate real functions. - * - */ -package org.apache.commons.math4.analysis.polynomials; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/AbstractPolynomialSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/AbstractPolynomialSolver.java deleted file mode 100644 index ec25f9869..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/AbstractPolynomialSolver.java +++ /dev/null @@ -1,80 +0,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. - */ - -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.analysis.polynomials.PolynomialFunction; - -/** - * Base class for solvers. - * - * @since 3.0 - */ -public abstract class AbstractPolynomialSolver - extends BaseAbstractUnivariateSolver - implements PolynomialSolver { - /** Function. */ - private PolynomialFunction polynomialFunction; - - /** - * Construct a solver with given absolute accuracy. - * - * @param absoluteAccuracy Maximum absolute error. - */ - protected AbstractPolynomialSolver(final double absoluteAccuracy) { - super(absoluteAccuracy); - } - /** - * Construct a solver with given accuracies. - * - * @param relativeAccuracy Maximum relative error. - * @param absoluteAccuracy Maximum absolute error. - */ - protected AbstractPolynomialSolver(final double relativeAccuracy, - final double absoluteAccuracy) { - super(relativeAccuracy, absoluteAccuracy); - } - /** - * Construct a solver with given accuracies. - * - * @param relativeAccuracy Maximum relative error. - * @param absoluteAccuracy Maximum absolute error. - * @param functionValueAccuracy Maximum function value error. - */ - protected AbstractPolynomialSolver(final double relativeAccuracy, - final double absoluteAccuracy, - final double functionValueAccuracy) { - super(relativeAccuracy, absoluteAccuracy, functionValueAccuracy); - } - - /** - * {@inheritDoc} - */ - @Override - protected void setup(int maxEval, PolynomialFunction f, - double min, double max, double startValue) { - super.setup(maxEval, f, min, max, startValue); - polynomialFunction = f; - } - - /** - * @return the coefficients of the polynomial function. - */ - protected double[] getCoefficients() { - return polynomialFunction.getCoefficients(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/AbstractUnivariateDifferentiableSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/AbstractUnivariateDifferentiableSolver.java deleted file mode 100644 index 50a1ac0e3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/AbstractUnivariateDifferentiableSolver.java +++ /dev/null @@ -1,82 +0,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. - */ - -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.exception.TooManyEvaluationsException; - -/** - * Provide a default implementation for several functions useful to generic - * solvers. - * - * @since 3.1 - */ -public abstract class AbstractUnivariateDifferentiableSolver - extends BaseAbstractUnivariateSolver - implements UnivariateDifferentiableSolver { - - /** Function to solve. */ - private UnivariateDifferentiableFunction function; - - /** - * Construct a solver with given absolute accuracy. - * - * @param absoluteAccuracy Maximum absolute error. - */ - protected AbstractUnivariateDifferentiableSolver(final double absoluteAccuracy) { - super(absoluteAccuracy); - } - - /** - * Construct a solver with given accuracies. - * - * @param relativeAccuracy Maximum relative error. - * @param absoluteAccuracy Maximum absolute error. - * @param functionValueAccuracy Maximum function value error. - */ - protected AbstractUnivariateDifferentiableSolver(final double relativeAccuracy, - final double absoluteAccuracy, - final double functionValueAccuracy) { - super(relativeAccuracy, absoluteAccuracy, functionValueAccuracy); - } - - /** - * Compute the objective function value. - * - * @param point Point at which the objective function must be evaluated. - * @return the objective function value and derivative at specified point. - * @throws TooManyEvaluationsException - * if the maximal number of evaluations is exceeded. - */ - protected DerivativeStructure computeObjectiveValueAndDerivative(double point) - throws TooManyEvaluationsException { - incrementEvaluationCount(); - return function.value(new DerivativeStructure(1, 1, 0, point)); - } - - /** - * {@inheritDoc} - */ - @Override - protected void setup(int maxEval, UnivariateDifferentiableFunction f, - double min, double max, double startValue) { - super.setup(maxEval, f, min, max, startValue); - function = f; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/AbstractUnivariateSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/AbstractUnivariateSolver.java deleted file mode 100644 index ebc8cb323..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/AbstractUnivariateSolver.java +++ /dev/null @@ -1,60 +0,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. - */ - -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.analysis.UnivariateFunction; - -/** - * Base class for solvers. - * - * @since 3.0 - */ -public abstract class AbstractUnivariateSolver - extends BaseAbstractUnivariateSolver - implements UnivariateSolver { - /** - * Construct a solver with given absolute accuracy. - * - * @param absoluteAccuracy Maximum absolute error. - */ - protected AbstractUnivariateSolver(final double absoluteAccuracy) { - super(absoluteAccuracy); - } - /** - * Construct a solver with given accuracies. - * - * @param relativeAccuracy Maximum relative error. - * @param absoluteAccuracy Maximum absolute error. - */ - protected AbstractUnivariateSolver(final double relativeAccuracy, - final double absoluteAccuracy) { - super(relativeAccuracy, absoluteAccuracy); - } - /** - * Construct a solver with given accuracies. - * - * @param relativeAccuracy Maximum relative error. - * @param absoluteAccuracy Maximum absolute error. - * @param functionValueAccuracy Maximum function value error. - */ - protected AbstractUnivariateSolver(final double relativeAccuracy, - final double absoluteAccuracy, - final double functionValueAccuracy) { - super(relativeAccuracy, absoluteAccuracy, functionValueAccuracy); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/AllowedSolution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/AllowedSolution.java deleted file mode 100644 index 511cc4fea..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/AllowedSolution.java +++ /dev/null @@ -1,75 +0,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. - */ - -package org.apache.commons.math4.analysis.solvers; - - -/** The kinds of solutions that a {@link BracketedUnivariateSolver - * (bracketed univariate real) root-finding algorithm} may accept as solutions. - * This basically controls whether or not under-approximations and - * over-approximations are allowed. - * - *

If all solutions are accepted ({@link #ANY_SIDE}), then the solution - * that the root-finding algorithm returns for a given root may be equal to the - * actual root, but it may also be an approximation that is slightly smaller - * or slightly larger than the actual root. Root-finding algorithms generally - * only guarantee that the returned solution is within the requested - * tolerances. In certain cases however, in particular for - * org.apache.commons.math4.ode.events.EventHandler state events of - * org.apache.commons.math4.ode.ODEIntegrator ODE solvers, it - * may be necessary to guarantee that a solution is returned that lies on a - * specific side the solution.

- * - * @see BracketedUnivariateSolver - * @since 3.0 - */ -public enum AllowedSolution { - /** There are no additional side restriction on the solutions for - * root-finding. That is, both under-approximations and over-approximations - * are allowed. So, if a function f(x) has a root at x = x0, then the - * root-finding result s may be smaller than x0, equal to x0, or greater - * than x0. - */ - ANY_SIDE, - - /** Only solutions that are less than or equal to the actual root are - * acceptable as solutions for root-finding. In other words, - * over-approximations are not allowed. So, if a function f(x) has a root - * at x = x0, then the root-finding result s must satisfy s <= x0. - */ - LEFT_SIDE, - - /** Only solutions that are greater than or equal to the actual root are - * acceptable as solutions for root-finding. In other words, - * under-approximations are not allowed. So, if a function f(x) has a root - * at x = x0, then the root-finding result s must satisfy s >= x0. - */ - RIGHT_SIDE, - - /** Only solutions for which values are less than or equal to zero are - * acceptable as solutions for root-finding. So, if a function f(x) has - * a root at x = x0, then the root-finding result s must satisfy f(s) <= 0. - */ - BELOW_SIDE, - - /** Only solutions for which values are greater than or equal to zero are - * acceptable as solutions for root-finding. So, if a function f(x) has - * a root at x = x0, then the root-finding result s must satisfy f(s) >= 0. - */ - ABOVE_SIDE; - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BaseAbstractUnivariateSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BaseAbstractUnivariateSolver.java deleted file mode 100644 index a65cd418d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BaseAbstractUnivariateSolver.java +++ /dev/null @@ -1,326 +0,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. - */ - -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NoBracketingException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.TooManyEvaluationsException; -import org.apache.commons.math4.util.Incrementor; -import org.apache.commons.math4.util.MathUtils; - -/** - * Provide a default implementation for several functions useful to generic - * solvers. - * The default values for relative and function tolerances are 1e-14 - * and 1e-15, respectively. It is however highly recommended to not - * rely on the default, but rather carefully consider values that match - * user's expectations, as well as the specifics of each implementation. - * - * @param Type of function to solve. - * - * @since 2.0 - */ -public abstract class BaseAbstractUnivariateSolver - implements BaseUnivariateSolver { - /** Default relative accuracy. */ - private static final double DEFAULT_RELATIVE_ACCURACY = 1e-14; - /** Default function value accuracy. */ - private static final double DEFAULT_FUNCTION_VALUE_ACCURACY = 1e-15; - /** Function value accuracy. */ - private final double functionValueAccuracy; - /** Absolute accuracy. */ - private final double absoluteAccuracy; - /** Relative accuracy. */ - private final double relativeAccuracy; - /** Evaluations counter. */ - private final Incrementor evaluations = new Incrementor(); - /** Lower end of search interval. */ - private double searchMin; - /** Higher end of search interval. */ - private double searchMax; - /** Initial guess. */ - private double searchStart; - /** Function to solve. */ - private FUNC function; - - /** - * Construct a solver with given absolute accuracy. - * - * @param absoluteAccuracy Maximum absolute error. - */ - protected BaseAbstractUnivariateSolver(final double absoluteAccuracy) { - this(DEFAULT_RELATIVE_ACCURACY, - absoluteAccuracy, - DEFAULT_FUNCTION_VALUE_ACCURACY); - } - - /** - * Construct a solver with given accuracies. - * - * @param relativeAccuracy Maximum relative error. - * @param absoluteAccuracy Maximum absolute error. - */ - protected BaseAbstractUnivariateSolver(final double relativeAccuracy, - final double absoluteAccuracy) { - this(relativeAccuracy, - absoluteAccuracy, - DEFAULT_FUNCTION_VALUE_ACCURACY); - } - - /** - * Construct a solver with given accuracies. - * - * @param relativeAccuracy Maximum relative error. - * @param absoluteAccuracy Maximum absolute error. - * @param functionValueAccuracy Maximum function value error. - */ - protected BaseAbstractUnivariateSolver(final double relativeAccuracy, - final double absoluteAccuracy, - final double functionValueAccuracy) { - this.absoluteAccuracy = absoluteAccuracy; - this.relativeAccuracy = relativeAccuracy; - this.functionValueAccuracy = functionValueAccuracy; - } - - /** {@inheritDoc} */ - @Override - public int getMaxEvaluations() { - return evaluations.getMaximalCount(); - } - /** {@inheritDoc} */ - @Override - public int getEvaluations() { - return evaluations.getCount(); - } - /** - * @return the lower end of the search interval. - */ - public double getMin() { - return searchMin; - } - /** - * @return the higher end of the search interval. - */ - public double getMax() { - return searchMax; - } - /** - * @return the initial guess. - */ - public double getStartValue() { - return searchStart; - } - /** - * {@inheritDoc} - */ - @Override - public double getAbsoluteAccuracy() { - return absoluteAccuracy; - } - /** - * {@inheritDoc} - */ - @Override - public double getRelativeAccuracy() { - return relativeAccuracy; - } - /** - * {@inheritDoc} - */ - @Override - public double getFunctionValueAccuracy() { - return functionValueAccuracy; - } - - /** - * Compute the objective function value. - * - * @param point Point at which the objective function must be evaluated. - * @return the objective function value at specified point. - * @throws TooManyEvaluationsException if the maximal number of evaluations - * is exceeded. - */ - protected double computeObjectiveValue(double point) - throws TooManyEvaluationsException { - incrementEvaluationCount(); - return function.value(point); - } - - /** - * Prepare for computation. - * Subclasses must call this method if they override any of the - * {@code solve} methods. - * - * @param f Function to solve. - * @param min Lower bound for the interval. - * @param max Upper bound for the interval. - * @param startValue Start value to use. - * @param maxEval Maximum number of evaluations. - * @exception NullArgumentException if f is null - */ - protected void setup(int maxEval, - FUNC f, - double min, double max, - double startValue) - throws NullArgumentException { - // Checks. - MathUtils.checkNotNull(f); - - // Reset. - searchMin = min; - searchMax = max; - searchStart = startValue; - function = f; - evaluations.setMaximalCount(maxEval); - evaluations.resetCount(); - } - - /** {@inheritDoc} */ - @Override - public double solve(int maxEval, FUNC f, double min, double max, double startValue) - throws TooManyEvaluationsException, - NoBracketingException { - // Initialization. - setup(maxEval, f, min, max, startValue); - - // Perform computation. - return doSolve(); - } - - /** {@inheritDoc} */ - @Override - public double solve(int maxEval, FUNC f, double min, double max) { - return solve(maxEval, f, min, max, min + 0.5 * (max - min)); - } - - /** {@inheritDoc} */ - @Override - public double solve(int maxEval, FUNC f, double startValue) - throws TooManyEvaluationsException, - NoBracketingException { - return solve(maxEval, f, Double.NaN, Double.NaN, startValue); - } - - /** - * Method for implementing actual optimization algorithms in derived - * classes. - * - * @return the root. - * @throws TooManyEvaluationsException if the maximal number of evaluations - * is exceeded. - * @throws NoBracketingException if the initial search interval does not bracket - * a root and the solver requires it. - */ - protected abstract double doSolve() - throws TooManyEvaluationsException, NoBracketingException; - - /** - * Check whether the function takes opposite signs at the endpoints. - * - * @param lower Lower endpoint. - * @param upper Upper endpoint. - * @return {@code true} if the function values have opposite signs at the - * given points. - */ - protected boolean isBracketing(final double lower, - final double upper) { - return UnivariateSolverUtils.isBracketing(function, lower, upper); - } - - /** - * Check whether the arguments form a (strictly) increasing sequence. - * - * @param start First number. - * @param mid Second number. - * @param end Third number. - * @return {@code true} if the arguments form an increasing sequence. - */ - protected boolean isSequence(final double start, - final double mid, - final double end) { - return UnivariateSolverUtils.isSequence(start, mid, end); - } - - /** - * Check that the endpoints specify an interval. - * - * @param lower Lower endpoint. - * @param upper Upper endpoint. - * @throws NumberIsTooLargeException if {@code lower >= upper}. - */ - protected void verifyInterval(final double lower, - final double upper) - throws NumberIsTooLargeException { - UnivariateSolverUtils.verifyInterval(lower, upper); - } - - /** - * Check that {@code lower < initial < upper}. - * - * @param lower Lower endpoint. - * @param initial Initial value. - * @param upper Upper endpoint. - * @throws NumberIsTooLargeException if {@code lower >= initial} or - * {@code initial >= upper}. - */ - protected void verifySequence(final double lower, - final double initial, - final double upper) - throws NumberIsTooLargeException { - UnivariateSolverUtils.verifySequence(lower, initial, upper); - } - - /** - * Check that the endpoints specify an interval and the function takes - * opposite signs at the endpoints. - * - * @param lower Lower endpoint. - * @param upper Upper endpoint. - * @throws NullArgumentException if the function has not been set. - * @throws NoBracketingException if the function has the same sign at - * the endpoints. - */ - protected void verifyBracketing(final double lower, - final double upper) - throws NullArgumentException, - NoBracketingException { - UnivariateSolverUtils.verifyBracketing(function, lower, upper); - } - - /** - * Increment the evaluation count by one. - * Method {@link #computeObjectiveValue(double)} calls this method internally. - * It is provided for subclasses that do not exclusively use - * {@code computeObjectiveValue} to solve the function. - * See e.g. {@link AbstractUnivariateDifferentiableSolver}. - * - * @throws TooManyEvaluationsException when the allowed number of function - * evaluations has been exhausted. - */ - protected void incrementEvaluationCount() - throws TooManyEvaluationsException { - try { - evaluations.incrementCount(); - } catch (MaxCountExceededException e) { - throw new TooManyEvaluationsException(e.getMax()); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BaseSecantSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BaseSecantSolver.java deleted file mode 100644 index 14e22a4f2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BaseSecantSolver.java +++ /dev/null @@ -1,280 +0,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. - */ - -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.exception.ConvergenceException; -import org.apache.commons.math4.exception.MathInternalError; -import org.apache.commons.math4.util.FastMath; - -/** - * Base class for all bracketing Secant-based methods for root-finding - * (approximating a zero of a univariate real function). - * - *

Implementation of the {@link RegulaFalsiSolver Regula Falsi} and - * {@link IllinoisSolver Illinois} methods is based on the - * following article: M. Dowell and P. Jarratt, - * A modified regula falsi method for computing the root of an - * equation, BIT Numerical Mathematics, volume 11, number 2, - * pages 168-174, Springer, 1971.

- * - *

Implementation of the {@link PegasusSolver Pegasus} method is - * based on the following article: M. Dowell and P. Jarratt, - * The "Pegasus" method for computing the root of an equation, - * BIT Numerical Mathematics, volume 12, number 4, pages 503-508, Springer, - * 1972.

- * - *

The {@link SecantSolver Secant} method is not a - * bracketing method, so it is not implemented here. It has a separate - * implementation.

- * - * @since 3.0 - */ -public abstract class BaseSecantSolver - extends AbstractUnivariateSolver - implements BracketedUnivariateSolver { - - /** Default absolute accuracy. */ - protected static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6; - - /** The kinds of solutions that the algorithm may accept. */ - private AllowedSolution allowed; - - /** The Secant-based root-finding method to use. */ - private final Method method; - - /** - * Construct a solver. - * - * @param absoluteAccuracy Absolute accuracy. - * @param method Secant-based root-finding method to use. - */ - protected BaseSecantSolver(final double absoluteAccuracy, final Method method) { - super(absoluteAccuracy); - this.allowed = AllowedSolution.ANY_SIDE; - this.method = method; - } - - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - * @param method Secant-based root-finding method to use. - */ - protected BaseSecantSolver(final double relativeAccuracy, - final double absoluteAccuracy, - final Method method) { - super(relativeAccuracy, absoluteAccuracy); - this.allowed = AllowedSolution.ANY_SIDE; - this.method = method; - } - - /** - * Construct a solver. - * - * @param relativeAccuracy Maximum relative error. - * @param absoluteAccuracy Maximum absolute error. - * @param functionValueAccuracy Maximum function value error. - * @param method Secant-based root-finding method to use - */ - protected BaseSecantSolver(final double relativeAccuracy, - final double absoluteAccuracy, - final double functionValueAccuracy, - final Method method) { - super(relativeAccuracy, absoluteAccuracy, functionValueAccuracy); - this.allowed = AllowedSolution.ANY_SIDE; - this.method = method; - } - - /** {@inheritDoc} */ - @Override - public double solve(final int maxEval, final UnivariateFunction f, - final double min, final double max, - final AllowedSolution allowedSolution) { - return solve(maxEval, f, min, max, min + 0.5 * (max - min), allowedSolution); - } - - /** {@inheritDoc} */ - @Override - public double solve(final int maxEval, final UnivariateFunction f, - final double min, final double max, final double startValue, - final AllowedSolution allowedSolution) { - this.allowed = allowedSolution; - return super.solve(maxEval, f, min, max, startValue); - } - - /** {@inheritDoc} */ - @Override - public double solve(final int maxEval, final UnivariateFunction f, - final double min, final double max, final double startValue) { - return solve(maxEval, f, min, max, startValue, AllowedSolution.ANY_SIDE); - } - - /** - * {@inheritDoc} - * - * @throws ConvergenceException if the algorithm failed due to finite - * precision. - */ - @Override - protected final double doSolve() - throws ConvergenceException { - // Get initial solution - double x0 = getMin(); - double x1 = getMax(); - double f0 = computeObjectiveValue(x0); - double f1 = computeObjectiveValue(x1); - - // If one of the bounds is the exact root, return it. Since these are - // not under-approximations or over-approximations, we can return them - // regardless of the allowed solutions. - if (f0 == 0.0) { - return x0; - } - if (f1 == 0.0) { - return x1; - } - - // Verify bracketing of initial solution. - verifyBracketing(x0, x1); - - // Get accuracies. - final double ftol = getFunctionValueAccuracy(); - final double atol = getAbsoluteAccuracy(); - final double rtol = getRelativeAccuracy(); - - // Keep track of inverted intervals, meaning that the left bound is - // larger than the right bound. - boolean inverted = false; - - // Keep finding better approximations. - while (true) { - // Calculate the next approximation. - final double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0)); - final double fx = computeObjectiveValue(x); - - // If the new approximation is the exact root, return it. Since - // this is not an under-approximation or an over-approximation, - // we can return it regardless of the allowed solutions. - if (fx == 0.0) { - return x; - } - - // Update the bounds with the new approximation. - if (f1 * fx < 0) { - // The value of x1 has switched to the other bound, thus inverting - // the interval. - x0 = x1; - f0 = f1; - inverted = !inverted; - } else { - switch (method) { - case ILLINOIS: - f0 *= 0.5; - break; - case PEGASUS: - f0 *= f1 / (f1 + fx); - break; - case REGULA_FALSI: - // Detect early that algorithm is stuck, instead of waiting - // for the maximum number of iterations to be exceeded. - if (x == x1) { - throw new ConvergenceException(); - } - break; - default: - // Should never happen. - throw new MathInternalError(); - } - } - // Update from [x0, x1] to [x0, x]. - x1 = x; - f1 = fx; - - // If the function value of the last approximation is too small, - // given the function value accuracy, then we can't get closer to - // the root than we already are. - if (FastMath.abs(f1) <= ftol) { - switch (allowed) { - case ANY_SIDE: - return x1; - case LEFT_SIDE: - if (inverted) { - return x1; - } - break; - case RIGHT_SIDE: - if (!inverted) { - return x1; - } - break; - case BELOW_SIDE: - if (f1 <= 0) { - return x1; - } - break; - case ABOVE_SIDE: - if (f1 >= 0) { - return x1; - } - break; - default: - throw new MathInternalError(); - } - } - - // If the current interval is within the given accuracies, we - // are satisfied with the current approximation. - if (FastMath.abs(x1 - x0) < FastMath.max(rtol * FastMath.abs(x1), - atol)) { - switch (allowed) { - case ANY_SIDE: - return x1; - case LEFT_SIDE: - return inverted ? x1 : x0; - case RIGHT_SIDE: - return inverted ? x0 : x1; - case BELOW_SIDE: - return (f1 <= 0) ? x1 : x0; - case ABOVE_SIDE: - return (f1 >= 0) ? x1 : x0; - default: - throw new MathInternalError(); - } - } - } - } - - /** Secant-based root-finding methods. */ - protected enum Method { - - /** - * The {@link RegulaFalsiSolver Regula Falsi} or - * False Position method. - */ - REGULA_FALSI, - - /** The {@link IllinoisSolver Illinois} method. */ - ILLINOIS, - - /** The {@link PegasusSolver Pegasus} method. */ - PEGASUS; - - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BaseUnivariateSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BaseUnivariateSolver.java deleted file mode 100644 index 94951e4b1..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BaseUnivariateSolver.java +++ /dev/null @@ -1,142 +0,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. - */ -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.TooManyEvaluationsException; - - -/** - * Interface for (univariate real) rootfinding algorithms. - * Implementations will search for only one zero in the given interval. - * - * This class is not intended for use outside of the Apache Commons Math - * library, regular user should rely on more specific interfaces like - * {@link UnivariateSolver}, {@link PolynomialSolver} or {@link - * UnivariateDifferentiableSolver}. - * @param Type of function to solve. - * - * @since 3.0 - * @see UnivariateSolver - * @see PolynomialSolver - * @see UnivariateDifferentiableSolver - */ -public interface BaseUnivariateSolver { - /** - * Get the maximum number of function evaluations. - * - * @return the maximum number of function evaluations. - */ - int getMaxEvaluations(); - - /** - * Get the number of evaluations of the objective function. - * The number of evaluations corresponds to the last call to the - * {@code optimize} method. It is 0 if the method has not been - * called yet. - * - * @return the number of evaluations of the objective function. - */ - int getEvaluations(); - - /** - * Get the absolute accuracy of the solver. Solutions returned by the - * solver should be accurate to this tolerance, i.e., if ε is the - * absolute accuracy of the solver and {@code v} is a value returned by - * one of the {@code solve} methods, then a root of the function should - * exist somewhere in the interval ({@code v} - ε, {@code v} + ε). - * - * @return the absolute accuracy. - */ - double getAbsoluteAccuracy(); - - /** - * Get the relative accuracy of the solver. The contract for relative - * accuracy is the same as {@link #getAbsoluteAccuracy()}, but using - * relative, rather than absolute error. If ρ is the relative accuracy - * configured for a solver and {@code v} is a value returned, then a root - * of the function should exist somewhere in the interval - * ({@code v} - ρ {@code v}, {@code v} + ρ {@code v}). - * - * @return the relative accuracy. - */ - double getRelativeAccuracy(); - - /** - * Get the function value accuracy of the solver. If {@code v} is - * a value returned by the solver for a function {@code f}, - * then by contract, {@code |f(v)|} should be less than or equal to - * the function value accuracy configured for the solver. - * - * @return the function value accuracy. - */ - double getFunctionValueAccuracy(); - - /** - * Solve for a zero root in the given interval. - * A solver may require that the interval brackets a single zero root. - * Solvers that do require bracketing should be able to handle the case - * where one of the endpoints is itself a root. - * - * @param maxEval Maximum number of evaluations. - * @param f Function to solve. - * @param min Lower bound for the interval. - * @param max Upper bound for the interval. - * @return a value where the function is zero. - * @throws MathIllegalArgumentException - * if the arguments do not satisfy the requirements specified by the solver. - * @throws TooManyEvaluationsException if - * the allowed number of evaluations is exceeded. - */ - double solve(int maxEval, FUNC f, double min, double max) - throws MathIllegalArgumentException, TooManyEvaluationsException; - - /** - * Solve for a zero in the given interval, start at {@code startValue}. - * A solver may require that the interval brackets a single zero root. - * Solvers that do require bracketing should be able to handle the case - * where one of the endpoints is itself a root. - * - * @param maxEval Maximum number of evaluations. - * @param f Function to solve. - * @param min Lower bound for the interval. - * @param max Upper bound for the interval. - * @param startValue Start value to use. - * @return a value where the function is zero. - * @throws MathIllegalArgumentException - * if the arguments do not satisfy the requirements specified by the solver. - * @throws TooManyEvaluationsException if - * the allowed number of evaluations is exceeded. - */ - double solve(int maxEval, FUNC f, double min, double max, double startValue) - throws MathIllegalArgumentException, TooManyEvaluationsException; - - /** - * Solve for a zero in the vicinity of {@code startValue}. - * - * @param f Function to solve. - * @param startValue Start value to use. - * @return a value where the function is zero. - * @param maxEval Maximum number of evaluations. - * @throws MathIllegalArgumentException - * if the arguments do not satisfy the requirements specified by the solver. - * @throws TooManyEvaluationsException if - * the allowed number of evaluations is exceeded. - */ - double solve(int maxEval, FUNC f, double startValue); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BisectionSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BisectionSolver.java deleted file mode 100644 index 658c2a0c9..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BisectionSolver.java +++ /dev/null @@ -1,91 +0,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. - */ -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.exception.TooManyEvaluationsException; -import org.apache.commons.math4.util.FastMath; - -/** - * Implements the - * bisection algorithm for finding zeros of univariate real functions. - *

- * The function should be continuous but not necessarily smooth.

- * - */ -public class BisectionSolver extends AbstractUnivariateSolver { - /** Default absolute accuracy. */ - private static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6; - - /** - * Construct a solver with default accuracy (1e-6). - */ - public BisectionSolver() { - this(DEFAULT_ABSOLUTE_ACCURACY); - } - /** - * Construct a solver. - * - * @param absoluteAccuracy Absolute accuracy. - */ - public BisectionSolver(double absoluteAccuracy) { - super(absoluteAccuracy); - } - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - */ - public BisectionSolver(double relativeAccuracy, - double absoluteAccuracy) { - super(relativeAccuracy, absoluteAccuracy); - } - - /** - * {@inheritDoc} - */ - @Override - protected double doSolve() - throws TooManyEvaluationsException { - double min = getMin(); - double max = getMax(); - verifyInterval(min, max); - final double absoluteAccuracy = getAbsoluteAccuracy(); - double m; - double fm; - double fmin; - - while (true) { - m = UnivariateSolverUtils.midpoint(min, max); - fmin = computeObjectiveValue(min); - fm = computeObjectiveValue(m); - - if (fm * fmin > 0) { - // max and m bracket the root. - min = m; - } else { - // min and m bracket the root. - max = m; - } - - if (FastMath.abs(max - min) <= absoluteAccuracy) { - m = UnivariateSolverUtils.midpoint(min, max); - return m; - } - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BracketedRealFieldUnivariateSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BracketedRealFieldUnivariateSolver.java deleted file mode 100644 index 3350efa35..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BracketedRealFieldUnivariateSolver.java +++ /dev/null @@ -1,142 +0,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. - */ - -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.RealFieldElement; -import org.apache.commons.math4.analysis.RealFieldUnivariateFunction; - -/** Interface for {@link UnivariateSolver (univariate real) root-finding - * algorithms} that maintain a bracketed solution. There are several advantages - * to having such root-finding algorithms: - *
    - *
  • The bracketed solution guarantees that the root is kept within the - * interval. As such, these algorithms generally also guarantee - * convergence.
  • - *
  • The bracketed solution means that we have the opportunity to only - * return roots that are greater than or equal to the actual root, or - * are less than or equal to the actual root. That is, we can control - * whether under-approximations and over-approximations are - * {@link AllowedSolution allowed solutions}. Other root-finding - * algorithms can usually only guarantee that the solution (the root that - * was found) is around the actual root.
  • - *
- * - *

For backwards compatibility, all root-finding algorithms must have - * {@link AllowedSolution#ANY_SIDE ANY_SIDE} as default for the allowed - * solutions.

- * - * @see AllowedSolution - * @param the type of the field elements - * @since 3.6 - */ -public interface BracketedRealFieldUnivariateSolver> { - - /** - * Get the maximum number of function evaluations. - * - * @return the maximum number of function evaluations. - */ - int getMaxEvaluations(); - - /** - * Get the number of evaluations of the objective function. - * The number of evaluations corresponds to the last call to the - * {@code optimize} method. It is 0 if the method has not been - * called yet. - * - * @return the number of evaluations of the objective function. - */ - int getEvaluations(); - - /** - * Get the absolute accuracy of the solver. Solutions returned by the - * solver should be accurate to this tolerance, i.e., if ε is the - * absolute accuracy of the solver and {@code v} is a value returned by - * one of the {@code solve} methods, then a root of the function should - * exist somewhere in the interval ({@code v} - ε, {@code v} + ε). - * - * @return the absolute accuracy. - */ - T getAbsoluteAccuracy(); - - /** - * Get the relative accuracy of the solver. The contract for relative - * accuracy is the same as {@link #getAbsoluteAccuracy()}, but using - * relative, rather than absolute error. If ρ is the relative accuracy - * configured for a solver and {@code v} is a value returned, then a root - * of the function should exist somewhere in the interval - * ({@code v} - ρ {@code v}, {@code v} + ρ {@code v}). - * - * @return the relative accuracy. - */ - T getRelativeAccuracy(); - - /** - * Get the function value accuracy of the solver. If {@code v} is - * a value returned by the solver for a function {@code f}, - * then by contract, {@code |f(v)|} should be less than or equal to - * the function value accuracy configured for the solver. - * - * @return the function value accuracy. - */ - T getFunctionValueAccuracy(); - - /** - * Solve for a zero in the given interval. - * A solver may require that the interval brackets a single zero root. - * Solvers that do require bracketing should be able to handle the case - * where one of the endpoints is itself a root. - * - * @param maxEval Maximum number of evaluations. - * @param f Function to solve. - * @param min Lower bound for the interval. - * @param max Upper bound for the interval. - * @param allowedSolution The kind of solutions that the root-finding algorithm may - * accept as solutions. - * @return A value where the function is zero. - * @throws org.apache.commons.math4.exception.MathIllegalArgumentException - * if the arguments do not satisfy the requirements specified by the solver. - * @throws org.apache.commons.math4.exception.TooManyEvaluationsException if - * the allowed number of evaluations is exceeded. - */ - T solve(int maxEval, RealFieldUnivariateFunction f, T min, T max, - AllowedSolution allowedSolution); - - /** - * Solve for a zero in the given interval, start at {@code startValue}. - * A solver may require that the interval brackets a single zero root. - * Solvers that do require bracketing should be able to handle the case - * where one of the endpoints is itself a root. - * - * @param maxEval Maximum number of evaluations. - * @param f Function to solve. - * @param min Lower bound for the interval. - * @param max Upper bound for the interval. - * @param startValue Start value to use. - * @param allowedSolution The kind of solutions that the root-finding algorithm may - * accept as solutions. - * @return A value where the function is zero. - * @throws org.apache.commons.math4.exception.MathIllegalArgumentException - * if the arguments do not satisfy the requirements specified by the solver. - * @throws org.apache.commons.math4.exception.TooManyEvaluationsException if - * the allowed number of evaluations is exceeded. - */ - T solve(int maxEval, RealFieldUnivariateFunction f, T min, T max, T startValue, - AllowedSolution allowedSolution); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BracketedUnivariateSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BracketedUnivariateSolver.java deleted file mode 100644 index 60e8a258f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BracketedUnivariateSolver.java +++ /dev/null @@ -1,92 +0,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. - */ - -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.analysis.UnivariateFunction; - -/** Interface for {@link UnivariateSolver (univariate real) root-finding - * algorithms} that maintain a bracketed solution. There are several advantages - * to having such root-finding algorithms: - *
    - *
  • The bracketed solution guarantees that the root is kept within the - * interval. As such, these algorithms generally also guarantee - * convergence.
  • - *
  • The bracketed solution means that we have the opportunity to only - * return roots that are greater than or equal to the actual root, or - * are less than or equal to the actual root. That is, we can control - * whether under-approximations and over-approximations are - * {@link AllowedSolution allowed solutions}. Other root-finding - * algorithms can usually only guarantee that the solution (the root that - * was found) is around the actual root.
  • - *
- * - *

For backwards compatibility, all root-finding algorithms must have - * {@link AllowedSolution#ANY_SIDE ANY_SIDE} as default for the allowed - * solutions.

- * @param Type of function to solve. - * - * @see AllowedSolution - * @since 3.0 - */ -public interface BracketedUnivariateSolver - extends BaseUnivariateSolver { - - /** - * Solve for a zero in the given interval. - * A solver may require that the interval brackets a single zero root. - * Solvers that do require bracketing should be able to handle the case - * where one of the endpoints is itself a root. - * - * @param maxEval Maximum number of evaluations. - * @param f Function to solve. - * @param min Lower bound for the interval. - * @param max Upper bound for the interval. - * @param allowedSolution The kind of solutions that the root-finding algorithm may - * accept as solutions. - * @return A value where the function is zero. - * @throws org.apache.commons.math4.exception.MathIllegalArgumentException - * if the arguments do not satisfy the requirements specified by the solver. - * @throws org.apache.commons.math4.exception.TooManyEvaluationsException if - * the allowed number of evaluations is exceeded. - */ - double solve(int maxEval, FUNC f, double min, double max, - AllowedSolution allowedSolution); - - /** - * Solve for a zero in the given interval, start at {@code startValue}. - * A solver may require that the interval brackets a single zero root. - * Solvers that do require bracketing should be able to handle the case - * where one of the endpoints is itself a root. - * - * @param maxEval Maximum number of evaluations. - * @param f Function to solve. - * @param min Lower bound for the interval. - * @param max Upper bound for the interval. - * @param startValue Start value to use. - * @param allowedSolution The kind of solutions that the root-finding algorithm may - * accept as solutions. - * @return A value where the function is zero. - * @throws org.apache.commons.math4.exception.MathIllegalArgumentException - * if the arguments do not satisfy the requirements specified by the solver. - * @throws org.apache.commons.math4.exception.TooManyEvaluationsException if - * the allowed number of evaluations is exceeded. - */ - double solve(int maxEval, FUNC f, double min, double max, double startValue, - AllowedSolution allowedSolution); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BracketingNthOrderBrentSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BracketingNthOrderBrentSolver.java deleted file mode 100644 index 8a185bbff..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BracketingNthOrderBrentSolver.java +++ /dev/null @@ -1,413 +0,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. - */ -package org.apache.commons.math4.analysis.solvers; - - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.exception.MathInternalError; -import org.apache.commons.math4.exception.NoBracketingException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.TooManyEvaluationsException; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.numbers.core.Precision; - -/** - * This class implements a modification of the Brent algorithm. - *

- * The changes with respect to the original Brent algorithm are: - *

    - *
  • the returned value is chosen in the current interval according - * to user specified {@link AllowedSolution},
  • - *
  • the maximal order for the invert polynomial root search is - * user-specified instead of being invert quadratic only
  • - *

- * The given interval must bracket the root.

- * - */ -public class BracketingNthOrderBrentSolver - extends AbstractUnivariateSolver - implements BracketedUnivariateSolver { - - /** Default absolute accuracy. */ - private static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6; - - /** Default maximal order. */ - private static final int DEFAULT_MAXIMAL_ORDER = 5; - - /** Maximal aging triggering an attempt to balance the bracketing interval. */ - private static final int MAXIMAL_AGING = 2; - - /** Reduction factor for attempts to balance the bracketing interval. */ - private static final double REDUCTION_FACTOR = 1.0 / 16.0; - - /** Maximal order. */ - private final int maximalOrder; - - /** The kinds of solutions that the algorithm may accept. */ - private AllowedSolution allowed; - - /** - * Construct a solver with default accuracy and maximal order (1e-6 and 5 respectively) - */ - public BracketingNthOrderBrentSolver() { - this(DEFAULT_ABSOLUTE_ACCURACY, DEFAULT_MAXIMAL_ORDER); - } - - /** - * Construct a solver. - * - * @param absoluteAccuracy Absolute accuracy. - * @param maximalOrder maximal order. - * @exception NumberIsTooSmallException if maximal order is lower than 2 - */ - public BracketingNthOrderBrentSolver(final double absoluteAccuracy, - final int maximalOrder) - throws NumberIsTooSmallException { - super(absoluteAccuracy); - if (maximalOrder < 2) { - throw new NumberIsTooSmallException(maximalOrder, 2, true); - } - this.maximalOrder = maximalOrder; - this.allowed = AllowedSolution.ANY_SIDE; - } - - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - * @param maximalOrder maximal order. - * @exception NumberIsTooSmallException if maximal order is lower than 2 - */ - public BracketingNthOrderBrentSolver(final double relativeAccuracy, - final double absoluteAccuracy, - final int maximalOrder) - throws NumberIsTooSmallException { - super(relativeAccuracy, absoluteAccuracy); - if (maximalOrder < 2) { - throw new NumberIsTooSmallException(maximalOrder, 2, true); - } - this.maximalOrder = maximalOrder; - this.allowed = AllowedSolution.ANY_SIDE; - } - - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - * @param functionValueAccuracy Function value accuracy. - * @param maximalOrder maximal order. - * @exception NumberIsTooSmallException if maximal order is lower than 2 - */ - public BracketingNthOrderBrentSolver(final double relativeAccuracy, - final double absoluteAccuracy, - final double functionValueAccuracy, - final int maximalOrder) - throws NumberIsTooSmallException { - super(relativeAccuracy, absoluteAccuracy, functionValueAccuracy); - if (maximalOrder < 2) { - throw new NumberIsTooSmallException(maximalOrder, 2, true); - } - this.maximalOrder = maximalOrder; - this.allowed = AllowedSolution.ANY_SIDE; - } - - /** Get the maximal order. - * @return maximal order - */ - public int getMaximalOrder() { - return maximalOrder; - } - - /** - * {@inheritDoc} - */ - @Override - protected double doSolve() - throws TooManyEvaluationsException, - NumberIsTooLargeException, - NoBracketingException { - // prepare arrays with the first points - final double[] x = new double[maximalOrder + 1]; - final double[] y = new double[maximalOrder + 1]; - x[0] = getMin(); - x[1] = getStartValue(); - x[2] = getMax(); - verifySequence(x[0], x[1], x[2]); - - // evaluate initial guess - y[1] = computeObjectiveValue(x[1]); - if (Precision.equals(y[1], 0.0, 1)) { - // return the initial guess if it is a perfect root. - return x[1]; - } - - // evaluate first endpoint - y[0] = computeObjectiveValue(x[0]); - if (Precision.equals(y[0], 0.0, 1)) { - // return the first endpoint if it is a perfect root. - return x[0]; - } - - int nbPoints; - int signChangeIndex; - if (y[0] * y[1] < 0) { - - // reduce interval if it brackets the root - nbPoints = 2; - signChangeIndex = 1; - - } else { - - // evaluate second endpoint - y[2] = computeObjectiveValue(x[2]); - if (Precision.equals(y[2], 0.0, 1)) { - // return the second endpoint if it is a perfect root. - return x[2]; - } - - if (y[1] * y[2] < 0) { - // use all computed point as a start sampling array for solving - nbPoints = 3; - signChangeIndex = 2; - } else { - throw new NoBracketingException(x[0], x[2], y[0], y[2]); - } - - } - - // prepare a work array for inverse polynomial interpolation - final double[] tmpX = new double[x.length]; - - // current tightest bracketing of the root - double xA = x[signChangeIndex - 1]; - double yA = y[signChangeIndex - 1]; - double absYA = FastMath.abs(yA); - int agingA = 0; - double xB = x[signChangeIndex]; - double yB = y[signChangeIndex]; - double absYB = FastMath.abs(yB); - int agingB = 0; - - // search loop - while (true) { - - // check convergence of bracketing interval - final double xTol = getAbsoluteAccuracy() + - getRelativeAccuracy() * FastMath.max(FastMath.abs(xA), FastMath.abs(xB)); - if (((xB - xA) <= xTol) || (FastMath.max(absYA, absYB) < getFunctionValueAccuracy())) { - switch (allowed) { - case ANY_SIDE : - return absYA < absYB ? xA : xB; - case LEFT_SIDE : - return xA; - case RIGHT_SIDE : - return xB; - case BELOW_SIDE : - return (yA <= 0) ? xA : xB; - case ABOVE_SIDE : - return (yA < 0) ? xB : xA; - default : - // this should never happen - throw new MathInternalError(); - } - } - - // target for the next evaluation point - double targetY; - if (agingA >= MAXIMAL_AGING) { - // we keep updating the high bracket, try to compensate this - final int p = agingA - MAXIMAL_AGING; - final double weightA = (1 << p) - 1; - final double weightB = p + 1; - targetY = (weightA * yA - weightB * REDUCTION_FACTOR * yB) / (weightA + weightB); - } else if (agingB >= MAXIMAL_AGING) { - // we keep updating the low bracket, try to compensate this - final int p = agingB - MAXIMAL_AGING; - final double weightA = p + 1; - final double weightB = (1 << p) - 1; - targetY = (weightB * yB - weightA * REDUCTION_FACTOR * yA) / (weightA + weightB); - } else { - // bracketing is balanced, try to find the root itself - targetY = 0; - } - - // make a few attempts to guess a root, - double nextX; - int start = 0; - int end = nbPoints; - do { - - // guess a value for current target, using inverse polynomial interpolation - System.arraycopy(x, start, tmpX, start, end - start); - nextX = guessX(targetY, tmpX, y, start, end); - - if (!((nextX > xA) && (nextX < xB))) { - // the guessed root is not strictly inside of the tightest bracketing interval - - // the guessed root is either not strictly inside the interval or it - // is a NaN (which occurs when some sampling points share the same y) - // we try again with a lower interpolation order - if (signChangeIndex - start >= end - signChangeIndex) { - // we have more points before the sign change, drop the lowest point - ++start; - } else { - // we have more points after sign change, drop the highest point - --end; - } - - // we need to do one more attempt - nextX = Double.NaN; - - } - - } while (Double.isNaN(nextX) && (end - start > 1)); - - if (Double.isNaN(nextX)) { - // fall back to bisection - nextX = xA + 0.5 * (xB - xA); - start = signChangeIndex - 1; - end = signChangeIndex; - } - - // evaluate the function at the guessed root - final double nextY = computeObjectiveValue(nextX); - if (Precision.equals(nextY, 0.0, 1)) { - // we have found an exact root, since it is not an approximation - // we don't need to bother about the allowed solutions setting - return nextX; - } - - if ((nbPoints > 2) && (end - start != nbPoints)) { - - // we have been forced to ignore some points to keep bracketing, - // they are probably too far from the root, drop them from now on - nbPoints = end - start; - System.arraycopy(x, start, x, 0, nbPoints); - System.arraycopy(y, start, y, 0, nbPoints); - signChangeIndex -= start; - - } else if (nbPoints == x.length) { - - // we have to drop one point in order to insert the new one - nbPoints--; - - // keep the tightest bracketing interval as centered as possible - if (signChangeIndex >= (x.length + 1) / 2) { - // we drop the lowest point, we have to shift the arrays and the index - System.arraycopy(x, 1, x, 0, nbPoints); - System.arraycopy(y, 1, y, 0, nbPoints); - --signChangeIndex; - } - - } - - // insert the last computed point - //(by construction, we know it lies inside the tightest bracketing interval) - System.arraycopy(x, signChangeIndex, x, signChangeIndex + 1, nbPoints - signChangeIndex); - x[signChangeIndex] = nextX; - System.arraycopy(y, signChangeIndex, y, signChangeIndex + 1, nbPoints - signChangeIndex); - y[signChangeIndex] = nextY; - ++nbPoints; - - // update the bracketing interval - if (nextY * yA <= 0) { - // the sign change occurs before the inserted point - xB = nextX; - yB = nextY; - absYB = FastMath.abs(yB); - ++agingA; - agingB = 0; - } else { - // the sign change occurs after the inserted point - xA = nextX; - yA = nextY; - absYA = FastMath.abs(yA); - agingA = 0; - ++agingB; - - // update the sign change index - signChangeIndex++; - - } - - } - - } - - /** Guess an x value by nth order inverse polynomial interpolation. - *

- * The x value is guessed by evaluating polynomial Q(y) at y = targetY, where Q - * is built such that for all considered points (xi, yi), - * Q(yi) = xi. - *

- * @param targetY target value for y - * @param x reference points abscissas for interpolation, - * note that this array is modified during computation - * @param y reference points ordinates for interpolation - * @param start start index of the points to consider (inclusive) - * @param end end index of the points to consider (exclusive) - * @return guessed root (will be a NaN if two points share the same y) - */ - private double guessX(final double targetY, final double[] x, final double[] y, - final int start, final int end) { - - // compute Q Newton coefficients by divided differences - for (int i = start; i < end - 1; ++i) { - final int delta = i + 1 - start; - for (int j = end - 1; j > i; --j) { - x[j] = (x[j] - x[j-1]) / (y[j] - y[j - delta]); - } - } - - // evaluate Q(targetY) - double x0 = 0; - for (int j = end - 1; j >= start; --j) { - x0 = x[j] + x0 * (targetY - y[j]); - } - - return x0; - - } - - /** {@inheritDoc} */ - @Override - public double solve(int maxEval, UnivariateFunction f, double min, - double max, AllowedSolution allowedSolution) - throws TooManyEvaluationsException, - NumberIsTooLargeException, - NoBracketingException { - this.allowed = allowedSolution; - return super.solve(maxEval, f, min, max); - } - - /** {@inheritDoc} */ - @Override - public double solve(int maxEval, UnivariateFunction f, double min, - double max, double startValue, - AllowedSolution allowedSolution) - throws TooManyEvaluationsException, - NumberIsTooLargeException, - NoBracketingException { - this.allowed = allowedSolution; - return super.solve(maxEval, f, min, max, startValue); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BrentSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BrentSolver.java deleted file mode 100644 index 9e1e55193..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/BrentSolver.java +++ /dev/null @@ -1,243 +0,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. - */ -package org.apache.commons.math4.analysis.solvers; - - -import org.apache.commons.math4.exception.NoBracketingException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.TooManyEvaluationsException; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.numbers.core.Precision; - -/** - * This class implements the - * Brent algorithm for finding zeros of real univariate functions. - * The function should be continuous but not necessarily smooth. - * The {@code solve} method returns a zero {@code x} of the function {@code f} - * in the given interval {@code [a, b]} to within a tolerance - * {@code 2 eps abs(x) + t} where {@code eps} is the relative accuracy and - * {@code t} is the absolute accuracy. - *

The given interval must bracket the root.

- *

- * The reference implementation is given in chapter 4 of - *

- * Algorithms for Minimization Without Derivatives, - * Richard P. Brent, - * Dover, 2002 - *
- * - * @see BaseAbstractUnivariateSolver - */ -public class BrentSolver extends AbstractUnivariateSolver { - - /** Default absolute accuracy. */ - private static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6; - - /** - * Construct a solver with default absolute accuracy (1e-6). - */ - public BrentSolver() { - this(DEFAULT_ABSOLUTE_ACCURACY); - } - /** - * Construct a solver. - * - * @param absoluteAccuracy Absolute accuracy. - */ - public BrentSolver(double absoluteAccuracy) { - super(absoluteAccuracy); - } - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - */ - public BrentSolver(double relativeAccuracy, - double absoluteAccuracy) { - super(relativeAccuracy, absoluteAccuracy); - } - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - * @param functionValueAccuracy Function value accuracy. - * - * @see BaseAbstractUnivariateSolver#BaseAbstractUnivariateSolver(double,double,double) - */ - public BrentSolver(double relativeAccuracy, - double absoluteAccuracy, - double functionValueAccuracy) { - super(relativeAccuracy, absoluteAccuracy, functionValueAccuracy); - } - - /** - * {@inheritDoc} - */ - @Override - protected double doSolve() - throws NoBracketingException, - TooManyEvaluationsException, - NumberIsTooLargeException { - double min = getMin(); - double max = getMax(); - final double initial = getStartValue(); - final double functionValueAccuracy = getFunctionValueAccuracy(); - - verifySequence(min, initial, max); - - // Return the initial guess if it is good enough. - double yInitial = computeObjectiveValue(initial); - if (FastMath.abs(yInitial) <= functionValueAccuracy) { - return initial; - } - - // Return the first endpoint if it is good enough. - double yMin = computeObjectiveValue(min); - if (FastMath.abs(yMin) <= functionValueAccuracy) { - return min; - } - - // Reduce interval if min and initial bracket the root. - if (yInitial * yMin < 0) { - return brent(min, initial, yMin, yInitial); - } - - // Return the second endpoint if it is good enough. - double yMax = computeObjectiveValue(max); - if (FastMath.abs(yMax) <= functionValueAccuracy) { - return max; - } - - // Reduce interval if initial and max bracket the root. - if (yInitial * yMax < 0) { - return brent(initial, max, yInitial, yMax); - } - - throw new NoBracketingException(min, max, yMin, yMax); - } - - /** - * Search for a zero inside the provided interval. - * This implementation is based on the algorithm described at page 58 of - * the book - *
- * Algorithms for Minimization Without Derivatives, - * Richard P. Brent, - * Dover 0-486-41998-3 - *
- * - * @param lo Lower bound of the search interval. - * @param hi Higher bound of the search interval. - * @param fLo Function value at the lower bound of the search interval. - * @param fHi Function value at the higher bound of the search interval. - * @return the value where the function is zero. - */ - private double brent(double lo, double hi, - double fLo, double fHi) { - double a = lo; - double fa = fLo; - double b = hi; - double fb = fHi; - double c = a; - double fc = fa; - double d = b - a; - double e = d; - - final double t = getAbsoluteAccuracy(); - final double eps = getRelativeAccuracy(); - - while (true) { - if (FastMath.abs(fc) < FastMath.abs(fb)) { - a = b; - b = c; - c = a; - fa = fb; - fb = fc; - fc = fa; - } - - final double tol = 2 * eps * FastMath.abs(b) + t; - final double m = 0.5 * (c - b); - - if (FastMath.abs(m) <= tol || - Precision.equals(fb, 0)) { - return b; - } - if (FastMath.abs(e) < tol || - FastMath.abs(fa) <= FastMath.abs(fb)) { - // Force bisection. - d = m; - e = d; - } else { - double s = fb / fa; - double p; - double q; - // The equality test (a == c) is intentional, - // it is part of the original Brent's method and - // it should NOT be replaced by proximity test. - if (a == c) { - // Linear interpolation. - p = 2 * m * s; - q = 1 - s; - } else { - // Inverse quadratic interpolation. - q = fa / fc; - final double r = fb / fc; - p = s * (2 * m * q * (q - r) - (b - a) * (r - 1)); - q = (q - 1) * (r - 1) * (s - 1); - } - if (p > 0) { - q = -q; - } else { - p = -p; - } - s = e; - e = d; - if (p >= 1.5 * m * q - FastMath.abs(tol * q) || - p >= FastMath.abs(0.5 * s * q)) { - // Inverse quadratic interpolation gives a value - // in the wrong direction, or progress is slow. - // Fall back to bisection. - d = m; - e = d; - } else { - d = p / q; - } - } - a = b; - fa = fb; - - if (FastMath.abs(d) > tol) { - b += d; - } else if (m > 0) { - b += tol; - } else { - b -= tol; - } - fb = computeObjectiveValue(b); - if ((fb > 0 && fc > 0) || - (fb <= 0 && fc <= 0)) { - c = a; - fc = fa; - d = b - a; - e = d; - } - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/FieldBracketingNthOrderBrentSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/FieldBracketingNthOrderBrentSolver.java deleted file mode 100644 index 9b902fdc7..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/FieldBracketingNthOrderBrentSolver.java +++ /dev/null @@ -1,453 +0,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. - */ -package org.apache.commons.math4.analysis.solvers; - - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.RealFieldElement; -import org.apache.commons.math4.analysis.RealFieldUnivariateFunction; -import org.apache.commons.math4.exception.MathInternalError; -import org.apache.commons.math4.exception.NoBracketingException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.util.IntegerSequence; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; -import org.apache.commons.numbers.core.Precision; - -/** - * This class implements a modification of the Brent algorithm. - *

- * The changes with respect to the original Brent algorithm are: - *

    - *
  • the returned value is chosen in the current interval according - * to user specified {@link AllowedSolution}
  • - *
  • the maximal order for the invert polynomial root search is - * user-specified instead of being invert quadratic only
  • - *

- * The given interval must bracket the root.

- * - * @param the type of the field elements - * @since 3.6 - */ -public class FieldBracketingNthOrderBrentSolver> - implements BracketedRealFieldUnivariateSolver { - - /** Maximal aging triggering an attempt to balance the bracketing interval. */ - private static final int MAXIMAL_AGING = 2; - - /** Field to which the elements belong. */ - private final Field field; - - /** Maximal order. */ - private final int maximalOrder; - - /** Function value accuracy. */ - private final T functionValueAccuracy; - - /** Absolute accuracy. */ - private final T absoluteAccuracy; - - /** Relative accuracy. */ - private final T relativeAccuracy; - - /** Evaluations counter. */ - private IntegerSequence.Incrementor evaluations; - - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - * @param functionValueAccuracy Function value accuracy. - * @param maximalOrder maximal order. - * @exception NumberIsTooSmallException if maximal order is lower than 2 - */ - public FieldBracketingNthOrderBrentSolver(final T relativeAccuracy, - final T absoluteAccuracy, - final T functionValueAccuracy, - final int maximalOrder) - throws NumberIsTooSmallException { - if (maximalOrder < 2) { - throw new NumberIsTooSmallException(maximalOrder, 2, true); - } - this.field = relativeAccuracy.getField(); - this.maximalOrder = maximalOrder; - this.absoluteAccuracy = absoluteAccuracy; - this.relativeAccuracy = relativeAccuracy; - this.functionValueAccuracy = functionValueAccuracy; - this.evaluations = IntegerSequence.Incrementor.create(); - } - - /** Get the maximal order. - * @return maximal order - */ - public int getMaximalOrder() { - return maximalOrder; - } - - /** - * Get the maximal number of function evaluations. - * - * @return the maximal number of function evaluations. - */ - @Override - public int getMaxEvaluations() { - return evaluations.getMaximalCount(); - } - - /** - * Get the number of evaluations of the objective function. - * The number of evaluations corresponds to the last call to the - * {@code optimize} method. It is 0 if the method has not been - * called yet. - * - * @return the number of evaluations of the objective function. - */ - @Override - public int getEvaluations() { - return evaluations.getCount(); - } - - /** - * Get the absolute accuracy. - * @return absolute accuracy - */ - @Override - public T getAbsoluteAccuracy() { - return absoluteAccuracy; - } - - /** - * Get the relative accuracy. - * @return relative accuracy - */ - @Override - public T getRelativeAccuracy() { - return relativeAccuracy; - } - - /** - * Get the function accuracy. - * @return function accuracy - */ - @Override - public T getFunctionValueAccuracy() { - return functionValueAccuracy; - } - - /** - * Solve for a zero in the given interval. - * A solver may require that the interval brackets a single zero root. - * Solvers that do require bracketing should be able to handle the case - * where one of the endpoints is itself a root. - * - * @param maxEval Maximum number of evaluations. - * @param f Function to solve. - * @param min Lower bound for the interval. - * @param max Upper bound for the interval. - * @param allowedSolution The kind of solutions that the root-finding algorithm may - * accept as solutions. - * @return a value where the function is zero. - * @exception NullArgumentException if f is null. - * @exception NoBracketingException if root cannot be bracketed - */ - @Override - public T solve(final int maxEval, final RealFieldUnivariateFunction f, - final T min, final T max, final AllowedSolution allowedSolution) - throws NullArgumentException, NoBracketingException { - return solve(maxEval, f, min, max, min.add(max).divide(2), allowedSolution); - } - - /** - * Solve for a zero in the given interval, start at {@code startValue}. - * A solver may require that the interval brackets a single zero root. - * Solvers that do require bracketing should be able to handle the case - * where one of the endpoints is itself a root. - * - * @param maxEval Maximum number of evaluations. - * @param f Function to solve. - * @param min Lower bound for the interval. - * @param max Upper bound for the interval. - * @param startValue Start value to use. - * @param allowedSolution The kind of solutions that the root-finding algorithm may - * accept as solutions. - * @return a value where the function is zero. - * @exception NullArgumentException if f is null. - * @exception NoBracketingException if root cannot be bracketed - */ - @Override - public T solve(final int maxEval, final RealFieldUnivariateFunction f, - final T min, final T max, final T startValue, - final AllowedSolution allowedSolution) - throws NullArgumentException, NoBracketingException { - - // Checks. - MathUtils.checkNotNull(f); - - // Reset. - evaluations = evaluations.withMaximalCount(maxEval).withStart(0); - T zero = field.getZero(); - T nan = zero.add(Double.NaN); - - // prepare arrays with the first points - final T[] x = MathArrays.buildArray(field, maximalOrder + 1); - final T[] y = MathArrays.buildArray(field, maximalOrder + 1); - x[0] = min; - x[1] = startValue; - x[2] = max; - - // evaluate initial guess - evaluations.increment(); - y[1] = f.value(x[1]); - if (Precision.equals(y[1].getReal(), 0.0, 1)) { - // return the initial guess if it is a perfect root. - return x[1]; - } - - // evaluate first endpoint - evaluations.increment(); - y[0] = f.value(x[0]); - if (Precision.equals(y[0].getReal(), 0.0, 1)) { - // return the first endpoint if it is a perfect root. - return x[0]; - } - - int nbPoints; - int signChangeIndex; - if (y[0].multiply(y[1]).getReal() < 0) { - - // reduce interval if it brackets the root - nbPoints = 2; - signChangeIndex = 1; - - } else { - - // evaluate second endpoint - evaluations.increment(); - y[2] = f.value(x[2]); - if (Precision.equals(y[2].getReal(), 0.0, 1)) { - // return the second endpoint if it is a perfect root. - return x[2]; - } - - if (y[1].multiply(y[2]).getReal() < 0) { - // use all computed point as a start sampling array for solving - nbPoints = 3; - signChangeIndex = 2; - } else { - throw new NoBracketingException(x[0].getReal(), x[2].getReal(), - y[0].getReal(), y[2].getReal()); - } - - } - - // prepare a work array for inverse polynomial interpolation - final T[] tmpX = MathArrays.buildArray(field, x.length); - - // current tightest bracketing of the root - T xA = x[signChangeIndex - 1]; - T yA = y[signChangeIndex - 1]; - T absXA = xA.abs(); - T absYA = yA.abs(); - int agingA = 0; - T xB = x[signChangeIndex]; - T yB = y[signChangeIndex]; - T absXB = xB.abs(); - T absYB = yB.abs(); - int agingB = 0; - - // search loop - while (true) { - - // check convergence of bracketing interval - T maxX = absXA.subtract(absXB).getReal() < 0 ? absXB : absXA; - T maxY = absYA.subtract(absYB).getReal() < 0 ? absYB : absYA; - final T xTol = absoluteAccuracy.add(relativeAccuracy.multiply(maxX)); - if (xB.subtract(xA).subtract(xTol).getReal() <= 0 || - maxY.subtract(functionValueAccuracy).getReal() < 0) { - switch (allowedSolution) { - case ANY_SIDE : - return absYA.subtract(absYB).getReal() < 0 ? xA : xB; - case LEFT_SIDE : - return xA; - case RIGHT_SIDE : - return xB; - case BELOW_SIDE : - return yA.getReal() <= 0 ? xA : xB; - case ABOVE_SIDE : - return yA.getReal() < 0 ? xB : xA; - default : - // this should never happen - throw new MathInternalError(null); - } - } - - // target for the next evaluation point - T targetY; - if (agingA >= MAXIMAL_AGING) { - // we keep updating the high bracket, try to compensate this - targetY = yB.divide(16).negate(); - } else if (agingB >= MAXIMAL_AGING) { - // we keep updating the low bracket, try to compensate this - targetY = yA.divide(16).negate(); - } else { - // bracketing is balanced, try to find the root itself - targetY = zero; - } - - // make a few attempts to guess a root, - T nextX; - int start = 0; - int end = nbPoints; - do { - - // guess a value for current target, using inverse polynomial interpolation - System.arraycopy(x, start, tmpX, start, end - start); - nextX = guessX(targetY, tmpX, y, start, end); - - if (!((nextX.subtract(xA).getReal() > 0) && (nextX.subtract(xB).getReal() < 0))) { - // the guessed root is not strictly inside of the tightest bracketing interval - - // the guessed root is either not strictly inside the interval or it - // is a NaN (which occurs when some sampling points share the same y) - // we try again with a lower interpolation order - if (signChangeIndex - start >= end - signChangeIndex) { - // we have more points before the sign change, drop the lowest point - ++start; - } else { - // we have more points after sign change, drop the highest point - --end; - } - - // we need to do one more attempt - nextX = nan; - - } - - } while (Double.isNaN(nextX.getReal()) && (end - start > 1)); - - if (Double.isNaN(nextX.getReal())) { - // fall back to bisection - nextX = xA.add(xB.subtract(xA).divide(2)); - start = signChangeIndex - 1; - end = signChangeIndex; - } - - // evaluate the function at the guessed root - evaluations.increment(); - final T nextY = f.value(nextX); - if (Precision.equals(nextY.getReal(), 0.0, 1)) { - // we have found an exact root, since it is not an approximation - // we don't need to bother about the allowed solutions setting - return nextX; - } - - if ((nbPoints > 2) && (end - start != nbPoints)) { - - // we have been forced to ignore some points to keep bracketing, - // they are probably too far from the root, drop them from now on - nbPoints = end - start; - System.arraycopy(x, start, x, 0, nbPoints); - System.arraycopy(y, start, y, 0, nbPoints); - signChangeIndex -= start; - - } else if (nbPoints == x.length) { - - // we have to drop one point in order to insert the new one - nbPoints--; - - // keep the tightest bracketing interval as centered as possible - if (signChangeIndex >= (x.length + 1) / 2) { - // we drop the lowest point, we have to shift the arrays and the index - System.arraycopy(x, 1, x, 0, nbPoints); - System.arraycopy(y, 1, y, 0, nbPoints); - --signChangeIndex; - } - - } - - // insert the last computed point - //(by construction, we know it lies inside the tightest bracketing interval) - System.arraycopy(x, signChangeIndex, x, signChangeIndex + 1, nbPoints - signChangeIndex); - x[signChangeIndex] = nextX; - System.arraycopy(y, signChangeIndex, y, signChangeIndex + 1, nbPoints - signChangeIndex); - y[signChangeIndex] = nextY; - ++nbPoints; - - // update the bracketing interval - if (nextY.multiply(yA).getReal() <= 0) { - // the sign change occurs before the inserted point - xB = nextX; - yB = nextY; - absYB = yB.abs(); - ++agingA; - agingB = 0; - } else { - // the sign change occurs after the inserted point - xA = nextX; - yA = nextY; - absYA = yA.abs(); - agingA = 0; - ++agingB; - - // update the sign change index - signChangeIndex++; - - } - - } - - } - - /** Guess an x value by nth order inverse polynomial interpolation. - *

- * The x value is guessed by evaluating polynomial Q(y) at y = targetY, where Q - * is built such that for all considered points (xi, yi), - * Q(yi) = xi. - *

- * @param targetY target value for y - * @param x reference points abscissas for interpolation, - * note that this array is modified during computation - * @param y reference points ordinates for interpolation - * @param start start index of the points to consider (inclusive) - * @param end end index of the points to consider (exclusive) - * @return guessed root (will be a NaN if two points share the same y) - */ - private T guessX(final T targetY, final T[] x, final T[] y, - final int start, final int end) { - - // compute Q Newton coefficients by divided differences - for (int i = start; i < end - 1; ++i) { - final int delta = i + 1 - start; - for (int j = end - 1; j > i; --j) { - x[j] = x[j].subtract(x[j-1]).divide(y[j].subtract(y[j - delta])); - } - } - - // evaluate Q(targetY) - T x0 = field.getZero(); - for (int j = end - 1; j >= start; --j) { - x0 = x[j].add(x0.multiply(targetY.subtract(y[j]))); - } - - return x0; - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/IllinoisSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/IllinoisSolver.java deleted file mode 100644 index 051b10e5c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/IllinoisSolver.java +++ /dev/null @@ -1,82 +0,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. - */ - -package org.apache.commons.math4.analysis.solvers; - - -/** - * Implements the Illinois method for root-finding (approximating - * a zero of a univariate real function). It is a modified - * {@link RegulaFalsiSolver Regula Falsi} method. - * - *

Like the Regula Falsi method, convergence is guaranteed by - * maintaining a bracketed solution. The Illinois method however, - * should converge much faster than the original Regula Falsi - * method. Furthermore, this implementation of the Illinois method - * should not suffer from the same implementation issues as the Regula - * Falsi method, which may fail to convergence in certain cases.

- * - *

The Illinois method assumes that the function is continuous, - * but not necessarily smooth.

- * - *

Implementation based on the following article: M. Dowell and P. Jarratt, - * A modified regula falsi method for computing the root of an - * equation, BIT Numerical Mathematics, volume 11, number 2, - * pages 168-174, Springer, 1971.

- * - * @since 3.0 - */ -public class IllinoisSolver extends BaseSecantSolver { - - /** Construct a solver with default accuracy (1e-6). */ - public IllinoisSolver() { - super(DEFAULT_ABSOLUTE_ACCURACY, Method.ILLINOIS); - } - - /** - * Construct a solver. - * - * @param absoluteAccuracy Absolute accuracy. - */ - public IllinoisSolver(final double absoluteAccuracy) { - super(absoluteAccuracy, Method.ILLINOIS); - } - - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - */ - public IllinoisSolver(final double relativeAccuracy, - final double absoluteAccuracy) { - super(relativeAccuracy, absoluteAccuracy, Method.ILLINOIS); - } - - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - * @param functionValueAccuracy Maximum function value error. - */ - public IllinoisSolver(final double relativeAccuracy, - final double absoluteAccuracy, - final double functionValueAccuracy) { - super(relativeAccuracy, absoluteAccuracy, functionValueAccuracy, Method.PEGASUS); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/LaguerreSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/LaguerreSolver.java deleted file mode 100644 index 099766f8c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/LaguerreSolver.java +++ /dev/null @@ -1,384 +0,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. - */ -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.numbers.complex.Complex; -import org.apache.commons.numbers.complex.streams.ComplexUtils; -import org.apache.commons.math4.analysis.polynomials.PolynomialFunction; -import org.apache.commons.math4.exception.NoBracketingException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.TooManyEvaluationsException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; - -/** - * Implements the - * Laguerre's Method for root finding of real coefficient polynomials. - * For reference, see - *
- * A First Course in Numerical Analysis, - * ISBN 048641454X, chapter 8. - *
- * Laguerre's method is global in the sense that it can start with any initial - * approximation and be able to solve all roots from that point. - * The algorithm requires a bracketing condition. - * - * @since 1.2 - */ -public class LaguerreSolver extends AbstractPolynomialSolver { - /** Default absolute accuracy. */ - private static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6; - /** Complex solver. */ - private final ComplexSolver complexSolver = new ComplexSolver(); - - /** - * Construct a solver with default accuracy (1e-6). - */ - public LaguerreSolver() { - this(DEFAULT_ABSOLUTE_ACCURACY); - } - /** - * Construct a solver. - * - * @param absoluteAccuracy Absolute accuracy. - */ - public LaguerreSolver(double absoluteAccuracy) { - super(absoluteAccuracy); - } - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - */ - public LaguerreSolver(double relativeAccuracy, - double absoluteAccuracy) { - super(relativeAccuracy, absoluteAccuracy); - } - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - * @param functionValueAccuracy Function value accuracy. - */ - public LaguerreSolver(double relativeAccuracy, - double absoluteAccuracy, - double functionValueAccuracy) { - super(relativeAccuracy, absoluteAccuracy, functionValueAccuracy); - } - - /** - * {@inheritDoc} - */ - @Override - public double doSolve() - throws TooManyEvaluationsException, - NumberIsTooLargeException, - NoBracketingException { - final double min = getMin(); - final double max = getMax(); - final double initial = getStartValue(); - final double functionValueAccuracy = getFunctionValueAccuracy(); - - verifySequence(min, initial, max); - - // Return the initial guess if it is good enough. - final double yInitial = computeObjectiveValue(initial); - if (FastMath.abs(yInitial) <= functionValueAccuracy) { - return initial; - } - - // Return the first endpoint if it is good enough. - final double yMin = computeObjectiveValue(min); - if (FastMath.abs(yMin) <= functionValueAccuracy) { - return min; - } - - // Reduce interval if min and initial bracket the root. - if (yInitial * yMin < 0) { - return laguerre(min, initial); - } - - // Return the second endpoint if it is good enough. - final double yMax = computeObjectiveValue(max); - if (FastMath.abs(yMax) <= functionValueAccuracy) { - return max; - } - - // Reduce interval if initial and max bracket the root. - if (yInitial * yMax < 0) { - return laguerre(initial, max); - } - - throw new NoBracketingException(min, max, yMin, yMax); - } - - /** - * Find a real root in the given interval. - * - * Despite the bracketing condition, the root returned by - * {@link ComplexSolver#solve(Complex[],Complex)} may - * not be a real zero inside {@code [min, max]}. - * For example, p(x) = x3 + 1, - * with {@code min = -2}, {@code max = 2}, {@code initial = 0}. - * When it occurs, this code calls - * {@link ComplexSolver#solveAll(Complex[],Complex)} - * in order to obtain all roots and picks up one real root. - * - * @param lo Lower bound of the search interval. - * @param hi Higher bound of the search interval. - * @return the point at which the function value is zero. - */ - private double laguerre(double lo, double hi) { - final Complex c[] = ComplexUtils.real2Complex(getCoefficients()); - - final Complex initial = Complex.ofCartesian(0.5 * (lo + hi), 0); - final Complex z = complexSolver.solve(c, initial); - if (complexSolver.isRoot(lo, hi, z)) { - return z.getReal(); - } else { - double r = Double.NaN; - // Solve all roots and select the one we are seeking. - Complex[] root = complexSolver.solveAll(c, initial); - for (int i = 0; i < root.length; i++) { - if (complexSolver.isRoot(lo, hi, root[i])) { - r = root[i].getReal(); - break; - } - } - return r; - } - } - - /** - * Find all complex roots for the polynomial with the given - * coefficients, starting from the given initial value. - *

- * Note: This method is not part of the API of {@link BaseUnivariateSolver}.

- * - * @param coefficients Polynomial coefficients. - * @param initial Start value. - * @return the point at which the function value is zero. - * @throws TooManyEvaluationsException - * if the maximum number of evaluations is exceeded. - * @throws NullArgumentException if the {@code coefficients} is - * {@code null}. - * @throws NoDataException if the {@code coefficients} array is empty. - * @since 3.1 - */ - public Complex[] solveAllComplex(double[] coefficients, - double initial) - throws NullArgumentException, - NoDataException, - TooManyEvaluationsException { - setup(Integer.MAX_VALUE, - new PolynomialFunction(coefficients), - Double.NEGATIVE_INFINITY, - Double.POSITIVE_INFINITY, - initial); - return complexSolver.solveAll(ComplexUtils.real2Complex(coefficients), - Complex.ofCartesian(initial, 0d)); - } - - /** - * Find a complex root for the polynomial with the given coefficients, - * starting from the given initial value. - *

- * Note: This method is not part of the API of {@link BaseUnivariateSolver}.

- * - * @param coefficients Polynomial coefficients. - * @param initial Start value. - * @return the point at which the function value is zero. - * @throws TooManyEvaluationsException - * if the maximum number of evaluations is exceeded. - * @throws NullArgumentException if the {@code coefficients} is - * {@code null}. - * @throws NoDataException if the {@code coefficients} array is empty. - * @since 3.1 - */ - public Complex solveComplex(double[] coefficients, - double initial) - throws NullArgumentException, - NoDataException, - TooManyEvaluationsException { - setup(Integer.MAX_VALUE, - new PolynomialFunction(coefficients), - Double.NEGATIVE_INFINITY, - Double.POSITIVE_INFINITY, - initial); - return complexSolver.solve(ComplexUtils.real2Complex(coefficients), - Complex.ofCartesian(initial, 0d)); - } - - /** - * Class for searching all (complex) roots. - */ - private class ComplexSolver { - /** - * Check whether the given complex root is actually a real zero - * in the given interval, within the solver tolerance level. - * - * @param min Lower bound for the interval. - * @param max Upper bound for the interval. - * @param z Complex root. - * @return {@code true} if z is a real zero. - */ - public boolean isRoot(double min, double max, Complex z) { - if (isSequence(min, z.getReal(), max)) { - double tolerance = FastMath.max(getRelativeAccuracy() * z.abs(), getAbsoluteAccuracy()); - return (FastMath.abs(z.getImaginary()) <= tolerance) || - (z.abs() <= getFunctionValueAccuracy()); - } - return false; - } - - /** - * Find all complex roots for the polynomial with the given - * coefficients, starting from the given initial value. - * - * @param coefficients Polynomial coefficients. - * @param initial Start value. - * @return the point at which the function value is zero. - * @throws TooManyEvaluationsException - * if the maximum number of evaluations is exceeded. - * @throws NullArgumentException if the {@code coefficients} is - * {@code null}. - * @throws NoDataException if the {@code coefficients} array is empty. - */ - public Complex[] solveAll(Complex coefficients[], Complex initial) - throws NullArgumentException, - NoDataException, - TooManyEvaluationsException { - if (coefficients == null) { - throw new NullArgumentException(); - } - final int n = coefficients.length - 1; - if (n == 0) { - throw new NoDataException(LocalizedFormats.POLYNOMIAL); - } - // Coefficients for deflated polynomial. - final Complex c[] = new Complex[n + 1]; - for (int i = 0; i <= n; i++) { - c[i] = coefficients[i]; - } - - // Solve individual roots successively. - final Complex root[] = new Complex[n]; - for (int i = 0; i < n; i++) { - final Complex subarray[] = new Complex[n - i + 1]; - System.arraycopy(c, 0, subarray, 0, subarray.length); - root[i] = solve(subarray, initial); - // Polynomial deflation using synthetic division. - Complex newc = c[n - i]; - Complex oldc = null; - for (int j = n - i - 1; j >= 0; j--) { - oldc = c[j]; - c[j] = newc; - newc = oldc.add(newc.multiply(root[i])); - } - } - - return root; - } - - /** - * Find a complex root for the polynomial with the given coefficients, - * starting from the given initial value. - * - * @param coefficients Polynomial coefficients. - * @param initial Start value. - * @return the point at which the function value is zero. - * @throws TooManyEvaluationsException - * if the maximum number of evaluations is exceeded. - * @throws NullArgumentException if the {@code coefficients} is - * {@code null}. - * @throws NoDataException if the {@code coefficients} array is empty. - */ - public Complex solve(Complex coefficients[], Complex initial) - throws NullArgumentException, - NoDataException, - TooManyEvaluationsException { - if (coefficients == null) { - throw new NullArgumentException(); - } - - final int n = coefficients.length - 1; - if (n == 0) { - throw new NoDataException(LocalizedFormats.POLYNOMIAL); - } - - final double absoluteAccuracy = getAbsoluteAccuracy(); - final double relativeAccuracy = getRelativeAccuracy(); - final double functionValueAccuracy = getFunctionValueAccuracy(); - - final Complex nC = Complex.ofCartesian(n, 0); - final Complex n1C = Complex.ofCartesian(n - 1, 0); - - Complex z = initial; - Complex oldz = Complex.ofCartesian(Double.POSITIVE_INFINITY, - Double.POSITIVE_INFINITY); - while (true) { - // Compute pv (polynomial value), dv (derivative value), and - // d2v (second derivative value) simultaneously. - Complex pv = coefficients[n]; - Complex dv = Complex.ZERO; - Complex d2v = Complex.ZERO; - for (int j = n-1; j >= 0; j--) { - d2v = dv.add(z.multiply(d2v)); - dv = pv.add(z.multiply(dv)); - pv = coefficients[j].add(z.multiply(pv)); - } - d2v = d2v.multiply(Complex.ofCartesian(2.0, 0.0)); - - // Check for convergence. - final double tolerance = FastMath.max(relativeAccuracy * z.abs(), - absoluteAccuracy); - if ((z.subtract(oldz)).abs() <= tolerance) { - return z; - } - if (pv.abs() <= functionValueAccuracy) { - return z; - } - - // Now pv != 0, calculate the new approximation. - final Complex G = dv.divide(pv); - final Complex G2 = G.multiply(G); - final Complex H = G2.subtract(d2v.divide(pv)); - final Complex delta = n1C.multiply((nC.multiply(H)).subtract(G2)); - // Choose a denominator larger in magnitude. - final Complex deltaSqrt = delta.sqrt(); - final Complex dplus = G.add(deltaSqrt); - final Complex dminus = G.subtract(deltaSqrt); - final Complex denominator = dplus.abs() > dminus.abs() ? dplus : dminus; - // Perturb z if denominator is zero, for instance, - // p(x) = x^3 + 1, z = 0. - if (denominator.equals(Complex.ofCartesian(0.0, 0.0))) { - z = z.add(Complex.ofCartesian(absoluteAccuracy, absoluteAccuracy)); - oldz = Complex.ofCartesian(Double.POSITIVE_INFINITY, - Double.POSITIVE_INFINITY); - } else { - oldz = z; - z = z.subtract(nC.divide(denominator)); - } - incrementEvaluationCount(); - } - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/MullerSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/MullerSolver.java deleted file mode 100644 index b71439966..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/MullerSolver.java +++ /dev/null @@ -1,202 +0,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. - */ -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.exception.NoBracketingException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.TooManyEvaluationsException; -import org.apache.commons.math4.util.FastMath; - -/** - * This class implements the - * Muller's Method for root finding of real univariate functions. For - * reference, see Elementary Numerical Analysis, ISBN 0070124477, - * chapter 3. - *

- * Muller's method applies to both real and complex functions, but here we - * restrict ourselves to real functions. - * This class differs from {@link MullerSolver} in the way it avoids complex - * operations.

- * Muller's original method would have function evaluation at complex point. - * Since our f(x) is real, we have to find ways to avoid that. Bracketing - * condition is one way to go: by requiring bracketing in every iteration, - * the newly computed approximation is guaranteed to be real.

- *

- * Normally Muller's method converges quadratically in the vicinity of a - * zero, however it may be very slow in regions far away from zeros. For - * example, f(x) = exp(x) - 1, min = -50, max = 100. In such case we use - * bisection as a safety backup if it performs very poorly.

- *

- * The formulas here use divided differences directly.

- * - * @since 1.2 - * @see MullerSolver2 - */ -public class MullerSolver extends AbstractUnivariateSolver { - - /** Default absolute accuracy. */ - private static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6; - - /** - * Construct a solver with default accuracy (1e-6). - */ - public MullerSolver() { - this(DEFAULT_ABSOLUTE_ACCURACY); - } - /** - * Construct a solver. - * - * @param absoluteAccuracy Absolute accuracy. - */ - public MullerSolver(double absoluteAccuracy) { - super(absoluteAccuracy); - } - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - */ - public MullerSolver(double relativeAccuracy, - double absoluteAccuracy) { - super(relativeAccuracy, absoluteAccuracy); - } - - /** - * {@inheritDoc} - */ - @Override - protected double doSolve() - throws TooManyEvaluationsException, - NumberIsTooLargeException, - NoBracketingException { - final double min = getMin(); - final double max = getMax(); - final double initial = getStartValue(); - - final double functionValueAccuracy = getFunctionValueAccuracy(); - - verifySequence(min, initial, max); - - // check for zeros before verifying bracketing - final double fMin = computeObjectiveValue(min); - if (FastMath.abs(fMin) < functionValueAccuracy) { - return min; - } - final double fMax = computeObjectiveValue(max); - if (FastMath.abs(fMax) < functionValueAccuracy) { - return max; - } - final double fInitial = computeObjectiveValue(initial); - if (FastMath.abs(fInitial) < functionValueAccuracy) { - return initial; - } - - verifyBracketing(min, max); - - if (isBracketing(min, initial)) { - return solve(min, initial, fMin, fInitial); - } else { - return solve(initial, max, fInitial, fMax); - } - } - - /** - * Find a real root in the given interval. - * - * @param min Lower bound for the interval. - * @param max Upper bound for the interval. - * @param fMin function value at the lower bound. - * @param fMax function value at the upper bound. - * @return the point at which the function value is zero. - * @throws TooManyEvaluationsException if the allowed number of calls to - * the function to be solved has been exhausted. - */ - private double solve(double min, double max, - double fMin, double fMax) - throws TooManyEvaluationsException { - final double relativeAccuracy = getRelativeAccuracy(); - final double absoluteAccuracy = getAbsoluteAccuracy(); - final double functionValueAccuracy = getFunctionValueAccuracy(); - - // [x0, x2] is the bracketing interval in each iteration - // x1 is the last approximation and an interpolation point in (x0, x2) - // x is the new root approximation and new x1 for next round - // d01, d12, d012 are divided differences - - double x0 = min; - double y0 = fMin; - double x2 = max; - double y2 = fMax; - double x1 = 0.5 * (x0 + x2); - double y1 = computeObjectiveValue(x1); - - double oldx = Double.POSITIVE_INFINITY; - while (true) { - // Muller's method employs quadratic interpolation through - // x0, x1, x2 and x is the zero of the interpolating parabola. - // Due to bracketing condition, this parabola must have two - // real roots and we choose one in [x0, x2] to be x. - final double d01 = (y1 - y0) / (x1 - x0); - final double d12 = (y2 - y1) / (x2 - x1); - final double d012 = (d12 - d01) / (x2 - x0); - final double c1 = d01 + (x1 - x0) * d012; - final double delta = c1 * c1 - 4 * y1 * d012; - final double xplus = x1 + (-2.0 * y1) / (c1 + FastMath.sqrt(delta)); - final double xminus = x1 + (-2.0 * y1) / (c1 - FastMath.sqrt(delta)); - // xplus and xminus are two roots of parabola and at least - // one of them should lie in (x0, x2) - final double x = isSequence(x0, xplus, x2) ? xplus : xminus; - final double y = computeObjectiveValue(x); - - // check for convergence - final double tolerance = FastMath.max(relativeAccuracy * FastMath.abs(x), absoluteAccuracy); - if (FastMath.abs(x - oldx) <= tolerance || - FastMath.abs(y) <= functionValueAccuracy) { - return x; - } - - // Bisect if convergence is too slow. Bisection would waste - // our calculation of x, hopefully it won't happen often. - // the real number equality test x == x1 is intentional and - // completes the proximity tests above it - boolean bisect = (x < x1 && (x1 - x0) > 0.95 * (x2 - x0)) || - (x > x1 && (x2 - x1) > 0.95 * (x2 - x0)) || - (x == x1); - // prepare the new bracketing interval for next iteration - if (!bisect) { - x0 = x < x1 ? x0 : x1; - y0 = x < x1 ? y0 : y1; - x2 = x > x1 ? x2 : x1; - y2 = x > x1 ? y2 : y1; - x1 = x; y1 = y; - oldx = x; - } else { - double xm = 0.5 * (x0 + x2); - double ym = computeObjectiveValue(xm); - if (FastMath.signum(y0) + FastMath.signum(ym) == 0.0) { - x2 = xm; y2 = ym; - } else { - x0 = xm; y0 = ym; - } - x1 = 0.5 * (x0 + x2); - y1 = computeObjectiveValue(x1); - oldx = Double.POSITIVE_INFINITY; - } - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/MullerSolver2.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/MullerSolver2.java deleted file mode 100644 index e5d8b9b53..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/MullerSolver2.java +++ /dev/null @@ -1,168 +0,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. - */ -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.exception.NoBracketingException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.TooManyEvaluationsException; -import org.apache.commons.math4.util.FastMath; - -/** - * This class implements the - * Muller's Method for root finding of real univariate functions. For - * reference, see Elementary Numerical Analysis, ISBN 0070124477, - * chapter 3. - *

- * Muller's method applies to both real and complex functions, but here we - * restrict ourselves to real functions. - * This class differs from {@link MullerSolver} in the way it avoids complex - * operations.

- * Except for the initial [min, max], it does not require bracketing - * condition, e.g. f(x0), f(x1), f(x2) can have the same sign. If a complex - * number arises in the computation, we simply use its modulus as a real - * approximation.

- *

- * Because the interval may not be bracketing, the bisection alternative is - * not applicable here. However in practice our treatment usually works - * well, especially near real zeroes where the imaginary part of the complex - * approximation is often negligible.

- *

- * The formulas here do not use divided differences directly.

- * - * @since 1.2 - * @see MullerSolver - */ -public class MullerSolver2 extends AbstractUnivariateSolver { - - /** Default absolute accuracy. */ - private static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6; - - /** - * Construct a solver with default accuracy (1e-6). - */ - public MullerSolver2() { - this(DEFAULT_ABSOLUTE_ACCURACY); - } - /** - * Construct a solver. - * - * @param absoluteAccuracy Absolute accuracy. - */ - public MullerSolver2(double absoluteAccuracy) { - super(absoluteAccuracy); - } - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - */ - public MullerSolver2(double relativeAccuracy, - double absoluteAccuracy) { - super(relativeAccuracy, absoluteAccuracy); - } - - /** - * {@inheritDoc} - */ - @Override - protected double doSolve() - throws TooManyEvaluationsException, - NumberIsTooLargeException, - NoBracketingException { - final double min = getMin(); - final double max = getMax(); - - verifyInterval(min, max); - - final double relativeAccuracy = getRelativeAccuracy(); - final double absoluteAccuracy = getAbsoluteAccuracy(); - final double functionValueAccuracy = getFunctionValueAccuracy(); - - // x2 is the last root approximation - // x is the new approximation and new x2 for next round - // x0 < x1 < x2 does not hold here - - double x0 = min; - double y0 = computeObjectiveValue(x0); - if (FastMath.abs(y0) < functionValueAccuracy) { - return x0; - } - double x1 = max; - double y1 = computeObjectiveValue(x1); - if (FastMath.abs(y1) < functionValueAccuracy) { - return x1; - } - - if(y0 * y1 > 0) { - throw new NoBracketingException(x0, x1, y0, y1); - } - - double x2 = 0.5 * (x0 + x1); - double y2 = computeObjectiveValue(x2); - - double oldx = Double.POSITIVE_INFINITY; - while (true) { - // quadratic interpolation through x0, x1, x2 - final double q = (x2 - x1) / (x1 - x0); - final double a = q * (y2 - (1 + q) * y1 + q * y0); - final double b = (2 * q + 1) * y2 - (1 + q) * (1 + q) * y1 + q * q * y0; - final double c = (1 + q) * y2; - final double delta = b * b - 4 * a * c; - double x; - final double denominator; - if (delta >= 0.0) { - // choose a denominator larger in magnitude - double dplus = b + FastMath.sqrt(delta); - double dminus = b - FastMath.sqrt(delta); - denominator = FastMath.abs(dplus) > FastMath.abs(dminus) ? dplus : dminus; - } else { - // take the modulus of (B +/- FastMath.sqrt(delta)) - denominator = FastMath.sqrt(b * b - delta); - } - if (denominator != 0) { - x = x2 - 2.0 * c * (x2 - x1) / denominator; - // perturb x if it exactly coincides with x1 or x2 - // the equality tests here are intentional - while (x == x1 || x == x2) { - x += absoluteAccuracy; - } - } else { - // extremely rare case, get a random number to skip it - x = min + FastMath.random() * (max - min); - oldx = Double.POSITIVE_INFINITY; - } - final double y = computeObjectiveValue(x); - - // check for convergence - final double tolerance = FastMath.max(relativeAccuracy * FastMath.abs(x), absoluteAccuracy); - if (FastMath.abs(x - oldx) <= tolerance || - FastMath.abs(y) <= functionValueAccuracy) { - return x; - } - - // prepare the next iteration - x0 = x1; - y0 = y1; - x1 = x2; - y1 = y2; - x2 = x; - y2 = y; - oldx = x; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/NewtonRaphsonSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/NewtonRaphsonSolver.java deleted file mode 100644 index 0ada86157..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/NewtonRaphsonSolver.java +++ /dev/null @@ -1,92 +0,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. - */ - -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.analysis.differentiation.DerivativeStructure; -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; -import org.apache.commons.math4.exception.TooManyEvaluationsException; -import org.apache.commons.math4.util.FastMath; - -/** - * Implements - * Newton's Method for finding zeros of real univariate differentiable - * functions. - * - * @since 3.1 - */ -public class NewtonRaphsonSolver extends AbstractUnivariateDifferentiableSolver { - /** Default absolute accuracy. */ - private static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6; - - /** - * Construct a solver. - */ - public NewtonRaphsonSolver() { - this(DEFAULT_ABSOLUTE_ACCURACY); - } - /** - * Construct a solver. - * - * @param absoluteAccuracy Absolute accuracy. - */ - public NewtonRaphsonSolver(double absoluteAccuracy) { - super(absoluteAccuracy); - } - - /** - * Find a zero near the midpoint of {@code min} and {@code max}. - * - * @param f Function to solve. - * @param min Lower bound for the interval. - * @param max Upper bound for the interval. - * @param maxEval Maximum number of evaluations. - * @return the value where the function is zero. - * @throws TooManyEvaluationsException - * if the maximum evaluation count is exceeded. - * @throws org.apache.commons.math4.exception.NumberIsTooLargeException - * if {@code min >= max}. - */ - @Override - public double solve(int maxEval, final UnivariateDifferentiableFunction f, - final double min, final double max) - throws TooManyEvaluationsException { - return super.solve(maxEval, f, UnivariateSolverUtils.midpoint(min, max)); - } - - /** - * {@inheritDoc} - */ - @Override - protected double doSolve() - throws TooManyEvaluationsException { - final double startValue = getStartValue(); - final double absoluteAccuracy = getAbsoluteAccuracy(); - - double x0 = startValue; - double x1; - while (true) { - final DerivativeStructure y0 = computeObjectiveValueAndDerivative(x0); - x1 = x0 - (y0.getValue() / y0.getPartialDerivative(1)); - if (FastMath.abs(x1 - x0) <= absoluteAccuracy) { - return x1; - } - - x0 = x1; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/PegasusSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/PegasusSolver.java deleted file mode 100644 index 3abb279eb..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/PegasusSolver.java +++ /dev/null @@ -1,84 +0,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. - */ - -package org.apache.commons.math4.analysis.solvers; - -/** - * Implements the Pegasus method for root-finding (approximating - * a zero of a univariate real function). It is a modified - * {@link RegulaFalsiSolver Regula Falsi} method. - * - *

Like the Regula Falsi method, convergence is guaranteed by - * maintaining a bracketed solution. The Pegasus method however, - * should converge much faster than the original Regula Falsi - * method. Furthermore, this implementation of the Pegasus method - * should not suffer from the same implementation issues as the Regula - * Falsi method, which may fail to convergence in certain cases. Also, - * the Pegasus method should converge faster than the - * {@link IllinoisSolver Illinois} method, another Regula - * Falsi-based method.

- * - *

The Pegasus method assumes that the function is continuous, - * but not necessarily smooth.

- * - *

Implementation based on the following article: M. Dowell and P. Jarratt, - * The "Pegasus" method for computing the root of an equation, - * BIT Numerical Mathematics, volume 12, number 4, pages 503-508, Springer, - * 1972.

- * - * @since 3.0 - */ -public class PegasusSolver extends BaseSecantSolver { - - /** Construct a solver with default accuracy (1e-6). */ - public PegasusSolver() { - super(DEFAULT_ABSOLUTE_ACCURACY, Method.PEGASUS); - } - - /** - * Construct a solver. - * - * @param absoluteAccuracy Absolute accuracy. - */ - public PegasusSolver(final double absoluteAccuracy) { - super(absoluteAccuracy, Method.PEGASUS); - } - - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - */ - public PegasusSolver(final double relativeAccuracy, - final double absoluteAccuracy) { - super(relativeAccuracy, absoluteAccuracy, Method.PEGASUS); - } - - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - * @param functionValueAccuracy Maximum function value error. - */ - public PegasusSolver(final double relativeAccuracy, - final double absoluteAccuracy, - final double functionValueAccuracy) { - super(relativeAccuracy, absoluteAccuracy, functionValueAccuracy, Method.PEGASUS); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/PolynomialSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/PolynomialSolver.java deleted file mode 100644 index e4d0c48c0..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/PolynomialSolver.java +++ /dev/null @@ -1,28 +0,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. - */ -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.analysis.polynomials.PolynomialFunction; - -/** - * Interface for (polynomial) root-finding algorithms. - * Implementations will search for only one zero in the given interval. - * - * @since 3.0 - */ -public interface PolynomialSolver - extends BaseUnivariateSolver {} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/RegulaFalsiSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/RegulaFalsiSolver.java deleted file mode 100644 index c59bd8926..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/RegulaFalsiSolver.java +++ /dev/null @@ -1,94 +0,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. - */ - -package org.apache.commons.math4.analysis.solvers; - -/** - * Implements the Regula Falsi or False position method for - * root-finding (approximating a zero of a univariate real function). It is a - * modified {@link SecantSolver Secant} method. - * - *

The Regula Falsi method is included for completeness, for - * testing purposes, for educational purposes, for comparison to other - * algorithms, etc. It is however not intended to be used - * for actual problems, as one of the bounds often remains fixed, resulting - * in very slow convergence. Instead, one of the well-known modified - * Regula Falsi algorithms can be used ({@link IllinoisSolver - * Illinois} or {@link PegasusSolver Pegasus}). These two - * algorithms solve the fundamental issues of the original Regula - * Falsi algorithm, and greatly out-performs it for most, if not all, - * (practical) functions. - * - *

Unlike the Secant method, the Regula Falsi guarantees - * convergence, by maintaining a bracketed solution. Note however, that due to - * the finite/limited precision of Java's {@link Double double} type, which is - * used in this implementation, the algorithm may get stuck in a situation - * where it no longer makes any progress. Such cases are detected and result - * in a {@code ConvergenceException} exception being thrown. In other words, - * the algorithm theoretically guarantees convergence, but the implementation - * does not.

- * - *

The Regula Falsi method assumes that the function is continuous, - * but not necessarily smooth.

- * - *

Implementation based on the following article: M. Dowell and P. Jarratt, - * A modified regula falsi method for computing the root of an - * equation, BIT Numerical Mathematics, volume 11, number 2, - * pages 168-174, Springer, 1971.

- * - * @since 3.0 - */ -public class RegulaFalsiSolver extends BaseSecantSolver { - - /** Construct a solver with default accuracy (1e-6). */ - public RegulaFalsiSolver() { - super(DEFAULT_ABSOLUTE_ACCURACY, Method.REGULA_FALSI); - } - - /** - * Construct a solver. - * - * @param absoluteAccuracy Absolute accuracy. - */ - public RegulaFalsiSolver(final double absoluteAccuracy) { - super(absoluteAccuracy, Method.REGULA_FALSI); - } - - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - */ - public RegulaFalsiSolver(final double relativeAccuracy, - final double absoluteAccuracy) { - super(relativeAccuracy, absoluteAccuracy, Method.REGULA_FALSI); - } - - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - * @param functionValueAccuracy Maximum function value error. - */ - public RegulaFalsiSolver(final double relativeAccuracy, - final double absoluteAccuracy, - final double functionValueAccuracy) { - super(relativeAccuracy, absoluteAccuracy, functionValueAccuracy, Method.REGULA_FALSI); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/RiddersSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/RiddersSolver.java deleted file mode 100644 index edce66890..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/RiddersSolver.java +++ /dev/null @@ -1,142 +0,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. - */ -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.exception.NoBracketingException; -import org.apache.commons.math4.exception.TooManyEvaluationsException; -import org.apache.commons.math4.util.FastMath; - -/** - * Implements the - * Ridders' Method for root finding of real univariate functions. For - * reference, see C. Ridders, A new algorithm for computing a single root - * of a real continuous function , IEEE Transactions on Circuits and - * Systems, 26 (1979), 979 - 980. - *

- * The function should be continuous but not necessarily smooth.

- * - * @since 1.2 - */ -public class RiddersSolver extends AbstractUnivariateSolver { - /** Default absolute accuracy. */ - private static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6; - - /** - * Construct a solver with default accuracy (1e-6). - */ - public RiddersSolver() { - this(DEFAULT_ABSOLUTE_ACCURACY); - } - /** - * Construct a solver. - * - * @param absoluteAccuracy Absolute accuracy. - */ - public RiddersSolver(double absoluteAccuracy) { - super(absoluteAccuracy); - } - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - */ - public RiddersSolver(double relativeAccuracy, - double absoluteAccuracy) { - super(relativeAccuracy, absoluteAccuracy); - } - - /** - * {@inheritDoc} - */ - @Override - protected double doSolve() - throws TooManyEvaluationsException, - NoBracketingException { - double min = getMin(); - double max = getMax(); - // [x1, x2] is the bracketing interval in each iteration - // x3 is the midpoint of [x1, x2] - // x is the new root approximation and an endpoint of the new interval - double x1 = min; - double y1 = computeObjectiveValue(x1); - double x2 = max; - double y2 = computeObjectiveValue(x2); - - // check for zeros before verifying bracketing - if (y1 == 0) { - return min; - } - if (y2 == 0) { - return max; - } - verifyBracketing(min, max); - - final double absoluteAccuracy = getAbsoluteAccuracy(); - final double functionValueAccuracy = getFunctionValueAccuracy(); - final double relativeAccuracy = getRelativeAccuracy(); - - double oldx = Double.POSITIVE_INFINITY; - while (true) { - // calculate the new root approximation - final double x3 = 0.5 * (x1 + x2); - final double y3 = computeObjectiveValue(x3); - if (FastMath.abs(y3) <= functionValueAccuracy) { - return x3; - } - final double delta = 1 - (y1 * y2) / (y3 * y3); // delta > 1 due to bracketing - final double correction = (FastMath.signum(y2) * FastMath.signum(y3)) * - (x3 - x1) / FastMath.sqrt(delta); - final double x = x3 - correction; // correction != 0 - final double y = computeObjectiveValue(x); - - // check for convergence - final double tolerance = FastMath.max(relativeAccuracy * FastMath.abs(x), absoluteAccuracy); - if (FastMath.abs(x - oldx) <= tolerance) { - return x; - } - if (FastMath.abs(y) <= functionValueAccuracy) { - return x; - } - - // prepare the new interval for next iteration - // Ridders' method guarantees x1 < x < x2 - if (correction > 0.0) { // x1 < x < x3 - if (FastMath.signum(y1) + FastMath.signum(y) == 0.0) { - x2 = x; - y2 = y; - } else { - x1 = x; - x2 = x3; - y1 = y; - y2 = y3; - } - } else { // x3 < x < x2 - if (FastMath.signum(y2) + FastMath.signum(y) == 0.0) { - x1 = x; - y1 = y; - } else { - x1 = x3; - x2 = x; - y1 = y3; - y2 = y; - } - } - oldx = x; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/SecantSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/SecantSolver.java deleted file mode 100644 index 2600caf5e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/SecantSolver.java +++ /dev/null @@ -1,135 +0,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. - */ - -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.exception.NoBracketingException; -import org.apache.commons.math4.exception.TooManyEvaluationsException; -import org.apache.commons.math4.util.FastMath; - -/** - * Implements the Secant method for root-finding (approximating a - * zero of a univariate real function). The solution that is maintained is - * not bracketed, and as such convergence is not guaranteed. - * - *

Implementation based on the following article: M. Dowell and P. Jarratt, - * A modified regula falsi method for computing the root of an - * equation, BIT Numerical Mathematics, volume 11, number 2, - * pages 168-174, Springer, 1971.

- * - *

Note that since release 3.0 this class implements the actual - * Secant algorithm, and not a modified one. As such, the 3.0 version - * is not backwards compatible with previous versions. To use an algorithm - * similar to the pre-3.0 releases, use the - * {@link IllinoisSolver Illinois} algorithm or the - * {@link PegasusSolver Pegasus} algorithm.

- * - */ -public class SecantSolver extends AbstractUnivariateSolver { - - /** Default absolute accuracy. */ - protected static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6; - - /** Construct a solver with default accuracy (1e-6). */ - public SecantSolver() { - super(DEFAULT_ABSOLUTE_ACCURACY); - } - - /** - * Construct a solver. - * - * @param absoluteAccuracy absolute accuracy - */ - public SecantSolver(final double absoluteAccuracy) { - super(absoluteAccuracy); - } - - /** - * Construct a solver. - * - * @param relativeAccuracy relative accuracy - * @param absoluteAccuracy absolute accuracy - */ - public SecantSolver(final double relativeAccuracy, - final double absoluteAccuracy) { - super(relativeAccuracy, absoluteAccuracy); - } - - /** {@inheritDoc} */ - @Override - protected final double doSolve() - throws TooManyEvaluationsException, - NoBracketingException { - // Get initial solution - double x0 = getMin(); - double x1 = getMax(); - double f0 = computeObjectiveValue(x0); - double f1 = computeObjectiveValue(x1); - - // If one of the bounds is the exact root, return it. Since these are - // not under-approximations or over-approximations, we can return them - // regardless of the allowed solutions. - if (f0 == 0.0) { - return x0; - } - if (f1 == 0.0) { - return x1; - } - - // Verify bracketing of initial solution. - verifyBracketing(x0, x1); - - // Get accuracies. - final double ftol = getFunctionValueAccuracy(); - final double atol = getAbsoluteAccuracy(); - final double rtol = getRelativeAccuracy(); - - // Keep finding better approximations. - while (true) { - // Calculate the next approximation. - final double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0)); - final double fx = computeObjectiveValue(x); - - // If the new approximation is the exact root, return it. Since - // this is not an under-approximation or an over-approximation, - // we can return it regardless of the allowed solutions. - if (fx == 0.0) { - return x; - } - - // Update the bounds with the new approximation. - x0 = x1; - f0 = f1; - x1 = x; - f1 = fx; - - // If the function value of the last approximation is too small, - // given the function value accuracy, then we can't get closer to - // the root than we already are. - if (FastMath.abs(f1) <= ftol) { - return x1; - } - - // If the current interval is within the given accuracies, we - // are satisfied with the current approximation. - if (FastMath.abs(x1 - x0) < FastMath.max(rtol * FastMath.abs(x1), atol)) { - return x1; - } - } - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/UnivariateDifferentiableSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/UnivariateDifferentiableSolver.java deleted file mode 100644 index 254085e94..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/UnivariateDifferentiableSolver.java +++ /dev/null @@ -1,29 +0,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. - */ -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.analysis.differentiation.UnivariateDifferentiableFunction; - - -/** - * Interface for (univariate real) rootfinding algorithms. - * Implementations will search for only one zero in the given interval. - * - * @since 3.1 - */ -public interface UnivariateDifferentiableSolver - extends BaseUnivariateSolver {} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/UnivariateSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/UnivariateSolver.java deleted file mode 100644 index 7755041d6..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/UnivariateSolver.java +++ /dev/null @@ -1,28 +0,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. - */ -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.analysis.UnivariateFunction; - - -/** - * Interface for (univariate real) root-finding algorithms. - * Implementations will search for only one zero in the given interval. - * - */ -public interface UnivariateSolver - extends BaseUnivariateSolver {} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/UnivariateSolverUtils.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/UnivariateSolverUtils.java deleted file mode 100644 index 2a588807d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/UnivariateSolverUtils.java +++ /dev/null @@ -1,467 +0,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. - */ -package org.apache.commons.math4.analysis.solvers; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.exception.NoBracketingException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; - -/** - * Utility routines for {@link UnivariateSolver} objects. - * - */ -public class UnivariateSolverUtils { - /** - * Class contains only static methods. - */ - private UnivariateSolverUtils() {} - - /** - * Convenience method to find a zero of a univariate real function. A default - * solver is used. - * - * @param function Function. - * @param x0 Lower bound for the interval. - * @param x1 Upper bound for the interval. - * @return a value where the function is zero. - * @throws NoBracketingException if the function has the same sign at the - * endpoints. - * @throws NullArgumentException if {@code function} is {@code null}. - */ - public static double solve(UnivariateFunction function, double x0, double x1) - throws NullArgumentException, - NoBracketingException { - if (function == null) { - throw new NullArgumentException(LocalizedFormats.FUNCTION); - } - final UnivariateSolver solver = new BrentSolver(); - return solver.solve(Integer.MAX_VALUE, function, x0, x1); - } - - /** - * Convenience method to find a zero of a univariate real function. A default - * solver is used. - * - * @param function Function. - * @param x0 Lower bound for the interval. - * @param x1 Upper bound for the interval. - * @param absoluteAccuracy Accuracy to be used by the solver. - * @return a value where the function is zero. - * @throws NoBracketingException if the function has the same sign at the - * endpoints. - * @throws NullArgumentException if {@code function} is {@code null}. - */ - public static double solve(UnivariateFunction function, - double x0, double x1, - double absoluteAccuracy) - throws NullArgumentException, - NoBracketingException { - if (function == null) { - throw new NullArgumentException(LocalizedFormats.FUNCTION); - } - final UnivariateSolver solver = new BrentSolver(absoluteAccuracy); - return solver.solve(Integer.MAX_VALUE, function, x0, x1); - } - - /** - * Force a root found by a non-bracketing solver to lie on a specified side, - * as if the solver were a bracketing one. - * - * @param maxEval maximal number of new evaluations of the function - * (evaluations already done for finding the root should have already been subtracted - * from this number) - * @param f function to solve - * @param bracketing bracketing solver to use for shifting the root - * @param baseRoot original root found by a previous non-bracketing solver - * @param min minimal bound of the search interval - * @param max maximal bound of the search interval - * @param allowedSolution the kind of solutions that the root-finding algorithm may - * accept as solutions. - * @return a root approximation, on the specified side of the exact root - * @throws NoBracketingException if the function has the same sign at the - * endpoints. - */ - public static double forceSide(final int maxEval, final UnivariateFunction f, - final BracketedUnivariateSolver bracketing, - final double baseRoot, final double min, final double max, - final AllowedSolution allowedSolution) - throws NoBracketingException { - - if (allowedSolution == AllowedSolution.ANY_SIDE) { - // no further bracketing required - return baseRoot; - } - - // find a very small interval bracketing the root - final double step = FastMath.max(bracketing.getAbsoluteAccuracy(), - FastMath.abs(baseRoot * bracketing.getRelativeAccuracy())); - double xLo = FastMath.max(min, baseRoot - step); - double fLo = f.value(xLo); - double xHi = FastMath.min(max, baseRoot + step); - double fHi = f.value(xHi); - int remainingEval = maxEval - 2; - while (remainingEval > 0) { - - if ((fLo >= 0 && fHi <= 0) || (fLo <= 0 && fHi >= 0)) { - // compute the root on the selected side - return bracketing.solve(remainingEval, f, xLo, xHi, baseRoot, allowedSolution); - } - - // try increasing the interval - boolean changeLo = false; - boolean changeHi = false; - if (fLo < fHi) { - // increasing function - if (fLo >= 0) { - changeLo = true; - } else { - changeHi = true; - } - } else if (fLo > fHi) { - // decreasing function - if (fLo <= 0) { - changeLo = true; - } else { - changeHi = true; - } - } else { - // unknown variation - changeLo = true; - changeHi = true; - } - - // update the lower bound - if (changeLo) { - xLo = FastMath.max(min, xLo - step); - fLo = f.value(xLo); - remainingEval--; - } - - // update the higher bound - if (changeHi) { - xHi = FastMath.min(max, xHi + step); - fHi = f.value(xHi); - remainingEval--; - } - - } - - throw new NoBracketingException(LocalizedFormats.FAILED_BRACKETING, - xLo, xHi, fLo, fHi, - maxEval - remainingEval, maxEval, baseRoot, - min, max); - - } - - /** - * This method simply calls {@link #bracket(UnivariateFunction, double, double, double, - * double, double, int) bracket(function, initial, lowerBound, upperBound, q, r, maximumIterations)} - * with {@code q} and {@code r} set to 1.0 and {@code maximumIterations} set to {@code Integer.MAX_VALUE}. - *

- * Note: this method can take {@code Integer.MAX_VALUE} - * iterations to throw a {@code ConvergenceException.} Unless you are - * confident that there is a root between {@code lowerBound} and - * {@code upperBound} near {@code initial}, it is better to use - * {@link #bracket(UnivariateFunction, double, double, double, double,double, int) - * bracket(function, initial, lowerBound, upperBound, q, r, maximumIterations)}, - * explicitly specifying the maximum number of iterations.

- * - * @param function Function. - * @param initial Initial midpoint of interval being expanded to - * bracket a root. - * @param lowerBound Lower bound (a is never lower than this value) - * @param upperBound Upper bound (b never is greater than this - * value). - * @return a two-element array holding a and b. - * @throws NoBracketingException if a root cannot be bracketted. - * @throws NotStrictlyPositiveException if {@code maximumIterations <= 0}. - * @throws NullArgumentException if {@code function} is {@code null}. - */ - public static double[] bracket(UnivariateFunction function, - double initial, - double lowerBound, double upperBound) - throws NullArgumentException, - NotStrictlyPositiveException, - NoBracketingException { - return bracket(function, initial, lowerBound, upperBound, 1.0, 1.0, Integer.MAX_VALUE); - } - - /** - * This method simply calls {@link #bracket(UnivariateFunction, double, double, double, - * double, double, int) bracket(function, initial, lowerBound, upperBound, q, r, maximumIterations)} - * with {@code q} and {@code r} set to 1.0. - * @param function Function. - * @param initial Initial midpoint of interval being expanded to - * bracket a root. - * @param lowerBound Lower bound (a is never lower than this value). - * @param upperBound Upper bound (b never is greater than this - * value). - * @param maximumIterations Maximum number of iterations to perform - * @return a two element array holding a and b. - * @throws NoBracketingException if the algorithm fails to find a and b - * satisfying the desired conditions. - * @throws NotStrictlyPositiveException if {@code maximumIterations <= 0}. - * @throws NullArgumentException if {@code function} is {@code null}. - */ - public static double[] bracket(UnivariateFunction function, - double initial, - double lowerBound, double upperBound, - int maximumIterations) - throws NullArgumentException, - NotStrictlyPositiveException, - NoBracketingException { - return bracket(function, initial, lowerBound, upperBound, 1.0, 1.0, maximumIterations); - } - - /** - * This method attempts to find two values a and b satisfying
    - *
  • {@code lowerBound <= a < initial < b <= upperBound}
  • - *
  • {@code f(a) * f(b) <= 0}
  • - *
- * If {@code f} is continuous on {@code [a,b]}, this means that {@code a} - * and {@code b} bracket a root of {@code f}. - *

- * The algorithm checks the sign of \( f(l_k) \) and \( f(u_k) \) for increasing - * values of k, where \( l_k = max(lower, initial - \delta_k) \), - * \( u_k = min(upper, initial + \delta_k) \), using recurrence - * \( \delta_{k+1} = r \delta_k + q, \delta_0 = 0\) and starting search with \( k=1 \). - * The algorithm stops when one of the following happens:

    - *
  • at least one positive and one negative value have been found -- success!
  • - *
  • both endpoints have reached their respective limits -- NoBracketingException
  • - *
  • {@code maximumIterations} iterations elapse -- NoBracketingException
- *

- * If different signs are found at first iteration ({@code k=1}), then the returned - * interval will be \( [a, b] = [l_1, u_1] \). If different signs are found at a later - * iteration {@code k>1}, then the returned interval will be either - * \( [a, b] = [l_{k+1}, l_{k}] \) or \( [a, b] = [u_{k}, u_{k+1}] \). A root solver called - * with these parameters will therefore start with the smallest bracketing interval known - * at this step. - *

- *

- * Interval expansion rate is tuned by changing the recurrence parameters {@code r} and - * {@code q}. When the multiplicative factor {@code r} is set to 1, the sequence is a - * simple arithmetic sequence with linear increase. When the multiplicative factor {@code r} - * is larger than 1, the sequence has an asymptotically exponential rate. Note than the - * additive parameter {@code q} should never be set to zero, otherwise the interval would - * degenerate to the single initial point for all values of {@code k}. - *

- *

- * As a rule of thumb, when the location of the root is expected to be approximately known - * within some error margin, {@code r} should be set to 1 and {@code q} should be set to the - * order of magnitude of the error margin. When the location of the root is really a wild guess, - * then {@code r} should be set to a value larger than 1 (typically 2 to double the interval - * length at each iteration) and {@code q} should be set according to half the initial - * search interval length. - *

- *

- * As an example, if we consider the trivial function {@code f(x) = 1 - x} and use - * {@code initial = 4}, {@code r = 1}, {@code q = 2}, the algorithm will compute - * {@code f(4-2) = f(2) = -1} and {@code f(4+2) = f(6) = -5} for {@code k = 1}, then - * {@code f(4-4) = f(0) = +1} and {@code f(4+4) = f(8) = -7} for {@code k = 2}. Then it will - * return the interval {@code [0, 2]} as the smallest one known to be bracketing the root. - * As shown by this example, the initial value (here {@code 4}) may lie outside of the returned - * bracketing interval. - *

- * @param function function to check - * @param initial Initial midpoint of interval being expanded to - * bracket a root. - * @param lowerBound Lower bound (a is never lower than this value). - * @param upperBound Upper bound (b never is greater than this - * value). - * @param q additive offset used to compute bounds sequence (must be strictly positive) - * @param r multiplicative factor used to compute bounds sequence - * @param maximumIterations Maximum number of iterations to perform - * @return a two element array holding the bracketing values. - * @exception NoBracketingException if function cannot be bracketed in the search interval - */ - public static double[] bracket(final UnivariateFunction function, final double initial, - final double lowerBound, final double upperBound, - final double q, final double r, final int maximumIterations) - throws NoBracketingException { - - if (function == null) { - throw new NullArgumentException(LocalizedFormats.FUNCTION); - } - if (q <= 0) { - throw new NotStrictlyPositiveException(q); - } - if (maximumIterations <= 0) { - throw new NotStrictlyPositiveException(LocalizedFormats.INVALID_MAX_ITERATIONS, maximumIterations); - } - verifySequence(lowerBound, initial, upperBound); - - // initialize the recurrence - double a = initial; - double b = initial; - double fa = Double.NaN; - double fb = Double.NaN; - double delta = 0; - - for (int numIterations = 0; - (numIterations < maximumIterations) && (a > lowerBound || b < upperBound); - ++numIterations) { - - final double previousA = a; - final double previousFa = fa; - final double previousB = b; - final double previousFb = fb; - - delta = r * delta + q; - a = FastMath.max(initial - delta, lowerBound); - b = FastMath.min(initial + delta, upperBound); - fa = function.value(a); - fb = function.value(b); - - if (numIterations == 0) { - // at first iteration, we don't have a previous interval - // we simply compare both sides of the initial interval - if (fa * fb <= 0) { - // the first interval already brackets a root - return new double[] { a, b }; - } - } else { - // we have a previous interval with constant sign and expand it, - // we expect sign changes to occur at boundaries - if (fa * previousFa <= 0) { - // sign change detected at near lower bound - return new double[] { a, previousA }; - } else if (fb * previousFb <= 0) { - // sign change detected at near upper bound - return new double[] { previousB, b }; - } - } - - } - - // no bracketing found - throw new NoBracketingException(a, b, fa, fb); - - } - - /** - * Compute the midpoint of two values. - * - * @param a first value. - * @param b second value. - * @return the midpoint. - */ - public static double midpoint(double a, double b) { - return (a + b) * 0.5; - } - - /** - * Check whether the interval bounds bracket a root. That is, if the - * values at the endpoints are not equal to zero, then the function takes - * opposite signs at the endpoints. - * - * @param function Function. - * @param lower Lower endpoint. - * @param upper Upper endpoint. - * @return {@code true} if the function values have opposite signs at the - * given points. - * @throws NullArgumentException if {@code function} is {@code null}. - */ - public static boolean isBracketing(UnivariateFunction function, - final double lower, - final double upper) - throws NullArgumentException { - if (function == null) { - throw new NullArgumentException(LocalizedFormats.FUNCTION); - } - final double fLo = function.value(lower); - final double fHi = function.value(upper); - return (fLo >= 0 && fHi <= 0) || (fLo <= 0 && fHi >= 0); - } - - /** - * Check whether the arguments form a (strictly) increasing sequence. - * - * @param start First number. - * @param mid Second number. - * @param end Third number. - * @return {@code true} if the arguments form an increasing sequence. - */ - public static boolean isSequence(final double start, - final double mid, - final double end) { - return (start < mid) && (mid < end); - } - - /** - * Check that the endpoints specify an interval. - * - * @param lower Lower endpoint. - * @param upper Upper endpoint. - * @throws NumberIsTooLargeException if {@code lower >= upper}. - */ - public static void verifyInterval(final double lower, - final double upper) - throws NumberIsTooLargeException { - if (lower >= upper) { - throw new NumberIsTooLargeException(LocalizedFormats.ENDPOINTS_NOT_AN_INTERVAL, - lower, upper, false); - } - } - - /** - * Check that {@code lower < initial < upper}. - * - * @param lower Lower endpoint. - * @param initial Initial value. - * @param upper Upper endpoint. - * @throws NumberIsTooLargeException if {@code lower >= initial} or - * {@code initial >= upper}. - */ - public static void verifySequence(final double lower, - final double initial, - final double upper) - throws NumberIsTooLargeException { - verifyInterval(lower, initial); - verifyInterval(initial, upper); - } - - /** - * Check that the endpoints specify an interval and the end points - * bracket a root. - * - * @param function Function. - * @param lower Lower endpoint. - * @param upper Upper endpoint. - * @throws NoBracketingException if the function has the same sign at the - * endpoints. - * @throws NullArgumentException if {@code function} is {@code null}. - */ - public static void verifyBracketing(UnivariateFunction function, - final double lower, - final double upper) - throws NullArgumentException, - NoBracketingException { - if (function == null) { - throw new NullArgumentException(LocalizedFormats.FUNCTION); - } - verifyInterval(lower, upper); - if (!isBracketing(function, lower, upper)) { - throw new NoBracketingException(lower, upper, - function.value(lower), - function.value(upper)); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/package-info.java deleted file mode 100644 index 95d466079..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/analysis/solvers/package-info.java +++ /dev/null @@ -1,22 +0,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. - */ -/** - * - * Root finding algorithms, for univariate real functions. - * - */ -package org.apache.commons.math4.analysis.solvers; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/AbstractIntegerDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/AbstractIntegerDistribution.java deleted file mode 100644 index b35a97bf4..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/AbstractIntegerDistribution.java +++ /dev/null @@ -1,227 +0,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. - */ -package org.apache.commons.math4.distribution; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathInternalError; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.InverseTransformDiscreteSampler; -import org.apache.commons.rng.sampling.distribution.DiscreteInverseCumulativeProbabilityFunction; -import org.apache.commons.rng.sampling.distribution.DiscreteSampler; -import org.apache.commons.math4.util.FastMath; - -/** - * Base class for integer-valued discrete distributions. Default - * implementations are provided for some of the methods that do not vary - * from distribution to distribution. - * - */ -public abstract class AbstractIntegerDistribution implements IntegerDistribution, Serializable { - /** Serializable version identifier */ - private static final long serialVersionUID = 20160318L; - - /** - * {@inheritDoc} - * - * The default implementation uses the identity - *

{@code P(x0 < X <= x1) = P(X <= x1) - P(X <= x0)}

- * - * @since 4.0, was previously named cumulativeProbability - */ - @Override - public double probability(int x0, int x1) throws NumberIsTooLargeException { - if (x1 < x0) { - throw new NumberIsTooLargeException(LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT, - x0, x1, true); - } - return cumulativeProbability(x1) - cumulativeProbability(x0); - } - - /** - * {@inheritDoc} - * - * The default implementation returns - *
    - *
  • {@link #getSupportLowerBound()} for {@code p = 0},
  • - *
  • {@link #getSupportUpperBound()} for {@code p = 1}, and
  • - *
  • {@link #solveInverseCumulativeProbability(double, int, int)} for - * {@code 0 < p < 1}.
  • - *
- */ - @Override - public int inverseCumulativeProbability(final double p) throws OutOfRangeException { - if (p < 0.0 || p > 1.0) { - throw new OutOfRangeException(p, 0, 1); - } - - int lower = getSupportLowerBound(); - if (p == 0.0) { - return lower; - } - if (lower == Integer.MIN_VALUE) { - if (checkedCumulativeProbability(lower) >= p) { - return lower; - } - } else { - lower -= 1; // this ensures cumulativeProbability(lower) < p, which - // is important for the solving step - } - - int upper = getSupportUpperBound(); - if (p == 1.0) { - return upper; - } - - // use the one-sided Chebyshev inequality to narrow the bracket - // cf. AbstractRealDistribution.inverseCumulativeProbability(double) - final double mu = getMean(); - final double sigma = FastMath.sqrt(getVariance()); - final boolean chebyshevApplies = !(Double.isInfinite(mu) || Double.isNaN(mu) || - Double.isInfinite(sigma) || Double.isNaN(sigma) || sigma == 0.0); - if (chebyshevApplies) { - double k = FastMath.sqrt((1.0 - p) / p); - double tmp = mu - k * sigma; - if (tmp > lower) { - lower = ((int) FastMath.ceil(tmp)) - 1; - } - k = 1.0 / k; - tmp = mu + k * sigma; - if (tmp < upper) { - upper = ((int) FastMath.ceil(tmp)) - 1; - } - } - - return solveInverseCumulativeProbability(p, lower, upper); - } - - /** - * This is a utility function used by {@link - * #inverseCumulativeProbability(double)}. It assumes {@code 0 < p < 1} and - * that the inverse cumulative probability lies in the bracket {@code - * (lower, upper]}. The implementation does simple bisection to find the - * smallest {@code p}-quantile {@code inf{x in Z | P(X<=x) >= p}}. - * - * @param p the cumulative probability - * @param lower a value satisfying {@code cumulativeProbability(lower) < p} - * @param upper a value satisfying {@code p <= cumulativeProbability(upper)} - * @return the smallest {@code p}-quantile of this distribution - */ - protected int solveInverseCumulativeProbability(final double p, int lower, int upper) { - while (lower + 1 < upper) { - int xm = (lower + upper) / 2; - if (xm < lower || xm > upper) { - /* - * Overflow. - * There will never be an overflow in both calculation methods - * for xm at the same time - */ - xm = lower + (upper - lower) / 2; - } - - double pm = checkedCumulativeProbability(xm); - if (pm >= p) { - upper = xm; - } else { - lower = xm; - } - } - return upper; - } - - /** - * Computes the cumulative probability function and checks for {@code NaN} - * values returned. Throws {@code MathInternalError} if the value is - * {@code NaN}. Rethrows any exception encountered evaluating the cumulative - * probability function. Throws {@code MathInternalError} if the cumulative - * probability function returns {@code NaN}. - * - * @param argument input value - * @return the cumulative probability - * @throws MathInternalError if the cumulative probability is {@code NaN} - */ - private double checkedCumulativeProbability(int argument) - throws MathInternalError { - final double result = cumulativeProbability(argument); - if (Double.isNaN(result)) { - throw new MathInternalError(LocalizedFormats - .DISCRETE_CUMULATIVE_PROBABILITY_RETURNED_NAN, argument); - } - return result; - } - - /** - * {@inheritDoc} - *

- * The default implementation simply computes the logarithm of {@code probability(x)}. - */ - @Override - public double logProbability(int x) { - return FastMath.log(probability(x)); - } - - /** - * Utility function for allocating an array and filling it with {@code n} - * samples generated by the given {@code sampler}. - * - * @param n Number of samples. - * @param sampler Sampler. - * @return an array of size {@code n}. - */ - public static int[] sample(int n, - Sampler sampler) { - final int[] samples = new int[n]; - for (int i = 0; i < n; i++) { - samples[i] = sampler.sample(); - } - return samples; - } - - /**{@inheritDoc} */ - @Override - public Sampler createSampler(final UniformRandomProvider rng) { - return new Sampler() { - /** - * Inversion method distribution sampler. - */ - private final DiscreteSampler sampler = - new InverseTransformDiscreteSampler(rng, createICPF()); - - /** {@inheritDoc} */ - @Override - public int sample() { - return sampler.sample(); - } - }; - } - - /** - * @return an instance for use by {@link #createSampler(UniformRandomProvider)} - */ - private DiscreteInverseCumulativeProbabilityFunction createICPF() { - return new DiscreteInverseCumulativeProbabilityFunction() { - /** {@inheritDoc} */ - @Override - public int inverseCumulativeProbability(double p) { - return AbstractIntegerDistribution.this.inverseCumulativeProbability(p); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/AbstractMultivariateRealDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/AbstractMultivariateRealDistribution.java deleted file mode 100644 index f48d188b4..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/AbstractMultivariateRealDistribution.java +++ /dev/null @@ -1,72 +0,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. - */ -package org.apache.commons.math4.distribution; - -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Base class for multivariate probability distributions. - * - * @since 3.1 - */ -public abstract class AbstractMultivariateRealDistribution - implements MultivariateRealDistribution { - /** The number of dimensions or columns in the multivariate distribution. */ - private final int dimension; - - /** - * @param n Number of dimensions. - */ - protected AbstractMultivariateRealDistribution(int n) { - dimension = n; - } - - /** {@inheritDoc} */ - @Override - public int getDimension() { - return dimension; - } - - /** {@inheritDoc} */ - @Override - public abstract Sampler createSampler(UniformRandomProvider rng); - - /** - * Utility function for creating {@code n} vectors generated by the - * given {@code sampler}. - * - * @param n Number of samples. - * @param sampler Sampler. - * @return an array of size {@code n} whose elements are random vectors - * sampled from this distribution. - */ - public static double[][] sample(int n, - MultivariateRealDistribution.Sampler sampler) { - if (n <= 0) { - throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES, - n); - } - - final double[][] samples = new double[n][]; - for (int i = 0; i < n; i++) { - samples[i] = sampler.sample(); - } - return samples; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/AbstractRealDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/AbstractRealDistribution.java deleted file mode 100644 index 20f02ab63..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/AbstractRealDistribution.java +++ /dev/null @@ -1,277 +0,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. - */ -package org.apache.commons.math4.distribution; - -import java.io.Serializable; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.analysis.solvers.UnivariateSolverUtils; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.InverseTransformContinuousSampler; -import org.apache.commons.rng.sampling.distribution.ContinuousInverseCumulativeProbabilityFunction; -import org.apache.commons.rng.sampling.distribution.ContinuousSampler; -import org.apache.commons.math4.util.FastMath; - -/** - * Base class for probability distributions on the reals. - * Default implementations are provided for some of the methods - * that do not vary from distribution to distribution. - * - *

- * This base class provides a default factory method for creating - * a {@link Sampler - * sampler instance} that uses the - * - * inversion method for generating random samples that follow the - * distribution. - *

- * - * @since 3.0 - */ -public abstract class AbstractRealDistribution - implements RealDistribution, - Serializable { - /** Default absolute accuracy for inverse cumulative computation. */ - public static final double SOLVER_DEFAULT_ABSOLUTE_ACCURACY = 1e-6; - /** Serializable version identifier */ - private static final long serialVersionUID = 20160311L; - - /** - * For a random variable {@code X} whose values are distributed according - * to this distribution, this method returns {@code P(x0 < X <= x1)}. - * - * @param x0 Lower bound (excluded). - * @param x1 Upper bound (included). - * @return the probability that a random variable with this distribution - * takes a value between {@code x0} and {@code x1}, excluding the lower - * and including the upper endpoint. - * @throws NumberIsTooLargeException if {@code x0 > x1}. - * - * The default implementation uses the identity - * {@code P(x0 < X <= x1) = P(X <= x1) - P(X <= x0)} - * - * @since 3.1 - */ - @Override - public double probability(double x0, - double x1) { - if (x0 > x1) { - throw new NumberIsTooLargeException(LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT, - x0, x1, true); - } - return cumulativeProbability(x1) - cumulativeProbability(x0); - } - - /** - * {@inheritDoc} - * - * The default implementation returns - *
    - *
  • {@link #getSupportLowerBound()} for {@code p = 0},
  • - *
  • {@link #getSupportUpperBound()} for {@code p = 1}.
  • - *
- */ - @Override - public double inverseCumulativeProbability(final double p) throws OutOfRangeException { - /* - * IMPLEMENTATION NOTES - * -------------------- - * Where applicable, use is made of the one-sided Chebyshev inequality - * to bracket the root. This inequality states that - * P(X - mu >= k * sig) <= 1 / (1 + k^2), - * mu: mean, sig: standard deviation. Equivalently - * 1 - P(X < mu + k * sig) <= 1 / (1 + k^2), - * F(mu + k * sig) >= k^2 / (1 + k^2). - * - * For k = sqrt(p / (1 - p)), we find - * F(mu + k * sig) >= p, - * and (mu + k * sig) is an upper-bound for the root. - * - * Then, introducing Y = -X, mean(Y) = -mu, sd(Y) = sig, and - * P(Y >= -mu + k * sig) <= 1 / (1 + k^2), - * P(-X >= -mu + k * sig) <= 1 / (1 + k^2), - * P(X <= mu - k * sig) <= 1 / (1 + k^2), - * F(mu - k * sig) <= 1 / (1 + k^2). - * - * For k = sqrt((1 - p) / p), we find - * F(mu - k * sig) <= p, - * and (mu - k * sig) is a lower-bound for the root. - * - * In cases where the Chebyshev inequality does not apply, geometric - * progressions 1, 2, 4, ... and -1, -2, -4, ... are used to bracket - * the root. - */ - if (p < 0.0 || p > 1.0) { - throw new OutOfRangeException(p, 0, 1); - } - - double lowerBound = getSupportLowerBound(); - if (p == 0.0) { - return lowerBound; - } - - double upperBound = getSupportUpperBound(); - if (p == 1.0) { - return upperBound; - } - - final double mu = getMean(); - final double sig = FastMath.sqrt(getVariance()); - final boolean chebyshevApplies; - chebyshevApplies = !(Double.isInfinite(mu) || Double.isNaN(mu) || - Double.isInfinite(sig) || Double.isNaN(sig)); - - if (lowerBound == Double.NEGATIVE_INFINITY) { - if (chebyshevApplies) { - lowerBound = mu - sig * FastMath.sqrt((1. - p) / p); - } else { - lowerBound = -1.0; - while (cumulativeProbability(lowerBound) >= p) { - lowerBound *= 2.0; - } - } - } - - if (upperBound == Double.POSITIVE_INFINITY) { - if (chebyshevApplies) { - upperBound = mu + sig * FastMath.sqrt(p / (1. - p)); - } else { - upperBound = 1.0; - while (cumulativeProbability(upperBound) < p) { - upperBound *= 2.0; - } - } - } - - final UnivariateFunction toSolve = new UnivariateFunction() { - /** {@inheritDoc} */ - @Override - public double value(final double x) { - return cumulativeProbability(x) - p; - } - }; - - double x = UnivariateSolverUtils.solve(toSolve, - lowerBound, - upperBound, - getSolverAbsoluteAccuracy()); - - if (!isSupportConnected()) { - /* Test for plateau. */ - final double dx = getSolverAbsoluteAccuracy(); - if (x - dx >= getSupportLowerBound()) { - double px = cumulativeProbability(x); - if (cumulativeProbability(x - dx) == px) { - upperBound = x; - while (upperBound - lowerBound > dx) { - final double midPoint = 0.5 * (lowerBound + upperBound); - if (cumulativeProbability(midPoint) < px) { - lowerBound = midPoint; - } else { - upperBound = midPoint; - } - } - return upperBound; - } - } - } - return x; - } - - /** - * Returns the solver absolute accuracy for inverse cumulative computation. - * You can override this method in order to use a Brent solver with an - * absolute accuracy different from the default. - * - * @return the maximum absolute error in inverse cumulative probability estimates - */ - protected double getSolverAbsoluteAccuracy() { - return SOLVER_DEFAULT_ABSOLUTE_ACCURACY; - } - - /** - * {@inheritDoc} - * - * @return zero. - * @since 3.1 - */ - @Override - public double probability(double x) { - return 0d; - } - - /** - * {@inheritDoc} - *

- * The default implementation simply computes the logarithm of {@code density(x)}. - */ - @Override - public double logDensity(double x) { - return FastMath.log(density(x)); - } - - /** - * Utility function for allocating an array and filling it with {@code n} - * samples generated by the given {@code sampler}. - * - * @param n Number of samples. - * @param sampler Sampler. - * @return an array of size {@code n}. - */ - public static double[] sample(int n, - Sampler sampler) { - final double[] samples = new double[n]; - for (int i = 0; i < n; i++) { - samples[i] = sampler.sample(); - } - return samples; - } - - /**{@inheritDoc} */ - @Override - public Sampler createSampler(final UniformRandomProvider rng) { - return new Sampler() { - /** - * Inversion method distribution sampler. - */ - private final ContinuousSampler sampler = - new InverseTransformContinuousSampler(rng, createICPF()); - - /** {@inheritDoc} */ - @Override - public double sample() { - return sampler.sample(); - } - }; - } - - /** - * @return an instance for use by {@link #createSampler(UniformRandomProvider)} - */ - private ContinuousInverseCumulativeProbabilityFunction createICPF() { - return new ContinuousInverseCumulativeProbabilityFunction() { - /** {@inheritDoc} */ - @Override - public double inverseCumulativeProbability(double p) { - return AbstractRealDistribution.this.inverseCumulativeProbability(p); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/EmpiricalDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/EmpiricalDistribution.java deleted file mode 100644 index 65ee260d1..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/EmpiricalDistribution.java +++ /dev/null @@ -1,747 +0,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. - */ - -package org.apache.commons.math4.distribution; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.statistics.distribution.NormalDistribution; -import org.apache.commons.statistics.distribution.ContinuousDistribution; -import org.apache.commons.statistics.distribution.ConstantContinuousDistribution; -import org.apache.commons.math4.exception.MathIllegalStateException; -import org.apache.commons.math4.exception.MathInternalError; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.ZeroException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.stat.descriptive.StatisticalSummary; -import org.apache.commons.math4.stat.descriptive.SummaryStatistics; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathUtils; - -/** - *

Represents an - * empirical probability distribution -- a probability distribution derived - * from observed data without making any assumptions about the functional form - * of the population distribution that the data come from.

- * - *

An EmpiricalDistribution maintains data structures, called - * distribution digests, that describe empirical distributions and - * support the following operations:

    - *
  • loading the distribution from a file of observed data values
  • - *
  • dividing the input data into "bin ranges" and reporting bin frequency - * counts (data for histogram)
  • - *
  • reporting univariate statistics describing the full set of data values - * as well as the observations within each bin
  • - *
  • generating random values from the distribution
  • - *
- * Applications can use EmpiricalDistribution to build grouped - * frequency histograms representing the input data or to generate random values - * "like" those in the input file -- i.e., the values generated will follow the - * distribution of the values in the file. - * - *

The implementation uses what amounts to the - * - * Variable Kernel Method with Gaussian smoothing:

- * Digesting the input file - *

  1. Pass the file once to compute min and max.
  2. - *
  3. Divide the range from min-max into binCount "bins."
  4. - *
  5. Pass the data file again, computing bin counts and univariate - * statistics (mean, std dev.) for each of the bins
  6. - *
  7. Divide the interval (0,1) into subintervals associated with the bins, - * with the length of a bin's subinterval proportional to its count.
- * Generating random values from the distribution
    - *
  1. Generate a uniformly distributed value in (0,1)
  2. - *
  3. Select the subinterval to which the value belongs. - *
  4. Generate a random Gaussian value with mean = mean of the associated - * bin and std dev = std dev of associated bin.
- * - *

EmpiricalDistribution implements the {@link RealDistribution} interface - * as follows. Given x within the range of values in the dataset, let B - * be the bin containing x and let K be the within-bin kernel for B. Let P(B-) - * be the sum of the probabilities of the bins below B and let K(B) be the - * mass of B under K (i.e., the integral of the kernel density over B). Then - * set {@code P(X < x) = P(B-) + P(B) * K(x) / K(B)} where {@code K(x)} is the - * kernel distribution evaluated at x. This results in a cdf that matches the - * grouped frequency distribution at the bin endpoints and interpolates within - * bins using within-bin kernels.

- * - *USAGE NOTES:
    - *
  • The binCount is set by default to 1000. A good rule of thumb - * is to set the bin count to approximately the length of the input file divided - * by 10.
  • - *
  • The input file must be a plain text file containing one valid numeric - * entry per line.
  • - *
- * - */ -public class EmpiricalDistribution extends AbstractRealDistribution - implements ContinuousDistribution { - - /** Default bin count */ - public static final int DEFAULT_BIN_COUNT = 1000; - - /** Character set for file input */ - private static final String FILE_CHARSET = "US-ASCII"; - - /** Serializable version identifier */ - private static final long serialVersionUID = 5729073523949762654L; - - /** List of SummaryStatistics objects characterizing the bins */ - private final List binStats; - - /** Sample statistics */ - private SummaryStatistics sampleStats = null; - - /** Max loaded value */ - private double max = Double.NEGATIVE_INFINITY; - - /** Min loaded value */ - private double min = Double.POSITIVE_INFINITY; - - /** Grid size */ - private double delta = 0d; - - /** number of bins */ - private final int binCount; - - /** is the distribution loaded? */ - private boolean loaded = false; - - /** upper bounds of subintervals in (0,1) "belonging" to the bins */ - private double[] upperBounds = null; - - /** - * Creates a new EmpiricalDistribution with the default bin count. - */ - public EmpiricalDistribution() { - this(DEFAULT_BIN_COUNT); - } - - /** - * Creates a new EmpiricalDistribution with the specified bin count. - * - * @param binCount number of bins. Must be strictly positive. - * @throws NotStrictlyPositiveException if {@code binCount <= 0}. - */ - public EmpiricalDistribution(int binCount) { - if (binCount <= 0) { - throw new NotStrictlyPositiveException(binCount); - } - this.binCount = binCount; - binStats = new ArrayList<>(); - } - - /** - * Computes the empirical distribution from the provided - * array of numbers. - * - * @param in the input data array - * @exception NullArgumentException if in is null - */ - public void load(double[] in) throws NullArgumentException { - DataAdapter da = new ArrayDataAdapter(in); - try { - da.computeStats(); - // new adapter for the second pass - fillBinStats(new ArrayDataAdapter(in)); - } catch (IOException ex) { - // Can't happen - throw new MathInternalError(); - } - loaded = true; - - } - - /** - * Computes the empirical distribution using data read from a URL. - * - *

The input file must be an ASCII text file containing one - * valid numeric entry per line.

- * - * @param url url of the input file - * - * @throws IOException if an IO error occurs - * @throws NullArgumentException if url is null - * @throws ZeroException if URL contains no data - */ - public void load(URL url) throws IOException, NullArgumentException, ZeroException { - MathUtils.checkNotNull(url); - Charset charset = Charset.forName(FILE_CHARSET); - BufferedReader in = - new BufferedReader(new InputStreamReader(url.openStream(), charset)); - try { - DataAdapter da = new StreamDataAdapter(in); - da.computeStats(); - if (sampleStats.getN() == 0) { - throw new ZeroException(LocalizedFormats.URL_CONTAINS_NO_DATA, url); - } - // new adapter for the second pass - in = new BufferedReader(new InputStreamReader(url.openStream(), charset)); - fillBinStats(new StreamDataAdapter(in)); - loaded = true; - } finally { - try { - in.close(); - } catch (IOException ex) { //NOPMD - // ignore - } - } - } - - /** - * Computes the empirical distribution from the input file. - * - *

The input file must be an ASCII text file containing one - * valid numeric entry per line.

- * - * @param file the input file - * @throws IOException if an IO error occurs - * @throws NullArgumentException if file is null - */ - public void load(File file) throws IOException, NullArgumentException { - MathUtils.checkNotNull(file); - Charset charset = Charset.forName(FILE_CHARSET); - InputStream is = new FileInputStream(file); - BufferedReader in = new BufferedReader(new InputStreamReader(is, charset)); - try { - DataAdapter da = new StreamDataAdapter(in); - da.computeStats(); - // new adapter for second pass - is = new FileInputStream(file); - in = new BufferedReader(new InputStreamReader(is, charset)); - fillBinStats(new StreamDataAdapter(in)); - loaded = true; - } finally { - try { - in.close(); - } catch (IOException ex) { //NOPMD - // ignore - } - } - } - - /** - * Provides methods for computing sampleStats and - * beanStats abstracting the source of data. - */ - private abstract class DataAdapter{ - - /** - * Compute bin stats. - * - * @throws IOException if an error occurs computing bin stats - */ - public abstract void computeBinStats() throws IOException; - - /** - * Compute sample statistics. - * - * @throws IOException if an error occurs computing sample stats - */ - public abstract void computeStats() throws IOException; - - } - - /** - * DataAdapter for data provided through some input stream - */ - private class StreamDataAdapter extends DataAdapter{ - - /** Input stream providing access to the data */ - private BufferedReader inputStream; - - /** - * Create a StreamDataAdapter from a BufferedReader - * - * @param in BufferedReader input stream - */ - StreamDataAdapter(BufferedReader in){ - super(); - inputStream = in; - } - - /** {@inheritDoc} */ - @Override - public void computeBinStats() throws IOException { - String str = null; - double val = 0.0d; - while ((str = inputStream.readLine()) != null) { - val = Double.parseDouble(str); - SummaryStatistics stats = binStats.get(findBin(val)); - stats.addValue(val); - } - - inputStream.close(); - inputStream = null; - } - - /** {@inheritDoc} */ - @Override - public void computeStats() throws IOException { - String str = null; - double val = 0.0; - sampleStats = new SummaryStatistics(); - while ((str = inputStream.readLine()) != null) { - val = Double.parseDouble(str); - sampleStats.addValue(val); - } - inputStream.close(); - inputStream = null; - } - } - - /** - * DataAdapter for data provided as array of doubles. - */ - private class ArrayDataAdapter extends DataAdapter { - - /** Array of input data values */ - private final double[] inputArray; - - /** - * Construct an ArrayDataAdapter from a double[] array - * - * @param in double[] array holding the data - * @throws NullArgumentException if in is null - */ - ArrayDataAdapter(double[] in) throws NullArgumentException { - super(); - MathUtils.checkNotNull(in); - inputArray = in; - } - - /** {@inheritDoc} */ - @Override - public void computeStats() throws IOException { - sampleStats = new SummaryStatistics(); - for (int i = 0; i < inputArray.length; i++) { - sampleStats.addValue(inputArray[i]); - } - } - - /** {@inheritDoc} */ - @Override - public void computeBinStats() throws IOException { - for (int i = 0; i < inputArray.length; i++) { - SummaryStatistics stats = - binStats.get(findBin(inputArray[i])); - stats.addValue(inputArray[i]); - } - } - } - - /** - * Fills binStats array (second pass through data file). - * - * @param da object providing access to the data - * @throws IOException if an IO error occurs - */ - private void fillBinStats(final DataAdapter da) - throws IOException { - // Set up grid - min = sampleStats.getMin(); - max = sampleStats.getMax(); - delta = (max - min)/binCount; - - // Initialize binStats ArrayList - if (!binStats.isEmpty()) { - binStats.clear(); - } - for (int i = 0; i < binCount; i++) { - SummaryStatistics stats = new SummaryStatistics(); - binStats.add(i,stats); - } - - // Filling data in binStats Array - da.computeBinStats(); - - // Assign upperBounds based on bin counts - upperBounds = new double[binCount]; - upperBounds[0] = - ((double) binStats.get(0).getN()) / (double) sampleStats.getN(); - for (int i = 1; i < binCount-1; i++) { - upperBounds[i] = upperBounds[i-1] + - ((double) binStats.get(i).getN()) / (double) sampleStats.getN(); - } - upperBounds[binCount-1] = 1.0d; - } - - /** - * Returns the index of the bin to which the given value belongs - * - * @param value the value whose bin we are trying to find - * @return the index of the bin containing the value - */ - private int findBin(double value) { - return FastMath.min( - FastMath.max((int) FastMath.ceil((value - min) / delta) - 1, 0), - binCount - 1); - } - - /** - * Returns a {@link StatisticalSummary} describing this distribution. - * Preconditions:
    - *
  • the distribution must be loaded before invoking this method
- * - * @return the sample statistics - * @throws IllegalStateException if the distribution has not been loaded - */ - public StatisticalSummary getSampleStats() { - return sampleStats; - } - - /** - * Returns the number of bins. - * - * @return the number of bins. - */ - public int getBinCount() { - return binCount; - } - - /** - * Returns a List of {@link SummaryStatistics} instances containing - * statistics describing the values in each of the bins. The list is - * indexed on the bin number. - * - * @return List of bin statistics. - */ - public List getBinStats() { - return binStats; - } - - /** - *

Returns a fresh copy of the array of upper bounds for the bins. - * Bins are:
- * [min,upperBounds[0]],(upperBounds[0],upperBounds[1]],..., - * (upperBounds[binCount-2], upperBounds[binCount-1] = max].

- * - *

Note: In versions 1.0-2.0 of commons-math, this method - * incorrectly returned the array of probability generator upper - * bounds now returned by {@link #getGeneratorUpperBounds()}.

- * - * @return array of bin upper bounds - * @since 2.1 - */ - public double[] getUpperBounds() { - double[] binUpperBounds = new double[binCount]; - for (int i = 0; i < binCount - 1; i++) { - binUpperBounds[i] = min + delta * (i + 1); - } - binUpperBounds[binCount - 1] = max; - return binUpperBounds; - } - - /** - *

Returns a fresh copy of the array of upper bounds of the subintervals - * of [0,1] used in generating data from the empirical distribution. - * Subintervals correspond to bins with lengths proportional to bin counts.

- * - * Preconditions:
    - *
  • the distribution must be loaded before invoking this method
- * - *

In versions 1.0-2.0 of commons-math, this array was (incorrectly) returned - * by {@link #getUpperBounds()}.

- * - * @since 2.1 - * @return array of upper bounds of subintervals used in data generation - * @throws NullPointerException unless a {@code load} method has been - * called beforehand. - */ - public double[] getGeneratorUpperBounds() { - int len = upperBounds.length; - double[] out = new double[len]; - System.arraycopy(upperBounds, 0, out, 0, len); - return out; - } - - /** - * Property indicating whether or not the distribution has been loaded. - * - * @return true if the distribution has been loaded - */ - public boolean isLoaded() { - return loaded; - } - - // Distribution methods --------------------------- - - /** - * {@inheritDoc} - * @since 3.1 - */ - @Override - public double probability(double x) { - return 0; - } - - /** - * {@inheritDoc} - * - *

Returns the kernel density normalized so that its integral over each bin - * equals the bin mass.

- * - *

Algorithm description:

    - *
  1. Find the bin B that x belongs to.
  2. - *
  3. Compute K(B) = the mass of B with respect to the within-bin kernel (i.e., the - * integral of the kernel density over B).
  4. - *
  5. Return k(x) * P(B) / K(B), where k is the within-bin kernel density - * and P(B) is the mass of B.
- * @since 3.1 - */ - @Override - public double density(double x) { - if (x < min || x > max) { - return 0d; - } - final int binIndex = findBin(x); - final ContinuousDistribution kernel = getKernel(binStats.get(binIndex)); - return kernel.density(x) * pB(binIndex) / kB(binIndex); - } - - /** - * {@inheritDoc} - * - *

Algorithm description:

    - *
  1. Find the bin B that x belongs to.
  2. - *
  3. Compute P(B) = the mass of B and P(B-) = the combined mass of the bins below B.
  4. - *
  5. Compute K(B) = the probability mass of B with respect to the within-bin kernel - * and K(B-) = the kernel distribution evaluated at the lower endpoint of B
  6. - *
  7. Return P(B-) + P(B) * [K(x) - K(B-)] / K(B) where - * K(x) is the within-bin kernel distribution function evaluated at x.
- * If K is a constant distribution, we return P(B-) + P(B) (counting the full - * mass of B). - * - * @since 3.1 - */ - @Override - public double cumulativeProbability(double x) { - if (x < min) { - return 0d; - } else if (x >= max) { - return 1d; - } - final int binIndex = findBin(x); - final double pBminus = pBminus(binIndex); - final double pB = pB(binIndex); - final ContinuousDistribution kernel = k(x); - if (kernel instanceof ConstantContinuousDistribution) { - if (x < kernel.getMean()) { - return pBminus; - } else { - return pBminus + pB; - } - } - final double[] binBounds = getUpperBounds(); - final double kB = kB(binIndex); - final double lower = binIndex == 0 ? min : binBounds[binIndex - 1]; - final double withinBinCum = - (kernel.cumulativeProbability(x) - kernel.cumulativeProbability(lower)) / kB; - return pBminus + pB * withinBinCum; - } - - /** - * {@inheritDoc} - * - *

Algorithm description:

    - *
  1. Find the smallest i such that the sum of the masses of the bins - * through i is at least p.
  2. - *
  3. - * Let K be the within-bin kernel distribution for bin i.
    - * Let K(B) be the mass of B under K.
    - * Let K(B-) be K evaluated at the lower endpoint of B (the combined - * mass of the bins below B under K).
    - * Let P(B) be the probability of bin i.
    - * Let P(B-) be the sum of the bin masses below bin i.
    - * Let pCrit = p - P(B-)
    - *
  4. Return the inverse of K evaluated at
    - * K(B-) + pCrit * K(B) / P(B)
  5. - *
- * - * @since 3.1 - */ - @Override - public double inverseCumulativeProbability(final double p) throws OutOfRangeException { - if (p < 0.0 || p > 1.0) { - throw new OutOfRangeException(p, 0, 1); - } - - if (p == 0.0) { - return getSupportLowerBound(); - } - - if (p == 1.0) { - return getSupportUpperBound(); - } - - int i = 0; - while (cumBinP(i) < p) { - i++; - } - - final ContinuousDistribution kernel = getKernel(binStats.get(i)); - final double kB = kB(i); - final double[] binBounds = getUpperBounds(); - final double lower = i == 0 ? min : binBounds[i - 1]; - final double kBminus = kernel.cumulativeProbability(lower); - final double pB = pB(i); - final double pBminus = pBminus(i); - final double pCrit = p - pBminus; - if (pCrit <= 0) { - return lower; - } - return kernel.inverseCumulativeProbability(kBminus + pCrit * kB / pB); - } - - /** - * {@inheritDoc} - * @since 3.1 - */ - @Override - public double getMean() { - return sampleStats.getMean(); - } - - /** - * {@inheritDoc} - * @since 3.1 - */ - @Override - public double getVariance() { - return sampleStats.getVariance(); - } - - /** - * {@inheritDoc} - * @since 3.1 - */ - @Override - public double getSupportLowerBound() { - return min; - } - - /** - * {@inheritDoc} - * @since 3.1 - */ - @Override - public double getSupportUpperBound() { - return max; - } - - /** - * {@inheritDoc} - * @since 3.1 - */ - @Override - public boolean isSupportConnected() { - return true; - } - - /**{@inheritDoc} */ - @Override - public Sampler createSampler(final UniformRandomProvider rng) { - if (!loaded) { - throw new MathIllegalStateException(LocalizedFormats.DISTRIBUTION_NOT_LOADED); - } - return super.createSampler(rng); - } - - /** - * The probability of bin i. - * - * @param i the index of the bin - * @return the probability that selection begins in bin i - */ - private double pB(int i) { - return i == 0 ? upperBounds[0] : - upperBounds[i] - upperBounds[i - 1]; - } - - /** - * The combined probability of the bins up to but not including bin i. - * - * @param i the index of the bin - * @return the probability that selection begins in a bin below bin i. - */ - private double pBminus(int i) { - return i == 0 ? 0 : upperBounds[i - 1]; - } - - /** - * Mass of bin i under the within-bin kernel of the bin. - * - * @param i index of the bin - * @return the difference in the within-bin kernel cdf between the - * upper and lower endpoints of bin i - */ - private double kB(int i) { - final double[] binBounds = getUpperBounds(); - final ContinuousDistribution kernel = getKernel(binStats.get(i)); - return i == 0 ? kernel.probability(min, binBounds[0]) : - kernel.probability(binBounds[i - 1], binBounds[i]); - } - - /** - * The within-bin kernel of the bin that x belongs to. - * - * @param x the value to locate within a bin - * @return the within-bin kernel of the bin containing x - */ - private ContinuousDistribution k(double x) { - final int binIndex = findBin(x); - return getKernel(binStats.get(binIndex)); - } - - /** - * The combined probability of the bins up to and including binIndex. - * - * @param binIndex maximum bin index - * @return sum of the probabilities of bins through binIndex - */ - private double cumBinP(int binIndex) { - return upperBounds[binIndex]; - } - - /** - * The within-bin smoothing kernel. Returns a Gaussian distribution - * parameterized by {@code bStats}, unless the bin contains only one - * observation, in which case a constant distribution is returned. - * - * @param bStats summary statistics for the bin - * @return within-bin kernel parameterized by bStats - */ - protected ContinuousDistribution getKernel(SummaryStatistics bStats) { - if (bStats.getN() == 1 || bStats.getVariance() == 0) { - return new ConstantContinuousDistribution(bStats.getMean()); - } else { - return new NormalDistribution(bStats.getMean(), bStats.getStandardDeviation()); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/EnumeratedDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/EnumeratedDistribution.java deleted file mode 100644 index 5b1cd302d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/EnumeratedDistribution.java +++ /dev/null @@ -1,255 +0,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. - */ -package org.apache.commons.math4.distribution; - -import java.io.Serializable; -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.NotANumberException; -import org.apache.commons.math4.exception.NotFiniteNumberException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.DiscreteProbabilityCollectionSampler; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.Pair; - -/** - *

A generic implementation of a - * - * discrete probability distribution (Wikipedia) over a finite sample space, - * based on an enumerated list of <value, probability> pairs. Input probabilities must all be non-negative, - * but zero values are allowed and their sum does not have to equal one. Constructors will normalize input - * probabilities to make them sum to one.

- * - *

The list of <value, probability> pairs does not, strictly speaking, have to be a function and it can - * contain null values. The pmf created by the constructor will combine probabilities of equal values and - * will treat null values as equal. For example, if the list of pairs <"dog", 0.2>, <null, 0.1>, - * <"pig", 0.2>, <"dog", 0.1>, <null, 0.4> is provided to the constructor, the resulting - * pmf will assign mass of 0.5 to null, 0.3 to "dog" and 0.2 to null.

- * - * @param type of the elements in the sample space. - * @since 3.2 - */ -public class EnumeratedDistribution implements Serializable { - /** Serializable UID. */ - private static final long serialVersionUID = 20160319L; - /** - * List of random variable values. - */ - private final List singletons; - /** - * Probabilities of respective random variable values. For i = 0, ..., singletons.size() - 1, - * probability[i] is the probability that a random variable following this distribution takes - * the value singletons[i]. - */ - private final double[] probabilities; - /** - * Cumulative probabilities, cached to speed up sampling. - */ - private final double[] cumulativeProbabilities; - - /** - * Create an enumerated distribution using the given random number generator - * and probability mass function enumeration. - * - * @param pmf probability mass function enumerated as a list of - * {@code } pairs. - * @throws NotPositiveException if any of the probabilities are negative. - * @throws NotFiniteNumberException if any of the probabilities are infinite. - * @throws NotANumberException if any of the probabilities are NaN. - * @throws MathArithmeticException all of the probabilities are 0. - */ - public EnumeratedDistribution(final List> pmf) - throws NotPositiveException, - MathArithmeticException, - NotFiniteNumberException, - NotANumberException { - singletons = new ArrayList<>(pmf.size()); - final double[] probs = new double[pmf.size()]; - - for (int i = 0; i < pmf.size(); i++) { - final Pair sample = pmf.get(i); - singletons.add(sample.getKey()); - final double p = sample.getValue(); - if (p < 0) { - throw new NotPositiveException(sample.getValue()); - } - if (Double.isInfinite(p)) { - throw new NotFiniteNumberException(p); - } - if (Double.isNaN(p)) { - throw new NotANumberException(); - } - probs[i] = p; - } - - probabilities = MathArrays.normalizeArray(probs, 1.0); - - cumulativeProbabilities = new double[probabilities.length]; - double sum = 0; - for (int i = 0; i < probabilities.length; i++) { - sum += probabilities[i]; - cumulativeProbabilities[i] = sum; - } - } - - /** - *

For a random variable {@code X} whose values are distributed according to - * this distribution, this method returns {@code P(X = x)}. In other words, - * this method represents the probability mass function (PMF) for the - * distribution.

- * - *

Note that if {@code x1} and {@code x2} satisfy {@code x1.equals(x2)}, - * or both are null, then {@code probability(x1) = probability(x2)}.

- * - * @param x the point at which the PMF is evaluated - * @return the value of the probability mass function at {@code x} - */ - double probability(final T x) { - double probability = 0; - - for (int i = 0; i < probabilities.length; i++) { - if ((x == null && singletons.get(i) == null) || - (x != null && x.equals(singletons.get(i)))) { - probability += probabilities[i]; - } - } - - return probability; - } - - /** - *

Return the probability mass function as a list of <value, probability> pairs.

- * - *

Note that if duplicate and / or null values were provided to the constructor - * when creating this EnumeratedDistribution, the returned list will contain these - * values. If duplicates values exist, what is returned will not represent - * a pmf (i.e., it is up to the caller to consolidate duplicate mass points).

- * - * @return the probability mass function. - */ - public List> getPmf() { - final List> samples = new ArrayList<>(probabilities.length); - - for (int i = 0; i < probabilities.length; i++) { - samples.add(new Pair<>(singletons.get(i), probabilities[i])); - } - - return samples; - } - - /** - * Creates a {@link Sampler}. - * - * @param rng Random number generator. - * @return a new sampler instance. - */ - public Sampler createSampler(final UniformRandomProvider rng) { - return new Sampler(rng); - } - - /** - * Sampler functionality. - */ - public class Sampler { - /** Underlying sampler. */ - private final DiscreteProbabilityCollectionSampler sampler; - - /** - * @param rng Random number generator. - */ - Sampler(UniformRandomProvider rng) { - sampler = new DiscreteProbabilityCollectionSampler(rng, singletons, probabilities); - } - - /** - * Generates a random value sampled from this distribution. - * - * @return a random value. - */ - public T sample() { - return sampler.sample(); - } - - /** - * Generates a random sample from the distribution. - * - * @param sampleSize the number of random values to generate. - * @return an array representing the random sample. - * @throws NotStrictlyPositiveException if {@code sampleSize} is not - * positive. - */ - public Object[] sample(int sampleSize) throws NotStrictlyPositiveException { - if (sampleSize <= 0) { - throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES, - sampleSize); - } - - final Object[] out = new Object[sampleSize]; - - for (int i = 0; i < sampleSize; i++) { - out[i] = sample(); - } - - return out; - } - - /** - * Generates a random sample from the distribution. - *

- * If the requested samples fit in the specified array, it is returned - * therein. Otherwise, a new array is allocated with the runtime type of - * the specified array and the size of this collection. - * - * @param sampleSize the number of random values to generate. - * @param array the array to populate. - * @return an array representing the random sample. - * @throws NotStrictlyPositiveException if {@code sampleSize} is not positive. - * @throws NullArgumentException if {@code array} is null - */ - public T[] sample(int sampleSize, final T[] array) throws NotStrictlyPositiveException { - if (sampleSize <= 0) { - throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES, sampleSize); - } - - if (array == null) { - throw new NullArgumentException(LocalizedFormats.INPUT_ARRAY); - } - - T[] out; - if (array.length < sampleSize) { - @SuppressWarnings("unchecked") // safe as both are of type T - final T[] unchecked = (T[]) Array.newInstance(array.getClass().getComponentType(), sampleSize); - out = unchecked; - } else { - out = array; - } - - for (int i = 0; i < sampleSize; i++) { - out[i] = sample(); - } - - return out; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/EnumeratedIntegerDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/EnumeratedIntegerDistribution.java deleted file mode 100644 index c12227141..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/EnumeratedIntegerDistribution.java +++ /dev/null @@ -1,246 +0,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. - */ -package org.apache.commons.math4.distribution; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.NotANumberException; -import org.apache.commons.math4.exception.NotFiniteNumberException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.math4.util.Pair; - -/** - *

Implementation of an integer-valued {@link EnumeratedDistribution}.

- * - *

Values with zero-probability are allowed but they do not extend the - * support.
- * Duplicate values are allowed. Probabilities of duplicate values are combined - * when computing cumulative probabilities and statistics.

- * - * @since 3.2 - */ -public class EnumeratedIntegerDistribution extends AbstractIntegerDistribution { - /** Serializable UID. */ - private static final long serialVersionUID = 20130308L; - /** - * {@link EnumeratedDistribution} instance (using the {@link Integer} wrapper) - * used to generate the pmf. - */ - protected final EnumeratedDistribution innerDistribution; - - /** - * Create a discrete distribution. - * - * @param singletons array of random variable values. - * @param probabilities array of probabilities. - * @throws DimensionMismatchException if - * {@code singletons.length != probabilities.length} - * @throws NotPositiveException if any of the probabilities are negative. - * @throws NotFiniteNumberException if any of the probabilities are infinite. - * @throws NotANumberException if any of the probabilities are NaN. - * @throws MathArithmeticException all of the probabilities are 0. - */ - public EnumeratedIntegerDistribution(final int[] singletons, - final double[] probabilities) - throws DimensionMismatchException, - NotPositiveException, - MathArithmeticException, - NotFiniteNumberException, - NotANumberException { - innerDistribution = new EnumeratedDistribution<>(createDistribution(singletons, - probabilities)); - } - - /** - * Create a discrete integer-valued distribution from the input data. - * Values are assigned mass based on their frequency. - * - * @param data input dataset - */ - public EnumeratedIntegerDistribution(final int[] data) { - final Map dataMap = new HashMap<>(); - for (int value : data) { - Integer count = dataMap.get(value); - if (count == null) { - count = 0; - } - dataMap.put(value, ++count); - } - final int massPoints = dataMap.size(); - final double denom = data.length; - final int[] values = new int[massPoints]; - final double[] probabilities = new double[massPoints]; - int index = 0; - for (Entry entry : dataMap.entrySet()) { - values[index] = entry.getKey(); - probabilities[index] = entry.getValue().intValue() / denom; - index++; - } - innerDistribution = new EnumeratedDistribution<>(createDistribution(values, probabilities)); - } - - /** - * Create the list of Pairs representing the distribution from singletons and probabilities. - * - * @param singletons values - * @param probabilities probabilities - * @return list of value/probability pairs - */ - private static List> createDistribution(int[] singletons, double[] probabilities) { - if (singletons.length != probabilities.length) { - throw new DimensionMismatchException(probabilities.length, singletons.length); - } - - final List> samples = new ArrayList<>(singletons.length); - - for (int i = 0; i < singletons.length; i++) { - samples.add(new Pair<>(singletons[i], probabilities[i])); - } - return samples; - } - - /** - * {@inheritDoc} - */ - @Override - public double probability(final int x) { - return innerDistribution.probability(x); - } - - /** - * {@inheritDoc} - */ - @Override - public double cumulativeProbability(final int x) { - double probability = 0; - - for (final Pair sample : innerDistribution.getPmf()) { - if (sample.getKey() <= x) { - probability += sample.getValue(); - } - } - - return probability; - } - - /** - * {@inheritDoc} - * - * @return {@code sum(singletons[i] * probabilities[i])} - */ - @Override - public double getMean() { - double mean = 0; - - for (final Pair sample : innerDistribution.getPmf()) { - mean += sample.getValue() * sample.getKey(); - } - - return mean; - } - - /** - * {@inheritDoc} - * - * @return {@code sum((singletons[i] - mean) ^ 2 * probabilities[i])} - */ - @Override - public double getVariance() { - double mean = 0; - double meanOfSquares = 0; - - for (final Pair sample : innerDistribution.getPmf()) { - mean += sample.getValue() * sample.getKey(); - meanOfSquares += sample.getValue() * sample.getKey() * sample.getKey(); - } - - return meanOfSquares - mean * mean; - } - - /** - * {@inheritDoc} - * - * Returns the lowest value with non-zero probability. - * - * @return the lowest value with non-zero probability. - */ - @Override - public int getSupportLowerBound() { - int min = Integer.MAX_VALUE; - for (final Pair sample : innerDistribution.getPmf()) { - if (sample.getKey() < min && sample.getValue() > 0) { - min = sample.getKey(); - } - } - - return min; - } - - /** - * {@inheritDoc} - * - * Returns the highest value with non-zero probability. - * - * @return the highest value with non-zero probability. - */ - @Override - public int getSupportUpperBound() { - int max = Integer.MIN_VALUE; - for (final Pair sample : innerDistribution.getPmf()) { - if (sample.getKey() > max && sample.getValue() > 0) { - max = sample.getKey(); - } - } - - return max; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } - - /** {@inheritDoc} */ - @Override - public Sampler createSampler(final UniformRandomProvider rng) { - return new Sampler() { - /** Delegate. */ - private final EnumeratedDistribution.Sampler inner = - innerDistribution.createSampler(rng); - - /** {@inheritDoc} */ - @Override - public int sample() { - return inner.sample(); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/EnumeratedRealDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/EnumeratedRealDistribution.java deleted file mode 100644 index 56c6d12ec..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/EnumeratedRealDistribution.java +++ /dev/null @@ -1,294 +0,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. - */ -package org.apache.commons.math4.distribution; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.io.Serializable; - -import org.apache.commons.statistics.distribution.ContinuousDistribution; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.NotANumberException; -import org.apache.commons.math4.exception.NotFiniteNumberException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.math4.util.Pair; - -/** - *

Implementation of a real-valued {@link EnumeratedDistribution}. - * - *

Values with zero-probability are allowed but they do not extend the - * support.
- * Duplicate values are allowed. Probabilities of duplicate values are combined - * when computing cumulative probabilities and statistics.

- * - * @since 3.2 - */ -public class EnumeratedRealDistribution - implements ContinuousDistribution, - Serializable { - /** Serializable UID. */ - private static final long serialVersionUID = 20160311L; - - /** - * {@link EnumeratedDistribution} (using the {@link Double} wrapper) - * used to generate the pmf. - */ - protected final EnumeratedDistribution innerDistribution; - - /** - * Create a discrete real-valued distribution using the given random number generator - * and probability mass function enumeration. - * - * @param singletons array of random variable values. - * @param probabilities array of probabilities. - * @throws DimensionMismatchException if - * {@code singletons.length != probabilities.length} - * @throws NotPositiveException if any of the probabilities are negative. - * @throws NotFiniteNumberException if any of the probabilities are infinite. - * @throws NotANumberException if any of the probabilities are NaN. - * @throws MathArithmeticException all of the probabilities are 0. - */ - public EnumeratedRealDistribution(final double[] singletons, - final double[] probabilities) - throws DimensionMismatchException, - NotPositiveException, - MathArithmeticException, - NotFiniteNumberException, - NotANumberException { - innerDistribution = new EnumeratedDistribution<>(createDistribution(singletons, probabilities)); - } - - /** - * Creates a discrete real-valued distribution from the input data. - * Values are assigned mass based on their frequency. - * - * @param data input dataset - */ - public EnumeratedRealDistribution(final double[] data) { - final Map dataMap = new HashMap<>(); - for (double value : data) { - Integer count = dataMap.get(value); - if (count == null) { - count = 0; - } - dataMap.put(value, ++count); - } - final int massPoints = dataMap.size(); - final double denom = data.length; - final double[] values = new double[massPoints]; - final double[] probabilities = new double[massPoints]; - int index = 0; - for (Entry entry : dataMap.entrySet()) { - values[index] = entry.getKey(); - probabilities[index] = entry.getValue().intValue() / denom; - index++; - } - innerDistribution = new EnumeratedDistribution<>(createDistribution(values, probabilities)); - } - - /** - * Create the list of Pairs representing the distribution from singletons and probabilities. - * - * @param singletons values - * @param probabilities probabilities - * @return list of value/probability pairs - */ - private static List> createDistribution(double[] singletons, double[] probabilities) { - if (singletons.length != probabilities.length) { - throw new DimensionMismatchException(probabilities.length, singletons.length); - } - - final List> samples = new ArrayList<>(singletons.length); - - for (int i = 0; i < singletons.length; i++) { - samples.add(new Pair<>(singletons[i], probabilities[i])); - } - return samples; - - } - - /** - * {@inheritDoc} - */ - @Override - public double probability(final double x) { - return innerDistribution.probability(x); - } - - /** - * For a random variable {@code X} whose values are distributed according to - * this distribution, this method returns {@code P(X = x)}. In other words, - * this method represents the probability mass function (PMF) for the - * distribution. - * - * @param x the point at which the PMF is evaluated - * @return the value of the probability mass function at point {@code x} - */ - @Override - public double density(final double x) { - return probability(x); - } - - /** - * {@inheritDoc} - */ - @Override - public double cumulativeProbability(final double x) { - double probability = 0; - - for (final Pair sample : innerDistribution.getPmf()) { - if (sample.getKey() <= x) { - probability += sample.getValue(); - } - } - - return probability; - } - - /** - * {@inheritDoc} - */ - @Override - public double inverseCumulativeProbability(final double p) throws OutOfRangeException { - if (p < 0.0 || p > 1.0) { - throw new OutOfRangeException(p, 0, 1); - } - - double probability = 0; - double x = getSupportLowerBound(); - for (final Pair sample : innerDistribution.getPmf()) { - if (sample.getValue() == 0.0) { - continue; - } - - probability += sample.getValue(); - x = sample.getKey(); - - if (probability >= p) { - break; - } - } - - return x; - } - - /** - * {@inheritDoc} - * - * @return {@code sum(singletons[i] * probabilities[i])} - */ - @Override - public double getMean() { - double mean = 0; - - for (final Pair sample : innerDistribution.getPmf()) { - mean += sample.getValue() * sample.getKey(); - } - - return mean; - } - - /** - * {@inheritDoc} - * - * @return {@code sum((singletons[i] - mean) ^ 2 * probabilities[i])} - */ - @Override - public double getVariance() { - double mean = 0; - double meanOfSquares = 0; - - for (final Pair sample : innerDistribution.getPmf()) { - mean += sample.getValue() * sample.getKey(); - meanOfSquares += sample.getValue() * sample.getKey() * sample.getKey(); - } - - return meanOfSquares - mean * mean; - } - - /** - * {@inheritDoc} - * - * Returns the lowest value with non-zero probability. - * - * @return the lowest value with non-zero probability. - */ - @Override - public double getSupportLowerBound() { - double min = Double.POSITIVE_INFINITY; - for (final Pair sample : innerDistribution.getPmf()) { - if (sample.getKey() < min && sample.getValue() > 0) { - min = sample.getKey(); - } - } - - return min; - } - - /** - * {@inheritDoc} - * - * Returns the highest value with non-zero probability. - * - * @return the highest value with non-zero probability. - */ - @Override - public double getSupportUpperBound() { - double max = Double.NEGATIVE_INFINITY; - for (final Pair sample : innerDistribution.getPmf()) { - if (sample.getKey() > max && sample.getValue() > 0) { - max = sample.getKey(); - } - } - - return max; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } - - /** {@inheritDoc} */ - @Override - public Sampler createSampler(final UniformRandomProvider rng) { - return new Sampler() { - /** Delegate. */ - private final EnumeratedDistribution.Sampler inner = - innerDistribution.createSampler(rng); - - /** {@inheritDoc} */ - @Override - public double sample() { - return inner.sample(); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/IntegerDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/IntegerDistribution.java deleted file mode 100644 index c65550d40..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/IntegerDistribution.java +++ /dev/null @@ -1,24 +0,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. - */ -package org.apache.commons.math4.distribution; - -import org.apache.commons.statistics.distribution.DiscreteDistribution; - -/** - * Interface for distributions on the integers. - */ -public interface IntegerDistribution extends DiscreteDistribution {} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/MixtureMultivariateNormalDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/MixtureMultivariateNormalDistribution.java deleted file mode 100644 index 4ae44f52a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/MixtureMultivariateNormalDistribution.java +++ /dev/null @@ -1,91 +0,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. - */ -package org.apache.commons.math4.distribution; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.util.Pair; - -/** - * Multivariate normal mixture distribution. - * This class is mainly syntactic sugar. - * - * @see MixtureMultivariateRealDistribution - * @since 3.2 - */ -public class MixtureMultivariateNormalDistribution - extends MixtureMultivariateRealDistribution { - /** - * Creates a mixture model from a list of distributions and their - * associated weights. - * - * @param components Distributions from which to sample. - * @throws NotPositiveException if any of the weights is negative. - * @throws DimensionMismatchException if not all components have the same - * number of variables. - */ - public MixtureMultivariateNormalDistribution(List> components) - throws NotPositiveException, - DimensionMismatchException { - super(components); - } - - /** - * Creates a multivariate normal mixture distribution. - * - * @param weights Weights of each component. - * @param means Mean vector for each component. - * @param covariances Covariance matrix for each component. - * @throws NotPositiveException if any of the weights is negative. - * @throws DimensionMismatchException if not all components have the same - * number of variables. - */ - public MixtureMultivariateNormalDistribution(double[] weights, - double[][] means, - double[][][] covariances) - throws NotPositiveException, - DimensionMismatchException { - this(createComponents(weights, means, covariances)); - } - - /** - * Creates components of the mixture model. - * - * @param weights Weights of each component. - * @param means Mean vector for each component. - * @param covariances Covariance matrix for each component. - * @return the list of components. - */ - private static List> createComponents(double[] weights, - double[][] means, - double[][][] covariances) { - final List> mvns - = new ArrayList<>(weights.length); - - for (int i = 0; i < weights.length; i++) { - final MultivariateNormalDistribution dist - = new MultivariateNormalDistribution(means[i], covariances[i]); - - mvns.add(new Pair<>(weights[i], dist)); - } - - return mvns; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/MixtureMultivariateRealDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/MixtureMultivariateRealDistribution.java deleted file mode 100644 index 0fdff80da..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/MixtureMultivariateRealDistribution.java +++ /dev/null @@ -1,166 +0,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. - */ -package org.apache.commons.math4.distribution; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.math4.util.Pair; - -/** - * Class for representing - * mixture model distributions. - * - * @param Type of the mixture components. - * - * @since 3.1 - */ -public class MixtureMultivariateRealDistribution - extends AbstractMultivariateRealDistribution { - /** Normalized weight of each mixture component. */ - private final double[] weight; - /** Mixture components. */ - private final List distribution; - - /** - * Creates a mixture model from a list of distributions and their - * associated weights. - * - * @param components Distributions from which to sample. - * @throws NotPositiveException if any of the weights is negative. - * @throws DimensionMismatchException if not all components have the same - * number of variables. - */ - public MixtureMultivariateRealDistribution(List> components) { - super(components.get(0).getSecond().getDimension()); - - final int numComp = components.size(); - final int dim = getDimension(); - double weightSum = 0; - for (int i = 0; i < numComp; i++) { - final Pair comp = components.get(i); - if (comp.getSecond().getDimension() != dim) { - throw new DimensionMismatchException(comp.getSecond().getDimension(), dim); - } - if (comp.getFirst() < 0) { - throw new NotPositiveException(comp.getFirst()); - } - weightSum += comp.getFirst(); - } - - // Check for overflow. - if (Double.isInfinite(weightSum)) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW); - } - - // Store each distribution and its normalized weight. - distribution = new ArrayList<>(); - weight = new double[numComp]; - for (int i = 0; i < numComp; i++) { - final Pair comp = components.get(i); - weight[i] = comp.getFirst() / weightSum; - distribution.add(comp.getSecond()); - } - } - - /** {@inheritDoc} */ - @Override - public double density(final double[] values) { - double p = 0; - for (int i = 0; i < weight.length; i++) { - p += weight[i] * distribution.get(i).density(values); - } - return p; - } - - /** - * Gets the distributions that make up the mixture model. - * - * @return the component distributions and associated weights. - */ - public List> getComponents() { - final List> list = new ArrayList<>(weight.length); - - for (int i = 0; i < weight.length; i++) { - list.add(new Pair<>(weight[i], distribution.get(i))); - } - - return list; - } - - /** {@inheritDoc} */ - @Override - public MultivariateRealDistribution.Sampler createSampler(UniformRandomProvider rng) { - return new MixtureSampler(rng); - } - - /** - * Sampler. - */ - private class MixtureSampler implements MultivariateRealDistribution.Sampler { - /** RNG */ - private final UniformRandomProvider rng; - /** Sampler for each of the distribution in the mixture. */ - private final MultivariateRealDistribution.Sampler[] samplers; - - /** - * @param generator RNG. - */ - MixtureSampler(UniformRandomProvider generator) { - rng = generator; - - samplers = new MultivariateRealDistribution.Sampler[weight.length]; - for (int i = 0; i < weight.length; i++) { - samplers[i] = distribution.get(i).createSampler(rng); - } - } - - /** {@inheritDoc} */ - @Override - public double[] sample() { - // Sampled values. - double[] vals = null; - - // Determine which component to sample from. - final double randomValue = rng.nextDouble(); - double sum = 0; - - for (int i = 0; i < weight.length; i++) { - sum += weight[i]; - if (randomValue <= sum) { - // pick model i - vals = samplers[i].sample(); - break; - } - } - - if (vals == null) { - // This should never happen, but it ensures we won't return a null in - // case the loop above has some floating point inequality problem on - // the final iteration. - vals = samplers[weight.length - 1].sample(); - } - - return vals; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/MultivariateNormalDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/MultivariateNormalDistribution.java deleted file mode 100644 index 76046a8ce..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/MultivariateNormalDistribution.java +++ /dev/null @@ -1,225 +0,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. - */ -package org.apache.commons.math4.distribution; - -import org.apache.commons.statistics.distribution.ContinuousDistribution; -import org.apache.commons.statistics.distribution.NormalDistribution; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.linear.Array2DRowRealMatrix; -import org.apache.commons.math4.linear.EigenDecomposition; -import org.apache.commons.math4.linear.NonPositiveDefiniteMatrixException; -import org.apache.commons.math4.linear.RealMatrix; -import org.apache.commons.math4.linear.SingularMatrixException; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; - -/** - * Implementation of the multivariate normal (Gaussian) distribution. - * - * @see - * Multivariate normal distribution (Wikipedia) - * @see - * Multivariate normal distribution (MathWorld) - * - * @since 3.1 - */ -public class MultivariateNormalDistribution - extends AbstractMultivariateRealDistribution { - /** Vector of means. */ - private final double[] means; - /** Covariance matrix. */ - private final RealMatrix covarianceMatrix; - /** The matrix inverse of the covariance matrix. */ - private final RealMatrix covarianceMatrixInverse; - /** The determinant of the covariance matrix. */ - private final double covarianceMatrixDeterminant; - /** Matrix used in computation of samples. */ - private final RealMatrix samplingMatrix; - - /** - * Creates a multivariate normal distribution with the given mean vector and - * covariance matrix. - *

- * The number of dimensions is equal to the length of the mean vector - * and to the number of rows and columns of the covariance matrix. - * It is frequently written as "p" in formulae. - *

- * - * @param means Vector of means. - * @param covariances Covariance matrix. - * @throws DimensionMismatchException if the arrays length are - * inconsistent. - * @throws SingularMatrixException if the eigenvalue decomposition cannot - * be performed on the provided covariance matrix. - * @throws NonPositiveDefiniteMatrixException if any of the eigenvalues is - * negative. - */ - public MultivariateNormalDistribution(final double[] means, - final double[][] covariances) - throws SingularMatrixException, - DimensionMismatchException, - NonPositiveDefiniteMatrixException { - super(means.length); - - final int dim = means.length; - - if (covariances.length != dim) { - throw new DimensionMismatchException(covariances.length, dim); - } - - for (int i = 0; i < dim; i++) { - if (dim != covariances[i].length) { - throw new DimensionMismatchException(covariances[i].length, dim); - } - } - - this.means = MathArrays.copyOf(means); - - covarianceMatrix = new Array2DRowRealMatrix(covariances); - - // Covariance matrix eigen decomposition. - final EigenDecomposition covMatDec = new EigenDecomposition(covarianceMatrix); - - // Compute and store the inverse. - covarianceMatrixInverse = covMatDec.getSolver().getInverse(); - // Compute and store the determinant. - covarianceMatrixDeterminant = covMatDec.getDeterminant(); - - // Eigenvalues of the covariance matrix. - final double[] covMatEigenvalues = covMatDec.getRealEigenvalues(); - - for (int i = 0; i < covMatEigenvalues.length; i++) { - if (covMatEigenvalues[i] < 0) { - throw new NonPositiveDefiniteMatrixException(covMatEigenvalues[i], i, 0); - } - } - - // Matrix where each column is an eigenvector of the covariance matrix. - final Array2DRowRealMatrix covMatEigenvectors = new Array2DRowRealMatrix(dim, dim); - for (int v = 0; v < dim; v++) { - final double[] evec = covMatDec.getEigenvector(v).toArray(); - covMatEigenvectors.setColumn(v, evec); - } - - final RealMatrix tmpMatrix = covMatEigenvectors.transpose(); - - // Scale each eigenvector by the square root of its eigenvalue. - for (int row = 0; row < dim; row++) { - final double factor = FastMath.sqrt(covMatEigenvalues[row]); - for (int col = 0; col < dim; col++) { - tmpMatrix.multiplyEntry(row, col, factor); - } - } - - samplingMatrix = covMatEigenvectors.multiply(tmpMatrix); - } - - /** - * Gets the mean vector. - * - * @return the mean vector. - */ - public double[] getMeans() { - return MathArrays.copyOf(means); - } - - /** - * Gets the covariance matrix. - * - * @return the covariance matrix. - */ - public RealMatrix getCovariances() { - return covarianceMatrix.copy(); - } - - /** {@inheritDoc} */ - @Override - public double density(final double[] vals) throws DimensionMismatchException { - final int dim = getDimension(); - if (vals.length != dim) { - throw new DimensionMismatchException(vals.length, dim); - } - - return FastMath.pow(2 * FastMath.PI, -0.5 * dim) * - FastMath.pow(covarianceMatrixDeterminant, -0.5) * - getExponentTerm(vals); - } - - /** - * Gets the square root of each element on the diagonal of the covariance - * matrix. - * - * @return the standard deviations. - */ - public double[] getStandardDeviations() { - final int dim = getDimension(); - final double[] std = new double[dim]; - final double[][] s = covarianceMatrix.getData(); - for (int i = 0; i < dim; i++) { - std[i] = FastMath.sqrt(s[i][i]); - } - return std; - } - - /** {@inheritDoc} */ - @Override - public MultivariateRealDistribution.Sampler createSampler(final UniformRandomProvider rng) { - return new MultivariateRealDistribution.Sampler() { - /** Normal distribution. */ - private final ContinuousDistribution.Sampler gauss = new NormalDistribution(0, 1).createSampler(rng); - - /** {@inheritDoc} */ - @Override - public double[] sample() { - final int dim = getDimension(); - final double[] normalVals = new double[dim]; - - for (int i = 0; i < dim; i++) { - normalVals[i] = gauss.sample(); - } - - final double[] vals = samplingMatrix.operate(normalVals); - - for (int i = 0; i < dim; i++) { - vals[i] += means[i]; - } - - return vals; - } - }; - } - - /** - * Computes the term used in the exponent (see definition of the distribution). - * - * @param values Values at which to compute density. - * @return the multiplication factor of density calculations. - */ - private double getExponentTerm(final double[] values) { - final double[] centered = new double[values.length]; - for (int i = 0; i < centered.length; i++) { - centered[i] = values[i] - means[i]; - } - final double[] preMultiplied = covarianceMatrixInverse.preMultiply(centered); - double sum = 0; - for (int i = 0; i < preMultiplied.length; i++) { - sum += preMultiplied[i] * centered[i]; - } - return FastMath.exp(-0.5 * sum); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/MultivariateRealDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/MultivariateRealDistribution.java deleted file mode 100644 index ef5fca98d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/MultivariateRealDistribution.java +++ /dev/null @@ -1,77 +0,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. - */ -package org.apache.commons.math4.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Base interface for multivariate distributions on the reals. - * - * This is based largely on the RealDistribution interface, but cumulative - * distribution functions are not required because they are often quite - * difficult to compute for multivariate distributions. - * - * @since 3.1 - */ -public interface MultivariateRealDistribution { - /** - * Returns the probability density function (PDF) of this distribution - * evaluated at the specified point {@code x}. In general, the PDF is the - * derivative of the cumulative distribution function. If the derivative - * does not exist at {@code x}, then an appropriate replacement should be - * returned, e.g. {@code Double.POSITIVE_INFINITY}, {@code Double.NaN}, or - * the limit inferior or limit superior of the difference quotient. - * - * @param x Point at which the PDF is evaluated. - * @return the value of the probability density function at point {@code x}. - */ - double density(double[] x); - - /** - * Gets the number of random variables of the distribution. - * It is the size of the array returned by the {@link Sampler#sample() sample} - * method. - * - * @return the number of variables. - */ - int getDimension(); - - /** - * Creates a sampler. - * - * @param rng Generator of uniformly distributed numbers. - * @return a sampler that produces random numbers according this - * distribution. - * - * @since 4.0 - */ - Sampler createSampler(UniformRandomProvider rng); - - /** - * Sampling functionality. - * - * @since 4.0 - */ - interface Sampler { - /** - * Generates a random value vector sampled from this distribution. - * - * @return a random value vector. - */ - double[] sample(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/RealDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/RealDistribution.java deleted file mode 100644 index 7d6eff2e7..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/RealDistribution.java +++ /dev/null @@ -1,26 +0,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. - */ -package org.apache.commons.math4.distribution; - -import org.apache.commons.statistics.distribution.ContinuousDistribution; - -/** - * Base interface for distributions on the reals. - * - * @since 3.0 - */ -public interface RealDistribution extends ContinuousDistribution {} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/fitting/MultivariateNormalMixtureExpectationMaximization.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/fitting/MultivariateNormalMixtureExpectationMaximization.java deleted file mode 100644 index 499a3df41..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/fitting/MultivariateNormalMixtureExpectationMaximization.java +++ /dev/null @@ -1,455 +0,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. - */ -package org.apache.commons.math4.distribution.fitting; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.commons.math4.distribution.MixtureMultivariateNormalDistribution; -import org.apache.commons.math4.distribution.MultivariateNormalDistribution; -import org.apache.commons.math4.exception.ConvergenceException; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.linear.Array2DRowRealMatrix; -import org.apache.commons.math4.linear.RealMatrix; -import org.apache.commons.math4.linear.SingularMatrixException; -import org.apache.commons.math4.stat.correlation.Covariance; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.Pair; - -/** - * Expectation-Maximization algorithm for fitting the parameters of - * multivariate normal mixture model distributions. - * - * This implementation is pure original code based on - * EM Demystified: An Expectation-Maximization Tutorial by Yihua Chen and Maya R. Gupta, - * Department of Electrical Engineering, University of Washington, Seattle, WA 98195. - * It was verified using external tools like CRAN Mixtools - * (see the JUnit test cases) but it is not based on Mixtools code at all. - * The discussion of the origin of this class can be seen in the comments of the MATH-817 JIRA issue. - * @since 3.2 - */ -public class MultivariateNormalMixtureExpectationMaximization { - /** - * Default maximum number of iterations allowed per fitting process. - */ - private static final int DEFAULT_MAX_ITERATIONS = 1000; - /** - * Default convergence threshold for fitting. - */ - private static final double DEFAULT_THRESHOLD = 1E-5; - /** - * The data to fit. - */ - private final double[][] data; - /** - * The model fit against the data. - */ - private MixtureMultivariateNormalDistribution fittedModel; - /** - * The log likelihood of the data given the fitted model. - */ - private double logLikelihood = 0d; - - /** - * Creates an object to fit a multivariate normal mixture model to data. - * - * @param data Data to use in fitting procedure - * @throws NotStrictlyPositiveException if data has no rows - * @throws DimensionMismatchException if rows of data have different numbers - * of columns - * @throws NumberIsTooSmallException if the number of columns in the data is - * less than 2 - */ - public MultivariateNormalMixtureExpectationMaximization(double[][] data) - throws NotStrictlyPositiveException, - DimensionMismatchException, - NumberIsTooSmallException { - if (data.length < 1) { - throw new NotStrictlyPositiveException(data.length); - } - - this.data = new double[data.length][data[0].length]; - - for (int i = 0; i < data.length; i++) { - if (data[i].length != data[0].length) { - // Jagged arrays not allowed - throw new DimensionMismatchException(data[i].length, - data[0].length); - } - if (data[i].length < 2) { - throw new NumberIsTooSmallException(LocalizedFormats.NUMBER_TOO_SMALL, - data[i].length, 2, true); - } - this.data[i] = MathArrays.copyOf(data[i], data[i].length); - } - } - - /** - * Fit a mixture model to the data supplied to the constructor. - * - * The quality of the fit depends on the concavity of the data provided to - * the constructor and the initial mixture provided to this function. If the - * data has many local optima, multiple runs of the fitting function with - * different initial mixtures may be required to find the optimal solution. - * If a SingularMatrixException is encountered, it is possible that another - * initialization would work. - * - * @param initialMixture Model containing initial values of weights and - * multivariate normals - * @param maxIterations Maximum iterations allowed for fit - * @param threshold Convergence threshold computed as difference in - * logLikelihoods between successive iterations - * @throws SingularMatrixException if any component's covariance matrix is - * singular during fitting - * @throws NotStrictlyPositiveException if numComponents is less than one - * or threshold is less than Double.MIN_VALUE - * @throws DimensionMismatchException if initialMixture mean vector and data - * number of columns are not equal - */ - public void fit(final MixtureMultivariateNormalDistribution initialMixture, - final int maxIterations, - final double threshold) - throws SingularMatrixException, - NotStrictlyPositiveException, - DimensionMismatchException { - if (maxIterations < 1) { - throw new NotStrictlyPositiveException(maxIterations); - } - - if (threshold < Double.MIN_VALUE) { - throw new NotStrictlyPositiveException(threshold); - } - - final int n = data.length; - - // Number of data columns. Jagged data already rejected in constructor, - // so we can assume the lengths of each row are equal. - final int numCols = data[0].length; - final int k = initialMixture.getComponents().size(); - - final int numMeanColumns - = initialMixture.getComponents().get(0).getSecond().getMeans().length; - - if (numMeanColumns != numCols) { - throw new DimensionMismatchException(numMeanColumns, numCols); - } - - int numIterations = 0; - double previousLogLikelihood = 0d; - - logLikelihood = Double.NEGATIVE_INFINITY; - - // Initialize model to fit to initial mixture. - fittedModel = new MixtureMultivariateNormalDistribution(initialMixture.getComponents()); - - while (numIterations++ <= maxIterations && - FastMath.abs(previousLogLikelihood - logLikelihood) > threshold) { - previousLogLikelihood = logLikelihood; - double sumLogLikelihood = 0d; - - // Mixture components - final List> components - = fittedModel.getComponents(); - - // Weight and distribution of each component - final double[] weights = new double[k]; - - final MultivariateNormalDistribution[] mvns = new MultivariateNormalDistribution[k]; - - for (int j = 0; j < k; j++) { - weights[j] = components.get(j).getFirst(); - mvns[j] = components.get(j).getSecond(); - } - - // E-step: compute the data dependent parameters of the expectation - // function. - // The percentage of row's total density between a row and a - // component - final double[][] gamma = new double[n][k]; - - // Sum of gamma for each component - final double[] gammaSums = new double[k]; - - // Sum of gamma times its row for each each component - final double[][] gammaDataProdSums = new double[k][numCols]; - - for (int i = 0; i < n; i++) { - final double rowDensity = fittedModel.density(data[i]); - sumLogLikelihood += FastMath.log(rowDensity); - - for (int j = 0; j < k; j++) { - gamma[i][j] = weights[j] * mvns[j].density(data[i]) / rowDensity; - gammaSums[j] += gamma[i][j]; - - for (int col = 0; col < numCols; col++) { - gammaDataProdSums[j][col] += gamma[i][j] * data[i][col]; - } - } - } - - logLikelihood = sumLogLikelihood / n; - - // M-step: compute the new parameters based on the expectation - // function. - final double[] newWeights = new double[k]; - final double[][] newMeans = new double[k][numCols]; - - for (int j = 0; j < k; j++) { - newWeights[j] = gammaSums[j] / n; - for (int col = 0; col < numCols; col++) { - newMeans[j][col] = gammaDataProdSums[j][col] / gammaSums[j]; - } - } - - // Compute new covariance matrices - final RealMatrix[] newCovMats = new RealMatrix[k]; - for (int j = 0; j < k; j++) { - newCovMats[j] = new Array2DRowRealMatrix(numCols, numCols); - } - for (int i = 0; i < n; i++) { - for (int j = 0; j < k; j++) { - final RealMatrix vec - = new Array2DRowRealMatrix(MathArrays.ebeSubtract(data[i], newMeans[j])); - final RealMatrix dataCov - = vec.multiply(vec.transpose()).scalarMultiply(gamma[i][j]); - newCovMats[j] = newCovMats[j].add(dataCov); - } - } - - // Converting to arrays for use by fitted model - final double[][][] newCovMatArrays = new double[k][numCols][numCols]; - for (int j = 0; j < k; j++) { - newCovMats[j] = newCovMats[j].scalarMultiply(1d / gammaSums[j]); - newCovMatArrays[j] = newCovMats[j].getData(); - } - - // Update current model - fittedModel = new MixtureMultivariateNormalDistribution(newWeights, - newMeans, - newCovMatArrays); - } - - if (FastMath.abs(previousLogLikelihood - logLikelihood) > threshold) { - // Did not converge before the maximum number of iterations - throw new ConvergenceException(); - } - } - - /** - * Fit a mixture model to the data supplied to the constructor. - * - * The quality of the fit depends on the concavity of the data provided to - * the constructor and the initial mixture provided to this function. If the - * data has many local optima, multiple runs of the fitting function with - * different initial mixtures may be required to find the optimal solution. - * If a SingularMatrixException is encountered, it is possible that another - * initialization would work. - * - * @param initialMixture Model containing initial values of weights and - * multivariate normals - * @throws SingularMatrixException if any component's covariance matrix is - * singular during fitting - * @throws NotStrictlyPositiveException if numComponents is less than one or - * threshold is less than Double.MIN_VALUE - */ - public void fit(MixtureMultivariateNormalDistribution initialMixture) - throws SingularMatrixException, - NotStrictlyPositiveException { - fit(initialMixture, DEFAULT_MAX_ITERATIONS, DEFAULT_THRESHOLD); - } - - /** - * Helper method to create a multivariate normal mixture model which can be - * used to initialize {@link #fit(MixtureMultivariateNormalDistribution)}. - * - * This method uses the data supplied to the constructor to try to determine - * a good mixture model at which to start the fit, but it is not guaranteed - * to supply a model which will find the optimal solution or even converge. - * - * @param data Data to estimate distribution - * @param numComponents Number of components for estimated mixture - * @return Multivariate normal mixture model estimated from the data - * @throws NumberIsTooLargeException if {@code numComponents} is greater - * than the number of data rows. - * @throws NumberIsTooSmallException if {@code numComponents < 2}. - * @throws NotStrictlyPositiveException if data has less than 2 rows - * @throws DimensionMismatchException if rows of data have different numbers - * of columns - */ - public static MixtureMultivariateNormalDistribution estimate(final double[][] data, - final int numComponents) - throws NotStrictlyPositiveException, - DimensionMismatchException { - if (data.length < 2) { - throw new NotStrictlyPositiveException(data.length); - } - if (numComponents < 2) { - throw new NumberIsTooSmallException(numComponents, 2, true); - } - if (numComponents > data.length) { - throw new NumberIsTooLargeException(numComponents, data.length, true); - } - - final int numRows = data.length; - final int numCols = data[0].length; - - // sort the data - final DataRow[] sortedData = new DataRow[numRows]; - for (int i = 0; i < numRows; i++) { - sortedData[i] = new DataRow(data[i]); - } - Arrays.sort(sortedData); - - // uniform weight for each bin - final double weight = 1d / numComponents; - - // components of mixture model to be created - final List> components = - new ArrayList<>(numComponents); - - // create a component based on data in each bin - for (int binIndex = 0; binIndex < numComponents; binIndex++) { - // minimum index (inclusive) from sorted data for this bin - final int minIndex = (binIndex * numRows) / numComponents; - - // maximum index (exclusive) from sorted data for this bin - final int maxIndex = ((binIndex + 1) * numRows) / numComponents; - - // number of data records that will be in this bin - final int numBinRows = maxIndex - minIndex; - - // data for this bin - final double[][] binData = new double[numBinRows][numCols]; - - // mean of each column for the data in the this bin - final double[] columnMeans = new double[numCols]; - - // populate bin and create component - for (int i = minIndex, iBin = 0; i < maxIndex; i++, iBin++) { - for (int j = 0; j < numCols; j++) { - final double val = sortedData[i].getRow()[j]; - columnMeans[j] += val; - binData[iBin][j] = val; - } - } - - MathArrays.scaleInPlace(1d / numBinRows, columnMeans); - - // covariance matrix for this bin - final double[][] covMat - = new Covariance(binData).getCovarianceMatrix().getData(); - final MultivariateNormalDistribution mvn - = new MultivariateNormalDistribution(columnMeans, covMat); - - components.add(new Pair<>(weight, mvn)); - } - - return new MixtureMultivariateNormalDistribution(components); - } - - /** - * Gets the log likelihood of the data under the fitted model. - * - * @return Log likelihood of data or zero of no data has been fit - */ - public double getLogLikelihood() { - return logLikelihood; - } - - /** - * Gets the fitted model. - * - * @return fitted model or {@code null} if no fit has been performed yet. - */ - public MixtureMultivariateNormalDistribution getFittedModel() { - return new MixtureMultivariateNormalDistribution(fittedModel.getComponents()); - } - - /** - * Class used for sorting user-supplied data. - */ - private static class DataRow implements Comparable { - /** One data row. */ - private final double[] row; - /** Mean of the data row. */ - private Double mean; - - /** - * Create a data row. - * @param data Data to use for the row - */ - DataRow(final double[] data) { - // Store reference. - row = data; - // Compute mean. - mean = 0d; - for (int i = 0; i < data.length; i++) { - mean += data[i]; - } - mean /= data.length; - } - - /** - * Compare two data rows. - * @param other The other row - * @return int for sorting - */ - @Override - public int compareTo(final DataRow other) { - return mean.compareTo(other.mean); - } - - /** {@inheritDoc} */ - @Override - public boolean equals(Object other) { - - if (this == other) { - return true; - } - - if (other instanceof DataRow) { - return MathArrays.equals(row, ((DataRow) other).row); - } - - return false; - - } - - /** {@inheritDoc} */ - @Override - public int hashCode() { - return Arrays.hashCode(row); - } - /** - * Get a data row. - * @return data row array - */ - public double[] getRow() { - return row; - } - } -} - diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/fitting/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/fitting/package-info.java deleted file mode 100644 index 4582120f3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/fitting/package-info.java +++ /dev/null @@ -1,20 +0,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. - */ -/** - * Fitting of parameters against distributions. - */ -package org.apache.commons.math4.distribution.fitting; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/package-info.java deleted file mode 100644 index 32d7b5fc6..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/distribution/package-info.java +++ /dev/null @@ -1,21 +0,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. - */ -/** - * Implementations of common discrete and continuous distributions. - * [Mostly moved to the "Commons Statistics" project (cf. JIRA: MATH-1443).] - */ -package org.apache.commons.math4.distribution; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/ConvergenceException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/ConvergenceException.java deleted file mode 100644 index 6e63615ed..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/ConvergenceException.java +++ /dev/null @@ -1,49 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Error thrown when a numerical computation can not be performed because the - * numerical result failed to converge to a finite value. - * - * @since 2.2 - */ -public class ConvergenceException extends MathIllegalStateException { - /** Serializable version Id. */ - private static final long serialVersionUID = 4330003017885151975L; - - /** - * Construct the exception. - */ - public ConvergenceException() { - this(LocalizedFormats.CONVERGENCE_FAILED); - } - - /** - * Construct the exception with a specific context and arguments. - * - * @param pattern Message pattern providing the specific context of - * the error. - * @param args Arguments. - */ - public ConvergenceException(Localizable pattern, Object ... args) { - getContext().addMessage(pattern, args); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/DimensionMismatchException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/DimensionMismatchException.java deleted file mode 100644 index fa5b30abb..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/DimensionMismatchException.java +++ /dev/null @@ -1,64 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when two dimensions differ. - * - * @since 2.2 - */ -public class DimensionMismatchException extends MathIllegalNumberException { - /** Serializable version Id. */ - private static final long serialVersionUID = -8415396756375798143L; - /** Correct dimension. */ - private final int dimension; - - /** - * Construct an exception from the mismatched dimensions. - * - * @param specific Specific context information pattern. - * @param wrong Wrong dimension. - * @param expected Expected dimension. - */ - public DimensionMismatchException(Localizable specific, - int wrong, - int expected) { - super(specific, Integer.valueOf(wrong), Integer.valueOf(expected)); - dimension = expected; - } - - /** - * Construct an exception from the mismatched dimensions. - * - * @param wrong Wrong dimension. - * @param expected Expected dimension. - */ - public DimensionMismatchException(int wrong, - int expected) { - this(LocalizedFormats.DIMENSIONS_MISMATCH_SIMPLE, wrong, expected); - } - - /** - * @return the expected dimension. - */ - public int getDimension() { - return dimension; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/InsufficientDataException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/InsufficientDataException.java deleted file mode 100644 index 5968c107b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/InsufficientDataException.java +++ /dev/null @@ -1,49 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when there is insufficient data to perform a computation. - * - * @since 3.3 - */ -public class InsufficientDataException - extends MathIllegalArgumentException { - - /** Serializable version Id. */ - private static final long serialVersionUID = -2629324471511903359L; - - /** - * Construct the exception. - */ - public InsufficientDataException() { - this(LocalizedFormats.INSUFFICIENT_DATA); - } - - /** - * Construct the exception with a specific context. - * - * @param pattern Message pattern providing the specific context of the error. - * @param arguments Values for replacing the placeholders in {@code pattern}. - */ - public InsufficientDataException(Localizable pattern, Object... arguments) { - super(pattern, arguments); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathArithmeticException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathArithmeticException.java deleted file mode 100644 index a14a03361..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathArithmeticException.java +++ /dev/null @@ -1,52 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Base class for arithmetic exceptions. - * It is used for all the exceptions that have the semantics of the standard - * {@link ArithmeticException}, but must also provide a localized - * message. - * - * @since 3.0 - */ -public class MathArithmeticException extends MathRuntimeException { - /** Serializable version Id. */ - private static final long serialVersionUID = -6024911025449780478L; - - /** - * Default constructor. - */ - public MathArithmeticException() { - this(LocalizedFormats.ARITHMETIC_EXCEPTION); - } - - /** - * Constructor with a specific message. - * - * @param pattern Message pattern providing the specific context of - * the error. - * @param args Arguments. - */ - public MathArithmeticException(Localizable pattern, Object ... args) { - super(pattern, args); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathIllegalArgumentException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathIllegalArgumentException.java deleted file mode 100644 index ea14f4203..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathIllegalArgumentException.java +++ /dev/null @@ -1,41 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; - -/** - * Base class for all preconditions violation exceptions. - * In most cases, this class should not be instantiated directly: it should - * serve as a base class to create all the exceptions that have the semantics - * of the standard {@link IllegalArgumentException}. - * - * @since 2.2 - */ -public class MathIllegalArgumentException extends MathRuntimeException { - /** Serializable version Id. */ - private static final long serialVersionUID = -6024911025449780478L; - - /** - * @param pattern Message pattern explaining the cause of the error. - * @param args Arguments. - */ - public MathIllegalArgumentException(Localizable pattern, Object ... args) { - super(pattern, args); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathIllegalNumberException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathIllegalNumberException.java deleted file mode 100644 index 29305169a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathIllegalNumberException.java +++ /dev/null @@ -1,60 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; - -/** - * Base class for exceptions raised by a wrong number. - * This class is not intended to be instantiated directly: it should serve - * as a base class to create all the exceptions that are raised because some - * precondition is violated by a number argument. - * - * @since 2.2 - */ -public class MathIllegalNumberException extends MathIllegalArgumentException { - - /** Helper to avoid boxing warnings. @since 3.3 */ - protected static final Integer INTEGER_ZERO = Integer.valueOf(0); - - /** Serializable version Id. */ - private static final long serialVersionUID = -7447085893598031110L; - - /** Requested. */ - private final Number argument; - - /** - * Construct an exception. - * - * @param pattern Localizable pattern. - * @param wrong Wrong number. - * @param arguments Arguments. - */ - protected MathIllegalNumberException(Localizable pattern, - Number wrong, - Object ... arguments) { - super(pattern, wrong, arguments); - argument = wrong; - } - - /** - * @return the requested value. - */ - public Number getArgument() { - return argument; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathIllegalStateException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathIllegalStateException.java deleted file mode 100644 index b5acb9e4e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathIllegalStateException.java +++ /dev/null @@ -1,63 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Base class for all exceptions that signal that the process - * throwing the exception is in a state that does not comply with - * the set of states that it is designed to be in. - * - * @since 2.2 - */ -public class MathIllegalStateException extends MathRuntimeException { - /** Serializable version Id. */ - private static final long serialVersionUID = -6024911025449780478L; - - /** - * Simple constructor. - * - * @param pattern Message pattern explaining the cause of the error. - * @param args Arguments. - */ - public MathIllegalStateException(Localizable pattern, Object ... args) { - super(pattern, args); - } - - /** - * Simple constructor. - * - * @param cause Root cause. - * @param pattern Message pattern explaining the cause of the error. - * @param args Arguments. - */ - public MathIllegalStateException(Throwable cause, - Localizable pattern, - Object ... args) { - super(cause, pattern, args); - } - - /** - * Default constructor. - */ - public MathIllegalStateException() { - this(LocalizedFormats.ILLEGAL_STATE); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathInternalError.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathInternalError.java deleted file mode 100644 index 142bd45ee..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathInternalError.java +++ /dev/null @@ -1,57 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception triggered when something that shouldn't happen does happen. - * - * @since 2.2 - */ -public class MathInternalError extends MathIllegalStateException { - /** Serializable version Id. */ - private static final long serialVersionUID = -6276776513966934846L; - /** URL for reporting problems. */ - private static final String REPORT_URL = "https://issues.apache.org/jira/browse/MATH"; - - /** - * Simple constructor. - */ - public MathInternalError() { - getContext().addMessage(LocalizedFormats.INTERNAL_ERROR, REPORT_URL); - } - - /** - * Simple constructor. - * @param cause root cause - */ - public MathInternalError(final Throwable cause) { - super(cause, LocalizedFormats.INTERNAL_ERROR, REPORT_URL); - } - - /** - * Constructor accepting a localized message. - * - * @param pattern Message pattern explaining the cause of the error. - * @param args Arguments. - */ - public MathInternalError(Localizable pattern, Object ... args) { - super(pattern, args); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathParseException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathParseException.java deleted file mode 100644 index ac4819e8e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathParseException.java +++ /dev/null @@ -1,51 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Class to signal parse failures. - * - * @since 2.2 - */ -public class MathParseException extends MathIllegalStateException { - /** Serializable version Id. */ - private static final long serialVersionUID = -6024911025449780478L; - - /** - * @param wrong Bad string representation of the object. - * @param position Index, in the {@code wrong} string, that caused the - * parsing to fail. - * @param type Class of the object supposedly represented by the - * {@code wrong} string. - */ - public MathParseException(String wrong, int position, Class type) { - getContext().addMessage(LocalizedFormats.CANNOT_PARSE_AS_TYPE, - wrong, Integer.valueOf(position), type.getName()); - } - - /** - * @param wrong Bad string representation of the object. - * @param position Index, in the {@code wrong} string, that caused the - * parsing to fail. - */ - public MathParseException(String wrong, int position) { - getContext().addMessage(LocalizedFormats.CANNOT_PARSE, - wrong, Integer.valueOf(position)); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathRuntimeException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathRuntimeException.java deleted file mode 100644 index 382af050f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathRuntimeException.java +++ /dev/null @@ -1,80 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.ExceptionContext; -import org.apache.commons.math4.exception.util.ExceptionContextProvider; -import org.apache.commons.math4.exception.util.Localizable; - -/** - * As of release 4.0, all exceptions thrown by the Commons Math code (except - * {@link NullArgumentException}) inherit from this class. - * In most cases, this class should not be instantiated directly: it should - * serve as a base class for implementing exception classes that describe a - * specific "problem". - * - * @since 3.1 - */ -public class MathRuntimeException extends RuntimeException - implements ExceptionContextProvider { - /** Serializable version Id. */ - private static final long serialVersionUID = 20120926L; - /** Context. */ - private final ExceptionContext context; - - /** - * @param pattern Message pattern explaining the cause of the error. - * @param args Arguments. - */ - public MathRuntimeException(Localizable pattern, - Object ... args) { - context = new ExceptionContext(this); - context.addMessage(pattern, args); - } - - /** - * @param cause Root cause. - * @param pattern Message pattern explaining the cause of the error. - * @param args Arguments. - * @since 4.0 - */ - public MathRuntimeException(Throwable cause, - Localizable pattern, - Object ... args) { - super(cause); - context = new ExceptionContext(this); - context.addMessage(pattern, args); - } - - /** {@inheritDoc} */ - @Override - public ExceptionContext getContext() { - return context; - } - - /** {@inheritDoc} */ - @Override - public String getMessage() { - return context.getMessage(); - } - - /** {@inheritDoc} */ - @Override - public String getLocalizedMessage() { - return context.getLocalizedMessage(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathUnsupportedOperationException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathUnsupportedOperationException.java deleted file mode 100644 index ede4a8f5b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MathUnsupportedOperationException.java +++ /dev/null @@ -1,49 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Base class for all unsupported features. - * It is used for all the exceptions that have the semantics of the standard - * {@link UnsupportedOperationException}, but must also provide a localized - * message. - * - * @since 2.2 - */ -public class MathUnsupportedOperationException extends MathRuntimeException { - /** Serializable version Id. */ - private static final long serialVersionUID = -6024911025449780478L; - - /** - * Default constructor. - */ - public MathUnsupportedOperationException() { - this(LocalizedFormats.UNSUPPORTED_OPERATION); - } - /** - * @param pattern Message pattern providing the specific context of - * the error. - * @param args Arguments. - */ - public MathUnsupportedOperationException(Localizable pattern, Object ... args) { - super(pattern, args); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MaxCountExceededException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MaxCountExceededException.java deleted file mode 100644 index 2813e6ebd..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MaxCountExceededException.java +++ /dev/null @@ -1,63 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when some counter maximum value is exceeded. - * - * @since 3.0 - */ -public class MaxCountExceededException extends MathIllegalStateException { - /** Serializable version Id. */ - private static final long serialVersionUID = 4330003017885151975L; - /** - * Maximum number of evaluations. - */ - private final Number max; - - /** - * Construct the exception. - * - * @param max Maximum. - */ - public MaxCountExceededException(Number max) { - this(LocalizedFormats.MAX_COUNT_EXCEEDED, max); - } - /** - * Construct the exception with a specific context. - * - * @param specific Specific context pattern. - * @param max Maximum. - * @param args Additional arguments. - */ - public MaxCountExceededException(Localizable specific, - Number max, - Object ... args) { - getContext().addMessage(specific, max, args); - this.max = max; - } - - /** - * @return the maximum number of evaluations. - */ - public Number getMax() { - return max; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MultiDimensionMismatchException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MultiDimensionMismatchException.java deleted file mode 100644 index 40289710c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/MultiDimensionMismatchException.java +++ /dev/null @@ -1,90 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when two sets of dimensions differ. - * - * @since 3.0 - */ -public class MultiDimensionMismatchException extends MathIllegalArgumentException { - /** Serializable version Id. */ - private static final long serialVersionUID = -8415396756375798143L; - - /** Wrong dimensions. */ - private final Integer[] wrong; - /** Correct dimensions. */ - private final Integer[] expected; - - /** - * Construct an exception from the mismatched dimensions. - * - * @param wrong Wrong dimensions. - * @param expected Expected dimensions. - */ - public MultiDimensionMismatchException(Integer[] wrong, - Integer[] expected) { - this(LocalizedFormats.DIMENSIONS_MISMATCH, wrong, expected); - } - - /** - * Construct an exception from the mismatched dimensions. - * - * @param specific Message pattern providing the specific context of - * the error. - * @param wrong Wrong dimensions. - * @param expected Expected dimensions. - */ - public MultiDimensionMismatchException(Localizable specific, - Integer[] wrong, - Integer[] expected) { - super(specific, wrong, expected); - this.wrong = wrong.clone(); - this.expected = expected.clone(); - } - - /** - * @return an array containing the wrong dimensions. - */ - public Integer[] getWrongDimensions() { - return wrong.clone(); - } - /** - * @return an array containing the expected dimensions. - */ - public Integer[] getExpectedDimensions() { - return expected.clone(); - } - - /** - * @param index Dimension index. - * @return the wrong dimension stored at {@code index}. - */ - public int getWrongDimension(int index) { - return wrong[index].intValue(); - } - /** - * @param index Dimension index. - * @return the expected dimension stored at {@code index}. - */ - public int getExpectedDimension(int index) { - return expected[index].intValue(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NoBracketingException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NoBracketingException.java deleted file mode 100644 index f48c91fe8..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NoBracketingException.java +++ /dev/null @@ -1,106 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when function values have the same sign at both - * ends of an interval. - * - * @since 3.0 - */ -public class NoBracketingException extends MathIllegalArgumentException { - /** Serializable version Id. */ - private static final long serialVersionUID = -3629324471511904459L; - /** Lower end of the interval. */ - private final double lo; - /** Higher end of the interval. */ - private final double hi; - /** Value at lower end of the interval. */ - private final double fLo; - /** Value at higher end of the interval. */ - private final double fHi; - - /** - * Construct the exception. - * - * @param lo Lower end of the interval. - * @param hi Higher end of the interval. - * @param fLo Value at lower end of the interval. - * @param fHi Value at higher end of the interval. - */ - public NoBracketingException(double lo, double hi, - double fLo, double fHi) { - this(LocalizedFormats.SAME_SIGN_AT_ENDPOINTS, lo, hi, fLo, fHi); - } - - /** - * Construct the exception with a specific context. - * - * @param specific Contextual information on what caused the exception. - * @param lo Lower end of the interval. - * @param hi Higher end of the interval. - * @param fLo Value at lower end of the interval. - * @param fHi Value at higher end of the interval. - * @param args Additional arguments. - */ - public NoBracketingException(Localizable specific, - double lo, double hi, - double fLo, double fHi, - Object ... args) { - super(specific, Double.valueOf(lo), Double.valueOf(hi), Double.valueOf(fLo), Double.valueOf(fHi), args); - this.lo = lo; - this.hi = hi; - this.fLo = fLo; - this.fHi = fHi; - } - - /** - * Get the lower end of the interval. - * - * @return the lower end. - */ - public double getLo() { - return lo; - } - /** - * Get the higher end of the interval. - * - * @return the higher end. - */ - public double getHi() { - return hi; - } - /** - * Get the value at the lower end of the interval. - * - * @return the value at the lower end. - */ - public double getFLo() { - return fLo; - } - /** - * Get the value at the higher end of the interval. - * - * @return the value at the higher end. - */ - public double getFHi() { - return fHi; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NoDataException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NoDataException.java deleted file mode 100644 index 90ca4d4d7..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NoDataException.java +++ /dev/null @@ -1,46 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when the required data is missing. - * - * @since 2.2 - */ -public class NoDataException extends MathIllegalArgumentException { - - /** Serializable version Id. */ - private static final long serialVersionUID = -3629324471511904459L; - - /** - * Construct the exception. - */ - public NoDataException() { - this(LocalizedFormats.NO_DATA); - } - /** - * Construct the exception with a specific context. - * - * @param specific Contextual information on what caused the exception. - */ - public NoDataException(Localizable specific) { - super(specific); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NonMonotonicSequenceException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NonMonotonicSequenceException.java deleted file mode 100644 index 7ee1908f0..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NonMonotonicSequenceException.java +++ /dev/null @@ -1,120 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.MathArrays; - -/** - * Exception to be thrown when the a sequence of values is not monotonically - * increasing or decreasing. - * - * @since 2.2 (name changed to "NonMonotonicSequenceException" in 3.0) - */ -public class NonMonotonicSequenceException extends MathIllegalNumberException { - /** Serializable version Id. */ - private static final long serialVersionUID = 3596849179428944575L; - /** - * Direction (positive for increasing, negative for decreasing). - */ - private final MathArrays.OrderDirection direction; - /** - * Whether the sequence must be strictly increasing or decreasing. - */ - private final boolean strict; - /** - * Index of the wrong value. - */ - private final int index; - /** - * Previous value. - */ - private final Number previous; - - /** - * Construct the exception. - * This constructor uses default values assuming that the sequence should - * have been strictly increasing. - * - * @param wrong Value that did not match the requirements. - * @param previous Previous value in the sequence. - * @param index Index of the value that did not match the requirements. - */ - public NonMonotonicSequenceException(Number wrong, - Number previous, - int index) { - this(wrong, previous, index, MathArrays.OrderDirection.INCREASING, true); - } - - /** - * Construct the exception. - * - * @param wrong Value that did not match the requirements. - * @param previous Previous value in the sequence. - * @param index Index of the value that did not match the requirements. - * @param direction Strictly positive for a sequence required to be - * increasing, negative (or zero) for a decreasing sequence. - * @param strict Whether the sequence must be strictly increasing or - * decreasing. - */ - public NonMonotonicSequenceException(Number wrong, - Number previous, - int index, - MathArrays.OrderDirection direction, - boolean strict) { - super(direction == MathArrays.OrderDirection.INCREASING ? - (strict ? - LocalizedFormats.NOT_STRICTLY_INCREASING_SEQUENCE : - LocalizedFormats.NOT_INCREASING_SEQUENCE) : - (strict ? - LocalizedFormats.NOT_STRICTLY_DECREASING_SEQUENCE : - LocalizedFormats.NOT_DECREASING_SEQUENCE), - wrong, previous, Integer.valueOf(index), Integer.valueOf(index - 1)); - - this.direction = direction; - this.strict = strict; - this.index = index; - this.previous = previous; - } - - /** - * @return the order direction. - **/ - public MathArrays.OrderDirection getDirection() { - return direction; - } - /** - * @return {@code true} is the sequence should be strictly monotonic. - **/ - public boolean getStrict() { - return strict; - } - /** - * Get the index of the wrong value. - * - * @return the current index. - */ - public int getIndex() { - return index; - } - /** - * @return the previous value. - */ - public Number getPrevious() { - return previous; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NotANumberException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NotANumberException.java deleted file mode 100644 index 78a646fda..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NotANumberException.java +++ /dev/null @@ -1,37 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when a number is not a number. - * - * @since 3.1 - */ -public class NotANumberException extends MathIllegalNumberException { - /** Serializable version Id. */ - private static final long serialVersionUID = 20120906L; - - /** - * Construct the exception. - */ - public NotANumberException() { - super(LocalizedFormats.NAN_NOT_ALLOWED, Double.valueOf(Double.NaN)); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NotFiniteNumberException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NotFiniteNumberException.java deleted file mode 100644 index 5157c6fb7..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NotFiniteNumberException.java +++ /dev/null @@ -1,54 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when a number is not finite. - * - * @since 3.0 - */ -public class NotFiniteNumberException extends MathIllegalNumberException { - /** Serializable version Id. */ - private static final long serialVersionUID = -6100997100383932834L; - - /** - * Construct the exception. - * - * @param wrong Value that is infinite or NaN. - * @param args Optional arguments. - */ - public NotFiniteNumberException(Number wrong, - Object ... args) { - this(LocalizedFormats.NOT_FINITE_NUMBER, wrong, args); - } - - /** - * Construct the exception with a specific context. - * - * @param specific Specific context pattern. - * @param wrong Value that is infinite or NaN. - * @param args Optional arguments. - */ - public NotFiniteNumberException(Localizable specific, - Number wrong, - Object ... args) { - super(specific, wrong, args); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NotPositiveException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NotPositiveException.java deleted file mode 100644 index 7d5515b67..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NotPositiveException.java +++ /dev/null @@ -1,48 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; - -/** - * Exception to be thrown when the argument is negative. - * - * @since 2.2 - */ -public class NotPositiveException extends NumberIsTooSmallException { - /** Serializable version Id. */ - private static final long serialVersionUID = -2250556892093726375L; - - /** - * Construct the exception. - * - * @param value Argument. - */ - public NotPositiveException(Number value) { - super(value, INTEGER_ZERO, true); - } - /** - * Construct the exception with a specific context. - * - * @param specific Specific context where the error occurred. - * @param value Argument. - */ - public NotPositiveException(Localizable specific, - Number value) { - super(specific, value, INTEGER_ZERO, true); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NotStrictlyPositiveException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NotStrictlyPositiveException.java deleted file mode 100644 index 156e78dc0..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NotStrictlyPositiveException.java +++ /dev/null @@ -1,49 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; - -/** - * Exception to be thrown when the argument is not greater than 0. - * - * @since 2.2 - */ -public class NotStrictlyPositiveException extends NumberIsTooSmallException { - - /** Serializable version Id. */ - private static final long serialVersionUID = -7824848630829852237L; - - /** - * Construct the exception. - * - * @param value Argument. - */ - public NotStrictlyPositiveException(Number value) { - super(value, INTEGER_ZERO, false); - } - /** - * Construct the exception with a specific context. - * - * @param specific Specific context where the error occurred. - * @param value Argument. - */ - public NotStrictlyPositiveException(Localizable specific, - Number value) { - super(specific, value, INTEGER_ZERO, false); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NullArgumentException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NullArgumentException.java deleted file mode 100644 index 06a3f8022..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NullArgumentException.java +++ /dev/null @@ -1,84 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.ExceptionContext; -import org.apache.commons.math4.exception.util.ExceptionContextProvider; -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * All conditions checks that fail due to a {@code null} argument must throw - * this exception. - * This class is meant to signal a precondition violation ("null is an illegal - * argument") and so does not extend the standard {@code NullPointerException}. - * Propagation of {@code NullPointerException} from within Commons-Math is - * construed to be a bug. - *

- * Note: from 4.0 onwards, this class extends {@link NullPointerException} instead - * of {@link MathIllegalArgumentException}. - * - * @since 2.2 - */ -public class NullArgumentException extends NullPointerException - implements ExceptionContextProvider { - - /** Serializable version Id. */ - private static final long serialVersionUID = 20150225L; - - /** Context. */ - private final ExceptionContext context; - - /** - * Default constructor. - */ - public NullArgumentException() { - this(LocalizedFormats.NULL_NOT_ALLOWED); - } - /** - * @param pattern Message pattern providing the specific context of - * the error. - * @param arguments Values for replacing the placeholders in {@code pattern}. - */ - public NullArgumentException(Localizable pattern, - Object ... arguments) { - context = new ExceptionContext(this); - context.addMessage(pattern, arguments); - } - - /** - * {@inheritDoc} - * @since 4.0 - */ - @Override - public ExceptionContext getContext() { - return context; - } - - /** {@inheritDoc} */ - @Override - public String getMessage() { - return context.getMessage(); - } - - /** {@inheritDoc} */ - @Override - public String getLocalizedMessage() { - return context.getLocalizedMessage(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NumberIsTooLargeException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NumberIsTooLargeException.java deleted file mode 100644 index 9498320a2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NumberIsTooLargeException.java +++ /dev/null @@ -1,85 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when a number is too large. - * - * @since 2.2 - */ -public class NumberIsTooLargeException extends MathIllegalNumberException { - /** Serializable version Id. */ - private static final long serialVersionUID = 4330003017885151975L; - /** - * Higher bound. - */ - private final Number max; - /** - * Whether the maximum is included in the allowed range. - */ - private final boolean boundIsAllowed; - - /** - * Construct the exception. - * - * @param wrong Value that is larger than the maximum. - * @param max Maximum. - * @param boundIsAllowed if true the maximum is included in the allowed range. - */ - public NumberIsTooLargeException(Number wrong, - Number max, - boolean boundIsAllowed) { - this(boundIsAllowed ? - LocalizedFormats.NUMBER_TOO_LARGE : - LocalizedFormats.NUMBER_TOO_LARGE_BOUND_EXCLUDED, - wrong, max, boundIsAllowed); - } - /** - * Construct the exception with a specific context. - * - * @param specific Specific context pattern. - * @param wrong Value that is larger than the maximum. - * @param max Maximum. - * @param boundIsAllowed if true the maximum is included in the allowed range. - */ - public NumberIsTooLargeException(Localizable specific, - Number wrong, - Number max, - boolean boundIsAllowed) { - super(specific, wrong, max); - - this.max = max; - this.boundIsAllowed = boundIsAllowed; - } - - /** - * @return {@code true} if the maximum is included in the allowed range. - */ - public boolean getBoundIsAllowed() { - return boundIsAllowed; - } - - /** - * @return the maximum. - */ - public Number getMax() { - return max; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NumberIsTooSmallException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NumberIsTooSmallException.java deleted file mode 100644 index 5a6cf700a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NumberIsTooSmallException.java +++ /dev/null @@ -1,86 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when a number is too small. - * - * @since 2.2 - */ -public class NumberIsTooSmallException extends MathIllegalNumberException { - /** Serializable version Id. */ - private static final long serialVersionUID = -6100997100383932834L; - /** - * Higher bound. - */ - private final Number min; - /** - * Whether the maximum is included in the allowed range. - */ - private final boolean boundIsAllowed; - - /** - * Construct the exception. - * - * @param wrong Value that is smaller than the minimum. - * @param min Minimum. - * @param boundIsAllowed Whether {@code min} is included in the allowed range. - */ - public NumberIsTooSmallException(Number wrong, - Number min, - boolean boundIsAllowed) { - this(boundIsAllowed ? - LocalizedFormats.NUMBER_TOO_SMALL : - LocalizedFormats.NUMBER_TOO_SMALL_BOUND_EXCLUDED, - wrong, min, boundIsAllowed); - } - - /** - * Construct the exception with a specific context. - * - * @param specific Specific context pattern. - * @param wrong Value that is smaller than the minimum. - * @param min Minimum. - * @param boundIsAllowed Whether {@code min} is included in the allowed range. - */ - public NumberIsTooSmallException(Localizable specific, - Number wrong, - Number min, - boolean boundIsAllowed) { - super(specific, wrong, min); - - this.min = min; - this.boundIsAllowed = boundIsAllowed; - } - - /** - * @return {@code true} if the minimum is included in the allowed range. - */ - public boolean getBoundIsAllowed() { - return boundIsAllowed; - } - - /** - * @return the minimum. - */ - public Number getMin() { - return min; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/OutOfRangeException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/OutOfRangeException.java deleted file mode 100644 index 4e8dd6212..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/OutOfRangeException.java +++ /dev/null @@ -1,78 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when some argument is out of range. - * - * @since 2.2 - */ -public class OutOfRangeException extends MathIllegalNumberException { - /** Serializable version Id. */ - private static final long serialVersionUID = 111601815794403609L; - /** Lower bound. */ - private final Number lo; - /** Higher bound. */ - private final Number hi; - - /** - * Construct an exception from the mismatched dimensions. - * - * @param wrong Requested value. - * @param lo Lower bound. - * @param hi Higher bound. - */ - public OutOfRangeException(Number wrong, - Number lo, - Number hi) { - this(LocalizedFormats.OUT_OF_RANGE_SIMPLE, wrong, lo, hi); - } - - /** - * Construct an exception from the mismatched dimensions with a - * specific context information. - * - * @param specific Context information. - * @param wrong Requested value. - * @param lo Lower bound. - * @param hi Higher bound. - */ - public OutOfRangeException(Localizable specific, - Number wrong, - Number lo, - Number hi) { - super(specific, wrong, lo, hi); - this.lo = lo; - this.hi = hi; - } - - /** - * @return the lower bound. - */ - public Number getLo() { - return lo; - } - /** - * @return the higher bound. - */ - public Number getHi() { - return hi; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/TooManyEvaluationsException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/TooManyEvaluationsException.java deleted file mode 100644 index 45d3c3aec..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/TooManyEvaluationsException.java +++ /dev/null @@ -1,39 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when the maximal number of evaluations is exceeded. - * - * @since 3.0 - */ -public class TooManyEvaluationsException extends MaxCountExceededException { - /** Serializable version Id. */ - private static final long serialVersionUID = 4330003017885151975L; - - /** - * Construct the exception. - * - * @param max Maximum number of evaluations. - */ - public TooManyEvaluationsException(Number max) { - super(max); - getContext().addMessage(LocalizedFormats.EVALUATIONS); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/TooManyIterationsException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/TooManyIterationsException.java deleted file mode 100644 index bd68f6ee2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/TooManyIterationsException.java +++ /dev/null @@ -1,39 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when the maximal number of iterations is exceeded. - * - * @since 3.1 - */ -public class TooManyIterationsException extends MaxCountExceededException { - /** Serializable version Id. */ - private static final long serialVersionUID = 20121211L; - - /** - * Construct the exception. - * - * @param max Maximum number of evaluations. - */ - public TooManyIterationsException(Number max) { - super(max); - getContext().addMessage(LocalizedFormats.ITERATIONS); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/ZeroException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/ZeroException.java deleted file mode 100644 index 617193a4f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/ZeroException.java +++ /dev/null @@ -1,48 +0,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. - */ -package org.apache.commons.math4.exception; - -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when zero is provided where it is not allowed. - * - * @since 2.2 - */ -public class ZeroException extends MathIllegalNumberException { - - /** Serializable version identifier */ - private static final long serialVersionUID = -1960874856936000015L; - - /** - * Construct the exception. - */ - public ZeroException() { - this(LocalizedFormats.ZERO_NOT_ALLOWED); - } - - /** - * Construct the exception with a specific context. - * - * @param specific Specific context pattern. - * @param arguments Arguments. - */ - public ZeroException(Localizable specific, Object ... arguments) { - super(specific, INTEGER_ZERO, arguments); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/package-info.java deleted file mode 100644 index 884f4c3fd..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/package-info.java +++ /dev/null @@ -1,23 +0,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. - */ -/** - * - * Specialized exceptions for algorithms errors. The exceptions can be localized - * using simple java properties. - * - */ -package org.apache.commons.math4.exception; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/ArgUtils.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/ArgUtils.java deleted file mode 100644 index 6e447a019..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/ArgUtils.java +++ /dev/null @@ -1,55 +0,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. - */ -package org.apache.commons.math4.exception.util; - -import java.util.List; -import java.util.ArrayList; - -/** - * Utility class for transforming the list of arguments passed to - * constructors of exceptions. - * - */ -public class ArgUtils { - /** - * Class contains only static methods. - */ - private ArgUtils() {} - - /** - * Transform a multidimensional array into a one-dimensional list. - * - * @param array Array (possibly multidimensional). - * @return a list of all the {@code Object} instances contained in - * {@code array}. - */ - public static Object[] flatten(Object[] array) { - final List list = new ArrayList<>(); - if (array != null) { - for (Object o : array) { - if (o instanceof Object[]) { - for (Object oR : flatten((Object[]) o)) { - list.add(oR); - } - } else { - list.add(o); - } - } - } - return list.toArray(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/DummyLocalizable.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/DummyLocalizable.java deleted file mode 100644 index 16c67f519..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/DummyLocalizable.java +++ /dev/null @@ -1,59 +0,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. - */ -package org.apache.commons.math4.exception.util; - -import java.util.Locale; - -/** - * Dummy implementation of the {@link Localizable} interface, without localization. - * - * @since 2.2 - */ -public class DummyLocalizable implements Localizable { - - /** Serializable version identifier. */ - private static final long serialVersionUID = 8843275624471387299L; - - /** Source string. */ - private final String source; - - /** Simple constructor. - * @param source source text - */ - public DummyLocalizable(final String source) { - this.source = source; - } - - /** {@inheritDoc} */ - @Override - public String getSourceString() { - return source; - } - - /** {@inheritDoc} */ - @Override - public String getLocalizedString(Locale locale) { - return source; - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return source; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/ExceptionContext.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/ExceptionContext.java deleted file mode 100644 index 4cdde9af9..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/ExceptionContext.java +++ /dev/null @@ -1,334 +0,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. - */ -package org.apache.commons.math4.exception.util; - -import java.util.List; -import java.util.ArrayList; -import java.util.Set; -import java.util.Map; -import java.io.IOException; -import java.io.Serializable; -import java.io.ObjectOutputStream; -import java.io.ObjectInputStream; -import java.util.HashMap; -import java.text.MessageFormat; -import java.util.Locale; - -/** - * Class that contains the actual implementation of the functionality mandated - * by the {@link ExceptionContext} interface. - * All Commons Math exceptions delegate the interface's methods to this class. - * - * @since 3.0 - */ -public class ExceptionContext implements Serializable { - /** Serializable version Id. */ - private static final long serialVersionUID = -6024911025449780478L; - /** - * The throwable to which this context refers to. - */ - private Throwable throwable; - /** - * Various informations that enrich the informative message. - */ - private List msgPatterns; - /** - * Various informations that enrich the informative message. - * The arguments will replace the corresponding place-holders in - * {@link #msgPatterns}. - */ - private List msgArguments; - /** - * Arbitrary context information. - */ - private Map context; - - /** Simple constructor. - * @param throwable the exception this context refers too - */ - public ExceptionContext(final Throwable throwable) { - this.throwable = throwable; - msgPatterns = new ArrayList<>(); - msgArguments = new ArrayList<>(); - context = new HashMap<>(); - } - - /** Get a reference to the exception to which the context relates. - * @return a reference to the exception to which the context relates - */ - public Throwable getThrowable() { - return throwable; - } - - /** - * Adds a message. - * - * @param pattern Message pattern. - * @param arguments Values for replacing the placeholders in the message - * pattern. - */ - public void addMessage(Localizable pattern, - Object ... arguments) { - msgPatterns.add(pattern); - msgArguments.add(ArgUtils.flatten(arguments)); - } - - /** - * Sets the context (key, value) pair. - * Keys are assumed to be unique within an instance. If the same key is - * assigned a new value, the previous one will be lost. - * - * @param key Context key (not null). - * @param value Context value. - */ - public void setValue(String key, Object value) { - context.put(key, value); - } - - /** - * Gets the value associated to the given context key. - * - * @param key Context key. - * @return the context value or {@code null} if the key does not exist. - */ - public Object getValue(String key) { - return context.get(key); - } - - /** - * Gets all the keys stored in the exception - * - * @return the set of keys. - */ - public Set getKeys() { - return context.keySet(); - } - - /** - * Gets the default message. - * - * @return the message. - */ - public String getMessage() { - return getMessage(Locale.US); - } - - /** - * Gets the message in the default locale. - * - * @return the localized message. - */ - public String getLocalizedMessage() { - return getMessage(Locale.getDefault()); - } - - /** - * Gets the message in a specified locale. - * - * @param locale Locale in which the message should be translated. - * @return the localized message. - */ - public String getMessage(final Locale locale) { - return buildMessage(locale, ": "); - } - - /** - * Gets the message in a specified locale. - * - * @param locale Locale in which the message should be translated. - * @param separator Separator inserted between the message parts. - * @return the localized message. - */ - public String getMessage(final Locale locale, - final String separator) { - return buildMessage(locale, separator); - } - - /** - * Builds a message string. - * - * @param locale Locale in which the message should be translated. - * @param separator Message separator. - * @return a localized message string. - */ - private String buildMessage(Locale locale, - String separator) { - final StringBuilder sb = new StringBuilder(); - int count = 0; - final int len = msgPatterns.size(); - for (int i = 0; i < len; i++) { - final Localizable pat = msgPatterns.get(i); - final Object[] args = msgArguments.get(i); - final MessageFormat fmt = new MessageFormat(pat.getLocalizedString(locale), - locale); - sb.append(fmt.format(args)); - if (++count < len) { - // Add a separator if there are other messages. - sb.append(separator); - } - } - - return sb.toString(); - } - - /** - * Serialize this object to the given stream. - * - * @param out Stream. - * @throws IOException This should never happen. - */ - private void writeObject(ObjectOutputStream out) - throws IOException { - out.writeObject(throwable); - serializeMessages(out); - serializeContext(out); - } - /** - * Deserialize this object from the given stream. - * - * @param in Stream. - * @throws IOException This should never happen. - * @throws ClassNotFoundException This should never happen. - */ - private void readObject(ObjectInputStream in) - throws IOException, - ClassNotFoundException { - throwable = (Throwable) in.readObject(); - deSerializeMessages(in); - deSerializeContext(in); - } - - /** - * Serialize {@link #msgPatterns} and {@link #msgArguments}. - * - * @param out Stream. - * @throws IOException This should never happen. - */ - private void serializeMessages(ObjectOutputStream out) - throws IOException { - // Step 1. - final int len = msgPatterns.size(); - out.writeInt(len); - // Step 2. - for (int i = 0; i < len; i++) { - final Localizable pat = msgPatterns.get(i); - // Step 3. - out.writeObject(pat); - final Object[] args = msgArguments.get(i); - final int aLen = args.length; - // Step 4. - out.writeInt(aLen); - for (int j = 0; j < aLen; j++) { - if (args[j] instanceof Serializable) { - // Step 5a. - out.writeObject(args[j]); - } else { - // Step 5b. - out.writeObject(nonSerializableReplacement(args[j])); - } - } - } - } - - /** - * Deserialize {@link #msgPatterns} and {@link #msgArguments}. - * - * @param in Stream. - * @throws IOException This should never happen. - * @throws ClassNotFoundException This should never happen. - */ - private void deSerializeMessages(ObjectInputStream in) - throws IOException, - ClassNotFoundException { - // Step 1. - final int len = in.readInt(); - msgPatterns = new ArrayList<>(len); - msgArguments = new ArrayList<>(len); - // Step 2. - for (int i = 0; i < len; i++) { - // Step 3. - final Localizable pat = (Localizable) in.readObject(); - msgPatterns.add(pat); - // Step 4. - final int aLen = in.readInt(); - final Object[] args = new Object[aLen]; - for (int j = 0; j < aLen; j++) { - // Step 5. - args[j] = in.readObject(); - } - msgArguments.add(args); - } - } - - /** - * Serialize {@link #context}. - * - * @param out Stream. - * @throws IOException This should never happen. - */ - private void serializeContext(ObjectOutputStream out) - throws IOException { - // Step 1. - final int len = context.size(); - out.writeInt(len); - for (Map.Entry entry : context.entrySet()) { - // Step 2. - out.writeObject(entry.getKey()); - final Object value = entry.getValue(); - if (value instanceof Serializable) { - // Step 3a. - out.writeObject(value); - } else { - // Step 3b. - out.writeObject(nonSerializableReplacement(value)); - } - } - } - - /** - * Deserialize {@link #context}. - * - * @param in Stream. - * @throws IOException This should never happen. - * @throws ClassNotFoundException This should never happen. - */ - private void deSerializeContext(ObjectInputStream in) - throws IOException, - ClassNotFoundException { - // Step 1. - final int len = in.readInt(); - context = new HashMap<>(); - for (int i = 0; i < len; i++) { - // Step 2. - final String key = (String) in.readObject(); - // Step 3. - final Object value = in.readObject(); - context.put(key, value); - } - } - - /** - * Replaces a non-serializable object with an error message string. - * - * @param obj Object that does not implement the {@code Serializable} - * interface. - * @return a string that mentions which class could not be serialized. - */ - private String nonSerializableReplacement(Object obj) { - return "[Object could not be serialized: " + obj.getClass().getName() + "]"; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/ExceptionContextProvider.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/ExceptionContextProvider.java deleted file mode 100644 index 06f5e2cd3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/ExceptionContextProvider.java +++ /dev/null @@ -1,33 +0,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. - */ -package org.apache.commons.math4.exception.util; - -/** - * Interface for accessing the context data structure stored in Commons Math - * exceptions. - * - */ -public interface ExceptionContextProvider { - /** - * Gets a reference to the "rich context" data structure that allows to - * customize error messages and store key, value pairs in exceptions. - * - * @return a reference to the exception context. - */ - ExceptionContext getContext(); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/Localizable.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/Localizable.java deleted file mode 100644 index 9e4a38f93..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/Localizable.java +++ /dev/null @@ -1,43 +0,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. - */ -package org.apache.commons.math4.exception.util; - -import java.io.Serializable; -import java.util.Locale; - -/** - * Interface for localizable strings. - * - * @since 2.2 - */ -public interface Localizable extends Serializable { - /** - * Gets the source (non-localized) string. - * - * @return the source string. - */ - String getSourceString(); - - /** - * Gets the localized string. - * - * @param locale locale into which to get the string. - * @return the localized string or the source string if no - * localized version is available. - */ - String getLocalizedString(Locale locale); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/LocalizedFormats.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/LocalizedFormats.java deleted file mode 100644 index f504516ee..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/LocalizedFormats.java +++ /dev/null @@ -1,417 +0,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. - */ -package org.apache.commons.math4.exception.util; - -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -/** - * Enumeration for localized messages formats used in exceptions messages. - *

- * The constants in this enumeration represent the available - * formats as localized strings. These formats are intended to be - * localized using simple properties files, using the constant - * name as the key and the property value as the message format. - * The source English format is provided in the constants themselves - * to serve both as a reminder for developers to understand the parameters - * needed by each format, as a basis for translators to create - * localized properties files, and as a default format if some - * translation is missing. - *

- * @since 2.2 - */ -public enum LocalizedFormats implements Localizable { - - // CHECKSTYLE: stop MultipleVariableDeclarations - // CHECKSTYLE: stop JavadocVariable - - ARGUMENT_OUTSIDE_DOMAIN("Argument {0} outside domain [{1} ; {2}]"), - ARRAY_SIZE_EXCEEDS_MAX_VARIABLES("array size cannot be greater than {0}"), - ARRAY_SIZES_SHOULD_HAVE_DIFFERENCE_1("array sizes should have difference 1 ({0} != {1} + 1)"), - ARRAY_SUMS_TO_ZERO("array sums to zero"), - ASSYMETRIC_EIGEN_NOT_SUPPORTED("eigen decomposition of assymetric matrices not supported yet"), - AT_LEAST_ONE_COLUMN("matrix must have at least one column"), - AT_LEAST_ONE_ROW("matrix must have at least one row"), - BANDWIDTH("bandwidth ({0})"), - BESSEL_FUNCTION_BAD_ARGUMENT("Bessel function of order {0} cannot be computed for x = {1}"), - BESSEL_FUNCTION_FAILED_CONVERGENCE("Bessel function of order {0} failed to converge for x = {1}"), - BINOMIAL_INVALID_PARAMETERS_ORDER("must have n >= k for binomial coefficient (n, k), got k = {0}, n = {1}"), - BINOMIAL_NEGATIVE_PARAMETER("must have n >= 0 for binomial coefficient (n, k), got n = {0}"), - CANNOT_CLEAR_STATISTIC_CONSTRUCTED_FROM_EXTERNAL_MOMENTS("statistics constructed from external moments cannot be cleared"), - CANNOT_COMPUTE_0TH_ROOT_OF_UNITY("cannot compute 0-th root of unity, indefinite result"), - CANNOT_COMPUTE_BETA_DENSITY_AT_0_FOR_SOME_ALPHA("cannot compute beta density at 0 when alpha = {0,number}"), - CANNOT_COMPUTE_BETA_DENSITY_AT_1_FOR_SOME_BETA("cannot compute beta density at 1 when beta = %.3g"), - CANNOT_COMPUTE_NTH_ROOT_FOR_NEGATIVE_N("cannot compute nth root for null or negative n: {0}"), - CANNOT_DISCARD_NEGATIVE_NUMBER_OF_ELEMENTS("cannot discard a negative number of elements ({0})"), - CANNOT_FORMAT_INSTANCE_AS_3D_VECTOR("cannot format a {0} instance as a 3D vector"), - CANNOT_FORMAT_INSTANCE_AS_COMPLEX("cannot format a {0} instance as a complex number"), - CANNOT_FORMAT_INSTANCE_AS_REAL_VECTOR("cannot format a {0} instance as a real vector"), - CANNOT_FORMAT_OBJECT_TO_FRACTION("cannot format given object as a fraction number"), - CANNOT_INCREMENT_STATISTIC_CONSTRUCTED_FROM_EXTERNAL_MOMENTS("statistics constructed from external moments cannot be incremented"), - CANNOT_NORMALIZE_A_ZERO_NORM_VECTOR("cannot normalize a zero norm vector"), - CANNOT_RETRIEVE_AT_NEGATIVE_INDEX("elements cannot be retrieved from a negative array index {0}"), - CANNOT_SET_AT_NEGATIVE_INDEX("cannot set an element at a negative index {0}"), - CANNOT_SUBSTITUTE_ELEMENT_FROM_EMPTY_ARRAY("cannot substitute an element from an empty array"), - CANNOT_TRANSFORM_TO_DOUBLE("Conversion Exception in Transformation: {0}"), - CARDAN_ANGLES_SINGULARITY("Cardan angles singularity"), - CLASS_DOESNT_IMPLEMENT_COMPARABLE("class ({0}) does not implement Comparable"), - CLOSE_VERTICES("too close vertices near point ({0}, {1}, {2})"), - CLOSEST_ORTHOGONAL_MATRIX_HAS_NEGATIVE_DETERMINANT("the closest orthogonal matrix has a negative determinant {0}"), - COLUMN_INDEX_OUT_OF_RANGE("column index {0} out of allowed range [{1}, {2}]"), - COLUMN_INDEX("column index ({0})"), /* keep */ - CONSTRAINT("constraint"), /* keep */ - CONTINUED_FRACTION_INFINITY_DIVERGENCE("Continued fraction convergents diverged to +/- infinity for value {0}"), - CONTINUED_FRACTION_NAN_DIVERGENCE("Continued fraction diverged to NaN for value {0}"), - CONTRACTION_CRITERIA_SMALLER_THAN_EXPANSION_FACTOR("contraction criteria ({0}) smaller than the expansion factor ({1}). This would lead to a never ending loop of expansion and contraction as a newly expanded internal storage array would immediately satisfy the criteria for contraction."), - CONTRACTION_CRITERIA_SMALLER_THAN_ONE("contraction criteria smaller than one ({0}). This would lead to a never ending loop of expansion and contraction as an internal storage array length equal to the number of elements would satisfy the contraction criteria."), - CONVERGENCE_FAILED("convergence failed"), /* keep */ - CROSSING_BOUNDARY_LOOPS("some outline boundary loops cross each other"), - CROSSOVER_RATE("crossover rate ({0})"), - CUMULATIVE_PROBABILITY_RETURNED_NAN("Cumulative probability function returned NaN for argument {0} p = {1}"), - DIFFERENT_ROWS_LENGTHS("some rows have length {0} while others have length {1}"), - DIFFERENT_ORIG_AND_PERMUTED_DATA("original and permuted data must contain the same elements"), - DIGEST_NOT_INITIALIZED("digest not initialized"), - DIMENSIONS_MISMATCH_2x2("got {0}x{1} but expected {2}x{3}"), /* keep */ - DIMENSIONS_MISMATCH_SIMPLE("{0} != {1}"), /* keep */ - DIMENSIONS_MISMATCH("dimensions mismatch"), /* keep */ - DISCRETE_CUMULATIVE_PROBABILITY_RETURNED_NAN("Discrete cumulative probability function returned NaN for argument {0}"), - DISTRIBUTION_NOT_LOADED("distribution not loaded"), - DUPLICATED_ABSCISSA_DIVISION_BY_ZERO("duplicated abscissa {0} causes division by zero"), - EDGE_CONNECTED_TO_ONE_FACET("edge joining points ({0}, {1}, {2}) and ({3}, {4}, {5}) is connected to one facet only"), - ELITISM_RATE("elitism rate ({0})"), - EMPTY_CLUSTER_IN_K_MEANS("empty cluster in k-means"), - EMPTY_INTERPOLATION_SAMPLE("sample for interpolation is empty"), - EMPTY_POLYNOMIALS_COEFFICIENTS_ARRAY("empty polynomials coefficients array"), /* keep */ - EMPTY_SELECTED_COLUMN_INDEX_ARRAY("empty selected column index array"), - EMPTY_SELECTED_ROW_INDEX_ARRAY("empty selected row index array"), - EMPTY_STRING_FOR_IMAGINARY_CHARACTER("empty string for imaginary character"), - ENDPOINTS_NOT_AN_INTERVAL("endpoints do not specify an interval: [{0}, {1}]"), - EQUAL_VERTICES_IN_SIMPLEX("equal vertices {0} and {1} in simplex configuration"), - EULER_ANGLES_SINGULARITY("Euler angles singularity"), - EVALUATION("evaluation"), /* keep */ - EXPANSION_FACTOR_SMALLER_THAN_ONE("expansion factor smaller than one ({0})"), - FACET_ORIENTATION_MISMATCH("facets orientation mismatch around edge joining points ({0}, {1}, {2}) and ({3}, {4}, {5})"), - FACTORIAL_NEGATIVE_PARAMETER("must have n >= 0 for n!, got n = {0}"), - FAILED_BRACKETING("number of iterations={4}, maximum iterations={5}, initial={6}, lower bound={7}, upper bound={8}, final a value={0}, final b value={1}, f(a)={2}, f(b)={3}"), - FAILED_FRACTION_CONVERSION("Unable to convert {0} to fraction after {1} iterations"), - FIRST_COLUMNS_NOT_INITIALIZED_YET("first {0} columns are not initialized yet"), - FIRST_ELEMENT_NOT_ZERO("first element is not 0: {0}"), - FIRST_ROWS_NOT_INITIALIZED_YET("first {0} rows are not initialized yet"), - FRACTION_CONVERSION_OVERFLOW("Overflow trying to convert {0} to fraction ({1}/{2})"), - FUNCTION_NOT_DIFFERENTIABLE("function is not differentiable"), - FUNCTION_NOT_POLYNOMIAL("function is not polynomial"), - GCD_OVERFLOW_32_BITS("overflow: gcd({0}, {1}) is 2^31"), - GCD_OVERFLOW_64_BITS("overflow: gcd({0}, {1}) is 2^63"), - HOLE_BETWEEN_MODELS_TIME_RANGES("{0} wide hole between models time ranges"), - ILL_CONDITIONED_OPERATOR("condition number {1} is too high "), - INCONSISTENT_STATE_AT_2_PI_WRAPPING("inconsistent state at 2\u03c0 wrapping"), - INDEX_LARGER_THAN_MAX("the index specified: {0} is larger than the current maximal index {1}"), - INDEX_NOT_POSITIVE("index ({0}) is not positive"), - INDEX_OUT_OF_RANGE("index {0} out of allowed range [{1}, {2}]"), - INDEX("index ({0})"), /* keep */ - NOT_FINITE_NUMBER("{0} is not a finite number"), /* keep */ - INFINITE_BOUND("interval bounds must be finite"), - ARRAY_ELEMENT("value {0} at index {1}"), /* keep */ - INFINITE_ARRAY_ELEMENT("Array contains an infinite element, {0} at index {1}"), - INFINITE_VALUE_CONVERSION("cannot convert infinite value"), - INITIAL_CAPACITY_NOT_POSITIVE("initial capacity ({0}) is not positive"), - INITIAL_COLUMN_AFTER_FINAL_COLUMN("initial column {1} after final column {0}"), - INITIAL_ROW_AFTER_FINAL_ROW("initial row {1} after final row {0}"), - INSTANCES_NOT_COMPARABLE_TO_EXISTING_VALUES("instance of class {0} not comparable to existing values"), - INSUFFICIENT_DATA("insufficient data"), - INSUFFICIENT_DATA_FOR_T_STATISTIC("insufficient data for t statistic, needs at least 2, got {0}"), - INSUFFICIENT_DIMENSION("insufficient dimension {0}, must be at least {1}"), - DIMENSION("dimension ({0})"), /* keep */ - INSUFFICIENT_OBSERVED_POINTS_IN_SAMPLE("sample contains {0} observed points, at least {1} are required"), - INSUFFICIENT_ROWS_AND_COLUMNS("insufficient data: only {0} rows and {1} columns."), - INTEGRATION_METHOD_NEEDS_AT_LEAST_TWO_PREVIOUS_POINTS("multistep method needs at least {0} previous steps, got {1}"), - INTERNAL_ERROR("internal error, please fill a bug report at {0}"), - INVALID_BINARY_DIGIT("invalid binary digit: {0}"), - INVALID_BINARY_CHROMOSOME("binary mutation works on BinaryChromosome only"), - INVALID_BRACKETING_PARAMETERS("invalid bracketing parameters: lower bound={0}, initial={1}, upper bound={2}"), - INVALID_FIXED_LENGTH_CHROMOSOME("one-point crossover only works with fixed-length chromosomes"), - INVALID_IMPLEMENTATION("required functionality is missing in {0}"), - INVALID_INTERVAL_INITIAL_VALUE_PARAMETERS("invalid interval, initial value parameters: lower={0}, initial={1}, upper={2}"), - INVALID_ITERATIONS_LIMITS("invalid iteration limits: min={0}, max={1}"), - INVALID_MAX_ITERATIONS("bad value for maximum iterations number: {0}"), - NOT_ENOUGH_DATA_REGRESSION("the number of observations is not sufficient to conduct regression"), - INVALID_REGRESSION_ARRAY("input data array length = {0} does not match the number of observations = {1} and the number of regressors = {2}"), - INVALID_REGRESSION_OBSERVATION("length of regressor array = {0} does not match the number of variables = {1} in the model"), - INVALID_ROUNDING_METHOD("invalid rounding method {0}, valid methods: {1} ({2}), {3} ({4}), {5} ({6}), {7} ({8}), {9} ({10}), {11} ({12}), {13} ({14}), {15} ({16})"), - ITERATOR_EXHAUSTED("iterator exhausted"), - ITERATIONS("iterations"), /* keep */ - LCM_OVERFLOW_32_BITS("overflow: lcm({0}, {1}) is 2^31"), - LCM_OVERFLOW_64_BITS("overflow: lcm({0}, {1}) is 2^63"), - LIST_OF_CHROMOSOMES_BIGGER_THAN_POPULATION_SIZE("list of chromosomes bigger than maxPopulationSize"), - LOESS_EXPECTS_AT_LEAST_ONE_POINT("Loess expects at least 1 point"), - LOWER_BOUND_NOT_BELOW_UPPER_BOUND("lower bound ({0}) must be strictly less than upper bound ({1})"), /* keep */ - LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT("lower endpoint ({0}) must be less than or equal to upper endpoint ({1})"), - MAP_MODIFIED_WHILE_ITERATING("map has been modified while iterating"), - MULTISTEP_STARTER_STOPPED_EARLY("multistep integrator starter stopped early, maybe too large step size"), - EVALUATIONS("evaluations"), /* keep */ - MAX_COUNT_EXCEEDED("maximal count ({0}) exceeded"), /* keep */ - MAX_ITERATIONS_EXCEEDED("maximal number of iterations ({0}) exceeded"), - MINIMAL_STEPSIZE_REACHED_DURING_INTEGRATION("minimal step size ({1,number,0.00E00}) reached, integration needs {0,number,0.00E00}"), - MISMATCHED_LOESS_ABSCISSA_ORDINATE_ARRAYS("Loess expects the abscissa and ordinate arrays to be of the same size, but got {0} abscissae and {1} ordinatae"), - MUTATION_RATE("mutation rate ({0})"), - NAN_ELEMENT_AT_INDEX("element {0} is NaN"), - NAN_VALUE_CONVERSION("cannot convert NaN value"), - NEGATIVE_BRIGHTNESS_EXPONENT("brightness exponent should be positive or null, but got {0}"), - NEGATIVE_COMPLEX_MODULE("negative complex module {0}"), - NEGATIVE_ELEMENT_AT_2D_INDEX("element ({0}, {1}) is negative: {2}"), - NEGATIVE_ELEMENT_AT_INDEX("element {0} is negative: {1}"), - NEGATIVE_NUMBER_OF_SUCCESSES("number of successes must be non-negative ({0})"), - NUMBER_OF_SUCCESSES("number of successes ({0})"), /* keep */ - NEGATIVE_NUMBER_OF_TRIALS("number of trials must be non-negative ({0})"), - NUMBER_OF_INTERPOLATION_POINTS("number of interpolation points ({0})"), /* keep */ - NUMBER_OF_TRIALS("number of trials ({0})"), - NOT_CONVEX("vertices do not form a convex hull in CCW winding"), - NOT_CONVEX_HYPERPLANES("hyperplanes do not define a convex region"), - ROBUSTNESS_ITERATIONS("number of robustness iterations ({0})"), - START_POSITION("start position ({0})"), /* keep */ - NON_CONVERGENT_CONTINUED_FRACTION("Continued fraction convergents failed to converge (in less than {0} iterations) for value {1}"), - NON_INVERTIBLE_TRANSFORM("non-invertible affine transform collapses some lines into single points"), - NON_POSITIVE_MICROSPHERE_ELEMENTS("number of microsphere elements must be positive, but got {0}"), - NON_POSITIVE_POLYNOMIAL_DEGREE("polynomial degree must be positive: degree={0}"), - NON_REAL_FINITE_ABSCISSA("all abscissae must be finite real numbers, but {0}-th is {1}"), - NON_REAL_FINITE_ORDINATE("all ordinatae must be finite real numbers, but {0}-th is {1}"), - NON_REAL_FINITE_WEIGHT("all weights must be finite real numbers, but {0}-th is {1}"), - NON_SQUARE_MATRIX("non square ({0}x{1}) matrix"), - NORM("Norm ({0})"), /* keep */ - NORMALIZE_INFINITE("Cannot normalize to an infinite value"), - NORMALIZE_NAN("Cannot normalize to NaN"), - NOT_ADDITION_COMPATIBLE_MATRICES("{0}x{1} and {2}x{3} matrices are not addition compatible"), - NOT_DECREASING_NUMBER_OF_POINTS("points {0} and {1} are not decreasing ({2} < {3})"), - NOT_DECREASING_SEQUENCE("points {3} and {2} are not decreasing ({1} < {0})"), /* keep */ - NOT_ENOUGH_DATA_FOR_NUMBER_OF_PREDICTORS("not enough data ({0} rows) for this many predictors ({1} predictors)"), - NOT_ENOUGH_POINTS_IN_SPLINE_PARTITION("spline partition must have at least {1} points, got {0}"), - NOT_INCREASING_NUMBER_OF_POINTS("points {0} and {1} are not increasing ({2} > {3})"), - NOT_INCREASING_SEQUENCE("points {3} and {2} are not increasing ({1} > {0})"), /* keep */ - NOT_MULTIPLICATION_COMPATIBLE_MATRICES("{0}x{1} and {2}x{3} matrices are not multiplication compatible"), - NOT_POSITIVE_DEFINITE_MATRIX("not positive definite matrix"), /* keep */ - NON_POSITIVE_DEFINITE_MATRIX("not positive definite matrix: diagonal element at ({1},{1}) is smaller than {2} ({0})"), - NON_POSITIVE_DEFINITE_OPERATOR("non positive definite linear operator"), /* keep */ - NON_SELF_ADJOINT_OPERATOR("non self-adjoint linear operator"), /* keep */ - NON_SQUARE_OPERATOR("non square ({0}x{1}) linear operator"), /* keep */ - DEGREES_OF_FREEDOM("degrees of freedom ({0})"), /* keep */ - NOT_POSITIVE_DEGREES_OF_FREEDOM("degrees of freedom must be positive ({0})"), - NOT_POSITIVE_ELEMENT_AT_INDEX("element {0} is not positive: {1}"), - NOT_POSITIVE_EXPONENT("invalid exponent {0} (must be positive)"), - NUMBER_OF_ELEMENTS_SHOULD_BE_POSITIVE("number of elements should be positive ({0})"), - BASE("base ({0})"), /* keep */ - EXPONENT("exponent ({0})"), /* keep */ - NOT_POSITIVE_LENGTH("length must be positive ({0})"), - LENGTH("length ({0})"), /* keep */ - NOT_POSITIVE_MEAN("mean must be positive ({0})"), - MEAN("mean ({0})"), /* keep */ - NOT_POSITIVE_NUMBER_OF_SAMPLES("number of sample is not positive: {0}"), - NUMBER_OF_SAMPLES("number of samples ({0})"), /* keep */ - NOT_POSITIVE_PERMUTATION("permutation k ({0}) must be positive"), - PERMUTATION_SIZE("permutation size ({0}"), /* keep */ - NOT_POSITIVE_POISSON_MEAN("the Poisson mean must be positive ({0})"), - NOT_POSITIVE_POPULATION_SIZE("population size must be positive ({0})"), - POPULATION_SIZE("population size ({0})"), /* keep */ - NOT_POSITIVE_ROW_DIMENSION("invalid row dimension: {0} (must be positive)"), - NOT_POSITIVE_SAMPLE_SIZE("sample size must be positive ({0})"), - NOT_POSITIVE_SCALE("scale must be positive ({0})"), - SCALE("scale ({0})"), /* keep */ - NOT_POSITIVE_SHAPE("shape must be positive ({0})"), - SHAPE("shape ({0})"), /* keep */ - NOT_POSITIVE_STANDARD_DEVIATION("standard deviation must be positive ({0})"), - STANDARD_DEVIATION("standard deviation ({0})"), /* keep */ - NOT_POSITIVE_UPPER_BOUND("upper bound must be positive ({0})"), - NOT_POSITIVE_WINDOW_SIZE("window size must be positive ({0})"), - NOT_POWER_OF_TWO("{0} is not a power of 2"), - NOT_POWER_OF_TWO_CONSIDER_PADDING("{0} is not a power of 2, consider padding for fix"), - NOT_POWER_OF_TWO_PLUS_ONE("{0} is not a power of 2 plus one"), - NOT_STRICTLY_DECREASING_NUMBER_OF_POINTS("points {0} and {1} are not strictly decreasing ({2} <= {3})"), - NOT_STRICTLY_DECREASING_SEQUENCE("points {3} and {2} are not strictly decreasing ({1} <= {0})"), /* keep */ - NOT_STRICTLY_INCREASING_KNOT_VALUES("knot values must be strictly increasing"), - NOT_STRICTLY_INCREASING_NUMBER_OF_POINTS("points {0} and {1} are not strictly increasing ({2} >= {3})"), - NOT_STRICTLY_INCREASING_SEQUENCE("points {3} and {2} are not strictly increasing ({1} >= {0})"), /* keep */ - NOT_SUBTRACTION_COMPATIBLE_MATRICES("{0}x{1} and {2}x{3} matrices are not subtraction compatible"), - NOT_SUPPORTED_IN_DIMENSION_N("method not supported in dimension {0}"), - NOT_SUPPORTED_NAN_STRATEGY("NaN strategy {0} not supported"), - NOT_SYMMETRIC_MATRIX("not symmetric matrix"), - NON_SYMMETRIC_MATRIX("non symmetric matrix: the difference between entries at ({0},{1}) and ({1},{0}) is larger than {2}"), /* keep */ - NO_BIN_SELECTED("no bin selected"), - NO_CONVERGENCE_WITH_ANY_START_POINT("none of the {0} start points lead to convergence"), /* keep */ - NO_DATA("no data"), /* keep */ - NO_DEGREES_OF_FREEDOM("no degrees of freedom ({0} measurements, {1} parameters)"), - NO_DENSITY_FOR_THIS_DISTRIBUTION("This distribution does not have a density function implemented"), - NO_FEASIBLE_SOLUTION("no feasible solution"), - NO_OPTIMUM_COMPUTED_YET("no optimum computed yet"), /* keep */ - NO_REGRESSORS("Regression model must include at least one regressor"), - NO_RESULT_AVAILABLE("no result available"), - NO_SUCH_MATRIX_ENTRY("no entry at indices ({0}, {1}) in a {2}x{3} matrix"), - NAN_NOT_ALLOWED("NaN is not allowed"), - NULL_NOT_ALLOWED("null is not allowed"), /* keep */ - ARRAY_ZERO_LENGTH_OR_NULL_NOT_ALLOWED("a null or zero length array not allowed"), - COVARIANCE_MATRIX("covariance matrix"), /* keep */ - DENOMINATOR("denominator"), /* keep */ - DENOMINATOR_FORMAT("denominator format"), /* keep */ - FRACTION("fraction"), /* keep */ - FUNCTION("function"), /* keep */ - IMAGINARY_FORMAT("imaginary format"), /* keep */ - INPUT_ARRAY("input array"), /* keep */ - NUMERATOR("numerator"), /* keep */ - NUMERATOR_FORMAT("numerator format"), /* keep */ - OBJECT_TRANSFORMATION("conversion exception in transformation"), /* keep */ - REAL_FORMAT("real format"), /* keep */ - WHOLE_FORMAT("whole format"), /* keep */ - NUMBER_TOO_LARGE("{0} is larger than the maximum ({1})"), /* keep */ - NUMBER_TOO_SMALL("{0} is smaller than the minimum ({1})"), /* keep */ - NUMBER_TOO_LARGE_BOUND_EXCLUDED("{0} is larger than, or equal to, the maximum ({1})"), /* keep */ - NUMBER_TOO_SMALL_BOUND_EXCLUDED("{0} is smaller than, or equal to, the minimum ({1})"), /* keep */ - NUMBER_OF_SUCCESS_LARGER_THAN_POPULATION_SIZE("number of successes ({0}) must be less than or equal to population size ({1})"), - NUMERATOR_OVERFLOW_AFTER_MULTIPLY("overflow, numerator too large after multiply: {0}"), - N_POINTS_GAUSS_LEGENDRE_INTEGRATOR_NOT_SUPPORTED("{0} points Legendre-Gauss integrator not supported, number of points must be in the {1}-{2} range"), - OBSERVED_COUNTS_ALL_ZERO("observed counts are all 0 in observed array {0}"), - OBSERVED_COUNTS_BOTTH_ZERO_FOR_ENTRY("observed counts are both zero for entry {0}"), - BOBYQA_BOUND_DIFFERENCE_CONDITION("the difference between the upper and lower bound must be larger than twice the initial trust region radius ({0})"), - OUT_OF_BOUNDS_QUANTILE_VALUE("out of bounds quantile value: {0}, must be in (0, 100]"), - OUT_OF_BOUNDS_CONFIDENCE_LEVEL("out of bounds confidence level {0}, must be between {1} and {2}"), - OUT_OF_BOUND_SIGNIFICANCE_LEVEL("out of bounds significance level {0}, must be between {1} and {2}"), - SIGNIFICANCE_LEVEL("significance level ({0})"), /* keep */ - OUT_OF_ORDER_ABSCISSA_ARRAY("the abscissae array must be sorted in a strictly increasing order, but the {0}-th element is {1} whereas {2}-th is {3}"), - OUT_OF_PLANE("point ({0}, {1}, {2}) is out of plane"), - OUT_OF_RANGE_ROOT_OF_UNITY_INDEX("out of range root of unity index {0} (must be in [{1};{2}])"), - OUT_OF_RANGE("out of range"), /* keep */ - OUT_OF_RANGE_SIMPLE("{0} out of [{1}, {2}] range"), /* keep */ - OUT_OF_RANGE_LEFT("{0} out of ({1}, {2}] range"), - OUT_OF_RANGE_RIGHT("{0} out of [{1}, {2}) range"), - OUTLINE_BOUNDARY_LOOP_OPEN("an outline boundary loop is open"), - OVERFLOW("overflow"), /* keep */ - OVERFLOW_IN_FRACTION("overflow in fraction {0}/{1}, cannot negate"), - OVERFLOW_IN_ADDITION("overflow in addition: {0} + {1}"), - OVERFLOW_IN_SUBTRACTION("overflow in subtraction: {0} - {1}"), - OVERFLOW_IN_MULTIPLICATION("overflow in multiplication: {0} * {1}"), - PERCENTILE_IMPLEMENTATION_CANNOT_ACCESS_METHOD("cannot access {0} method in percentile implementation {1}"), - PERCENTILE_IMPLEMENTATION_UNSUPPORTED_METHOD("percentile implementation {0} does not support {1}"), - PERMUTATION_EXCEEDS_N("permutation size ({0}) exceeds permuation domain ({1})"), /* keep */ - POLYNOMIAL("polynomial"), /* keep */ - POLYNOMIAL_INTERPOLANTS_MISMATCH_SEGMENTS("number of polynomial interpolants must match the number of segments ({0} != {1} - 1)"), - POPULATION_LIMIT_NOT_POSITIVE("population limit has to be positive"), - POWER_NEGATIVE_PARAMETERS("cannot raise an integral value to a negative power ({0}^{1})"), - PROPAGATION_DIRECTION_MISMATCH("propagation direction mismatch"), - RANDOMKEY_MUTATION_WRONG_CLASS("RandomKeyMutation works only with RandomKeys, not {0}"), - ROOTS_OF_UNITY_NOT_COMPUTED_YET("roots of unity have not been computed yet"), - ROTATION_MATRIX_DIMENSIONS("a {0}x{1} matrix cannot be a rotation matrix"), - ROW_INDEX_OUT_OF_RANGE("row index {0} out of allowed range [{1}, {2}]"), - ROW_INDEX("row index ({0})"), /* keep */ - SAME_SIGN_AT_ENDPOINTS("function values at endpoints do not have different signs, endpoints: [{0}, {1}], values: [{2}, {3}]"), - SAMPLE_SIZE_EXCEEDS_COLLECTION_SIZE("sample size ({0}) exceeds collection size ({1})"), /* keep */ - SAMPLE_SIZE_LARGER_THAN_POPULATION_SIZE("sample size ({0}) must be less than or equal to population size ({1})"), - SIMPLEX_NEED_ONE_POINT("simplex must contain at least one point"), - SIMPLE_MESSAGE("{0}"), - SINGULAR_MATRIX("matrix is singular"), /* keep */ - SINGULAR_OPERATOR("operator is singular"), - SUBARRAY_ENDS_AFTER_ARRAY_END("subarray ends after array end"), - TOO_LARGE_CUTOFF_SINGULAR_VALUE("cutoff singular value is {0}, should be at most {1}"), - TOO_LARGE_TOURNAMENT_ARITY("tournament arity ({0}) cannot be bigger than population size ({1})"), - TOO_MANY_ELEMENTS_TO_DISCARD_FROM_ARRAY("cannot discard {0} elements from a {1} elements array"), - TOO_MANY_REGRESSORS("too many regressors ({0}) specified, only {1} in the model"), - TOO_SMALL_COST_RELATIVE_TOLERANCE("cost relative tolerance is too small ({0}), no further reduction in the sum of squares is possible"), - TOO_SMALL_INTEGRATION_INTERVAL("too small integration interval: length = {0}"), - TOO_SMALL_ORTHOGONALITY_TOLERANCE("orthogonality tolerance is too small ({0}), solution is orthogonal to the jacobian"), - TOO_SMALL_PARAMETERS_RELATIVE_TOLERANCE("parameters relative tolerance is too small ({0}), no further improvement in the approximate solution is possible"), - TRUST_REGION_STEP_FAILED("trust region step has failed to reduce Q"), - TWO_OR_MORE_CATEGORIES_REQUIRED("two or more categories required, got {0}"), - TWO_OR_MORE_VALUES_IN_CATEGORY_REQUIRED("two or more values required in each category, one has {0}"), - UNABLE_TO_BRACKET_OPTIMUM_IN_LINE_SEARCH("unable to bracket optimum in line search"), - UNABLE_TO_COMPUTE_COVARIANCE_SINGULAR_PROBLEM("unable to compute covariances: singular problem"), - UNABLE_TO_FIRST_GUESS_HARMONIC_COEFFICIENTS("unable to first guess the harmonic coefficients"), - UNABLE_TO_ORTHOGONOLIZE_MATRIX("unable to orthogonalize matrix in {0} iterations"), - UNABLE_TO_PERFORM_QR_DECOMPOSITION_ON_JACOBIAN("unable to perform Q.R decomposition on the {0}x{1} jacobian matrix"), - UNABLE_TO_SOLVE_SINGULAR_PROBLEM("unable to solve: singular problem"), - UNBOUNDED_SOLUTION("unbounded solution"), - UNKNOWN_MODE("unknown mode {0}, known modes: {1} ({2}), {3} ({4}), {5} ({6}), {7} ({8}), {9} ({10}) and {11} ({12})"), - UNKNOWN_PARAMETER("unknown parameter {0}"), - UNMATCHED_ODE_IN_EXPANDED_SET("ode does not match the main ode set in the extended set"), - CANNOT_PARSE_AS_TYPE("string \"{0}\" unparseable (from position {1}) as an object of type {2}"), /* keep */ - CANNOT_PARSE("string \"{0}\" unparseable (from position {1})"), /* keep */ - UNPARSEABLE_3D_VECTOR("unparseable 3D vector: \"{0}\""), - UNPARSEABLE_COMPLEX_NUMBER("unparseable complex number: \"{0}\""), - UNPARSEABLE_REAL_VECTOR("unparseable real vector: \"{0}\""), - UNSUPPORTED_EXPANSION_MODE("unsupported expansion mode {0}, supported modes are {1} ({2}) and {3} ({4})"), - UNSUPPORTED_OPERATION("unsupported operation"), /* keep */ - ARITHMETIC_EXCEPTION("arithmetic exception"), /* keep */ - ILLEGAL_STATE("illegal state"), /* keep */ - USER_EXCEPTION("exception generated in user code"), /* keep */ - URL_CONTAINS_NO_DATA("URL {0} contains no data"), - VALUES_ADDED_BEFORE_CONFIGURING_STATISTIC("{0} values have been added before statistic is configured"), - VECTOR_LENGTH_MISMATCH("vector length mismatch: got {0} but expected {1}"), - VECTOR_MUST_HAVE_AT_LEAST_ONE_ELEMENT("vector must have at least one element"), - WEIGHT_AT_LEAST_ONE_NON_ZERO("weigth array must contain at least one non-zero value"), - WRONG_BLOCK_LENGTH("wrong array shape (block length = {0}, expected {1})"), - WRONG_NUMBER_OF_POINTS("{0} points are required, got only {1}"), - NUMBER_OF_POINTS("number of points ({0})"), /* keep */ - ZERO_DENOMINATOR("denominator must be different from 0"), /* keep */ - ZERO_DENOMINATOR_IN_FRACTION("zero denominator in fraction {0}/{1}"), - ZERO_FRACTION_TO_DIVIDE_BY("the fraction to divide by must not be zero: {0}/{1}"), - ZERO_NORM("zero norm"), - ZERO_NORM_FOR_ROTATION_AXIS("zero norm for rotation axis"), - ZERO_NORM_FOR_ROTATION_DEFINING_VECTOR("zero norm for rotation defining vector"), - ZERO_NOT_ALLOWED("zero not allowed here"); - - // CHECKSTYLE: resume JavadocVariable - // CHECKSTYLE: resume MultipleVariableDeclarations - - - /** Source English format. */ - private final String sourceFormat; - - /** Simple constructor. - * @param sourceFormat source English format to use when no - * localized version is available - */ - LocalizedFormats(final String sourceFormat) { - this.sourceFormat = sourceFormat; - } - - /** {@inheritDoc} */ - @Override - public String getSourceString() { - return sourceFormat; - } - - /** {@inheritDoc} */ - @Override - public String getLocalizedString(final Locale locale) { - try { - final String path = LocalizedFormats.class.getName().replaceAll("\\.", "/"); - final ResourceBundle bundle = ResourceBundle.getBundle("assets/" + path, locale); - if (bundle.getLocale().getLanguage().equals(locale.getLanguage())) { - final String key = toString(); - if (bundle.containsKey(key)) { - // the value of the resource is the translated format - return bundle.getString(key); - } else { - // Use default. - return sourceFormat; - } - } - } catch (MissingResourceException mre) { // NOPMD - // do nothing here - } - - // either the locale is not supported or the resource is unknown - // don't translate and fall back to using the source format - return sourceFormat; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/package-info.java deleted file mode 100644 index 25c583bee..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/util/package-info.java +++ /dev/null @@ -1,22 +0,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. - */ -/** - * - * Classes supporting exception localization. - * - */ -package org.apache.commons.math4.exception.util; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/BigFraction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/BigFraction.java deleted file mode 100644 index 83261e602..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/BigFraction.java +++ /dev/null @@ -1,1219 +0,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. - */ -package org.apache.commons.math4.fraction; - -import org.apache.commons.math4.FieldElement; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.ZeroException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathUtils; -import org.apache.commons.numbers.core.ArithmeticUtils; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.math.BigInteger; - -/** - * Representation of a rational number without any overflow. This class is - * immutable. - * - * @since 2.0 - */ -public class BigFraction - extends Number - implements FieldElement, Comparable, Serializable { - - /** A fraction representing "2 / 1". */ - public static final BigFraction TWO = new BigFraction(2); - - /** A fraction representing "1". */ - public static final BigFraction ONE = new BigFraction(1); - - /** A fraction representing "0". */ - public static final BigFraction ZERO = new BigFraction(0); - - /** A fraction representing "-1 / 1". */ - public static final BigFraction MINUS_ONE = new BigFraction(-1); - - /** A fraction representing "4/5". */ - public static final BigFraction FOUR_FIFTHS = new BigFraction(4, 5); - - /** A fraction representing "1/5". */ - public static final BigFraction ONE_FIFTH = new BigFraction(1, 5); - - /** A fraction representing "1/2". */ - public static final BigFraction ONE_HALF = new BigFraction(1, 2); - - /** A fraction representing "1/4". */ - public static final BigFraction ONE_QUARTER = new BigFraction(1, 4); - - /** A fraction representing "1/3". */ - public static final BigFraction ONE_THIRD = new BigFraction(1, 3); - - /** A fraction representing "3/5". */ - public static final BigFraction THREE_FIFTHS = new BigFraction(3, 5); - - /** A fraction representing "3/4". */ - public static final BigFraction THREE_QUARTERS = new BigFraction(3, 4); - - /** A fraction representing "2/5". */ - public static final BigFraction TWO_FIFTHS = new BigFraction(2, 5); - - /** A fraction representing "2/4". */ - public static final BigFraction TWO_QUARTERS = new BigFraction(2, 4); - - /** A fraction representing "2/3". */ - public static final BigFraction TWO_THIRDS = new BigFraction(2, 3); - - /** Serializable version identifier. */ - private static final long serialVersionUID = -5630213147331578515L; - - /** BigInteger representation of 100. */ - private static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100); - - /** The numerator. */ - private final BigInteger numerator; - - /** The denominator. */ - private final BigInteger denominator; - - /** - *

- * Create a {@link BigFraction} equivalent to the passed {@code BigInteger}, ie - * "num / 1". - *

- * - * @param num - * the numerator. - */ - public BigFraction(final BigInteger num) { - this(num, BigInteger.ONE); - } - - /** - * Create a {@link BigFraction} given the numerator and denominator as - * {@code BigInteger}. The {@link BigFraction} is reduced to lowest terms. - * - * @param num the numerator, must not be {@code null}. - * @param den the denominator, must not be {@code null}. - * @throws ZeroException if the denominator is zero. - * @throws NullArgumentException if either of the arguments is null - */ - public BigFraction(BigInteger num, BigInteger den) { - MathUtils.checkNotNull(num, LocalizedFormats.NUMERATOR); - MathUtils.checkNotNull(den, LocalizedFormats.DENOMINATOR); - if (den.signum() == 0) { - throw new ZeroException(LocalizedFormats.ZERO_DENOMINATOR); - } - if (num.signum() == 0) { - numerator = BigInteger.ZERO; - denominator = BigInteger.ONE; - } else { - - // reduce numerator and denominator by greatest common denominator - final BigInteger gcd = num.gcd(den); - if (BigInteger.ONE.compareTo(gcd) < 0) { - num = num.divide(gcd); - den = den.divide(gcd); - } - - // move sign to numerator - if (den.signum() == -1) { - num = num.negate(); - den = den.negate(); - } - - // store the values in the final fields - numerator = num; - denominator = den; - - } - } - - /** - * Create a fraction given the double value. - *

- * This constructor behaves differently from - * {@link #BigFraction(double, double, int)}. It converts the double value - * exactly, considering its internal bits representation. This works for all - * values except NaN and infinities and does not requires any loop or - * convergence threshold. - *

- *

- * Since this conversion is exact and since double numbers are sometimes - * approximated, the fraction created may seem strange in some cases. For example, - * calling new BigFraction(1.0 / 3.0) does not create - * the fraction 1/3, but the fraction 6004799503160661 / 18014398509481984 - * because the double number passed to the constructor is not exactly 1/3 - * (this number cannot be stored exactly in IEEE754). - *

- * @see #BigFraction(double, double, int) - * @param value the double value to convert to a fraction. - * @exception MathIllegalArgumentException if value is NaN or infinite - */ - public BigFraction(final double value) throws MathIllegalArgumentException { - if (Double.isNaN(value)) { - throw new MathIllegalArgumentException(LocalizedFormats.NAN_VALUE_CONVERSION); - } - if (Double.isInfinite(value)) { - throw new MathIllegalArgumentException(LocalizedFormats.INFINITE_VALUE_CONVERSION); - } - - // compute m and k such that value = m * 2^k - final long bits = Double.doubleToLongBits(value); - final long sign = bits & 0x8000000000000000L; - final long exponent = bits & 0x7ff0000000000000L; - long m = bits & 0x000fffffffffffffL; - if (exponent != 0) { - // this was a normalized number, add the implicit most significant bit - m |= 0x0010000000000000L; - } - if (sign != 0) { - m = -m; - } - int k = ((int) (exponent >> 52)) - 1075; - while (((m & 0x001ffffffffffffeL) != 0) && ((m & 0x1) == 0)) { - m >>= 1; - ++k; - } - - if (k < 0) { - numerator = BigInteger.valueOf(m); - denominator = BigInteger.ZERO.flipBit(-k); - } else { - numerator = BigInteger.valueOf(m).multiply(BigInteger.ZERO.flipBit(k)); - denominator = BigInteger.ONE; - } - - } - - /** - * Create a fraction given the double value and maximum error allowed. - *

- * References: - *

- * - * @param value - * the double value to convert to a fraction. - * @param epsilon - * maximum error allowed. The resulting fraction is within - * epsilon of value, in absolute terms. - * @param maxIterations - * maximum number of convergents. - * @throws FractionConversionException - * if the continued fraction failed to converge. - * @see #BigFraction(double) - */ - public BigFraction(final double value, final double epsilon, - final int maxIterations) - throws FractionConversionException { - this(value, epsilon, Integer.MAX_VALUE, maxIterations); - } - - /** - * Create a fraction given the double value and either the maximum error - * allowed or the maximum number of denominator digits. - *

- * - * NOTE: This constructor is called with EITHER - a valid epsilon value and - * the maxDenominator set to Integer.MAX_VALUE (that way the maxDenominator - * has no effect). OR - a valid maxDenominator value and the epsilon value - * set to zero (that way epsilon only has effect if there is an exact match - * before the maxDenominator value is reached). - *

- *

- * - * It has been done this way so that the same code can be (re)used for both - * scenarios. However this could be confusing to users if it were part of - * the public API and this constructor should therefore remain PRIVATE. - *

- * - * See JIRA issue ticket MATH-181 for more details: - * - * https://issues.apache.org/jira/browse/MATH-181 - * - * @param value - * the double value to convert to a fraction. - * @param epsilon - * maximum error allowed. The resulting fraction is within - * epsilon of value, in absolute terms. - * @param maxDenominator - * maximum denominator value allowed. - * @param maxIterations - * maximum number of convergents. - * @throws FractionConversionException - * if the continued fraction failed to converge. - */ - private BigFraction(final double value, final double epsilon, - final int maxDenominator, int maxIterations) - throws FractionConversionException { - long overflow = Integer.MAX_VALUE; - double r0 = value; - long a0 = (long) FastMath.floor(r0); - - if (FastMath.abs(a0) > overflow) { - throw new FractionConversionException(value, a0, 1l); - } - - // check for (almost) integer arguments, which should not go - // to iterations. - if (FastMath.abs(a0 - value) < epsilon) { - numerator = BigInteger.valueOf(a0); - denominator = BigInteger.ONE; - return; - } - - long p0 = 1; - long q0 = 0; - long p1 = a0; - long q1 = 1; - - long p2 = 0; - long q2 = 1; - - int n = 0; - boolean stop = false; - do { - ++n; - final double r1 = 1.0 / (r0 - a0); - final long a1 = (long) FastMath.floor(r1); - p2 = (a1 * p1) + p0; - q2 = (a1 * q1) + q0; - if ((p2 > overflow) || (q2 > overflow)) { - // in maxDenominator mode, if the last fraction was very close to the actual value - // q2 may overflow in the next iteration; in this case return the last one. - if (epsilon == 0.0 && FastMath.abs(q1) < maxDenominator) { - break; - } - throw new FractionConversionException(value, p2, q2); - } - - final double convergent = (double) p2 / (double) q2; - if ((n < maxIterations) && - (FastMath.abs(convergent - value) > epsilon) && - (q2 < maxDenominator)) { - p0 = p1; - p1 = p2; - q0 = q1; - q1 = q2; - a0 = a1; - r0 = r1; - } else { - stop = true; - } - } while (!stop); - - if (n >= maxIterations) { - throw new FractionConversionException(value, maxIterations); - } - - if (q2 < maxDenominator) { - numerator = BigInteger.valueOf(p2); - denominator = BigInteger.valueOf(q2); - } else { - numerator = BigInteger.valueOf(p1); - denominator = BigInteger.valueOf(q1); - } - } - - /** - * Create a fraction given the double value and maximum denominator. - *

- * References: - *

- * - * @param value - * the double value to convert to a fraction. - * @param maxDenominator - * The maximum allowed value for denominator. - * @throws FractionConversionException - * if the continued fraction failed to converge. - */ - public BigFraction(final double value, final int maxDenominator) - throws FractionConversionException { - this(value, 0, maxDenominator, 100); - } - - /** - *

- * Create a {@link BigFraction} equivalent to the passed {@code int}, ie - * "num / 1". - *

- * - * @param num - * the numerator. - */ - public BigFraction(final int num) { - this(BigInteger.valueOf(num), BigInteger.ONE); - } - - /** - *

- * Create a {@link BigFraction} given the numerator and denominator as simple - * {@code int}. The {@link BigFraction} is reduced to lowest terms. - *

- * - * @param num - * the numerator. - * @param den - * the denominator. - */ - public BigFraction(final int num, final int den) { - this(BigInteger.valueOf(num), BigInteger.valueOf(den)); - } - - /** - *

- * Create a {@link BigFraction} equivalent to the passed long, ie "num / 1". - *

- * - * @param num - * the numerator. - */ - public BigFraction(final long num) { - this(BigInteger.valueOf(num), BigInteger.ONE); - } - - /** - *

- * Create a {@link BigFraction} given the numerator and denominator as simple - * {@code long}. The {@link BigFraction} is reduced to lowest terms. - *

- * - * @param num - * the numerator. - * @param den - * the denominator. - */ - public BigFraction(final long num, final long den) { - this(BigInteger.valueOf(num), BigInteger.valueOf(den)); - } - - /** - *

- * Creates a BigFraction instance with the 2 parts of a fraction - * Y/Z. - *

- * - *

- * Any negative signs are resolved to be on the numerator. - *

- * - * @param numerator - * the numerator, for example the three in 'three sevenths'. - * @param denominator - * the denominator, for example the seven in 'three sevenths'. - * @return a new fraction instance, with the numerator and denominator - * reduced. - * @throws ArithmeticException - * if the denominator is zero. - */ - public static BigFraction getReducedFraction(final int numerator, - final int denominator) { - if (numerator == 0) { - return ZERO; // normalize zero. - } - - return new BigFraction(numerator, denominator); - } - - /** - *

- * Returns the absolute value of this {@link BigFraction}. - *

- * - * @return the absolute value as a {@link BigFraction}. - */ - public BigFraction abs() { - return (numerator.signum() == 1) ? this : negate(); - } - - /** - *

- * Adds the value of this fraction to the passed {@link BigInteger}, - * returning the result in reduced form. - *

- * - * @param bg - * the {@link BigInteger} to add, must'nt be null. - * @return a BigFraction instance with the resulting values. - * @throws NullArgumentException - * if the {@link BigInteger} is null. - */ - public BigFraction add(final BigInteger bg) throws NullArgumentException { - MathUtils.checkNotNull(bg); - - if (numerator.signum() == 0) { - return new BigFraction(bg); - } - if (bg.signum() == 0) { - return this; - } - - return new BigFraction(numerator.add(denominator.multiply(bg)), denominator); - } - - /** - *

- * Adds the value of this fraction to the passed {@code integer}, returning - * the result in reduced form. - *

- * - * @param i - * the {@code integer} to add. - * @return a BigFraction instance with the resulting values. - */ - public BigFraction add(final int i) { - return add(BigInteger.valueOf(i)); - } - - /** - *

- * Adds the value of this fraction to the passed {@code long}, returning - * the result in reduced form. - *

- * - * @param l - * the {@code long} to add. - * @return a BigFraction instance with the resulting values. - */ - public BigFraction add(final long l) { - return add(BigInteger.valueOf(l)); - } - - /** - *

- * Adds the value of this fraction to another, returning the result in - * reduced form. - *

- * - * @param fraction - * the {@link BigFraction} to add, must not be null. - * @return a {@link BigFraction} instance with the resulting values. - * @throws NullArgumentException if the {@link BigFraction} is {@code null}. - */ - @Override - public BigFraction add(final BigFraction fraction) { - MathUtils.checkNotNull(fraction, LocalizedFormats.FRACTION); - if (fraction.numerator.signum() == 0) { - return this; - } - if (numerator.signum() == 0) { - return fraction; - } - - BigInteger num = null; - BigInteger den = null; - - if (denominator.equals(fraction.denominator)) { - num = numerator.add(fraction.numerator); - den = denominator; - } else { - num = (numerator.multiply(fraction.denominator)).add((fraction.numerator).multiply(denominator)); - den = denominator.multiply(fraction.denominator); - } - - if (num.signum() == 0) { - return ZERO; - } - - return new BigFraction(num, den); - - } - - /** - *

- * Gets the fraction as a BigDecimal. This calculates the - * fraction as the numerator divided by denominator. - *

- * - * @return the fraction as a BigDecimal. - * @throws ArithmeticException - * if the exact quotient does not have a terminating decimal - * expansion. - * @see BigDecimal - */ - public BigDecimal bigDecimalValue() { - return new BigDecimal(numerator).divide(new BigDecimal(denominator)); - } - - /** - *

- * Gets the fraction as a BigDecimal following the passed - * rounding mode. This calculates the fraction as the numerator divided by - * denominator. - *

- * - * @param roundingMode - * rounding mode to apply. see {@link BigDecimal} constants. - * @return the fraction as a BigDecimal. - * @throws IllegalArgumentException - * if {@code roundingMode} does not represent a valid rounding - * mode. - * @see BigDecimal - */ - public BigDecimal bigDecimalValue(final int roundingMode) { - return new BigDecimal(numerator).divide(new BigDecimal(denominator), roundingMode); - } - - /** - *

- * Gets the fraction as a BigDecimal following the passed scale - * and rounding mode. This calculates the fraction as the numerator divided - * by denominator. - *

- * - * @param scale - * scale of the BigDecimal quotient to be returned. - * see {@link BigDecimal} for more information. - * @param roundingMode - * rounding mode to apply. see {@link BigDecimal} constants. - * @return the fraction as a BigDecimal. - * @see BigDecimal - */ - public BigDecimal bigDecimalValue(final int scale, final int roundingMode) { - return new BigDecimal(numerator).divide(new BigDecimal(denominator), scale, roundingMode); - } - - /** - *

- * Compares this object to another based on size. - *

- * - * @param object - * the object to compare to, must not be null. - * @return -1 if this is less than {@code object}, +1 if this is greater - * than {@code object}, 0 if they are equal. - * @see Comparable#compareTo(Object) - */ - @Override - public int compareTo(final BigFraction object) { - int lhsSigNum = numerator.signum(); - int rhsSigNum = object.numerator.signum(); - - if (lhsSigNum != rhsSigNum) { - return (lhsSigNum > rhsSigNum) ? 1 : -1; - } - if (lhsSigNum == 0) { - return 0; - } - - BigInteger nOd = numerator.multiply(object.denominator); - BigInteger dOn = denominator.multiply(object.numerator); - return nOd.compareTo(dOn); - } - - /** - *

- * Divide the value of this fraction by the passed {@code BigInteger}, - * ie {@code this * 1 / bg}, returning the result in reduced form. - *

- * - * @param bg the {@code BigInteger} to divide by, must not be {@code null} - * @return a {@link BigFraction} instance with the resulting values - * @throws NullArgumentException if the {@code BigInteger} is {@code null} - * @throws MathArithmeticException if the fraction to divide by is zero - */ - public BigFraction divide(final BigInteger bg) { - MathUtils.checkNotNull(bg); - if (bg.signum() == 0) { - throw new MathArithmeticException(LocalizedFormats.ZERO_DENOMINATOR); - } - if (numerator.signum() == 0) { - return ZERO; - } - return new BigFraction(numerator, denominator.multiply(bg)); - } - - /** - *

- * Divide the value of this fraction by the passed {@code int}, ie - * {@code this * 1 / i}, returning the result in reduced form. - *

- * - * @param i the {@code int} to divide by - * @return a {@link BigFraction} instance with the resulting values - * @throws MathArithmeticException if the fraction to divide by is zero - */ - public BigFraction divide(final int i) { - return divide(BigInteger.valueOf(i)); - } - - /** - *

- * Divide the value of this fraction by the passed {@code long}, ie - * {@code this * 1 / l}, returning the result in reduced form. - *

- * - * @param l the {@code long} to divide by - * @return a {@link BigFraction} instance with the resulting values - * @throws MathArithmeticException if the fraction to divide by is zero - */ - public BigFraction divide(final long l) { - return divide(BigInteger.valueOf(l)); - } - - /** - *

- * Divide the value of this fraction by another, returning the result in - * reduced form. - *

- * - * @param fraction Fraction to divide by, must not be {@code null}. - * @return a {@link BigFraction} instance with the resulting values. - * @throws NullArgumentException if the {@code fraction} is {@code null}. - * @throws MathArithmeticException if the fraction to divide by is zero - */ - @Override - public BigFraction divide(final BigFraction fraction) { - MathUtils.checkNotNull(fraction, LocalizedFormats.FRACTION); - if (fraction.numerator.signum() == 0) { - throw new MathArithmeticException(LocalizedFormats.ZERO_DENOMINATOR); - } - if (numerator.signum() == 0) { - return ZERO; - } - - return multiply(fraction.reciprocal()); - } - - /** - *

- * Gets the fraction as a {@code double}. This calculates the fraction as - * the numerator divided by denominator. - *

- * - * @return the fraction as a {@code double} - * @see Number#doubleValue() - */ - @Override - public double doubleValue() { - double result = numerator.doubleValue() / denominator.doubleValue(); - if (Double.isNaN(result)) { - // Numerator and/or denominator must be out of range: - // Calculate how far to shift them to put them in range. - int shift = FastMath.max(numerator.bitLength(), - denominator.bitLength()) - FastMath.getExponent(Double.MAX_VALUE); - result = numerator.shiftRight(shift).doubleValue() / - denominator.shiftRight(shift).doubleValue(); - } - return result; - } - - /** - *

- * Test for the equality of two fractions. If the lowest term numerator and - * denominators are the same for both fractions, the two fractions are - * considered to be equal. - *

- * - * @param other - * fraction to test for equality to this fraction, can be - * null. - * @return true if two fractions are equal, false if object is - * null, not an instance of {@link BigFraction}, or not - * equal to this fraction instance. - * @see Object#equals(Object) - */ - @Override - public boolean equals(final Object other) { - boolean ret = false; - - if (this == other) { - ret = true; - } else if (other instanceof BigFraction) { - BigFraction rhs = ((BigFraction) other).reduce(); - BigFraction thisOne = this.reduce(); - ret = thisOne.numerator.equals(rhs.numerator) && thisOne.denominator.equals(rhs.denominator); - } - - return ret; - } - - /** - *

- * Gets the fraction as a {@code float}. This calculates the fraction as - * the numerator divided by denominator. - *

- * - * @return the fraction as a {@code float}. - * @see Number#floatValue() - */ - @Override - public float floatValue() { - float result = numerator.floatValue() / denominator.floatValue(); - if (Double.isNaN(result)) { - // Numerator and/or denominator must be out of range: - // Calculate how far to shift them to put them in range. - int shift = FastMath.max(numerator.bitLength(), - denominator.bitLength()) - FastMath.getExponent(Float.MAX_VALUE); - result = numerator.shiftRight(shift).floatValue() / - denominator.shiftRight(shift).floatValue(); - } - return result; - } - - /** - *

- * Access the denominator as a BigInteger. - *

- * - * @return the denominator as a BigInteger. - */ - public BigInteger getDenominator() { - return denominator; - } - - /** - *

- * Access the denominator as a {@code int}. - *

- * - * @return the denominator as a {@code int}. - */ - public int getDenominatorAsInt() { - return denominator.intValue(); - } - - /** - *

- * Access the denominator as a {@code long}. - *

- * - * @return the denominator as a {@code long}. - */ - public long getDenominatorAsLong() { - return denominator.longValue(); - } - - /** - *

- * Access the numerator as a BigInteger. - *

- * - * @return the numerator as a BigInteger. - */ - public BigInteger getNumerator() { - return numerator; - } - - /** - *

- * Access the numerator as a {@code int}. - *

- * - * @return the numerator as a {@code int}. - */ - public int getNumeratorAsInt() { - return numerator.intValue(); - } - - /** - *

- * Access the numerator as a {@code long}. - *

- * - * @return the numerator as a {@code long}. - */ - public long getNumeratorAsLong() { - return numerator.longValue(); - } - - /** - *

- * Gets a hashCode for the fraction. - *

- * - * @return a hash code value for this object. - * @see Object#hashCode() - */ - @Override - public int hashCode() { - return 37 * (37 * 17 + numerator.hashCode()) + denominator.hashCode(); - } - - /** - *

- * Gets the fraction as an {@code int}. This returns the whole number part - * of the fraction. - *

- * - * @return the whole number fraction part. - * @see Number#intValue() - */ - @Override - public int intValue() { - return numerator.divide(denominator).intValue(); - } - - /** - *

- * Gets the fraction as a {@code long}. This returns the whole number part - * of the fraction. - *

- * - * @return the whole number fraction part. - * @see Number#longValue() - */ - @Override - public long longValue() { - return numerator.divide(denominator).longValue(); - } - - /** - *

- * Multiplies the value of this fraction by the passed - * BigInteger, returning the result in reduced form. - *

- * - * @param bg the {@code BigInteger} to multiply by. - * @return a {@code BigFraction} instance with the resulting values. - * @throws NullArgumentException if {@code bg} is {@code null}. - */ - public BigFraction multiply(final BigInteger bg) { - MathUtils.checkNotNull(bg); - if (numerator.signum() == 0 || bg.signum() == 0) { - return ZERO; - } - return new BigFraction(bg.multiply(numerator), denominator); - } - - /** - *

- * Multiply the value of this fraction by the passed {@code int}, returning - * the result in reduced form. - *

- * - * @param i - * the {@code int} to multiply by. - * @return a {@link BigFraction} instance with the resulting values. - */ - @Override - public BigFraction multiply(final int i) { - if (i == 0 || numerator.signum() == 0) { - return ZERO; - } - - return multiply(BigInteger.valueOf(i)); - } - - /** - *

- * Multiply the value of this fraction by the passed {@code long}, - * returning the result in reduced form. - *

- * - * @param l - * the {@code long} to multiply by. - * @return a {@link BigFraction} instance with the resulting values. - */ - public BigFraction multiply(final long l) { - if (l == 0 || numerator.signum() == 0) { - return ZERO; - } - - return multiply(BigInteger.valueOf(l)); - } - - /** - *

- * Multiplies the value of this fraction by another, returning the result in - * reduced form. - *

- * - * @param fraction Fraction to multiply by, must not be {@code null}. - * @return a {@link BigFraction} instance with the resulting values. - * @throws NullArgumentException if {@code fraction} is {@code null}. - */ - @Override - public BigFraction multiply(final BigFraction fraction) { - MathUtils.checkNotNull(fraction, LocalizedFormats.FRACTION); - if (numerator.signum() == 0 || - fraction.numerator.signum() == 0) { - return ZERO; - } - return new BigFraction(numerator.multiply(fraction.numerator), - denominator.multiply(fraction.denominator)); - } - - /** - *

- * Return the additive inverse of this fraction, returning the result in - * reduced form. - *

- * - * @return the negation of this fraction. - */ - @Override - public BigFraction negate() { - return new BigFraction(numerator.negate(), denominator); - } - - /** - *

- * Gets the fraction percentage as a {@code double}. This calculates the - * fraction as the numerator divided by denominator multiplied by 100. - *

- * - * @return the fraction percentage as a {@code double}. - */ - public double percentageValue() { - return multiply(ONE_HUNDRED).doubleValue(); - } - - /** - *

- * Returns a {@code BigFraction} whose value is - * {@code (thisexponent)}, returning the result in reduced form. - *

- * - * @param exponent - * exponent to which this {@code BigFraction} is to be - * raised. - * @return thisexponent. - */ - public BigFraction pow(final int exponent) { - if (exponent == 0) { - return ONE; - } - if (numerator.signum() == 0) { - return this; - } - - if (exponent < 0) { - return new BigFraction(denominator.pow(-exponent), numerator.pow(-exponent)); - } - return new BigFraction(numerator.pow(exponent), denominator.pow(exponent)); - } - - /** - *

- * Returns a BigFraction whose value is - * (thisexponent), returning the result in reduced form. - *

- * - * @param exponent - * exponent to which this BigFraction is to be raised. - * @return thisexponent as a BigFraction. - */ - public BigFraction pow(final long exponent) { - if (exponent == 0) { - return ONE; - } - if (numerator.signum() == 0) { - return this; - } - - if (exponent < 0) { - return new BigFraction(ArithmeticUtils.pow(denominator, -exponent), - ArithmeticUtils.pow(numerator, -exponent)); - } - return new BigFraction(ArithmeticUtils.pow(numerator, exponent), - ArithmeticUtils.pow(denominator, exponent)); - } - - /** - *

- * Returns a BigFraction whose value is - * (thisexponent), returning the result in reduced form. - *

- * - * @param exponent - * exponent to which this BigFraction is to be raised. - * @return thisexponent as a BigFraction. - */ - public BigFraction pow(final BigInteger exponent) { - if (exponent.signum() == 0) { - return ONE; - } - if (numerator.signum() == 0) { - return this; - } - - if (exponent.signum() == -1) { - final BigInteger eNeg = exponent.negate(); - return new BigFraction(ArithmeticUtils.pow(denominator, eNeg), - ArithmeticUtils.pow(numerator, eNeg)); - } - return new BigFraction(ArithmeticUtils.pow(numerator, exponent), - ArithmeticUtils.pow(denominator, exponent)); - } - - /** - *

- * Returns a double whose value is - * (thisexponent), returning the result in reduced form. - *

- * - * @param exponent - * exponent to which this BigFraction is to be raised. - * @return thisexponent. - */ - public double pow(final double exponent) { - return FastMath.pow(numerator.doubleValue(), exponent) / - FastMath.pow(denominator.doubleValue(), exponent); - } - - /** - *

- * Return the multiplicative inverse of this fraction. - *

- * - * @return the reciprocal fraction. - */ - @Override - public BigFraction reciprocal() { - return new BigFraction(denominator, numerator); - } - - /** - *

- * Reduce this BigFraction to its lowest terms. - *

- * - * @return the reduced BigFraction. It doesn't change anything if - * the fraction can be reduced. - */ - public BigFraction reduce() { - final BigInteger gcd = numerator.gcd(denominator); - - if (BigInteger.ONE.compareTo(gcd) < 0) { - return new BigFraction(numerator.divide(gcd), denominator.divide(gcd)); - } else { - return this; - } - } - - /** - *

- * Subtracts the value of an {@link BigInteger} from the value of this - * {@code BigFraction}, returning the result in reduced form. - *

- * - * @param bg the {@link BigInteger} to subtract, cannot be {@code null}. - * @return a {@code BigFraction} instance with the resulting values. - * @throws NullArgumentException if the {@link BigInteger} is {@code null}. - */ - public BigFraction subtract(final BigInteger bg) { - MathUtils.checkNotNull(bg); - if (bg.signum() == 0) { - return this; - } - if (numerator.signum() == 0) { - return new BigFraction(bg.negate()); - } - - return new BigFraction(numerator.subtract(denominator.multiply(bg)), denominator); - } - - /** - *

- * Subtracts the value of an {@code integer} from the value of this - * {@code BigFraction}, returning the result in reduced form. - *

- * - * @param i the {@code integer} to subtract. - * @return a {@code BigFraction} instance with the resulting values. - */ - public BigFraction subtract(final int i) { - return subtract(BigInteger.valueOf(i)); - } - - /** - *

- * Subtracts the value of a {@code long} from the value of this - * {@code BigFraction}, returning the result in reduced form. - *

- * - * @param l the {@code long} to subtract. - * @return a {@code BigFraction} instance with the resulting values. - */ - public BigFraction subtract(final long l) { - return subtract(BigInteger.valueOf(l)); - } - - /** - *

- * Subtracts the value of another fraction from the value of this one, - * returning the result in reduced form. - *

- * - * @param fraction {@link BigFraction} to subtract, must not be {@code null}. - * @return a {@link BigFraction} instance with the resulting values - * @throws NullArgumentException if the {@code fraction} is {@code null}. - */ - @Override - public BigFraction subtract(final BigFraction fraction) { - MathUtils.checkNotNull(fraction, LocalizedFormats.FRACTION); - if (fraction.numerator.signum() == 0) { - return this; - } - if (numerator.signum() == 0) { - return fraction.negate(); - } - - BigInteger num = null; - BigInteger den = null; - if (denominator.equals(fraction.denominator)) { - num = numerator.subtract(fraction.numerator); - den = denominator; - } else { - num = (numerator.multiply(fraction.denominator)).subtract((fraction.numerator).multiply(denominator)); - den = denominator.multiply(fraction.denominator); - } - return new BigFraction(num, den); - - } - - /** - *

- * Returns the String representing this fraction, ie - * "num / dem" or just "num" if the denominator is one. - *

- * - * @return a string representation of the fraction. - * @see Object#toString() - */ - @Override - public String toString() { - String str = null; - if (BigInteger.ONE.equals(denominator)) { - str = numerator.toString(); - } else if (BigInteger.ZERO.equals(numerator)) { - str = "0"; - } else { - str = numerator + " / " + denominator; - } - return str; - } - - /** {@inheritDoc} */ - @Override - public BigFractionField getField() { - return BigFractionField.getInstance(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/BigFractionField.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/BigFractionField.java deleted file mode 100644 index fd5500248..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/BigFractionField.java +++ /dev/null @@ -1,85 +0,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. - */ - -package org.apache.commons.math4.fraction; - -import java.io.Serializable; - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; - -/** - * Representation of the fractional numbers without any overflow field. - *

- * This class is a singleton. - *

- * @see Fraction - * @since 2.0 - */ -public class BigFractionField implements Field, Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = -1699294557189741703L; - - /** Private constructor for the singleton. - */ - private BigFractionField() { - } - - /** Get the unique instance. - * @return the unique instance - */ - public static BigFractionField getInstance() { - return LazyHolder.INSTANCE; - } - - /** {@inheritDoc} */ - @Override - public BigFraction getOne() { - return BigFraction.ONE; - } - - /** {@inheritDoc} */ - @Override - public BigFraction getZero() { - return BigFraction.ZERO; - } - - /** {@inheritDoc} */ - @Override - public Class> getRuntimeClass() { - return BigFraction.class; - } - // CHECKSTYLE: stop HideUtilityClassConstructor - /** Holder for the instance. - *

We use here the Initialization On Demand Holder Idiom.

- */ - private static class LazyHolder { - /** Cached field instance. */ - private static final BigFractionField INSTANCE = new BigFractionField(); - } - // CHECKSTYLE: resume HideUtilityClassConstructor - - /** Handle deserialization of the singleton. - * @return the singleton instance - */ - private Object readResolve() { - // return the singleton instance - return LazyHolder.INSTANCE; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/Fraction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/Fraction.java deleted file mode 100644 index c2b26ade5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/Fraction.java +++ /dev/null @@ -1,680 +0,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. - */ -package org.apache.commons.math4.fraction; - -import org.apache.commons.math4.FieldElement; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.numbers.core.ArithmeticUtils; - -import java.io.Serializable; -import java.math.BigInteger; - -/** - * Representation of a rational number. - * - * implements Serializable since 2.0 - * - * @since 1.1 - */ -public class Fraction - extends Number - implements FieldElement, Comparable, Serializable { - - /** A fraction representing "2 / 1". */ - public static final Fraction TWO = new Fraction(2, 1); - - /** A fraction representing "1". */ - public static final Fraction ONE = new Fraction(1, 1); - - /** A fraction representing "0". */ - public static final Fraction ZERO = new Fraction(0, 1); - - /** A fraction representing "4/5". */ - public static final Fraction FOUR_FIFTHS = new Fraction(4, 5); - - /** A fraction representing "1/5". */ - public static final Fraction ONE_FIFTH = new Fraction(1, 5); - - /** A fraction representing "1/2". */ - public static final Fraction ONE_HALF = new Fraction(1, 2); - - /** A fraction representing "1/4". */ - public static final Fraction ONE_QUARTER = new Fraction(1, 4); - - /** A fraction representing "1/3". */ - public static final Fraction ONE_THIRD = new Fraction(1, 3); - - /** A fraction representing "3/5". */ - public static final Fraction THREE_FIFTHS = new Fraction(3, 5); - - /** A fraction representing "3/4". */ - public static final Fraction THREE_QUARTERS = new Fraction(3, 4); - - /** A fraction representing "2/5". */ - public static final Fraction TWO_FIFTHS = new Fraction(2, 5); - - /** A fraction representing "2/4". */ - public static final Fraction TWO_QUARTERS = new Fraction(2, 4); - - /** A fraction representing "2/3". */ - public static final Fraction TWO_THIRDS = new Fraction(2, 3); - - /** A fraction representing "-1 / 1". */ - public static final Fraction MINUS_ONE = new Fraction(-1, 1); - - /** Serializable version identifier */ - private static final long serialVersionUID = 3698073679419233275L; - - /** The default epsilon used for convergence. */ - private static final double DEFAULT_EPSILON = 1e-5; - - /** The denominator. */ - private final int denominator; - - /** The numerator. */ - private final int numerator; - - /** - * Create a fraction given the double value. - * @param value the double value to convert to a fraction. - * @throws FractionConversionException if the continued fraction failed to - * converge. - */ - public Fraction(double value) throws FractionConversionException { - this(value, DEFAULT_EPSILON, 100); - } - - /** - * Create a fraction given the double value and maximum error allowed. - *

- * References: - *

- * @param value the double value to convert to a fraction. - * @param epsilon maximum error allowed. The resulting fraction is within - * {@code epsilon} of {@code value}, in absolute terms. - * @param maxIterations maximum number of convergents - * @throws FractionConversionException if the continued fraction failed to - * converge. - */ - public Fraction(double value, double epsilon, int maxIterations) - throws FractionConversionException - { - this(value, epsilon, Integer.MAX_VALUE, maxIterations); - } - - /** - * Create a fraction given the double value and maximum denominator. - *

- * References: - *

- * @param value the double value to convert to a fraction. - * @param maxDenominator The maximum allowed value for denominator - * @throws FractionConversionException if the continued fraction failed to - * converge - */ - public Fraction(double value, int maxDenominator) - throws FractionConversionException - { - this(value, 0, maxDenominator, 100); - } - - /** - * Create a fraction given the double value and either the maximum error - * allowed or the maximum number of denominator digits. - *

- * - * NOTE: This constructor is called with EITHER - * - a valid epsilon value and the maxDenominator set to Integer.MAX_VALUE - * (that way the maxDenominator has no effect). - * OR - * - a valid maxDenominator value and the epsilon value set to zero - * (that way epsilon only has effect if there is an exact match before - * the maxDenominator value is reached). - *

- * - * It has been done this way so that the same code can be (re)used for both - * scenarios. However this could be confusing to users if it were part of - * the public API and this constructor should therefore remain PRIVATE. - *

- * - * See JIRA issue ticket MATH-181 for more details: - * - * https://issues.apache.org/jira/browse/MATH-181 - * - * @param value the double value to convert to a fraction. - * @param epsilon maximum error allowed. The resulting fraction is within - * {@code epsilon} of {@code value}, in absolute terms. - * @param maxDenominator maximum denominator value allowed. - * @param maxIterations maximum number of convergents - * @throws FractionConversionException if the continued fraction failed to - * converge. - */ - private Fraction(double value, double epsilon, int maxDenominator, int maxIterations) - throws FractionConversionException - { - long overflow = Integer.MAX_VALUE; - double r0 = value; - long a0 = (long)FastMath.floor(r0); - if (FastMath.abs(a0) > overflow) { - throw new FractionConversionException(value, a0, 1l); - } - - // check for (almost) integer arguments, which should not go to iterations. - if (FastMath.abs(a0 - value) < epsilon) { - this.numerator = (int) a0; - this.denominator = 1; - return; - } - - long p0 = 1; - long q0 = 0; - long p1 = a0; - long q1 = 1; - - long p2 = 0; - long q2 = 1; - - int n = 0; - boolean stop = false; - do { - ++n; - double r1 = 1.0 / (r0 - a0); - long a1 = (long)FastMath.floor(r1); - p2 = (a1 * p1) + p0; - q2 = (a1 * q1) + q0; - - if ((FastMath.abs(p2) > overflow) || (FastMath.abs(q2) > overflow)) { - // in maxDenominator mode, if the last fraction was very close to the actual value - // q2 may overflow in the next iteration; in this case return the last one. - if (epsilon == 0.0 && FastMath.abs(q1) < maxDenominator) { - break; - } - throw new FractionConversionException(value, p2, q2); - } - - double convergent = (double)p2 / (double)q2; - if (n < maxIterations && FastMath.abs(convergent - value) > epsilon && q2 < maxDenominator) { - p0 = p1; - p1 = p2; - q0 = q1; - q1 = q2; - a0 = a1; - r0 = r1; - } else { - stop = true; - } - } while (!stop); - - if (n >= maxIterations) { - throw new FractionConversionException(value, maxIterations); - } - - if (q2 < maxDenominator) { - this.numerator = (int) p2; - this.denominator = (int) q2; - } else { - this.numerator = (int) p1; - this.denominator = (int) q1; - } - - } - - /** - * Create a fraction from an int. - * The fraction is num / 1. - * @param num the numerator. - */ - public Fraction(int num) { - this(num, 1); - } - - /** - * Create a fraction given the numerator and denominator. The fraction is - * reduced to lowest terms. - * @param num the numerator. - * @param den the denominator. - * @throws MathArithmeticException if the denominator is {@code zero} - */ - public Fraction(int num, int den) { - if (den == 0) { - throw new MathArithmeticException(LocalizedFormats.ZERO_DENOMINATOR_IN_FRACTION, - num, den); - } - if (den < 0) { - if (num == Integer.MIN_VALUE || - den == Integer.MIN_VALUE) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_FRACTION, - num, den); - } - num = -num; - den = -den; - } - // reduce numerator and denominator by greatest common denominator. - final int d = ArithmeticUtils.gcd(num, den); - if (d > 1) { - num /= d; - den /= d; - } - - // move sign to numerator. - if (den < 0) { - num = -num; - den = -den; - } - this.numerator = num; - this.denominator = den; - } - - /** - * Returns the absolute value of this fraction. - * @return the absolute value. - */ - public Fraction abs() { - Fraction ret; - if (numerator >= 0) { - ret = this; - } else { - ret = negate(); - } - return ret; - } - - /** - * Compares this object to another based on size. - * @param object the object to compare to - * @return -1 if this is less than {@code object}, +1 if this is greater - * than {@code object}, 0 if they are equal. - */ - @Override - public int compareTo(Fraction object) { - long nOd = ((long) numerator) * object.denominator; - long dOn = ((long) denominator) * object.numerator; - return (nOd < dOn) ? -1 : ((nOd > dOn) ? +1 : 0); - } - - /** - * Gets the fraction as a {@code double}. This calculates the fraction as - * the numerator divided by denominator. - * @return the fraction as a {@code double} - */ - @Override - public double doubleValue() { - return (double)numerator / (double)denominator; - } - - /** - * Test for the equality of two fractions. If the lowest term - * numerator and denominators are the same for both fractions, the two - * fractions are considered to be equal. - * @param other fraction to test for equality to this fraction - * @return true if two fractions are equal, false if object is - * {@code null}, not an instance of {@link Fraction}, or not equal - * to this fraction instance. - */ - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other instanceof Fraction) { - // since fractions are always in lowest terms, numerators and - // denominators can be compared directly for equality. - Fraction rhs = (Fraction)other; - return (numerator == rhs.numerator) && - (denominator == rhs.denominator); - } - return false; - } - - /** - * Gets the fraction as a {@code float}. This calculates the fraction as - * the numerator divided by denominator. - * @return the fraction as a {@code float} - */ - @Override - public float floatValue() { - return (float)doubleValue(); - } - - /** - * Access the denominator. - * @return the denominator. - */ - public int getDenominator() { - return denominator; - } - - /** - * Access the numerator. - * @return the numerator. - */ - public int getNumerator() { - return numerator; - } - - /** - * Gets a hashCode for the fraction. - * @return a hash code value for this object - */ - @Override - public int hashCode() { - return 37 * (37 * 17 + numerator) + denominator; - } - - /** - * Gets the fraction as an {@code int}. This returns the whole number part - * of the fraction. - * @return the whole number fraction part - */ - @Override - public int intValue() { - return (int)doubleValue(); - } - - /** - * Gets the fraction as a {@code long}. This returns the whole number part - * of the fraction. - * @return the whole number fraction part - */ - @Override - public long longValue() { - return (long)doubleValue(); - } - - /** - * Return the additive inverse of this fraction. - * @return the negation of this fraction. - */ - @Override - public Fraction negate() { - if (numerator==Integer.MIN_VALUE) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_FRACTION, numerator, denominator); - } - return new Fraction(-numerator, denominator); - } - - /** - * Return the multiplicative inverse of this fraction. - * @return the reciprocal fraction - */ - @Override - public Fraction reciprocal() { - return new Fraction(denominator, numerator); - } - - /** - *

Adds the value of this fraction to another, returning the result in reduced form. - * The algorithm follows Knuth, 4.5.1.

- * - * @param fraction the fraction to add, must not be {@code null} - * @return a {@code Fraction} instance with the resulting values - * @throws NullArgumentException if the fraction is {@code null} - * @throws MathArithmeticException if the resulting numerator or denominator exceeds - * {@code Integer.MAX_VALUE} - */ - @Override - public Fraction add(Fraction fraction) { - return addSub(fraction, true /* add */); - } - - /** - * Add an integer to the fraction. - * @param i the {@code integer} to add. - * @return this + i - */ - public Fraction add(final int i) { - return new Fraction(numerator + i * denominator, denominator); - } - - /** - *

Subtracts the value of another fraction from the value of this one, - * returning the result in reduced form.

- * - * @param fraction the fraction to subtract, must not be {@code null} - * @return a {@code Fraction} instance with the resulting values - * @throws NullArgumentException if the fraction is {@code null} - * @throws MathArithmeticException if the resulting numerator or denominator - * cannot be represented in an {@code int}. - */ - @Override - public Fraction subtract(Fraction fraction) { - return addSub(fraction, false /* subtract */); - } - - /** - * Subtract an integer from the fraction. - * @param i the {@code integer} to subtract. - * @return this - i - */ - public Fraction subtract(final int i) { - return new Fraction(numerator - i * denominator, denominator); - } - - /** - * Implement add and subtract using algorithm described in Knuth 4.5.1. - * - * @param fraction the fraction to subtract, must not be {@code null} - * @param isAdd true to add, false to subtract - * @return a {@code Fraction} instance with the resulting values - * @throws NullArgumentException if the fraction is {@code null} - * @throws MathArithmeticException if the resulting numerator or denominator - * cannot be represented in an {@code int}. - */ - private Fraction addSub(Fraction fraction, boolean isAdd) { - if (fraction == null) { - throw new NullArgumentException(LocalizedFormats.FRACTION); - } - // zero is identity for addition. - if (numerator == 0) { - return isAdd ? fraction : fraction.negate(); - } - if (fraction.numerator == 0) { - return this; - } - // if denominators are randomly distributed, d1 will be 1 about 61% - // of the time. - int d1 = ArithmeticUtils.gcd(denominator, fraction.denominator); - if (d1==1) { - // result is ( (u*v' +/- u'v) / u'v') - int uvp = ArithmeticUtils.mulAndCheck(numerator, fraction.denominator); - int upv = ArithmeticUtils.mulAndCheck(fraction.numerator, denominator); - return new Fraction - (isAdd ? ArithmeticUtils.addAndCheck(uvp, upv) : - ArithmeticUtils.subAndCheck(uvp, upv), - ArithmeticUtils.mulAndCheck(denominator, fraction.denominator)); - } - // the quantity 't' requires 65 bits of precision; see knuth 4.5.1 - // exercise 7. we're going to use a BigInteger. - // t = u(v'/d1) +/- v(u'/d1) - BigInteger uvp = BigInteger.valueOf(numerator) - .multiply(BigInteger.valueOf(fraction.denominator/d1)); - BigInteger upv = BigInteger.valueOf(fraction.numerator) - .multiply(BigInteger.valueOf(denominator/d1)); - BigInteger t = isAdd ? uvp.add(upv) : uvp.subtract(upv); - // but d2 doesn't need extra precision because - // d2 = gcd(t,d1) = gcd(t mod d1, d1) - int tmodd1 = t.mod(BigInteger.valueOf(d1)).intValue(); - int d2 = (tmodd1==0)?d1:ArithmeticUtils.gcd(tmodd1, d1); - - // result is (t/d2) / (u'/d1)(v'/d2) - BigInteger w = t.divide(BigInteger.valueOf(d2)); - if (w.bitLength() > 31) { - throw new MathArithmeticException(LocalizedFormats.NUMERATOR_OVERFLOW_AFTER_MULTIPLY, - w); - } - return new Fraction (w.intValue(), - ArithmeticUtils.mulAndCheck(denominator/d1, - fraction.denominator/d2)); - } - - /** - *

Multiplies the value of this fraction by another, returning the - * result in reduced form.

- * - * @param fraction the fraction to multiply by, must not be {@code null} - * @return a {@code Fraction} instance with the resulting values - * @throws NullArgumentException if the fraction is {@code null} - * @throws MathArithmeticException if the resulting numerator or denominator exceeds - * {@code Integer.MAX_VALUE} - */ - @Override - public Fraction multiply(Fraction fraction) { - if (fraction == null) { - throw new NullArgumentException(LocalizedFormats.FRACTION); - } - if (numerator == 0 || fraction.numerator == 0) { - return ZERO; - } - // knuth 4.5.1 - // make sure we don't overflow unless the result *must* overflow. - int d1 = ArithmeticUtils.gcd(numerator, fraction.denominator); - int d2 = ArithmeticUtils.gcd(fraction.numerator, denominator); - return getReducedFraction - (ArithmeticUtils.mulAndCheck(numerator/d1, fraction.numerator/d2), - ArithmeticUtils.mulAndCheck(denominator/d2, fraction.denominator/d1)); - } - - /** - * Multiply the fraction by an integer. - * @param i the {@code integer} to multiply by. - * @return this * i - */ - @Override - public Fraction multiply(final int i) { - return multiply(new Fraction(i)); - } - - /** - *

Divide the value of this fraction by another.

- * - * @param fraction the fraction to divide by, must not be {@code null} - * @return a {@code Fraction} instance with the resulting values - * @throws IllegalArgumentException if the fraction is {@code null} - * @throws MathArithmeticException if the fraction to divide by is zero - * @throws MathArithmeticException if the resulting numerator or denominator exceeds - * {@code Integer.MAX_VALUE} - */ - @Override - public Fraction divide(Fraction fraction) { - if (fraction == null) { - throw new NullArgumentException(LocalizedFormats.FRACTION); - } - if (fraction.numerator == 0) { - throw new MathArithmeticException(LocalizedFormats.ZERO_FRACTION_TO_DIVIDE_BY, - fraction.numerator, fraction.denominator); - } - return multiply(fraction.reciprocal()); - } - - /** - * Divide the fraction by an integer. - * @param i the {@code integer} to divide by. - * @return this * i - */ - public Fraction divide(final int i) { - return divide(new Fraction(i)); - } - - /** - *

- * Gets the fraction percentage as a {@code double}. This calculates the - * fraction as the numerator divided by denominator multiplied by 100. - *

- * - * @return the fraction percentage as a {@code double}. - */ - public double percentageValue() { - return 100 * doubleValue(); - } - - /** - *

Creates a {@code Fraction} instance with the 2 parts - * of a fraction Y/Z.

- * - *

Any negative signs are resolved to be on the numerator.

- * - * @param numerator the numerator, for example the three in 'three sevenths' - * @param denominator the denominator, for example the seven in 'three sevenths' - * @return a new fraction instance, with the numerator and denominator reduced - * @throws MathArithmeticException if the denominator is {@code zero} - */ - public static Fraction getReducedFraction(int numerator, int denominator) { - if (denominator == 0) { - throw new MathArithmeticException(LocalizedFormats.ZERO_DENOMINATOR_IN_FRACTION, - numerator, denominator); - } - if (numerator==0) { - return ZERO; // normalize zero. - } - // allow 2^k/-2^31 as a valid fraction (where k>0) - if (denominator==Integer.MIN_VALUE && (numerator&1)==0) { - numerator/=2; denominator/=2; - } - if (denominator < 0) { - if (numerator==Integer.MIN_VALUE || - denominator==Integer.MIN_VALUE) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_FRACTION, - numerator, denominator); - } - numerator = -numerator; - denominator = -denominator; - } - // simplify fraction. - int gcd = ArithmeticUtils.gcd(numerator, denominator); - numerator /= gcd; - denominator /= gcd; - return new Fraction(numerator, denominator); - } - - /** - *

- * Returns the {@code String} representing this fraction, ie - * "num / dem" or just "num" if the denominator is one. - *

- * - * @return a string representation of the fraction. - * @see Object#toString() - */ - @Override - public String toString() { - String str = null; - if (denominator == 1) { - str = Integer.toString(numerator); - } else if (numerator == 0) { - str = "0"; - } else { - str = numerator + " / " + denominator; - } - return str; - } - - /** {@inheritDoc} */ - @Override - public FractionField getField() { - return FractionField.getInstance(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/FractionConversionException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/FractionConversionException.java deleted file mode 100644 index f74a7cff8..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/FractionConversionException.java +++ /dev/null @@ -1,55 +0,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. - */ - -package org.apache.commons.math4.fraction; - -import org.apache.commons.math4.exception.ConvergenceException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Error thrown when a double value cannot be converted to a fraction - * in the allowed number of iterations. - * - * @since 1.2 - */ -public class FractionConversionException extends ConvergenceException { - - /** Serializable version identifier. */ - private static final long serialVersionUID = -4661812640132576263L; - - /** - * Constructs an exception with specified formatted detail message. - * Message formatting is delegated to {@link java.text.MessageFormat}. - * @param value double value to convert - * @param maxIterations maximal number of iterations allowed - */ - public FractionConversionException(double value, int maxIterations) { - super(LocalizedFormats.FAILED_FRACTION_CONVERSION, value, maxIterations); - } - - /** - * Constructs an exception with specified formatted detail message. - * Message formatting is delegated to {@link java.text.MessageFormat}. - * @param value double value to convert - * @param p current numerator - * @param q current denominator - */ - public FractionConversionException(double value, long p, long q) { - super(LocalizedFormats.FRACTION_CONVERSION_OVERFLOW, value, p, q); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/FractionField.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/FractionField.java deleted file mode 100644 index 0b513a59f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/FractionField.java +++ /dev/null @@ -1,85 +0,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. - */ - -package org.apache.commons.math4.fraction; - -import java.io.Serializable; - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; - -/** - * Representation of the fractional numbers field. - *

- * This class is a singleton. - *

- * @see Fraction - * @since 2.0 - */ -public class FractionField implements Field, Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = -1257768487499119313L; - - /** Private constructor for the singleton. - */ - private FractionField() { - } - - /** Get the unique instance. - * @return the unique instance - */ - public static FractionField getInstance() { - return LazyHolder.INSTANCE; - } - - /** {@inheritDoc} */ - @Override - public Fraction getOne() { - return Fraction.ONE; - } - - /** {@inheritDoc} */ - @Override - public Fraction getZero() { - return Fraction.ZERO; - } - - /** {@inheritDoc} */ - @Override - public Class> getRuntimeClass() { - return Fraction.class; - } - // CHECKSTYLE: stop HideUtilityClassConstructor - /** Holder for the instance. - *

We use here the Initialization On Demand Holder Idiom.

- */ - private static class LazyHolder { - /** Cached field instance. */ - private static final FractionField INSTANCE = new FractionField(); - } - // CHECKSTYLE: resume HideUtilityClassConstructor - - /** Handle deserialization of the singleton. - * @return the singleton instance - */ - private Object readResolve() { - // return the singleton instance - return LazyHolder.INSTANCE; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/package-info.java deleted file mode 100644 index 254710240..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/fraction/package-info.java +++ /dev/null @@ -1,22 +0,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. - */ -/** - * - * Fraction number type and fraction number formatting. - * - */ -package org.apache.commons.math4.fraction; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/AbstractFieldMatrix.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/AbstractFieldMatrix.java deleted file mode 100644 index c2f3b1803..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/AbstractFieldMatrix.java +++ /dev/null @@ -1,1174 +0,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. - */ - -package org.apache.commons.math4.linear; - -import java.util.ArrayList; - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.MathArrays; - -/** - * Basic implementation of {@link FieldMatrix} methods regardless of the underlying storage. - *

All the methods implemented here use {@link #getEntry(int, int)} to access - * matrix elements. Derived class can provide faster implementations.

- * - * @param Type of the field elements. - * - * @since 2.0 - */ -public abstract class AbstractFieldMatrix> - implements FieldMatrix { - /** Field to which the elements belong. */ - private final Field field; - - /** - * Constructor for use with Serializable - */ - protected AbstractFieldMatrix() { - field = null; - } - - /** - * Creates a matrix with no data - * @param field field to which the elements belong - */ - protected AbstractFieldMatrix(final Field field) { - this.field = field; - } - - /** - * Create a new {@code FieldMatrix} with the supplied row and column dimensions. - * - * @param field Field to which the elements belong. - * @param rowDimension Number of rows in the new matrix. - * @param columnDimension Number of columns in the new matrix. - * @throws NotStrictlyPositiveException if row or column dimension is not - * positive. - */ - protected AbstractFieldMatrix(final Field field, - final int rowDimension, - final int columnDimension) - throws NotStrictlyPositiveException { - if (rowDimension <= 0) { - throw new NotStrictlyPositiveException(LocalizedFormats.DIMENSION, - rowDimension); - } - if (columnDimension <= 0) { - throw new NotStrictlyPositiveException(LocalizedFormats.DIMENSION, - columnDimension); - } - this.field = field; - } - - /** - * Get the elements type from an array. - * - * @param Type of the field elements. - * @param d Data array. - * @return the field to which the array elements belong. - * @throws NullArgumentException if the array is {@code null}. - * @throws NoDataException if the array is empty. - */ - protected static > Field extractField(final T[][] d) - throws NoDataException, NullArgumentException { - if (d == null) { - throw new NullArgumentException(); - } - if (d.length == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW); - } - if (d[0].length == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN); - } - return d[0][0].getField(); - } - - /** - * Get the elements type from an array. - * - * @param Type of the field elements. - * @param d Data array. - * @return the field to which the array elements belong. - * @throws NoDataException if array is empty. - */ - protected static > Field extractField(final T[] d) - throws NoDataException { - if (d.length == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW); - } - return d[0].getField(); - } - - /** {@inheritDoc} */ - @Override - public Field getField() { - return field; - } - - /** {@inheritDoc} */ - @Override - public abstract FieldMatrix createMatrix(final int rowDimension, - final int columnDimension) - throws NotStrictlyPositiveException; - - /** {@inheritDoc} */ - @Override - public abstract FieldMatrix copy(); - - /** {@inheritDoc} */ - @Override - public FieldMatrix add(FieldMatrix m) - throws MatrixDimensionMismatchException { - // safety check - checkAdditionCompatible(m); - - final int rowCount = getRowDimension(); - final int columnCount = getColumnDimension(); - final FieldMatrix out = createMatrix(rowCount, columnCount); - for (int row = 0; row < rowCount; ++row) { - for (int col = 0; col < columnCount; ++col) { - out.setEntry(row, col, getEntry(row, col).add(m.getEntry(row, col))); - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix subtract(final FieldMatrix m) - throws MatrixDimensionMismatchException { - // safety check - checkSubtractionCompatible(m); - - final int rowCount = getRowDimension(); - final int columnCount = getColumnDimension(); - final FieldMatrix out = createMatrix(rowCount, columnCount); - for (int row = 0; row < rowCount; ++row) { - for (int col = 0; col < columnCount; ++col) { - out.setEntry(row, col, getEntry(row, col).subtract(m.getEntry(row, col))); - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix scalarAdd(final T d) { - - final int rowCount = getRowDimension(); - final int columnCount = getColumnDimension(); - final FieldMatrix out = createMatrix(rowCount, columnCount); - for (int row = 0; row < rowCount; ++row) { - for (int col = 0; col < columnCount; ++col) { - out.setEntry(row, col, getEntry(row, col).add(d)); - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix scalarMultiply(final T d) { - final int rowCount = getRowDimension(); - final int columnCount = getColumnDimension(); - final FieldMatrix out = createMatrix(rowCount, columnCount); - for (int row = 0; row < rowCount; ++row) { - for (int col = 0; col < columnCount; ++col) { - out.setEntry(row, col, getEntry(row, col).multiply(d)); - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix multiply(final FieldMatrix m) - throws DimensionMismatchException { - // safety check - checkMultiplicationCompatible(m); - - final int nRows = getRowDimension(); - final int nCols = m.getColumnDimension(); - final int nSum = getColumnDimension(); - final FieldMatrix out = createMatrix(nRows, nCols); - for (int row = 0; row < nRows; ++row) { - for (int col = 0; col < nCols; ++col) { - T sum = field.getZero(); - for (int i = 0; i < nSum; ++i) { - sum = sum.add(getEntry(row, i).multiply(m.getEntry(i, col))); - } - out.setEntry(row, col, sum); - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix preMultiply(final FieldMatrix m) - throws DimensionMismatchException { - return m.multiply(this); - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix power(final int p) throws NonSquareMatrixException, - NotPositiveException { - if (p < 0) { - throw new NotPositiveException(p); - } - - if (!isSquare()) { - throw new NonSquareMatrixException(getRowDimension(), getColumnDimension()); - } - - if (p == 0) { - return MatrixUtils.createFieldIdentityMatrix(this.getField(), this.getRowDimension()); - } - - if (p == 1) { - return this.copy(); - } - - final int power = p - 1; - - /* - * Only log_2(p) operations is used by doing as follows: - * 5^214 = 5^128 * 5^64 * 5^16 * 5^4 * 5^2 - * - * In general, the same approach is used for A^p. - */ - - final char[] binaryRepresentation = Integer.toBinaryString(power) - .toCharArray(); - final ArrayList nonZeroPositions = new ArrayList<>(); - - for (int i = 0; i < binaryRepresentation.length; ++i) { - if (binaryRepresentation[i] == '1') { - final int pos = binaryRepresentation.length - i - 1; - nonZeroPositions.add(pos); - } - } - - ArrayList> results = new ArrayList<>( - binaryRepresentation.length); - - results.add(0, this.copy()); - - for (int i = 1; i < binaryRepresentation.length; ++i) { - final FieldMatrix s = results.get(i - 1); - final FieldMatrix r = s.multiply(s); - results.add(i, r); - } - - FieldMatrix result = this.copy(); - - for (Integer i : nonZeroPositions) { - result = result.multiply(results.get(i)); - } - - return result; - } - - /** {@inheritDoc} */ - @Override - public T[][] getData() { - final T[][] data = MathArrays.buildArray(field, getRowDimension(), getColumnDimension()); - - for (int i = 0; i < data.length; ++i) { - final T[] dataI = data[i]; - for (int j = 0; j < dataI.length; ++j) { - dataI[j] = getEntry(i, j); - } - } - - return data; - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix getSubMatrix(final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws NumberIsTooSmallException, OutOfRangeException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); - - final FieldMatrix subMatrix = - createMatrix(endRow - startRow + 1, endColumn - startColumn + 1); - for (int i = startRow; i <= endRow; ++i) { - for (int j = startColumn; j <= endColumn; ++j) { - subMatrix.setEntry(i - startRow, j - startColumn, getEntry(i, j)); - } - } - - return subMatrix; - - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix getSubMatrix(final int[] selectedRows, - final int[] selectedColumns) - throws NoDataException, NullArgumentException, OutOfRangeException { - - // safety checks - checkSubMatrixIndex(selectedRows, selectedColumns); - - // copy entries - final FieldMatrix subMatrix = - createMatrix(selectedRows.length, selectedColumns.length); - subMatrix.walkInOptimizedOrder(new DefaultFieldMatrixChangingVisitor(field.getZero()) { - - /** {@inheritDoc} */ - @Override - public T visit(final int row, final int column, final T value) { - return getEntry(selectedRows[row], selectedColumns[column]); - } - - }); - - return subMatrix; - - } - - /** {@inheritDoc} */ - @Override - public void copySubMatrix(final int startRow, final int endRow, - final int startColumn, final int endColumn, - final T[][] destination) - throws MatrixDimensionMismatchException, NumberIsTooSmallException, - OutOfRangeException{ - // safety checks - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); - final int rowsCount = endRow + 1 - startRow; - final int columnsCount = endColumn + 1 - startColumn; - if ((destination.length < rowsCount) || (destination[0].length < columnsCount)) { - throw new MatrixDimensionMismatchException(destination.length, - destination[0].length, - rowsCount, - columnsCount); - } - - // copy entries - walkInOptimizedOrder(new DefaultFieldMatrixPreservingVisitor(field.getZero()) { - - /** Initial row index. */ - private int startRow; - - /** Initial column index. */ - private int startColumn; - - /** {@inheritDoc} */ - @Override - public void start(final int rows, final int columns, - final int startRow, final int endRow, - final int startColumn, final int endColumn) { - this.startRow = startRow; - this.startColumn = startColumn; - } - - /** {@inheritDoc} */ - @Override - public void visit(final int row, final int column, final T value) { - destination[row - startRow][column - startColumn] = value; - } - - }, startRow, endRow, startColumn, endColumn); - - } - - /** {@inheritDoc} */ - @Override - public void copySubMatrix(int[] selectedRows, int[] selectedColumns, T[][] destination) - throws MatrixDimensionMismatchException, NoDataException, - NullArgumentException, OutOfRangeException { - // safety checks - checkSubMatrixIndex(selectedRows, selectedColumns); - if ((destination.length < selectedRows.length) || - (destination[0].length < selectedColumns.length)) { - throw new MatrixDimensionMismatchException(destination.length, - destination[0].length, - selectedRows.length, - selectedColumns.length); - } - - // copy entries - for (int i = 0; i < selectedRows.length; i++) { - final T[] destinationI = destination[i]; - for (int j = 0; j < selectedColumns.length; j++) { - destinationI[j] = getEntry(selectedRows[i], selectedColumns[j]); - } - } - - } - - /** {@inheritDoc} */ - @Override - public void setSubMatrix(final T[][] subMatrix, final int row, - final int column) - throws DimensionMismatchException, OutOfRangeException, - NoDataException, NullArgumentException { - if (subMatrix == null) { - throw new NullArgumentException(); - } - final int nRows = subMatrix.length; - if (nRows == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW); - } - - final int nCols = subMatrix[0].length; - if (nCols == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN); - } - - for (int r = 1; r < nRows; ++r) { - if (subMatrix[r].length != nCols) { - throw new DimensionMismatchException(nCols, subMatrix[r].length); - } - } - - checkRowIndex(row); - checkColumnIndex(column); - checkRowIndex(nRows + row - 1); - checkColumnIndex(nCols + column - 1); - - for (int i = 0; i < nRows; ++i) { - for (int j = 0; j < nCols; ++j) { - setEntry(row + i, column + j, subMatrix[i][j]); - } - } - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix getRowMatrix(final int row) throws OutOfRangeException { - checkRowIndex(row); - final int nCols = getColumnDimension(); - final FieldMatrix out = createMatrix(1, nCols); - for (int i = 0; i < nCols; ++i) { - out.setEntry(0, i, getEntry(row, i)); - } - - return out; - - } - - /** {@inheritDoc} */ - @Override - public void setRowMatrix(final int row, final FieldMatrix matrix) - throws OutOfRangeException, MatrixDimensionMismatchException { - checkRowIndex(row); - final int nCols = getColumnDimension(); - if ((matrix.getRowDimension() != 1) || - (matrix.getColumnDimension() != nCols)) { - throw new MatrixDimensionMismatchException(matrix.getRowDimension(), - matrix.getColumnDimension(), - 1, nCols); - } - for (int i = 0; i < nCols; ++i) { - setEntry(row, i, matrix.getEntry(0, i)); - } - - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix getColumnMatrix(final int column) - throws OutOfRangeException { - - checkColumnIndex(column); - final int nRows = getRowDimension(); - final FieldMatrix out = createMatrix(nRows, 1); - for (int i = 0; i < nRows; ++i) { - out.setEntry(i, 0, getEntry(i, column)); - } - - return out; - - } - - /** {@inheritDoc} */ - @Override - public void setColumnMatrix(final int column, final FieldMatrix matrix) - throws OutOfRangeException, MatrixDimensionMismatchException { - checkColumnIndex(column); - final int nRows = getRowDimension(); - if ((matrix.getRowDimension() != nRows) || - (matrix.getColumnDimension() != 1)) { - throw new MatrixDimensionMismatchException(matrix.getRowDimension(), - matrix.getColumnDimension(), - nRows, 1); - } - for (int i = 0; i < nRows; ++i) { - setEntry(i, column, matrix.getEntry(i, 0)); - } - - } - - /** {@inheritDoc} */ - @Override - public FieldVector getRowVector(final int row) - throws OutOfRangeException { - return new ArrayFieldVector<>(field, getRow(row), false); - } - - /** {@inheritDoc} */ - @Override - public void setRowVector(final int row, final FieldVector vector) - throws OutOfRangeException, MatrixDimensionMismatchException { - checkRowIndex(row); - final int nCols = getColumnDimension(); - if (vector.getDimension() != nCols) { - throw new MatrixDimensionMismatchException(1, vector.getDimension(), - 1, nCols); - } - for (int i = 0; i < nCols; ++i) { - setEntry(row, i, vector.getEntry(i)); - } - - } - - /** {@inheritDoc} */ - @Override - public FieldVector getColumnVector(final int column) - throws OutOfRangeException { - return new ArrayFieldVector<>(field, getColumn(column), false); - } - - /** {@inheritDoc} */ - @Override - public void setColumnVector(final int column, final FieldVector vector) - throws OutOfRangeException, MatrixDimensionMismatchException { - - checkColumnIndex(column); - final int nRows = getRowDimension(); - if (vector.getDimension() != nRows) { - throw new MatrixDimensionMismatchException(vector.getDimension(), 1, - nRows, 1); - } - for (int i = 0; i < nRows; ++i) { - setEntry(i, column, vector.getEntry(i)); - } - - } - - /** {@inheritDoc} */ - @Override - public T[] getRow(final int row) throws OutOfRangeException { - checkRowIndex(row); - final int nCols = getColumnDimension(); - final T[] out = MathArrays.buildArray(field, nCols); - for (int i = 0; i < nCols; ++i) { - out[i] = getEntry(row, i); - } - - return out; - - } - - /** {@inheritDoc} */ - @Override - public void setRow(final int row, final T[] array) - throws OutOfRangeException, MatrixDimensionMismatchException { - checkRowIndex(row); - final int nCols = getColumnDimension(); - if (array.length != nCols) { - throw new MatrixDimensionMismatchException(1, array.length, 1, nCols); - } - for (int i = 0; i < nCols; ++i) { - setEntry(row, i, array[i]); - } - - } - - /** {@inheritDoc} */ - @Override - public T[] getColumn(final int column) throws OutOfRangeException { - checkColumnIndex(column); - final int nRows = getRowDimension(); - final T[] out = MathArrays.buildArray(field, nRows); - for (int i = 0; i < nRows; ++i) { - out[i] = getEntry(i, column); - } - - return out; - - } - - /** {@inheritDoc} */ - @Override - public void setColumn(final int column, final T[] array) - throws OutOfRangeException, MatrixDimensionMismatchException { - checkColumnIndex(column); - final int nRows = getRowDimension(); - if (array.length != nRows) { - throw new MatrixDimensionMismatchException(array.length, 1, nRows, 1); - } - for (int i = 0; i < nRows; ++i) { - setEntry(i, column, array[i]); - } - } - - /** {@inheritDoc} */ - @Override - public abstract T getEntry(int row, int column) throws OutOfRangeException; - - /** {@inheritDoc} */ - @Override - public abstract void setEntry(int row, int column, T value) throws OutOfRangeException; - - /** {@inheritDoc} */ - @Override - public abstract void addToEntry(int row, int column, T increment) throws OutOfRangeException; - - /** {@inheritDoc} */ - @Override - public abstract void multiplyEntry(int row, int column, T factor) throws OutOfRangeException; - - /** {@inheritDoc} */ - @Override - public FieldMatrix transpose() { - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - final FieldMatrix out = createMatrix(nCols, nRows); - walkInOptimizedOrder(new DefaultFieldMatrixPreservingVisitor(field.getZero()) { - /** {@inheritDoc} */ - @Override - public void visit(final int row, final int column, final T value) { - out.setEntry(column, row, value); - } - }); - - return out; - } - - /** {@inheritDoc} */ - @Override - public boolean isSquare() { - return getColumnDimension() == getRowDimension(); - } - - /** {@inheritDoc} */ - @Override - public abstract int getRowDimension(); - - /** {@inheritDoc} */ - @Override - public abstract int getColumnDimension(); - - /** {@inheritDoc} */ - @Override - public T getTrace() throws NonSquareMatrixException { - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - if (nRows != nCols) { - throw new NonSquareMatrixException(nRows, nCols); - } - T trace = field.getZero(); - for (int i = 0; i < nRows; ++i) { - trace = trace.add(getEntry(i, i)); - } - return trace; - } - - /** {@inheritDoc} */ - @Override - public T[] operate(final T[] v) throws DimensionMismatchException { - - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - if (v.length != nCols) { - throw new DimensionMismatchException(v.length, nCols); - } - - final T[] out = MathArrays.buildArray(field, nRows); - for (int row = 0; row < nRows; ++row) { - T sum = field.getZero(); - for (int i = 0; i < nCols; ++i) { - sum = sum.add(getEntry(row, i).multiply(v[i])); - } - out[row] = sum; - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public FieldVector operate(final FieldVector v) - throws DimensionMismatchException { - try { - return new ArrayFieldVector<>(field, operate(((ArrayFieldVector) v).getDataRef()), false); - } catch (ClassCastException cce) { - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - if (v.getDimension() != nCols) { - throw new DimensionMismatchException(v.getDimension(), nCols); - } - - final T[] out = MathArrays.buildArray(field, nRows); - for (int row = 0; row < nRows; ++row) { - T sum = field.getZero(); - for (int i = 0; i < nCols; ++i) { - sum = sum.add(getEntry(row, i).multiply(v.getEntry(i))); - } - out[row] = sum; - } - - return new ArrayFieldVector<>(field, out, false); - } - } - - /** {@inheritDoc} */ - @Override - public T[] preMultiply(final T[] v) throws DimensionMismatchException { - - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - if (v.length != nRows) { - throw new DimensionMismatchException(v.length, nRows); - } - - final T[] out = MathArrays.buildArray(field, nCols); - for (int col = 0; col < nCols; ++col) { - T sum = field.getZero(); - for (int i = 0; i < nRows; ++i) { - sum = sum.add(getEntry(i, col).multiply(v[i])); - } - out[col] = sum; - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public FieldVector preMultiply(final FieldVector v) - throws DimensionMismatchException { - try { - return new ArrayFieldVector<>(field, preMultiply(((ArrayFieldVector) v).getDataRef()), false); - } catch (ClassCastException cce) { - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - if (v.getDimension() != nRows) { - throw new DimensionMismatchException(v.getDimension(), nRows); - } - - final T[] out = MathArrays.buildArray(field, nCols); - for (int col = 0; col < nCols; ++col) { - T sum = field.getZero(); - for (int i = 0; i < nRows; ++i) { - sum = sum.add(getEntry(i, col).multiply(v.getEntry(i))); - } - out[col] = sum; - } - - return new ArrayFieldVector<>(field, out, false); - } - } - - /** {@inheritDoc} */ - @Override - public T walkInRowOrder(final FieldMatrixChangingVisitor visitor) { - final int rows = getRowDimension(); - final int columns = getColumnDimension(); - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int row = 0; row < rows; ++row) { - for (int column = 0; column < columns; ++column) { - final T oldValue = getEntry(row, column); - final T newValue = visitor.visit(row, column, oldValue); - setEntry(row, column, newValue); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInRowOrder(final FieldMatrixPreservingVisitor visitor) { - final int rows = getRowDimension(); - final int columns = getColumnDimension(); - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int row = 0; row < rows; ++row) { - for (int column = 0; column < columns; ++column) { - visitor.visit(row, column, getEntry(row, column)); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInRowOrder(final FieldMatrixChangingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws NumberIsTooSmallException, OutOfRangeException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); - visitor.start(getRowDimension(), getColumnDimension(), - startRow, endRow, startColumn, endColumn); - for (int row = startRow; row <= endRow; ++row) { - for (int column = startColumn; column <= endColumn; ++column) { - final T oldValue = getEntry(row, column); - final T newValue = visitor.visit(row, column, oldValue); - setEntry(row, column, newValue); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInRowOrder(final FieldMatrixPreservingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws NumberIsTooSmallException, OutOfRangeException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); - visitor.start(getRowDimension(), getColumnDimension(), - startRow, endRow, startColumn, endColumn); - for (int row = startRow; row <= endRow; ++row) { - for (int column = startColumn; column <= endColumn; ++column) { - visitor.visit(row, column, getEntry(row, column)); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInColumnOrder(final FieldMatrixChangingVisitor visitor) { - final int rows = getRowDimension(); - final int columns = getColumnDimension(); - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int column = 0; column < columns; ++column) { - for (int row = 0; row < rows; ++row) { - final T oldValue = getEntry(row, column); - final T newValue = visitor.visit(row, column, oldValue); - setEntry(row, column, newValue); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInColumnOrder(final FieldMatrixPreservingVisitor visitor) { - final int rows = getRowDimension(); - final int columns = getColumnDimension(); - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int column = 0; column < columns; ++column) { - for (int row = 0; row < rows; ++row) { - visitor.visit(row, column, getEntry(row, column)); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInColumnOrder(final FieldMatrixChangingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws NumberIsTooSmallException, OutOfRangeException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); - visitor.start(getRowDimension(), getColumnDimension(), - startRow, endRow, startColumn, endColumn); - for (int column = startColumn; column <= endColumn; ++column) { - for (int row = startRow; row <= endRow; ++row) { - final T oldValue = getEntry(row, column); - final T newValue = visitor.visit(row, column, oldValue); - setEntry(row, column, newValue); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInColumnOrder(final FieldMatrixPreservingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws NumberIsTooSmallException, OutOfRangeException{ - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); - visitor.start(getRowDimension(), getColumnDimension(), - startRow, endRow, startColumn, endColumn); - for (int column = startColumn; column <= endColumn; ++column) { - for (int row = startRow; row <= endRow; ++row) { - visitor.visit(row, column, getEntry(row, column)); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInOptimizedOrder(final FieldMatrixChangingVisitor visitor) { - return walkInRowOrder(visitor); - } - - /** {@inheritDoc} */ - @Override - public T walkInOptimizedOrder(final FieldMatrixPreservingVisitor visitor) { - return walkInRowOrder(visitor); - } - - /** {@inheritDoc} */ - @Override - public T walkInOptimizedOrder(final FieldMatrixChangingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws NumberIsTooSmallException, OutOfRangeException { - return walkInRowOrder(visitor, startRow, endRow, startColumn, endColumn); - } - - /** {@inheritDoc} */ - @Override - public T walkInOptimizedOrder(final FieldMatrixPreservingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws NumberIsTooSmallException, OutOfRangeException { - return walkInRowOrder(visitor, startRow, endRow, startColumn, endColumn); - } - - /** - * Get a string representation for this matrix. - * @return a string representation for this matrix - */ - @Override - public String toString() { - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - final StringBuffer res = new StringBuffer(); - String fullClassName = getClass().getName(); - String shortClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1); - res.append(shortClassName).append("{"); - - for (int i = 0; i < nRows; ++i) { - if (i > 0) { - res.append(","); - } - res.append("{"); - for (int j = 0; j < nCols; ++j) { - if (j > 0) { - res.append(","); - } - res.append(getEntry(i, j)); - } - res.append("}"); - } - - res.append("}"); - return res.toString(); - } - - /** - * Returns true iff object is a - * FieldMatrix instance with the same dimensions as this - * and all corresponding matrix entries are equal. - * - * @param object the object to test equality against. - * @return true if object equals this - */ - @Override - public boolean equals(final Object object) { - if (object == this ) { - return true; - } - if (object instanceof FieldMatrix == false) { - return false; - } - FieldMatrix m = (FieldMatrix) object; - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - if (m.getColumnDimension() != nCols || m.getRowDimension() != nRows) { - return false; - } - for (int row = 0; row < nRows; ++row) { - for (int col = 0; col < nCols; ++col) { - if (!getEntry(row, col).equals(m.getEntry(row, col))) { - return false; - } - } - } - return true; - } - - /** - * Computes a hashcode for the matrix. - * - * @return hashcode for matrix - */ - @Override - public int hashCode() { - int ret = 322562; - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - ret = ret * 31 + nRows; - ret = ret * 31 + nCols; - for (int row = 0; row < nRows; ++row) { - for (int col = 0; col < nCols; ++col) { - ret = ret * 31 + (11 * (row+1) + 17 * (col+1)) * getEntry(row, col).hashCode(); - } - } - return ret; - } - - /** - * Check if a row index is valid. - * - * @param row Row index to check. - * @throws OutOfRangeException if {@code index} is not valid. - */ - protected void checkRowIndex(final int row) throws OutOfRangeException { - if (row < 0 || row >= getRowDimension()) { - throw new OutOfRangeException(LocalizedFormats.ROW_INDEX, - row, 0, getRowDimension() - 1); - } - } - - /** - * Check if a column index is valid. - * - * @param column Column index to check. - * @throws OutOfRangeException if {@code index} is not valid. - */ - protected void checkColumnIndex(final int column) - throws OutOfRangeException { - if (column < 0 || column >= getColumnDimension()) { - throw new OutOfRangeException(LocalizedFormats.COLUMN_INDEX, - column, 0, getColumnDimension() - 1); - } - } - - /** - * Check if submatrix ranges indices are valid. - * Rows and columns are indicated counting from 0 to n-1. - * - * @param startRow Initial row index. - * @param endRow Final row index. - * @param startColumn Initial column index. - * @param endColumn Final column index. - * @throws OutOfRangeException if the indices are not valid. - * @throws NumberIsTooSmallException if {@code endRow < startRow} or - * {@code endColumn < startColumn}. - */ - protected void checkSubMatrixIndex(final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws NumberIsTooSmallException, OutOfRangeException { - checkRowIndex(startRow); - checkRowIndex(endRow); - if (endRow < startRow) { - throw new NumberIsTooSmallException(LocalizedFormats.INITIAL_ROW_AFTER_FINAL_ROW, - endRow, startRow, true); - } - - checkColumnIndex(startColumn); - checkColumnIndex(endColumn); - if (endColumn < startColumn) { - throw new NumberIsTooSmallException(LocalizedFormats.INITIAL_COLUMN_AFTER_FINAL_COLUMN, - endColumn, startColumn, true); - } - } - - /** - * Check if submatrix ranges indices are valid. - * Rows and columns are indicated counting from 0 to n-1. - * - * @param selectedRows Array of row indices. - * @param selectedColumns Array of column indices. - * @throws NullArgumentException if the arrays are {@code null}. - * @throws NoDataException if the arrays have zero length. - * @throws OutOfRangeException if row or column selections are not valid. - */ - protected void checkSubMatrixIndex(final int[] selectedRows, final int[] selectedColumns) - throws NoDataException, NullArgumentException, OutOfRangeException { - if (selectedRows == null || - selectedColumns == null) { - throw new NullArgumentException(); - } - if (selectedRows.length == 0 || - selectedColumns.length == 0) { - throw new NoDataException(); - } - - for (final int row : selectedRows) { - checkRowIndex(row); - } - for (final int column : selectedColumns) { - checkColumnIndex(column); - } - } - - /** - * Check if a matrix is addition compatible with the instance. - * - * @param m Matrix to check. - * @throws MatrixDimensionMismatchException if the matrix is not - * addition-compatible with instance. - */ - protected void checkAdditionCompatible(final FieldMatrix m) - throws MatrixDimensionMismatchException { - if ((getRowDimension() != m.getRowDimension()) || - (getColumnDimension() != m.getColumnDimension())) { - throw new MatrixDimensionMismatchException(m.getRowDimension(), m.getColumnDimension(), - getRowDimension(), getColumnDimension()); - } - } - - /** - * Check if a matrix is subtraction compatible with the instance. - * - * @param m Matrix to check. - * @throws MatrixDimensionMismatchException if the matrix is not - * subtraction-compatible with instance. - */ - protected void checkSubtractionCompatible(final FieldMatrix m) - throws MatrixDimensionMismatchException { - if ((getRowDimension() != m.getRowDimension()) || - (getColumnDimension() != m.getColumnDimension())) { - throw new MatrixDimensionMismatchException(m.getRowDimension(), m.getColumnDimension(), - getRowDimension(), getColumnDimension()); - } - } - - /** - * Check if a matrix is multiplication compatible with the instance. - * - * @param m Matrix to check. - * @throws DimensionMismatchException if the matrix is not - * multiplication-compatible with instance. - */ - protected void checkMultiplicationCompatible(final FieldMatrix m) - throws DimensionMismatchException { - if (getColumnDimension() != m.getRowDimension()) { - throw new DimensionMismatchException(m.getRowDimension(), getColumnDimension()); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/AbstractRealMatrix.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/AbstractRealMatrix.java deleted file mode 100644 index 76ef1cb89..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/AbstractRealMatrix.java +++ /dev/null @@ -1,1049 +0,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. - */ - -package org.apache.commons.math4.linear; - -import java.util.ArrayList; -import java.util.Locale; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathUtils; - -/** - * Basic implementation of RealMatrix methods regardless of the underlying storage. - *

All the methods implemented here use {@link #getEntry(int, int)} to access - * matrix elements. Derived class can provide faster implementations.

- * - * @since 2.0 - */ -public abstract class AbstractRealMatrix - extends RealLinearOperator - implements RealMatrix { - - /** Default format. */ - private static final RealMatrixFormat DEFAULT_FORMAT = RealMatrixFormat.getInstance(Locale.US); - static { - // set the minimum fraction digits to 1 to keep compatibility - DEFAULT_FORMAT.getFormat().setMinimumFractionDigits(1); - } - - /** - * Creates a matrix with no data - */ - protected AbstractRealMatrix() {} - - /** - * Create a new RealMatrix with the supplied row and column dimensions. - * - * @param rowDimension the number of rows in the new matrix - * @param columnDimension the number of columns in the new matrix - * @throws NotStrictlyPositiveException if row or column dimension is not positive - */ - protected AbstractRealMatrix(final int rowDimension, - final int columnDimension) - throws NotStrictlyPositiveException { - if (rowDimension < 1) { - throw new NotStrictlyPositiveException(rowDimension); - } - if (columnDimension < 1) { - throw new NotStrictlyPositiveException(columnDimension); - } - } - - /** {@inheritDoc} */ - @Override - public RealMatrix add(RealMatrix m) - throws MatrixDimensionMismatchException { - MatrixUtils.checkAdditionCompatible(this, m); - - final int rowCount = getRowDimension(); - final int columnCount = getColumnDimension(); - final RealMatrix out = createMatrix(rowCount, columnCount); - for (int row = 0; row < rowCount; ++row) { - for (int col = 0; col < columnCount; ++col) { - out.setEntry(row, col, getEntry(row, col) + m.getEntry(row, col)); - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public RealMatrix subtract(final RealMatrix m) - throws MatrixDimensionMismatchException { - MatrixUtils.checkSubtractionCompatible(this, m); - - final int rowCount = getRowDimension(); - final int columnCount = getColumnDimension(); - final RealMatrix out = createMatrix(rowCount, columnCount); - for (int row = 0; row < rowCount; ++row) { - for (int col = 0; col < columnCount; ++col) { - out.setEntry(row, col, getEntry(row, col) - m.getEntry(row, col)); - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public RealMatrix scalarAdd(final double d) { - final int rowCount = getRowDimension(); - final int columnCount = getColumnDimension(); - final RealMatrix out = createMatrix(rowCount, columnCount); - for (int row = 0; row < rowCount; ++row) { - for (int col = 0; col < columnCount; ++col) { - out.setEntry(row, col, getEntry(row, col) + d); - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public RealMatrix scalarMultiply(final double d) { - final int rowCount = getRowDimension(); - final int columnCount = getColumnDimension(); - final RealMatrix out = createMatrix(rowCount, columnCount); - for (int row = 0; row < rowCount; ++row) { - for (int col = 0; col < columnCount; ++col) { - out.setEntry(row, col, getEntry(row, col) * d); - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public RealMatrix multiply(final RealMatrix m) - throws DimensionMismatchException { - MatrixUtils.checkMultiplicationCompatible(this, m); - - final int nRows = getRowDimension(); - final int nCols = m.getColumnDimension(); - final int nSum = getColumnDimension(); - final RealMatrix out = createMatrix(nRows, nCols); - for (int row = 0; row < nRows; ++row) { - for (int col = 0; col < nCols; ++col) { - double sum = 0; - for (int i = 0; i < nSum; ++i) { - sum += getEntry(row, i) * m.getEntry(i, col); - } - out.setEntry(row, col, sum); - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public RealMatrix preMultiply(final RealMatrix m) - throws DimensionMismatchException { - return m.multiply(this); - } - - /** {@inheritDoc} */ - @Override - public RealMatrix power(final int p) - throws NotPositiveException, NonSquareMatrixException { - if (p < 0) { - throw new NotPositiveException(LocalizedFormats.NOT_POSITIVE_EXPONENT, p); - } - - if (!isSquare()) { - throw new NonSquareMatrixException(getRowDimension(), getColumnDimension()); - } - - if (p == 0) { - return MatrixUtils.createRealIdentityMatrix(this.getRowDimension()); - } - - if (p == 1) { - return this.copy(); - } - - final int power = p - 1; - - /* - * Only log_2(p) operations is used by doing as follows: - * 5^214 = 5^128 * 5^64 * 5^16 * 5^4 * 5^2 - * - * In general, the same approach is used for A^p. - */ - - final char[] binaryRepresentation = Integer.toBinaryString(power).toCharArray(); - final ArrayList nonZeroPositions = new ArrayList<>(); - int maxI = -1; - - for (int i = 0; i < binaryRepresentation.length; ++i) { - if (binaryRepresentation[i] == '1') { - final int pos = binaryRepresentation.length - i - 1; - nonZeroPositions.add(pos); - - // The positions are taken in turn, so maxI is only changed once - if (maxI == -1) { - maxI = pos; - } - } - } - - RealMatrix[] results = new RealMatrix[maxI + 1]; - results[0] = this.copy(); - - for (int i = 1; i <= maxI; ++i) { - results[i] = results[i-1].multiply(results[i-1]); - } - - RealMatrix result = this.copy(); - - for (Integer i : nonZeroPositions) { - result = result.multiply(results[i]); - } - - return result; - } - - /** {@inheritDoc} */ - @Override - public double[][] getData() { - final double[][] data = new double[getRowDimension()][getColumnDimension()]; - - for (int i = 0; i < data.length; ++i) { - final double[] dataI = data[i]; - for (int j = 0; j < dataI.length; ++j) { - dataI[j] = getEntry(i, j); - } - } - - return data; - } - - /** {@inheritDoc} */ - @Override - public double getNorm() { - return walkInColumnOrder(new RealMatrixPreservingVisitor() { - - /** Last row index. */ - private double endRow; - - /** Sum of absolute values on one column. */ - private double columnSum; - - /** Maximal sum across all columns. */ - private double maxColSum; - - /** {@inheritDoc} */ - @Override - public void start(final int rows, final int columns, - final int startRow, final int endRow, - final int startColumn, final int endColumn) { - this.endRow = endRow; - columnSum = 0; - maxColSum = 0; - } - - /** {@inheritDoc} */ - @Override - public void visit(final int row, final int column, final double value) { - columnSum += FastMath.abs(value); - if (row == endRow) { - maxColSum = FastMath.max(maxColSum, columnSum); - columnSum = 0; - } - } - - /** {@inheritDoc} */ - @Override - public double end() { - return maxColSum; - } - }); - } - - /** {@inheritDoc} */ - @Override - public double getFrobeniusNorm() { - return walkInOptimizedOrder(new RealMatrixPreservingVisitor() { - - /** Sum of squared entries. */ - private double sum; - - /** {@inheritDoc} */ - @Override - public void start(final int rows, final int columns, - final int startRow, final int endRow, - final int startColumn, final int endColumn) { - sum = 0; - } - - /** {@inheritDoc} */ - @Override - public void visit(final int row, final int column, final double value) { - sum += value * value; - } - - /** {@inheritDoc} */ - @Override - public double end() { - return FastMath.sqrt(sum); - } - }); - } - - /** {@inheritDoc} */ - @Override - public RealMatrix getSubMatrix(final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); - - final RealMatrix subMatrix = - createMatrix(endRow - startRow + 1, endColumn - startColumn + 1); - for (int i = startRow; i <= endRow; ++i) { - for (int j = startColumn; j <= endColumn; ++j) { - subMatrix.setEntry(i - startRow, j - startColumn, getEntry(i, j)); - } - } - - return subMatrix; - } - - /** {@inheritDoc} */ - @Override - public RealMatrix getSubMatrix(final int[] selectedRows, - final int[] selectedColumns) - throws NullArgumentException, NoDataException, OutOfRangeException { - MatrixUtils.checkSubMatrixIndex(this, selectedRows, selectedColumns); - - final RealMatrix subMatrix = - createMatrix(selectedRows.length, selectedColumns.length); - subMatrix.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() { - - /** {@inheritDoc} */ - @Override - public double visit(final int row, final int column, final double value) { - return getEntry(selectedRows[row], selectedColumns[column]); - } - - }); - - return subMatrix; - } - - /** {@inheritDoc} */ - @Override - public void copySubMatrix(final int startRow, final int endRow, - final int startColumn, final int endColumn, - final double[][] destination) - throws OutOfRangeException, NumberIsTooSmallException, - MatrixDimensionMismatchException { - MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); - final int rowsCount = endRow + 1 - startRow; - final int columnsCount = endColumn + 1 - startColumn; - if ((destination.length < rowsCount) || (destination[0].length < columnsCount)) { - throw new MatrixDimensionMismatchException(destination.length, destination[0].length, - rowsCount, columnsCount); - } - - for (int i = 1; i < rowsCount; i++) { - if (destination[i].length < columnsCount) { - throw new MatrixDimensionMismatchException(destination.length, destination[i].length, - rowsCount, columnsCount); - } - } - - walkInOptimizedOrder(new DefaultRealMatrixPreservingVisitor() { - - /** Initial row index. */ - private int startRow; - - /** Initial column index. */ - private int startColumn; - - /** {@inheritDoc} */ - @Override - public void start(final int rows, final int columns, - final int startRow, final int endRow, - final int startColumn, final int endColumn) { - this.startRow = startRow; - this.startColumn = startColumn; - } - - /** {@inheritDoc} */ - @Override - public void visit(final int row, final int column, final double value) { - destination[row - startRow][column - startColumn] = value; - } - - }, startRow, endRow, startColumn, endColumn); - } - - /** {@inheritDoc} */ - @Override - public void copySubMatrix(int[] selectedRows, int[] selectedColumns, - double[][] destination) - throws OutOfRangeException, NullArgumentException, NoDataException, - MatrixDimensionMismatchException { - MatrixUtils.checkSubMatrixIndex(this, selectedRows, selectedColumns); - final int nCols = selectedColumns.length; - if ((destination.length < selectedRows.length) || - (destination[0].length < nCols)) { - throw new MatrixDimensionMismatchException(destination.length, destination[0].length, - selectedRows.length, selectedColumns.length); - } - - for (int i = 0; i < selectedRows.length; i++) { - final double[] destinationI = destination[i]; - if (destinationI.length < nCols) { - throw new MatrixDimensionMismatchException(destination.length, destinationI.length, - selectedRows.length, selectedColumns.length); - } - for (int j = 0; j < selectedColumns.length; j++) { - destinationI[j] = getEntry(selectedRows[i], selectedColumns[j]); - } - } - } - - /** {@inheritDoc} */ - @Override - public void setSubMatrix(final double[][] subMatrix, final int row, final int column) - throws NoDataException, OutOfRangeException, - DimensionMismatchException, NullArgumentException { - MathUtils.checkNotNull(subMatrix); - final int nRows = subMatrix.length; - if (nRows == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW); - } - - final int nCols = subMatrix[0].length; - if (nCols == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN); - } - - for (int r = 1; r < nRows; ++r) { - if (subMatrix[r].length != nCols) { - throw new DimensionMismatchException(nCols, subMatrix[r].length); - } - } - - MatrixUtils.checkRowIndex(this, row); - MatrixUtils.checkColumnIndex(this, column); - MatrixUtils.checkRowIndex(this, nRows + row - 1); - MatrixUtils.checkColumnIndex(this, nCols + column - 1); - - for (int i = 0; i < nRows; ++i) { - for (int j = 0; j < nCols; ++j) { - setEntry(row + i, column + j, subMatrix[i][j]); - } - } - } - - /** {@inheritDoc} */ - @Override - public RealMatrix getRowMatrix(final int row) throws OutOfRangeException { - MatrixUtils.checkRowIndex(this, row); - final int nCols = getColumnDimension(); - final RealMatrix out = createMatrix(1, nCols); - for (int i = 0; i < nCols; ++i) { - out.setEntry(0, i, getEntry(row, i)); - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public void setRowMatrix(final int row, final RealMatrix matrix) - throws OutOfRangeException, MatrixDimensionMismatchException { - MatrixUtils.checkRowIndex(this, row); - final int nCols = getColumnDimension(); - if ((matrix.getRowDimension() != 1) || - (matrix.getColumnDimension() != nCols)) { - throw new MatrixDimensionMismatchException(matrix.getRowDimension(), - matrix.getColumnDimension(), - 1, nCols); - } - for (int i = 0; i < nCols; ++i) { - setEntry(row, i, matrix.getEntry(0, i)); - } - } - - /** {@inheritDoc} */ - @Override - public RealMatrix getColumnMatrix(final int column) - throws OutOfRangeException { - MatrixUtils.checkColumnIndex(this, column); - final int nRows = getRowDimension(); - final RealMatrix out = createMatrix(nRows, 1); - for (int i = 0; i < nRows; ++i) { - out.setEntry(i, 0, getEntry(i, column)); - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public void setColumnMatrix(final int column, final RealMatrix matrix) - throws OutOfRangeException, MatrixDimensionMismatchException { - MatrixUtils.checkColumnIndex(this, column); - final int nRows = getRowDimension(); - if ((matrix.getRowDimension() != nRows) || - (matrix.getColumnDimension() != 1)) { - throw new MatrixDimensionMismatchException(matrix.getRowDimension(), - matrix.getColumnDimension(), - nRows, 1); - } - for (int i = 0; i < nRows; ++i) { - setEntry(i, column, matrix.getEntry(i, 0)); - } - } - - /** {@inheritDoc} */ - @Override - public RealVector getRowVector(final int row) - throws OutOfRangeException { - return new ArrayRealVector(getRow(row), false); - } - - /** {@inheritDoc} */ - @Override - public void setRowVector(final int row, final RealVector vector) - throws OutOfRangeException, MatrixDimensionMismatchException { - MatrixUtils.checkRowIndex(this, row); - final int nCols = getColumnDimension(); - if (vector.getDimension() != nCols) { - throw new MatrixDimensionMismatchException(1, vector.getDimension(), - 1, nCols); - } - for (int i = 0; i < nCols; ++i) { - setEntry(row, i, vector.getEntry(i)); - } - } - - /** {@inheritDoc} */ - @Override - public RealVector getColumnVector(final int column) - throws OutOfRangeException { - return new ArrayRealVector(getColumn(column), false); - } - - /** {@inheritDoc} */ - @Override - public void setColumnVector(final int column, final RealVector vector) - throws OutOfRangeException, MatrixDimensionMismatchException { - MatrixUtils.checkColumnIndex(this, column); - final int nRows = getRowDimension(); - if (vector.getDimension() != nRows) { - throw new MatrixDimensionMismatchException(vector.getDimension(), 1, - nRows, 1); - } - for (int i = 0; i < nRows; ++i) { - setEntry(i, column, vector.getEntry(i)); - } - } - - /** {@inheritDoc} */ - @Override - public double[] getRow(final int row) throws OutOfRangeException { - MatrixUtils.checkRowIndex(this, row); - final int nCols = getColumnDimension(); - final double[] out = new double[nCols]; - for (int i = 0; i < nCols; ++i) { - out[i] = getEntry(row, i); - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public void setRow(final int row, final double[] array) - throws OutOfRangeException, MatrixDimensionMismatchException { - MatrixUtils.checkRowIndex(this, row); - final int nCols = getColumnDimension(); - if (array.length != nCols) { - throw new MatrixDimensionMismatchException(1, array.length, 1, nCols); - } - for (int i = 0; i < nCols; ++i) { - setEntry(row, i, array[i]); - } - } - - /** {@inheritDoc} */ - @Override - public double[] getColumn(final int column) throws OutOfRangeException { - MatrixUtils.checkColumnIndex(this, column); - final int nRows = getRowDimension(); - final double[] out = new double[nRows]; - for (int i = 0; i < nRows; ++i) { - out[i] = getEntry(i, column); - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public void setColumn(final int column, final double[] array) - throws OutOfRangeException, MatrixDimensionMismatchException { - MatrixUtils.checkColumnIndex(this, column); - final int nRows = getRowDimension(); - if (array.length != nRows) { - throw new MatrixDimensionMismatchException(array.length, 1, nRows, 1); - } - for (int i = 0; i < nRows; ++i) { - setEntry(i, column, array[i]); - } - } - - /** {@inheritDoc} */ - @Override - public void addToEntry(int row, int column, double increment) - throws OutOfRangeException { - MatrixUtils.checkMatrixIndex(this, row, column); - setEntry(row, column, getEntry(row, column) + increment); - } - - /** {@inheritDoc} */ - @Override - public void multiplyEntry(int row, int column, double factor) - throws OutOfRangeException { - MatrixUtils.checkMatrixIndex(this, row, column); - setEntry(row, column, getEntry(row, column) * factor); - } - - /** {@inheritDoc} */ - @Override - public RealMatrix transpose() { - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - final RealMatrix out = createMatrix(nCols, nRows); - walkInOptimizedOrder(new DefaultRealMatrixPreservingVisitor() { - - /** {@inheritDoc} */ - @Override - public void visit(final int row, final int column, final double value) { - out.setEntry(column, row, value); - } - - }); - - return out; - } - - /** {@inheritDoc} */ - @Override - public boolean isSquare() { - return getColumnDimension() == getRowDimension(); - } - - /** - * Returns the number of rows of this matrix. - * - * @return the number of rows. - */ - @Override - public abstract int getRowDimension(); - - /** - * Returns the number of columns of this matrix. - * - * @return the number of columns. - */ - @Override - public abstract int getColumnDimension(); - - /** {@inheritDoc} */ - @Override - public double getTrace() throws NonSquareMatrixException { - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - if (nRows != nCols) { - throw new NonSquareMatrixException(nRows, nCols); - } - double trace = 0; - for (int i = 0; i < nRows; ++i) { - trace += getEntry(i, i); - } - return trace; - } - - /** {@inheritDoc} */ - @Override - public double[] operate(final double[] v) - throws DimensionMismatchException { - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - if (v.length != nCols) { - throw new DimensionMismatchException(v.length, nCols); - } - - final double[] out = new double[nRows]; - for (int row = 0; row < nRows; ++row) { - double sum = 0; - for (int i = 0; i < nCols; ++i) { - sum += getEntry(row, i) * v[i]; - } - out[row] = sum; - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public RealVector operate(final RealVector v) - throws DimensionMismatchException { - try { - return new ArrayRealVector(operate(((ArrayRealVector) v).getDataRef()), false); - } catch (ClassCastException cce) { - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - if (v.getDimension() != nCols) { - throw new DimensionMismatchException(v.getDimension(), nCols); - } - - final double[] out = new double[nRows]; - for (int row = 0; row < nRows; ++row) { - double sum = 0; - for (int i = 0; i < nCols; ++i) { - sum += getEntry(row, i) * v.getEntry(i); - } - out[row] = sum; - } - - return new ArrayRealVector(out, false); - } - } - - /** {@inheritDoc} */ - @Override - public double[] preMultiply(final double[] v) throws DimensionMismatchException { - - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - if (v.length != nRows) { - throw new DimensionMismatchException(v.length, nRows); - } - - final double[] out = new double[nCols]; - for (int col = 0; col < nCols; ++col) { - double sum = 0; - for (int i = 0; i < nRows; ++i) { - sum += getEntry(i, col) * v[i]; - } - out[col] = sum; - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public RealVector preMultiply(final RealVector v) throws DimensionMismatchException { - try { - return new ArrayRealVector(preMultiply(((ArrayRealVector) v).getDataRef()), false); - } catch (ClassCastException cce) { - - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - if (v.getDimension() != nRows) { - throw new DimensionMismatchException(v.getDimension(), nRows); - } - - final double[] out = new double[nCols]; - for (int col = 0; col < nCols; ++col) { - double sum = 0; - for (int i = 0; i < nRows; ++i) { - sum += getEntry(i, col) * v.getEntry(i); - } - out[col] = sum; - } - - return new ArrayRealVector(out, false); - } - } - - /** {@inheritDoc} */ - @Override - public double walkInRowOrder(final RealMatrixChangingVisitor visitor) { - final int rows = getRowDimension(); - final int columns = getColumnDimension(); - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int row = 0; row < rows; ++row) { - for (int column = 0; column < columns; ++column) { - final double oldValue = getEntry(row, column); - final double newValue = visitor.visit(row, column, oldValue); - setEntry(row, column, newValue); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInRowOrder(final RealMatrixPreservingVisitor visitor) { - final int rows = getRowDimension(); - final int columns = getColumnDimension(); - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int row = 0; row < rows; ++row) { - for (int column = 0; column < columns; ++column) { - visitor.visit(row, column, getEntry(row, column)); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInRowOrder(final RealMatrixChangingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); - visitor.start(getRowDimension(), getColumnDimension(), - startRow, endRow, startColumn, endColumn); - for (int row = startRow; row <= endRow; ++row) { - for (int column = startColumn; column <= endColumn; ++column) { - final double oldValue = getEntry(row, column); - final double newValue = visitor.visit(row, column, oldValue); - setEntry(row, column, newValue); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInRowOrder(final RealMatrixPreservingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); - visitor.start(getRowDimension(), getColumnDimension(), - startRow, endRow, startColumn, endColumn); - for (int row = startRow; row <= endRow; ++row) { - for (int column = startColumn; column <= endColumn; ++column) { - visitor.visit(row, column, getEntry(row, column)); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInColumnOrder(final RealMatrixChangingVisitor visitor) { - final int rows = getRowDimension(); - final int columns = getColumnDimension(); - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int column = 0; column < columns; ++column) { - for (int row = 0; row < rows; ++row) { - final double oldValue = getEntry(row, column); - final double newValue = visitor.visit(row, column, oldValue); - setEntry(row, column, newValue); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInColumnOrder(final RealMatrixPreservingVisitor visitor) { - final int rows = getRowDimension(); - final int columns = getColumnDimension(); - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int column = 0; column < columns; ++column) { - for (int row = 0; row < rows; ++row) { - visitor.visit(row, column, getEntry(row, column)); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInColumnOrder(final RealMatrixChangingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); - visitor.start(getRowDimension(), getColumnDimension(), - startRow, endRow, startColumn, endColumn); - for (int column = startColumn; column <= endColumn; ++column) { - for (int row = startRow; row <= endRow; ++row) { - final double oldValue = getEntry(row, column); - final double newValue = visitor.visit(row, column, oldValue); - setEntry(row, column, newValue); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInColumnOrder(final RealMatrixPreservingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); - visitor.start(getRowDimension(), getColumnDimension(), - startRow, endRow, startColumn, endColumn); - for (int column = startColumn; column <= endColumn; ++column) { - for (int row = startRow; row <= endRow; ++row) { - visitor.visit(row, column, getEntry(row, column)); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInOptimizedOrder(final RealMatrixChangingVisitor visitor) { - return walkInRowOrder(visitor); - } - - /** {@inheritDoc} */ - @Override - public double walkInOptimizedOrder(final RealMatrixPreservingVisitor visitor) { - return walkInRowOrder(visitor); - } - - /** {@inheritDoc} */ - @Override - public double walkInOptimizedOrder(final RealMatrixChangingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, - final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - return walkInRowOrder(visitor, startRow, endRow, startColumn, endColumn); - } - - /** {@inheritDoc} */ - @Override - public double walkInOptimizedOrder(final RealMatrixPreservingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, - final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - return walkInRowOrder(visitor, startRow, endRow, startColumn, endColumn); - } - - /** - * Get a string representation for this matrix. - * @return a string representation for this matrix - */ - @Override - public String toString() { - final StringBuilder res = new StringBuilder(); - String fullClassName = getClass().getName(); - String shortClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1); - res.append(shortClassName); - res.append(DEFAULT_FORMAT.format(this)); - return res.toString(); - } - - /** - * Returns true iff object is a - * RealMatrix instance with the same dimensions as this - * and all corresponding matrix entries are equal. - * - * @param object the object to test equality against. - * @return true if object equals this - */ - @Override - public boolean equals(final Object object) { - if (object == this ) { - return true; - } - if (object instanceof RealMatrix == false) { - return false; - } - RealMatrix m = (RealMatrix) object; - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - if (m.getColumnDimension() != nCols || m.getRowDimension() != nRows) { - return false; - } - for (int row = 0; row < nRows; ++row) { - for (int col = 0; col < nCols; ++col) { - if (getEntry(row, col) != m.getEntry(row, col)) { - return false; - } - } - } - return true; - } - - /** - * Computes a hashcode for the matrix. - * - * @return hashcode for matrix - */ - @Override - public int hashCode() { - int ret = 7; - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - ret = ret * 31 + nRows; - ret = ret * 31 + nCols; - for (int row = 0; row < nRows; ++row) { - for (int col = 0; col < nCols; ++col) { - ret = ret * 31 + (11 * (row+1) + 17 * (col+1)) * - MathUtils.hash(getEntry(row, col)); - } - } - return ret; - } - - - /* - * Empty implementations of these methods are provided in order to allow for - * the use of the @Override tag with Java 1.5. - */ - - /** {@inheritDoc} */ - @Override - public abstract RealMatrix createMatrix(int rowDimension, int columnDimension) - throws NotStrictlyPositiveException; - - /** {@inheritDoc} */ - @Override - public abstract RealMatrix copy(); - - /** {@inheritDoc} */ - @Override - public abstract double getEntry(int row, int column) - throws OutOfRangeException; - - /** {@inheritDoc} */ - @Override - public abstract void setEntry(int row, int column, double value) - throws OutOfRangeException; -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/AnyMatrix.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/AnyMatrix.java deleted file mode 100644 index 85a5fe7a5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/AnyMatrix.java +++ /dev/null @@ -1,47 +0,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. - */ - -package org.apache.commons.math4.linear; - - -/** - * Interface defining very basic matrix operations. - * @since 2.0 - */ -public interface AnyMatrix { - - /** - * Is this a square matrix? - * @return true if the matrix is square (rowDimension = columnDimension) - */ - boolean isSquare(); - - /** - * Returns the number of rows in the matrix. - * - * @return rowDimension - */ - int getRowDimension(); - - /** - * Returns the number of columns in the matrix. - * - * @return columnDimension - */ - int getColumnDimension(); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/Array2DRowFieldMatrix.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/Array2DRowFieldMatrix.java deleted file mode 100644 index f49f88860..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/Array2DRowFieldMatrix.java +++ /dev/null @@ -1,612 +0,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. - */ - -package org.apache.commons.math4.linear; - -import java.io.Serializable; - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathIllegalStateException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - -/** - * Implementation of {@code FieldMatrix} using a {@link FieldElement}[][] array to store entries. - *

- * As specified in the {@link FieldMatrix} interface, matrix element indexing - * is 0-based -- e.g., getEntry(0, 0) - * returns the element in the first row, first column of the matrix. - *

- * - * @param the type of the field elements - */ -public class Array2DRowFieldMatrix> - extends AbstractFieldMatrix - implements Serializable { - /** Serializable version identifier */ - private static final long serialVersionUID = 7260756672015356458L; - /** Entries of the matrix */ - private T[][] data; - - /** - * Creates a matrix with no data - * @param field field to which the elements belong - */ - public Array2DRowFieldMatrix(final Field field) { - super(field); - } - - /** - * Create a new {@code FieldMatrix} with the supplied row and column dimensions. - * - * @param field Field to which the elements belong. - * @param rowDimension Number of rows in the new matrix. - * @param columnDimension Number of columns in the new matrix. - * @throws NotStrictlyPositiveException if row or column dimension is not positive. - */ - public Array2DRowFieldMatrix(final Field field, final int rowDimension, - final int columnDimension) - throws NotStrictlyPositiveException { - super(field, rowDimension, columnDimension); - data = MathArrays.buildArray(field, rowDimension, columnDimension); - } - - /** - * Create a new {@code FieldMatrix} using the input array as the underlying - * data array. - *

The input array is copied, not referenced. This constructor has - * the same effect as calling {@link #Array2DRowFieldMatrix(FieldElement[][], boolean)} - * with the second argument set to {@code true}.

- * - * @param d Data for the new matrix. - * @throws DimensionMismatchException if {@code d} is not rectangular. - * @throws NullArgumentException if {@code d} is {@code null}. - * @throws NoDataException if there are not at least one row and one column. - * @see #Array2DRowFieldMatrix(FieldElement[][], boolean) - */ - public Array2DRowFieldMatrix(final T[][] d) - throws DimensionMismatchException, NullArgumentException, - NoDataException { - this(extractField(d), d); - } - - /** - * Create a new {@code FieldMatrix} using the input array as the underlying - * data array. - *

The input array is copied, not referenced. This constructor has - * the same effect as calling {@link #Array2DRowFieldMatrix(FieldElement[][], boolean)} - * with the second argument set to {@code true}.

- * - * @param field Field to which the elements belong. - * @param d Data for the new matrix. - * @throws DimensionMismatchException if {@code d} is not rectangular. - * @throws NullArgumentException if {@code d} is {@code null}. - * @throws NoDataException if there are not at least one row and one column. - * @see #Array2DRowFieldMatrix(FieldElement[][], boolean) - */ - public Array2DRowFieldMatrix(final Field field, final T[][] d) - throws DimensionMismatchException, NullArgumentException, - NoDataException { - super(field); - copyIn(d); - } - - /** - * Create a new {@code FieldMatrix} using the input array as the underlying - * data array. - *

If an array is built specially in order to be embedded in a - * {@code FieldMatrix} and not used directly, the {@code copyArray} may be - * set to {@code false}. This will prevent the copying and improve - * performance as no new array will be built and no data will be copied.

- * - * @param d Data for the new matrix. - * @param copyArray Whether to copy or reference the input array. - * @throws DimensionMismatchException if {@code d} is not rectangular. - * @throws NoDataException if there are not at least one row and one column. - * @throws NullArgumentException if {@code d} is {@code null}. - * @see #Array2DRowFieldMatrix(FieldElement[][]) - */ - public Array2DRowFieldMatrix(final T[][] d, final boolean copyArray) - throws DimensionMismatchException, NoDataException, - NullArgumentException { - this(extractField(d), d, copyArray); - } - - /** - * Create a new {@code FieldMatrix} using the input array as the underlying - * data array. - *

If an array is built specially in order to be embedded in a - * {@code FieldMatrix} and not used directly, the {@code copyArray} may be - * set to {@code false}. This will prevent the copying and improve - * performance as no new array will be built and no data will be copied.

- * - * @param field Field to which the elements belong. - * @param d Data for the new matrix. - * @param copyArray Whether to copy or reference the input array. - * @throws DimensionMismatchException if {@code d} is not rectangular. - * @throws NoDataException if there are not at least one row and one column. - * @throws NullArgumentException if {@code d} is {@code null}. - * @see #Array2DRowFieldMatrix(FieldElement[][]) - */ - public Array2DRowFieldMatrix(final Field field, final T[][] d, final boolean copyArray) - throws DimensionMismatchException, NoDataException, NullArgumentException { - super(field); - if (copyArray) { - copyIn(d); - } else { - MathUtils.checkNotNull(d); - final int nRows = d.length; - if (nRows == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW); - } - final int nCols = d[0].length; - if (nCols == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN); - } - for (int r = 1; r < nRows; r++) { - if (d[r].length != nCols) { - throw new DimensionMismatchException(nCols, d[r].length); - } - } - data = d; - } - } - - /** - * Create a new (column) {@code FieldMatrix} using {@code v} as the - * data for the unique column of the created matrix. - * The input array is copied. - * - * @param v Column vector holding data for new matrix. - * @throws NoDataException if v is empty - */ - public Array2DRowFieldMatrix(final T[] v) throws NoDataException { - this(extractField(v), v); - } - - /** - * Create a new (column) {@code FieldMatrix} using {@code v} as the - * data for the unique column of the created matrix. - * The input array is copied. - * - * @param field Field to which the elements belong. - * @param v Column vector holding data for new matrix. - */ - public Array2DRowFieldMatrix(final Field field, final T[] v) { - super(field); - final int nRows = v.length; - data = MathArrays.buildArray(getField(), nRows, 1); - for (int row = 0; row < nRows; row++) { - data[row][0] = v[row]; - } - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix createMatrix(final int rowDimension, - final int columnDimension) - throws NotStrictlyPositiveException { - return new Array2DRowFieldMatrix<>(getField(), rowDimension, columnDimension); - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix copy() { - return new Array2DRowFieldMatrix<>(getField(), copyOut(), false); - } - - /** - * Add {@code m} to this matrix. - * - * @param m Matrix to be added. - * @return {@code this} + m. - * @throws MatrixDimensionMismatchException if {@code m} is not the same - * size as this matrix. - */ - public Array2DRowFieldMatrix add(final Array2DRowFieldMatrix m) - throws MatrixDimensionMismatchException { - // safety check - checkAdditionCompatible(m); - - final int rowCount = getRowDimension(); - final int columnCount = getColumnDimension(); - final T[][] outData = MathArrays.buildArray(getField(), rowCount, columnCount); - for (int row = 0; row < rowCount; row++) { - final T[] dataRow = data[row]; - final T[] mRow = m.data[row]; - final T[] outDataRow = outData[row]; - for (int col = 0; col < columnCount; col++) { - outDataRow[col] = dataRow[col].add(mRow[col]); - } - } - - return new Array2DRowFieldMatrix<>(getField(), outData, false); - } - - /** - * Subtract {@code m} from this matrix. - * - * @param m Matrix to be subtracted. - * @return {@code this} + m. - * @throws MatrixDimensionMismatchException if {@code m} is not the same - * size as this matrix. - */ - public Array2DRowFieldMatrix subtract(final Array2DRowFieldMatrix m) - throws MatrixDimensionMismatchException { - // safety check - checkSubtractionCompatible(m); - - final int rowCount = getRowDimension(); - final int columnCount = getColumnDimension(); - final T[][] outData = MathArrays.buildArray(getField(), rowCount, columnCount); - for (int row = 0; row < rowCount; row++) { - final T[] dataRow = data[row]; - final T[] mRow = m.data[row]; - final T[] outDataRow = outData[row]; - for (int col = 0; col < columnCount; col++) { - outDataRow[col] = dataRow[col].subtract(mRow[col]); - } - } - - return new Array2DRowFieldMatrix<>(getField(), outData, false); - - } - - /** - * Postmultiplying this matrix by {@code m}. - * - * @param m Matrix to postmultiply by. - * @return {@code this} * m. - * @throws DimensionMismatchException if the number of columns of this - * matrix is not equal to the number of rows of {@code m}. - */ - public Array2DRowFieldMatrix multiply(final Array2DRowFieldMatrix m) - throws DimensionMismatchException { - // safety check - checkMultiplicationCompatible(m); - - final int nRows = this.getRowDimension(); - final int nCols = m.getColumnDimension(); - final int nSum = this.getColumnDimension(); - final T[][] outData = MathArrays.buildArray(getField(), nRows, nCols); - for (int row = 0; row < nRows; row++) { - final T[] dataRow = data[row]; - final T[] outDataRow = outData[row]; - for (int col = 0; col < nCols; col++) { - T sum = getField().getZero(); - for (int i = 0; i < nSum; i++) { - sum = sum.add(dataRow[i].multiply(m.data[i][col])); - } - outDataRow[col] = sum; - } - } - - return new Array2DRowFieldMatrix<>(getField(), outData, false); - - } - - /** {@inheritDoc} */ - @Override - public T[][] getData() { - return copyOut(); - } - - /** - * Get a reference to the underlying data array. - * This methods returns internal data, not fresh copy of it. - * - * @return the 2-dimensional array of entries. - */ - public T[][] getDataRef() { - return data; - } - - /** {@inheritDoc} */ - @Override - public void setSubMatrix(final T[][] subMatrix, final int row, - final int column) - throws OutOfRangeException, NullArgumentException, NoDataException, - DimensionMismatchException { - if (data == null) { - if (row > 0) { - throw new MathIllegalStateException(LocalizedFormats.FIRST_ROWS_NOT_INITIALIZED_YET, row); - } - if (column > 0) { - throw new MathIllegalStateException(LocalizedFormats.FIRST_COLUMNS_NOT_INITIALIZED_YET, column); - } - final int nRows = subMatrix.length; - if (nRows == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW); - } - - final int nCols = subMatrix[0].length; - if (nCols == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN); - } - data = MathArrays.buildArray(getField(), subMatrix.length, nCols); - for (int i = 0; i < data.length; ++i) { - if (subMatrix[i].length != nCols) { - throw new DimensionMismatchException(nCols, subMatrix[i].length); - } - System.arraycopy(subMatrix[i], 0, data[i + row], column, nCols); - } - } else { - super.setSubMatrix(subMatrix, row, column); - } - - } - - /** {@inheritDoc} */ - @Override - public T getEntry(final int row, final int column) - throws OutOfRangeException { - checkRowIndex(row); - checkColumnIndex(column); - - return data[row][column]; - } - - /** {@inheritDoc} */ - @Override - public void setEntry(final int row, final int column, final T value) - throws OutOfRangeException { - checkRowIndex(row); - checkColumnIndex(column); - - data[row][column] = value; - } - - /** {@inheritDoc} */ - @Override - public void addToEntry(final int row, final int column, final T increment) - throws OutOfRangeException { - checkRowIndex(row); - checkColumnIndex(column); - - data[row][column] = data[row][column].add(increment); - } - - /** {@inheritDoc} */ - @Override - public void multiplyEntry(final int row, final int column, final T factor) - throws OutOfRangeException { - checkRowIndex(row); - checkColumnIndex(column); - - data[row][column] = data[row][column].multiply(factor); - } - - /** {@inheritDoc} */ - @Override - public int getRowDimension() { - return (data == null) ? 0 : data.length; - } - - /** {@inheritDoc} */ - @Override - public int getColumnDimension() { - return ((data == null) || (data[0] == null)) ? 0 : data[0].length; - } - - /** {@inheritDoc} */ - @Override - public T[] operate(final T[] v) throws DimensionMismatchException { - final int nRows = this.getRowDimension(); - final int nCols = this.getColumnDimension(); - if (v.length != nCols) { - throw new DimensionMismatchException(v.length, nCols); - } - final T[] out = MathArrays.buildArray(getField(), nRows); - for (int row = 0; row < nRows; row++) { - final T[] dataRow = data[row]; - T sum = getField().getZero(); - for (int i = 0; i < nCols; i++) { - sum = sum.add(dataRow[i].multiply(v[i])); - } - out[row] = sum; - } - return out; - } - - /** {@inheritDoc} */ - @Override - public T[] preMultiply(final T[] v) throws DimensionMismatchException { - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - if (v.length != nRows) { - throw new DimensionMismatchException(v.length, nRows); - } - - final T[] out = MathArrays.buildArray(getField(), nCols); - for (int col = 0; col < nCols; ++col) { - T sum = getField().getZero(); - for (int i = 0; i < nRows; ++i) { - sum = sum.add(data[i][col].multiply(v[i])); - } - out[col] = sum; - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public T walkInRowOrder(final FieldMatrixChangingVisitor visitor) { - final int rows = getRowDimension(); - final int columns = getColumnDimension(); - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int i = 0; i < rows; ++i) { - final T[] rowI = data[i]; - for (int j = 0; j < columns; ++j) { - rowI[j] = visitor.visit(i, j, rowI[j]); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInRowOrder(final FieldMatrixPreservingVisitor visitor) { - final int rows = getRowDimension(); - final int columns = getColumnDimension(); - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int i = 0; i < rows; ++i) { - final T[] rowI = data[i]; - for (int j = 0; j < columns; ++j) { - visitor.visit(i, j, rowI[j]); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInRowOrder(final FieldMatrixChangingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); - visitor.start(getRowDimension(), getColumnDimension(), - startRow, endRow, startColumn, endColumn); - for (int i = startRow; i <= endRow; ++i) { - final T[] rowI = data[i]; - for (int j = startColumn; j <= endColumn; ++j) { - rowI[j] = visitor.visit(i, j, rowI[j]); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInRowOrder(final FieldMatrixPreservingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); - visitor.start(getRowDimension(), getColumnDimension(), - startRow, endRow, startColumn, endColumn); - for (int i = startRow; i <= endRow; ++i) { - final T[] rowI = data[i]; - for (int j = startColumn; j <= endColumn; ++j) { - visitor.visit(i, j, rowI[j]); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInColumnOrder(final FieldMatrixChangingVisitor visitor) { - final int rows = getRowDimension(); - final int columns = getColumnDimension(); - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int j = 0; j < columns; ++j) { - for (int i = 0; i < rows; ++i) { - final T[] rowI = data[i]; - rowI[j] = visitor.visit(i, j, rowI[j]); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInColumnOrder(final FieldMatrixPreservingVisitor visitor) { - final int rows = getRowDimension(); - final int columns = getColumnDimension(); - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int j = 0; j < columns; ++j) { - for (int i = 0; i < rows; ++i) { - visitor.visit(i, j, data[i][j]); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInColumnOrder(final FieldMatrixChangingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); - visitor.start(getRowDimension(), getColumnDimension(), - startRow, endRow, startColumn, endColumn); - for (int j = startColumn; j <= endColumn; ++j) { - for (int i = startRow; i <= endRow; ++i) { - final T[] rowI = data[i]; - rowI[j] = visitor.visit(i, j, rowI[j]); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInColumnOrder(final FieldMatrixPreservingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); - visitor.start(getRowDimension(), getColumnDimension(), - startRow, endRow, startColumn, endColumn); - for (int j = startColumn; j <= endColumn; ++j) { - for (int i = startRow; i <= endRow; ++i) { - visitor.visit(i, j, data[i][j]); - } - } - return visitor.end(); - } - - /** - * Get a fresh copy of the underlying data array. - * - * @return a copy of the underlying data array. - */ - private T[][] copyOut() { - final int nRows = this.getRowDimension(); - final T[][] out = MathArrays.buildArray(getField(), nRows, getColumnDimension()); - // can't copy 2-d array in one shot, otherwise get row references - for (int i = 0; i < nRows; i++) { - System.arraycopy(data[i], 0, out[i], 0, data[i].length); - } - return out; - } - - /** - * Replace data with a fresh copy of the input array. - * - * @param in Data to copy. - * @throws NoDataException if the input array is empty. - * @throws DimensionMismatchException if the input array is not rectangular. - * @throws NullArgumentException if the input array is {@code null}. - */ - private void copyIn(final T[][] in) - throws NullArgumentException, NoDataException, - DimensionMismatchException { - setSubMatrix(in, 0, 0); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/Array2DRowRealMatrix.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/Array2DRowRealMatrix.java deleted file mode 100644 index b9b41e02d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/Array2DRowRealMatrix.java +++ /dev/null @@ -1,589 +0,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. - */ - -package org.apache.commons.math4.linear; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathIllegalStateException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.MathUtils; - -/** - * Implementation of {@link RealMatrix} using a {@code double[][]} array to - * store entries. - */ -public class Array2DRowRealMatrix extends AbstractRealMatrix implements Serializable { - /** Serializable version identifier. */ - private static final long serialVersionUID = -1067294169172445528L; - - /** Entries of the matrix. */ - private double data[][]; - - /** - * Creates a matrix with no data - */ - public Array2DRowRealMatrix() {} - - /** - * Create a new RealMatrix with the supplied row and column dimensions. - * - * @param rowDimension Number of rows in the new matrix. - * @param columnDimension Number of columns in the new matrix. - * @throws NotStrictlyPositiveException if the row or column dimension is - * not positive. - */ - public Array2DRowRealMatrix(final int rowDimension, - final int columnDimension) - throws NotStrictlyPositiveException { - super(rowDimension, columnDimension); - data = new double[rowDimension][columnDimension]; - } - - /** - * Create a new {@code RealMatrix} using the input array as the underlying - * data array. - *

The input array is copied, not referenced. This constructor has - * the same effect as calling {@link #Array2DRowRealMatrix(double[][], boolean)} - * with the second argument set to {@code true}.

- * - * @param d Data for the new matrix. - * @throws DimensionMismatchException if {@code d} is not rectangular. - * @throws NoDataException if {@code d} row or column dimension is zero. - * @throws NullArgumentException if {@code d} is {@code null}. - * @see #Array2DRowRealMatrix(double[][], boolean) - */ - public Array2DRowRealMatrix(final double[][] d) - throws DimensionMismatchException, NoDataException, NullArgumentException { - copyIn(d); - } - - /** - * Create a new RealMatrix using the input array as the underlying - * data array. - * If an array is built specially in order to be embedded in a - * RealMatrix and not used directly, the {@code copyArray} may be - * set to {@code false}. This will prevent the copying and improve - * performance as no new array will be built and no data will be copied. - * - * @param d Data for new matrix. - * @param copyArray if {@code true}, the input array will be copied, - * otherwise it will be referenced. - * @throws DimensionMismatchException if {@code d} is not rectangular. - * @throws NoDataException if {@code d} row or column dimension is zero. - * @throws NullArgumentException if {@code d} is {@code null}. - * @see #Array2DRowRealMatrix(double[][]) - */ - public Array2DRowRealMatrix(final double[][] d, final boolean copyArray) - throws DimensionMismatchException, NoDataException, - NullArgumentException { - if (copyArray) { - copyIn(d); - } else { - if (d == null) { - throw new NullArgumentException(); - } - final int nRows = d.length; - if (nRows == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW); - } - final int nCols = d[0].length; - if (nCols == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN); - } - for (int r = 1; r < nRows; r++) { - if (d[r].length != nCols) { - throw new DimensionMismatchException(d[r].length, nCols); - } - } - data = d; - } - } - - /** - * Create a new (column) RealMatrix using {@code v} as the - * data for the unique column of the created matrix. - * The input array is copied. - * - * @param v Column vector holding data for new matrix. - */ - public Array2DRowRealMatrix(final double[] v) { - final int nRows = v.length; - data = new double[nRows][1]; - for (int row = 0; row < nRows; row++) { - data[row][0] = v[row]; - } - } - - /** {@inheritDoc} */ - @Override - public RealMatrix createMatrix(final int rowDimension, - final int columnDimension) - throws NotStrictlyPositiveException { - return new Array2DRowRealMatrix(rowDimension, columnDimension); - } - - /** {@inheritDoc} */ - @Override - public RealMatrix copy() { - return new Array2DRowRealMatrix(copyOut(), false); - } - - /** - * Compute the sum of {@code this} and {@code m}. - * - * @param m Matrix to be added. - * @return {@code this + m}. - * @throws MatrixDimensionMismatchException if {@code m} is not the same - * size as {@code this}. - */ - public Array2DRowRealMatrix add(final Array2DRowRealMatrix m) - throws MatrixDimensionMismatchException { - // Safety check. - MatrixUtils.checkAdditionCompatible(this, m); - - final int rowCount = getRowDimension(); - final int columnCount = getColumnDimension(); - final double[][] outData = new double[rowCount][columnCount]; - for (int row = 0; row < rowCount; row++) { - final double[] dataRow = data[row]; - final double[] mRow = m.data[row]; - final double[] outDataRow = outData[row]; - for (int col = 0; col < columnCount; col++) { - outDataRow[col] = dataRow[col] + mRow[col]; - } - } - - return new Array2DRowRealMatrix(outData, false); - } - - /** - * Returns {@code this} minus {@code m}. - * - * @param m Matrix to be subtracted. - * @return {@code this - m} - * @throws MatrixDimensionMismatchException if {@code m} is not the same - * size as {@code this}. - */ - public Array2DRowRealMatrix subtract(final Array2DRowRealMatrix m) - throws MatrixDimensionMismatchException { - MatrixUtils.checkSubtractionCompatible(this, m); - - final int rowCount = getRowDimension(); - final int columnCount = getColumnDimension(); - final double[][] outData = new double[rowCount][columnCount]; - for (int row = 0; row < rowCount; row++) { - final double[] dataRow = data[row]; - final double[] mRow = m.data[row]; - final double[] outDataRow = outData[row]; - for (int col = 0; col < columnCount; col++) { - outDataRow[col] = dataRow[col] - mRow[col]; - } - } - - return new Array2DRowRealMatrix(outData, false); - } - - /** - * Returns the result of postmultiplying {@code this} by {@code m}. - * - * @param m matrix to postmultiply by - * @return {@code this * m} - * @throws DimensionMismatchException if - * {@code columnDimension(this) != rowDimension(m)} - */ - public Array2DRowRealMatrix multiply(final Array2DRowRealMatrix m) - throws DimensionMismatchException { - MatrixUtils.checkMultiplicationCompatible(this, m); - - final int nRows = this.getRowDimension(); - final int nCols = m.getColumnDimension(); - final int nSum = this.getColumnDimension(); - - final double[][] outData = new double[nRows][nCols]; - // Will hold a column of "m". - final double[] mCol = new double[nSum]; - final double[][] mData = m.data; - - // Multiply. - for (int col = 0; col < nCols; col++) { - // Copy all elements of column "col" of "m" so that - // will be in contiguous memory. - for (int mRow = 0; mRow < nSum; mRow++) { - mCol[mRow] = mData[mRow][col]; - } - - for (int row = 0; row < nRows; row++) { - final double[] dataRow = data[row]; - double sum = 0; - for (int i = 0; i < nSum; i++) { - sum += dataRow[i] * mCol[i]; - } - outData[row][col] = sum; - } - } - - return new Array2DRowRealMatrix(outData, false); - } - - /** {@inheritDoc} */ - @Override - public double[][] getData() { - return copyOut(); - } - - /** - * Get a reference to the underlying data array. - * - * @return 2-dimensional array of entries. - */ - public double[][] getDataRef() { - return data; - } - - /** {@inheritDoc} */ - @Override - public void setSubMatrix(final double[][] subMatrix, final int row, - final int column) - throws NoDataException, OutOfRangeException, - DimensionMismatchException, NullArgumentException { - if (data == null) { - if (row > 0) { - throw new MathIllegalStateException(LocalizedFormats.FIRST_ROWS_NOT_INITIALIZED_YET, row); - } - if (column > 0) { - throw new MathIllegalStateException(LocalizedFormats.FIRST_COLUMNS_NOT_INITIALIZED_YET, column); - } - MathUtils.checkNotNull(subMatrix); - final int nRows = subMatrix.length; - if (nRows == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW); - } - - final int nCols = subMatrix[0].length; - if (nCols == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN); - } - data = new double[subMatrix.length][nCols]; - for (int i = 0; i < data.length; ++i) { - if (subMatrix[i].length != nCols) { - throw new DimensionMismatchException(subMatrix[i].length, nCols); - } - System.arraycopy(subMatrix[i], 0, data[i + row], column, nCols); - } - } else { - super.setSubMatrix(subMatrix, row, column); - } - - } - - /** {@inheritDoc} */ - @Override - public double getEntry(final int row, final int column) - throws OutOfRangeException { - MatrixUtils.checkMatrixIndex(this, row, column); - return data[row][column]; - } - - /** {@inheritDoc} */ - @Override - public void setEntry(final int row, final int column, final double value) - throws OutOfRangeException { - MatrixUtils.checkMatrixIndex(this, row, column); - data[row][column] = value; - } - - /** {@inheritDoc} */ - @Override - public void addToEntry(final int row, final int column, - final double increment) - throws OutOfRangeException { - MatrixUtils.checkMatrixIndex(this, row, column); - data[row][column] += increment; - } - - /** {@inheritDoc} */ - @Override - public void multiplyEntry(final int row, final int column, - final double factor) - throws OutOfRangeException { - MatrixUtils.checkMatrixIndex(this, row, column); - data[row][column] *= factor; - } - - /** {@inheritDoc} */ - @Override - public int getRowDimension() { - return (data == null) ? 0 : data.length; - } - - /** {@inheritDoc} */ - @Override - public int getColumnDimension() { - return ((data == null) || (data[0] == null)) ? 0 : data[0].length; - } - - /** {@inheritDoc} */ - @Override - public double[] operate(final double[] v) - throws DimensionMismatchException { - final int nRows = this.getRowDimension(); - final int nCols = this.getColumnDimension(); - if (v.length != nCols) { - throw new DimensionMismatchException(v.length, nCols); - } - final double[] out = new double[nRows]; - for (int row = 0; row < nRows; row++) { - final double[] dataRow = data[row]; - double sum = 0; - for (int i = 0; i < nCols; i++) { - sum += dataRow[i] * v[i]; - } - out[row] = sum; - } - return out; - } - - /** {@inheritDoc} */ - @Override - public double[] preMultiply(final double[] v) - throws DimensionMismatchException { - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - if (v.length != nRows) { - throw new DimensionMismatchException(v.length, nRows); - } - - final double[] out = new double[nCols]; - for (int col = 0; col < nCols; ++col) { - double sum = 0; - for (int i = 0; i < nRows; ++i) { - sum += data[i][col] * v[i]; - } - out[col] = sum; - } - - return out; - - } - - /** {@inheritDoc} */ - @Override - public RealMatrix getSubMatrix(final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); - final int rowCount = endRow - startRow + 1; - final int columnCount = endColumn - startColumn + 1; - final double[][] outData = new double[rowCount][columnCount]; - for (int i = 0; i < rowCount; ++i) { - System.arraycopy(data[startRow + i], startColumn, outData[i], 0, columnCount); - } - - Array2DRowRealMatrix subMatrix = new Array2DRowRealMatrix(); - subMatrix.data = outData; - return subMatrix; - } - - /** {@inheritDoc} */ - @Override - public double walkInRowOrder(final RealMatrixChangingVisitor visitor) { - final int rows = getRowDimension(); - final int columns = getColumnDimension(); - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int i = 0; i < rows; ++i) { - final double[] rowI = data[i]; - for (int j = 0; j < columns; ++j) { - rowI[j] = visitor.visit(i, j, rowI[j]); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInRowOrder(final RealMatrixPreservingVisitor visitor) { - final int rows = getRowDimension(); - final int columns = getColumnDimension(); - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int i = 0; i < rows; ++i) { - final double[] rowI = data[i]; - for (int j = 0; j < columns; ++j) { - visitor.visit(i, j, rowI[j]); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInRowOrder(final RealMatrixChangingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); - visitor.start(getRowDimension(), getColumnDimension(), - startRow, endRow, startColumn, endColumn); - for (int i = startRow; i <= endRow; ++i) { - final double[] rowI = data[i]; - for (int j = startColumn; j <= endColumn; ++j) { - rowI[j] = visitor.visit(i, j, rowI[j]); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInRowOrder(final RealMatrixPreservingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); - visitor.start(getRowDimension(), getColumnDimension(), - startRow, endRow, startColumn, endColumn); - for (int i = startRow; i <= endRow; ++i) { - final double[] rowI = data[i]; - for (int j = startColumn; j <= endColumn; ++j) { - visitor.visit(i, j, rowI[j]); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInColumnOrder(final RealMatrixChangingVisitor visitor) { - final int rows = getRowDimension(); - final int columns = getColumnDimension(); - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int j = 0; j < columns; ++j) { - for (int i = 0; i < rows; ++i) { - final double[] rowI = data[i]; - rowI[j] = visitor.visit(i, j, rowI[j]); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInColumnOrder(final RealMatrixPreservingVisitor visitor) { - final int rows = getRowDimension(); - final int columns = getColumnDimension(); - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int j = 0; j < columns; ++j) { - for (int i = 0; i < rows; ++i) { - visitor.visit(i, j, data[i][j]); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInColumnOrder(final RealMatrixChangingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); - visitor.start(getRowDimension(), getColumnDimension(), - startRow, endRow, startColumn, endColumn); - for (int j = startColumn; j <= endColumn; ++j) { - for (int i = startRow; i <= endRow; ++i) { - final double[] rowI = data[i]; - rowI[j] = visitor.visit(i, j, rowI[j]); - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInColumnOrder(final RealMatrixPreservingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); - visitor.start(getRowDimension(), getColumnDimension(), - startRow, endRow, startColumn, endColumn); - for (int j = startColumn; j <= endColumn; ++j) { - for (int i = startRow; i <= endRow; ++i) { - visitor.visit(i, j, data[i][j]); - } - } - return visitor.end(); - } - - /** - * Get a fresh copy of the underlying data array. - * - * @return a copy of the underlying data array. - */ - private double[][] copyOut() { - final int nRows = this.getRowDimension(); - final double[][] out = new double[nRows][this.getColumnDimension()]; - // can't copy 2-d array in one shot, otherwise get row references - for (int i = 0; i < nRows; i++) { - System.arraycopy(data[i], 0, out[i], 0, data[i].length); - } - return out; - } - - /** - * Replace data with a fresh copy of the input array. - * - * @param in Data to copy. - * @throws NoDataException if the input array is empty. - * @throws DimensionMismatchException if the input array is not rectangular. - * @throws NullArgumentException if the input array is {@code null}. - */ - private void copyIn(final double[][] in) - throws DimensionMismatchException, NoDataException, NullArgumentException { - setSubMatrix(in, 0, 0); - } - - /** {@inheritDoc} */ - @Override - public double[] getRow(final int row) - throws OutOfRangeException { - MatrixUtils.checkRowIndex(this, row); - final int nCols = getColumnDimension(); - final double[] out = new double[nCols]; - System.arraycopy(data[row], 0, out, 0, nCols); - return out; - } - - /** {@inheritDoc} */ - @Override - public void setRow(final int row, - final double[] array) - throws OutOfRangeException, MatrixDimensionMismatchException { - MatrixUtils.checkRowIndex(this, row); - final int nCols = getColumnDimension(); - if (array.length != nCols) { - throw new MatrixDimensionMismatchException(1, array.length, 1, nCols); - } - System.arraycopy(array, 0, data[row], 0, nCols); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/ArrayFieldVector.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/ArrayFieldVector.java deleted file mode 100644 index b468bb7d1..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/ArrayFieldVector.java +++ /dev/null @@ -1,1125 +0,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. - */ -package org.apache.commons.math4.linear; - -import java.io.Serializable; -import java.util.Arrays; - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.ZeroException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - -/** - * This class implements the {@link FieldVector} interface with a {@link FieldElement} array. - * @param the type of the field elements - * @since 2.0 - */ -public class ArrayFieldVector> implements FieldVector, Serializable { - /** Serializable version identifier. */ - private static final long serialVersionUID = 7648186910365927050L; - - /** Entries of the vector. */ - private T[] data; - - /** Field to which the elements belong. */ - private final Field field; - - /** - * Build a 0-length vector. - * Zero-length vectors may be used to initialize construction of vectors - * by data gathering. We start with zero-length and use either the {@link - * #ArrayFieldVector(FieldVector, FieldVector)} constructor - * or one of the {@code append} methods ({@link #add(FieldVector)} or - * {@link #append(ArrayFieldVector)}) to gather data into this vector. - * - * @param field field to which the elements belong - */ - public ArrayFieldVector(final Field field) { - this(field, 0); - } - - /** - * Construct a vector of zeroes. - * - * @param field Field to which the elements belong. - * @param size Size of the vector. - */ - public ArrayFieldVector(Field field, int size) { - this.field = field; - this.data = MathArrays.buildArray(field, size); - } - - /** - * Construct a vector with preset values. - * - * @param size Size of the vector. - * @param preset All entries will be set with this value. - */ - public ArrayFieldVector(int size, T preset) { - this(preset.getField(), size); - Arrays.fill(data, preset); - } - - /** - * Construct a vector from an array, copying the input array. - * This constructor needs a non-empty {@code d} array to retrieve - * the field from its first element. This implies it cannot build - * 0 length vectors. To build vectors from any size, one should - * use the {@link #ArrayFieldVector(Field, FieldElement[])} constructor. - * - * @param d Array. - * @throws NullArgumentException if {@code d} is {@code null}. - * @throws ZeroException if {@code d} is empty. - * @see #ArrayFieldVector(Field, FieldElement[]) - */ - public ArrayFieldVector(T[] d) - throws NullArgumentException, ZeroException { - MathUtils.checkNotNull(d); - try { - field = d[0].getField(); - data = d.clone(); - } catch (ArrayIndexOutOfBoundsException e) { - throw new ZeroException(LocalizedFormats.VECTOR_MUST_HAVE_AT_LEAST_ONE_ELEMENT); - } - } - - /** - * Construct a vector from an array, copying the input array. - * - * @param field Field to which the elements belong. - * @param d Array. - * @throws NullArgumentException if {@code d} is {@code null}. - * @see #ArrayFieldVector(FieldElement[]) - */ - public ArrayFieldVector(Field field, T[] d) - throws NullArgumentException { - MathUtils.checkNotNull(d); - this.field = field; - data = d.clone(); - } - - /** - * Create a new ArrayFieldVector using the input array as the underlying - * data array. - * If an array is built specially in order to be embedded in a - * ArrayFieldVector and not used directly, the {@code copyArray} may be - * set to {@code false}. This will prevent the copying and improve - * performance as no new array will be built and no data will be copied. - * This constructor needs a non-empty {@code d} array to retrieve - * the field from its first element. This implies it cannot build - * 0 length vectors. To build vectors from any size, one should - * use the {@link #ArrayFieldVector(Field, FieldElement[], boolean)} - * constructor. - * - * @param d Data for the new vector. - * @param copyArray If {@code true}, the input array will be copied, - * otherwise it will be referenced. - * @throws NullArgumentException if {@code d} is {@code null}. - * @throws ZeroException if {@code d} is empty. - * @see #ArrayFieldVector(FieldElement[]) - * @see #ArrayFieldVector(Field, FieldElement[], boolean) - */ - public ArrayFieldVector(T[] d, boolean copyArray) - throws NullArgumentException, ZeroException { - MathUtils.checkNotNull(d); - if (d.length == 0) { - throw new ZeroException(LocalizedFormats.VECTOR_MUST_HAVE_AT_LEAST_ONE_ELEMENT); - } - field = d[0].getField(); - data = copyArray ? d.clone() : d; - } - - /** - * Create a new ArrayFieldVector using the input array as the underlying - * data array. - * If an array is built specially in order to be embedded in a - * ArrayFieldVector and not used directly, the {@code copyArray} may be - * set to {@code false}. This will prevent the copying and improve - * performance as no new array will be built and no data will be copied. - * - * @param field Field to which the elements belong. - * @param d Data for the new vector. - * @param copyArray If {@code true}, the input array will be copied, - * otherwise it will be referenced. - * @throws NullArgumentException if {@code d} is {@code null}. - * @see #ArrayFieldVector(FieldElement[], boolean) - */ - public ArrayFieldVector(Field field, T[] d, boolean copyArray) - throws NullArgumentException { - MathUtils.checkNotNull(d); - this.field = field; - data = copyArray ? d.clone() : d; - } - - /** - * Construct a vector from part of a array. - * - * @param d Array. - * @param pos Position of the first entry. - * @param size Number of entries to copy. - * @throws NullArgumentException if {@code d} is {@code null}. - * @throws NumberIsTooLargeException if the size of {@code d} is less - * than {@code pos + size}. - */ - public ArrayFieldVector(T[] d, int pos, int size) - throws NullArgumentException, NumberIsTooLargeException { - MathUtils.checkNotNull(d); - if (d.length < pos + size) { - throw new NumberIsTooLargeException(pos + size, d.length, true); - } - field = d[0].getField(); - data = MathArrays.buildArray(field, size); - System.arraycopy(d, pos, data, 0, size); - } - - /** - * Construct a vector from part of a array. - * - * @param field Field to which the elements belong. - * @param d Array. - * @param pos Position of the first entry. - * @param size Number of entries to copy. - * @throws NullArgumentException if {@code d} is {@code null}. - * @throws NumberIsTooLargeException if the size of {@code d} is less - * than {@code pos + size}. - */ - public ArrayFieldVector(Field field, T[] d, int pos, int size) - throws NullArgumentException, NumberIsTooLargeException { - MathUtils.checkNotNull(d); - if (d.length < pos + size) { - throw new NumberIsTooLargeException(pos + size, d.length, true); - } - this.field = field; - data = MathArrays.buildArray(field, size); - System.arraycopy(d, pos, data, 0, size); - } - - /** - * Construct a vector from another vector, using a deep copy. - * - * @param v Vector to copy. - * @throws NullArgumentException if {@code v} is {@code null}. - */ - public ArrayFieldVector(FieldVector v) - throws NullArgumentException { - MathUtils.checkNotNull(v); - field = v.getField(); - data = MathArrays.buildArray(field, v.getDimension()); - for (int i = 0; i < data.length; ++i) { - data[i] = v.getEntry(i); - } - } - - /** - * Construct a vector from another vector, using a deep copy. - * - * @param v Vector to copy. - * @throws NullArgumentException if {@code v} is {@code null}. - */ - public ArrayFieldVector(ArrayFieldVector v) - throws NullArgumentException { - MathUtils.checkNotNull(v); - field = v.getField(); - data = v.data.clone(); - } - - /** - * Construct a vector from another vector. - * - * @param v Vector to copy. - * @param deep If {@code true} perform a deep copy, otherwise perform - * a shallow copy - * @throws NullArgumentException if {@code v} is {@code null}. - */ - public ArrayFieldVector(ArrayFieldVector v, boolean deep) - throws NullArgumentException { - MathUtils.checkNotNull(v); - field = v.getField(); - data = deep ? v.data.clone() : v.data; - } - - /** - * Construct a vector by appending one vector to another vector. - * - * @param v1 First vector (will be put in front of the new vector). - * @param v2 Second vector (will be put at back of the new vector). - * @throws NullArgumentException if {@code v1} or {@code v2} is - * {@code null}. - * @since 3.2 - */ - public ArrayFieldVector(FieldVector v1, FieldVector v2) - throws NullArgumentException { - MathUtils.checkNotNull(v1); - MathUtils.checkNotNull(v2); - field = v1.getField(); - final T[] v1Data = - (v1 instanceof ArrayFieldVector) ? ((ArrayFieldVector) v1).data : v1.toArray(); - final T[] v2Data = - (v2 instanceof ArrayFieldVector) ? ((ArrayFieldVector) v2).data : v2.toArray(); - data = MathArrays.buildArray(field, v1Data.length + v2Data.length); - System.arraycopy(v1Data, 0, data, 0, v1Data.length); - System.arraycopy(v2Data, 0, data, v1Data.length, v2Data.length); - } - - /** - * Construct a vector by appending one vector to another vector. - * - * @param v1 First vector (will be put in front of the new vector). - * @param v2 Second vector (will be put at back of the new vector). - * @throws NullArgumentException if {@code v1} or {@code v2} is - * {@code null}. - * @since 3.2 - */ - public ArrayFieldVector(FieldVector v1, T[] v2) - throws NullArgumentException { - MathUtils.checkNotNull(v1); - MathUtils.checkNotNull(v2); - field = v1.getField(); - final T[] v1Data = - (v1 instanceof ArrayFieldVector) ? ((ArrayFieldVector) v1).data : v1.toArray(); - data = MathArrays.buildArray(field, v1Data.length + v2.length); - System.arraycopy(v1Data, 0, data, 0, v1Data.length); - System.arraycopy(v2, 0, data, v1Data.length, v2.length); - } - - /** - * Construct a vector by appending one vector to another vector. - * - * @param v1 First vector (will be put in front of the new vector). - * @param v2 Second vector (will be put at back of the new vector). - * @throws NullArgumentException if {@code v1} or {@code v2} is - * {@code null}. - * @since 3.2 - */ - public ArrayFieldVector(T[] v1, FieldVector v2) - throws NullArgumentException { - MathUtils.checkNotNull(v1); - MathUtils.checkNotNull(v2); - field = v2.getField(); - final T[] v2Data = - (v2 instanceof ArrayFieldVector) ? ((ArrayFieldVector) v2).data : v2.toArray(); - data = MathArrays.buildArray(field, v1.length + v2Data.length); - System.arraycopy(v1, 0, data, 0, v1.length); - System.arraycopy(v2Data, 0, data, v1.length, v2Data.length); - } - - /** - * Construct a vector by appending one vector to another vector. - * This constructor needs at least one non-empty array to retrieve - * the field from its first element. This implies it cannot build - * 0 length vectors. To build vectors from any size, one should - * use the {@link #ArrayFieldVector(Field, FieldElement[], FieldElement[])} - * constructor. - * - * @param v1 First vector (will be put in front of the new vector). - * @param v2 Second vector (will be put at back of the new vector). - * @throws NullArgumentException if {@code v1} or {@code v2} is - * {@code null}. - * @throws ZeroException if both arrays are empty. - * @see #ArrayFieldVector(Field, FieldElement[], FieldElement[]) - */ - public ArrayFieldVector(T[] v1, T[] v2) - throws NullArgumentException, ZeroException { - MathUtils.checkNotNull(v1); - MathUtils.checkNotNull(v2); - if (v1.length + v2.length == 0) { - throw new ZeroException(LocalizedFormats.VECTOR_MUST_HAVE_AT_LEAST_ONE_ELEMENT); - } - data = MathArrays.buildArray(v1[0].getField(), v1.length + v2.length); - System.arraycopy(v1, 0, data, 0, v1.length); - System.arraycopy(v2, 0, data, v1.length, v2.length); - field = data[0].getField(); - } - - /** - * Construct a vector by appending one vector to another vector. - * - * @param field Field to which the elements belong. - * @param v1 First vector (will be put in front of the new vector). - * @param v2 Second vector (will be put at back of the new vector). - * @throws NullArgumentException if {@code v1} or {@code v2} is - * {@code null}. - * @throws ZeroException if both arrays are empty. - * @see #ArrayFieldVector(FieldElement[], FieldElement[]) - */ - public ArrayFieldVector(Field field, T[] v1, T[] v2) - throws NullArgumentException, ZeroException { - MathUtils.checkNotNull(v1); - MathUtils.checkNotNull(v2); - if (v1.length + v2.length == 0) { - throw new ZeroException(LocalizedFormats.VECTOR_MUST_HAVE_AT_LEAST_ONE_ELEMENT); - } - data = MathArrays.buildArray(field, v1.length + v2.length); - System.arraycopy(v1, 0, data, 0, v1.length); - System.arraycopy(v2, 0, data, v1.length, v2.length); - this.field = field; - } - - /** {@inheritDoc} */ - @Override - public Field getField() { - return field; - } - - /** {@inheritDoc} */ - @Override - public FieldVector copy() { - return new ArrayFieldVector<>(this, true); - } - - /** {@inheritDoc} */ - @Override - public FieldVector add(FieldVector v) - throws DimensionMismatchException { - try { - return add((ArrayFieldVector) v); - } catch (ClassCastException cce) { - checkVectorDimensions(v); - T[] out = MathArrays.buildArray(field, data.length); - for (int i = 0; i < data.length; i++) { - out[i] = data[i].add(v.getEntry(i)); - } - return new ArrayFieldVector<>(field, out, false); - } - } - - /** - * Compute the sum of {@code this} and {@code v}. - * @param v vector to be added - * @return {@code this + v} - * @throws DimensionMismatchException if {@code v} is not the same size as - * {@code this} - */ - public ArrayFieldVector add(ArrayFieldVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.data.length); - T[] out = MathArrays.buildArray(field, data.length); - for (int i = 0; i < data.length; i++) { - out[i] = data[i].add(v.data[i]); - } - return new ArrayFieldVector<>(field, out, false); - } - - /** {@inheritDoc} */ - @Override - public FieldVector subtract(FieldVector v) - throws DimensionMismatchException { - try { - return subtract((ArrayFieldVector) v); - } catch (ClassCastException cce) { - checkVectorDimensions(v); - T[] out = MathArrays.buildArray(field, data.length); - for (int i = 0; i < data.length; i++) { - out[i] = data[i].subtract(v.getEntry(i)); - } - return new ArrayFieldVector<>(field, out, false); - } - } - - /** - * Compute {@code this} minus {@code v}. - * @param v vector to be subtracted - * @return {@code this - v} - * @throws DimensionMismatchException if {@code v} is not the same size as - * {@code this} - */ - public ArrayFieldVector subtract(ArrayFieldVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.data.length); - T[] out = MathArrays.buildArray(field, data.length); - for (int i = 0; i < data.length; i++) { - out[i] = data[i].subtract(v.data[i]); - } - return new ArrayFieldVector<>(field, out, false); - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapAdd(T d) throws NullArgumentException { - T[] out = MathArrays.buildArray(field, data.length); - for (int i = 0; i < data.length; i++) { - out[i] = data[i].add(d); - } - return new ArrayFieldVector<>(field, out, false); - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapAddToSelf(T d) throws NullArgumentException { - for (int i = 0; i < data.length; i++) { - data[i] = data[i].add(d); - } - return this; - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapSubtract(T d) throws NullArgumentException { - T[] out = MathArrays.buildArray(field, data.length); - for (int i = 0; i < data.length; i++) { - out[i] = data[i].subtract(d); - } - return new ArrayFieldVector<>(field, out, false); - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapSubtractToSelf(T d) throws NullArgumentException { - for (int i = 0; i < data.length; i++) { - data[i] = data[i].subtract(d); - } - return this; - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapMultiply(T d) throws NullArgumentException { - T[] out = MathArrays.buildArray(field, data.length); - for (int i = 0; i < data.length; i++) { - out[i] = data[i].multiply(d); - } - return new ArrayFieldVector<>(field, out, false); - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapMultiplyToSelf(T d) throws NullArgumentException { - for (int i = 0; i < data.length; i++) { - data[i] = data[i].multiply(d); - } - return this; - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapDivide(T d) - throws NullArgumentException, MathArithmeticException { - MathUtils.checkNotNull(d); - T[] out = MathArrays.buildArray(field, data.length); - for (int i = 0; i < data.length; i++) { - out[i] = data[i].divide(d); - } - return new ArrayFieldVector<>(field, out, false); - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapDivideToSelf(T d) - throws NullArgumentException, MathArithmeticException { - MathUtils.checkNotNull(d); - for (int i = 0; i < data.length; i++) { - data[i] = data[i].divide(d); - } - return this; - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapInv() throws MathArithmeticException { - T[] out = MathArrays.buildArray(field, data.length); - final T one = field.getOne(); - for (int i = 0; i < data.length; i++) { - try { - out[i] = one.divide(data[i]); - } catch (final MathArithmeticException e) { - throw new MathArithmeticException(LocalizedFormats.INDEX, i); - } - } - return new ArrayFieldVector<>(field, out, false); - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapInvToSelf() throws MathArithmeticException { - final T one = field.getOne(); - for (int i = 0; i < data.length; i++) { - try { - data[i] = one.divide(data[i]); - } catch (final MathArithmeticException e) { - throw new MathArithmeticException(LocalizedFormats.INDEX, i); - } - } - return this; - } - - /** {@inheritDoc} */ - @Override - public FieldVector ebeMultiply(FieldVector v) - throws DimensionMismatchException { - try { - return ebeMultiply((ArrayFieldVector) v); - } catch (ClassCastException cce) { - checkVectorDimensions(v); - T[] out = MathArrays.buildArray(field, data.length); - for (int i = 0; i < data.length; i++) { - out[i] = data[i].multiply(v.getEntry(i)); - } - return new ArrayFieldVector<>(field, out, false); - } - } - - /** - * Element-by-element multiplication. - * @param v vector by which instance elements must be multiplied - * @return a vector containing {@code this[i] * v[i]} for all {@code i} - * @throws DimensionMismatchException if {@code v} is not the same size as - * {@code this} - */ - public ArrayFieldVector ebeMultiply(ArrayFieldVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.data.length); - T[] out = MathArrays.buildArray(field, data.length); - for (int i = 0; i < data.length; i++) { - out[i] = data[i].multiply(v.data[i]); - } - return new ArrayFieldVector<>(field, out, false); - } - - /** {@inheritDoc} */ - @Override - public FieldVector ebeDivide(FieldVector v) - throws DimensionMismatchException, MathArithmeticException { - try { - return ebeDivide((ArrayFieldVector) v); - } catch (ClassCastException cce) { - checkVectorDimensions(v); - T[] out = MathArrays.buildArray(field, data.length); - for (int i = 0; i < data.length; i++) { - try { - out[i] = data[i].divide(v.getEntry(i)); - } catch (final MathArithmeticException e) { - throw new MathArithmeticException(LocalizedFormats.INDEX, i); - } - } - return new ArrayFieldVector<>(field, out, false); - } - } - - /** - * Element-by-element division. - * @param v vector by which instance elements must be divided - * @return a vector containing {@code this[i] / v[i]} for all {@code i} - * @throws DimensionMismatchException if {@code v} is not the same size as - * {@code this} - * @throws MathArithmeticException if one entry of {@code v} is zero. - */ - public ArrayFieldVector ebeDivide(ArrayFieldVector v) - throws DimensionMismatchException, MathArithmeticException { - checkVectorDimensions(v.data.length); - T[] out = MathArrays.buildArray(field, data.length); - for (int i = 0; i < data.length; i++) { - try { - out[i] = data[i].divide(v.data[i]); - } catch (final MathArithmeticException e) { - throw new MathArithmeticException(LocalizedFormats.INDEX, i); - } - } - return new ArrayFieldVector<>(field, out, false); - } - - /** - * Returns a reference to the underlying data array. - *

Does not make a fresh copy of the underlying data.

- * @return array of entries - */ - public T[] getDataRef() { - return data; - } - - /** {@inheritDoc} */ - @Override - public T dotProduct(FieldVector v) - throws DimensionMismatchException { - try { - return dotProduct((ArrayFieldVector) v); - } catch (ClassCastException cce) { - checkVectorDimensions(v); - T dot = field.getZero(); - for (int i = 0; i < data.length; i++) { - dot = dot.add(data[i].multiply(v.getEntry(i))); - } - return dot; - } - } - - /** - * Compute the dot product. - * @param v vector with which dot product should be computed - * @return the scalar dot product of {@code this} and {@code v} - * @throws DimensionMismatchException if {@code v} is not the same size as - * {@code this} - */ - public T dotProduct(ArrayFieldVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.data.length); - T dot = field.getZero(); - for (int i = 0; i < data.length; i++) { - dot = dot.add(data[i].multiply(v.data[i])); - } - return dot; - } - - /** {@inheritDoc} */ - @Override - public FieldVector projection(FieldVector v) - throws DimensionMismatchException, MathArithmeticException { - return v.mapMultiply(dotProduct(v).divide(v.dotProduct(v))); - } - - /** Find the orthogonal projection of this vector onto another vector. - * @param v vector onto which {@code this} must be projected - * @return projection of {@code this} onto {@code v} - * @throws DimensionMismatchException if {@code v} is not the same size as - * {@code this} - * @throws MathArithmeticException if {@code v} is the null vector. - */ - public ArrayFieldVector projection(ArrayFieldVector v) - throws DimensionMismatchException, MathArithmeticException { - return (ArrayFieldVector) v.mapMultiply(dotProduct(v).divide(v.dotProduct(v))); - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix outerProduct(FieldVector v) { - try { - return outerProduct((ArrayFieldVector) v); - } catch (ClassCastException cce) { - final int m = data.length; - final int n = v.getDimension(); - final FieldMatrix out = new Array2DRowFieldMatrix<>(field, m, n); - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - out.setEntry(i, j, data[i].multiply(v.getEntry(j))); - } - } - return out; - } - } - - /** - * Compute the outer product. - * @param v vector with which outer product should be computed - * @return the matrix outer product between instance and v - */ - public FieldMatrix outerProduct(ArrayFieldVector v) { - final int m = data.length; - final int n = v.data.length; - final FieldMatrix out = new Array2DRowFieldMatrix<>(field, m, n); - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - out.setEntry(i, j, data[i].multiply(v.data[j])); - } - } - return out; - } - - /** {@inheritDoc} */ - @Override - public T getEntry(int index) { - return data[index]; - } - - /** {@inheritDoc} */ - @Override - public int getDimension() { - return data.length; - } - - /** {@inheritDoc} */ - @Override - public FieldVector append(FieldVector v) { - try { - return append((ArrayFieldVector) v); - } catch (ClassCastException cce) { - return new ArrayFieldVector<>(this,new ArrayFieldVector<>(v)); - } - } - - /** - * Construct a vector by appending a vector to this vector. - * @param v vector to append to this one. - * @return a new vector - */ - public ArrayFieldVector append(ArrayFieldVector v) { - return new ArrayFieldVector<>(this, v); - } - - /** {@inheritDoc} */ - @Override - public FieldVector append(T in) { - final T[] out = MathArrays.buildArray(field, data.length + 1); - System.arraycopy(data, 0, out, 0, data.length); - out[data.length] = in; - return new ArrayFieldVector<>(field, out, false); - } - - /** {@inheritDoc} */ - @Override - public FieldVector getSubVector(int index, int n) - throws OutOfRangeException, NotPositiveException { - if (n < 0) { - throw new NotPositiveException(LocalizedFormats.NUMBER_OF_ELEMENTS_SHOULD_BE_POSITIVE, n); - } - ArrayFieldVector out = new ArrayFieldVector<>(field, n); - try { - System.arraycopy(data, index, out.data, 0, n); - } catch (IndexOutOfBoundsException e) { - checkIndex(index); - checkIndex(index + n - 1); - } - return out; - } - - /** {@inheritDoc} */ - @Override - public void setEntry(int index, T value) { - try { - data[index] = value; - } catch (IndexOutOfBoundsException e) { - checkIndex(index); - } - } - - /** {@inheritDoc} */ - @Override - public void setSubVector(int index, FieldVector v) throws OutOfRangeException { - try { - try { - set(index, (ArrayFieldVector) v); - } catch (ClassCastException cce) { - for (int i = index; i < index + v.getDimension(); ++i) { - data[i] = v.getEntry(i-index); - } - } - } catch (IndexOutOfBoundsException e) { - checkIndex(index); - checkIndex(index + v.getDimension() - 1); - } - } - - /** - * Set a set of consecutive elements. - * - * @param index index of first element to be set. - * @param v vector containing the values to set. - * @throws OutOfRangeException if the index is invalid. - */ - public void set(int index, ArrayFieldVector v) throws OutOfRangeException { - try { - System.arraycopy(v.data, 0, data, index, v.data.length); - } catch (IndexOutOfBoundsException e) { - checkIndex(index); - checkIndex(index + v.data.length - 1); - } - } - - /** {@inheritDoc} */ - @Override - public void set(T value) { - Arrays.fill(data, value); - } - - /** {@inheritDoc} */ - @Override - public T[] toArray(){ - return data.clone(); - } - - /** - * Check if instance and specified vectors have the same dimension. - * @param v vector to compare instance with - * @exception DimensionMismatchException if the vectors do not - * have the same dimensions - */ - protected void checkVectorDimensions(FieldVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - } - - /** - * Check if instance dimension is equal to some expected value. - * - * @param n Expected dimension. - * @throws DimensionMismatchException if the dimension is not equal to the - * size of {@code this} vector. - */ - protected void checkVectorDimensions(int n) - throws DimensionMismatchException { - if (data.length != n) { - throw new DimensionMismatchException(data.length, n); - } - } - - /** - * Visits (but does not alter) all entries of this vector in default order - * (increasing index). - * - * @param visitor the visitor to be used to process the entries of this - * vector - * @return the value returned by {@link FieldVectorPreservingVisitor#end()} - * at the end of the walk - * @since 3.3 - */ - public T walkInDefaultOrder(final FieldVectorPreservingVisitor visitor) { - final int dim = getDimension(); - visitor.start(dim, 0, dim - 1); - for (int i = 0; i < dim; i++) { - visitor.visit(i, getEntry(i)); - } - return visitor.end(); - } - - /** - * Visits (but does not alter) some entries of this vector in default order - * (increasing index). - * - * @param visitor visitor to be used to process the entries of this vector - * @param start the index of the first entry to be visited - * @param end the index of the last entry to be visited (inclusive) - * @return the value returned by {@link FieldVectorPreservingVisitor#end()} - * at the end of the walk - * @throws NumberIsTooSmallException if {@code end < start}. - * @throws OutOfRangeException if the indices are not valid. - * @since 3.3 - */ - public T walkInDefaultOrder(final FieldVectorPreservingVisitor visitor, - final int start, final int end) - throws NumberIsTooSmallException, OutOfRangeException { - checkIndices(start, end); - visitor.start(getDimension(), start, end); - for (int i = start; i <= end; i++) { - visitor.visit(i, getEntry(i)); - } - return visitor.end(); - } - - /** - * Visits (but does not alter) all entries of this vector in optimized - * order. The order in which the entries are visited is selected so as to - * lead to the most efficient implementation; it might depend on the - * concrete implementation of this abstract class. - * - * @param visitor the visitor to be used to process the entries of this - * vector - * @return the value returned by {@link FieldVectorPreservingVisitor#end()} - * at the end of the walk - * @since 3.3 - */ - public T walkInOptimizedOrder(final FieldVectorPreservingVisitor visitor) { - return walkInDefaultOrder(visitor); - } - - /** - * Visits (but does not alter) some entries of this vector in optimized - * order. The order in which the entries are visited is selected so as to - * lead to the most efficient implementation; it might depend on the - * concrete implementation of this abstract class. - * - * @param visitor visitor to be used to process the entries of this vector - * @param start the index of the first entry to be visited - * @param end the index of the last entry to be visited (inclusive) - * @return the value returned by {@link FieldVectorPreservingVisitor#end()} - * at the end of the walk - * @throws NumberIsTooSmallException if {@code end < start}. - * @throws OutOfRangeException if the indices are not valid. - * @since 3.3 - */ - public T walkInOptimizedOrder(final FieldVectorPreservingVisitor visitor, - final int start, final int end) - throws NumberIsTooSmallException, OutOfRangeException { - return walkInDefaultOrder(visitor, start, end); - } - - /** - * Visits (and possibly alters) all entries of this vector in default order - * (increasing index). - * - * @param visitor the visitor to be used to process and modify the entries - * of this vector - * @return the value returned by {@link FieldVectorChangingVisitor#end()} - * at the end of the walk - * @since 3.3 - */ - public T walkInDefaultOrder(final FieldVectorChangingVisitor visitor) { - final int dim = getDimension(); - visitor.start(dim, 0, dim - 1); - for (int i = 0; i < dim; i++) { - setEntry(i, visitor.visit(i, getEntry(i))); - } - return visitor.end(); - } - - /** - * Visits (and possibly alters) some entries of this vector in default order - * (increasing index). - * - * @param visitor visitor to be used to process the entries of this vector - * @param start the index of the first entry to be visited - * @param end the index of the last entry to be visited (inclusive) - * @return the value returned by {@link FieldVectorChangingVisitor#end()} - * at the end of the walk - * @throws NumberIsTooSmallException if {@code end < start}. - * @throws OutOfRangeException if the indices are not valid. - * @since 3.3 - */ - public T walkInDefaultOrder(final FieldVectorChangingVisitor visitor, - final int start, final int end) - throws NumberIsTooSmallException, OutOfRangeException { - checkIndices(start, end); - visitor.start(getDimension(), start, end); - for (int i = start; i <= end; i++) { - setEntry(i, visitor.visit(i, getEntry(i))); - } - return visitor.end(); - } - - /** - * Visits (and possibly alters) all entries of this vector in optimized - * order. The order in which the entries are visited is selected so as to - * lead to the most efficient implementation; it might depend on the - * concrete implementation of this abstract class. - * - * @param visitor the visitor to be used to process the entries of this - * vector - * @return the value returned by {@link FieldVectorChangingVisitor#end()} - * at the end of the walk - * @since 3.3 - */ - public T walkInOptimizedOrder(final FieldVectorChangingVisitor visitor) { - return walkInDefaultOrder(visitor); - } - - /** - * Visits (and possibly change) some entries of this vector in optimized - * order. The order in which the entries are visited is selected so as to - * lead to the most efficient implementation; it might depend on the - * concrete implementation of this abstract class. - * - * @param visitor visitor to be used to process the entries of this vector - * @param start the index of the first entry to be visited - * @param end the index of the last entry to be visited (inclusive) - * @return the value returned by {@link FieldVectorChangingVisitor#end()} - * at the end of the walk - * @throws NumberIsTooSmallException if {@code end < start}. - * @throws OutOfRangeException if the indices are not valid. - * @since 3.3 - */ - public T walkInOptimizedOrder(final FieldVectorChangingVisitor visitor, - final int start, final int end) - throws NumberIsTooSmallException, OutOfRangeException { - return walkInDefaultOrder(visitor, start, end); - } - - /** - * Test for the equality of two vectors. - * - * @param other Object to test for equality. - * @return {@code true} if two vector objects are equal, {@code false} - * otherwise. - */ - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null) { - return false; - } - - try { - @SuppressWarnings("unchecked") // May fail, but we ignore ClassCastException - FieldVector rhs = (FieldVector) other; - if (data.length != rhs.getDimension()) { - return false; - } - - for (int i = 0; i < data.length; ++i) { - if (!data[i].equals(rhs.getEntry(i))) { - return false; - } - } - return true; - } catch (ClassCastException ex) { - // ignore exception - return false; - } - } - - /** - * Get a hashCode for the real vector. - *

All NaN values have the same hash code.

- * @return a hash code value for this object - */ - @Override - public int hashCode() { - int h = 3542; - for (final T a : data) { - h ^= a.hashCode(); - } - return h; - } - - /** - * Check if an index is valid. - * - * @param index Index to check. - * @exception OutOfRangeException if the index is not valid. - */ - private void checkIndex(final int index) throws OutOfRangeException { - if (index < 0 || index >= getDimension()) { - throw new OutOfRangeException(LocalizedFormats.INDEX, - index, 0, getDimension() - 1); - } - } - - /** - * Checks that the indices of a subvector are valid. - * - * @param start the index of the first entry of the subvector - * @param end the index of the last entry of the subvector (inclusive) - * @throws OutOfRangeException if {@code start} of {@code end} are not valid - * @throws NumberIsTooSmallException if {@code end < start} - * @since 3.3 - */ - private void checkIndices(final int start, final int end) - throws NumberIsTooSmallException, OutOfRangeException { - final int dim = getDimension(); - if ((start < 0) || (start >= dim)) { - throw new OutOfRangeException(LocalizedFormats.INDEX, start, 0, - dim - 1); - } - if ((end < 0) || (end >= dim)) { - throw new OutOfRangeException(LocalizedFormats.INDEX, end, 0, - dim - 1); - } - if (end < start) { - throw new NumberIsTooSmallException(LocalizedFormats.INITIAL_ROW_AFTER_FINAL_ROW, - end, start, false); - } - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/ArrayRealVector.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/ArrayRealVector.java deleted file mode 100644 index 1dfc220da..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/ArrayRealVector.java +++ /dev/null @@ -1,954 +0,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. - */ -package org.apache.commons.math4.linear; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.Iterator; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathUtils; - -/** - * This class implements the {@link RealVector} interface with a double array. - * @since 2.0 - */ -public class ArrayRealVector extends RealVector implements Serializable { - /** Serializable version identifier. */ - private static final long serialVersionUID = -1097961340710804027L; - /** Default format. */ - private static final RealVectorFormat DEFAULT_FORMAT = RealVectorFormat.getInstance(); - - /** Entries of the vector. */ - private double data[]; - - /** - * Build a 0-length vector. - * Zero-length vectors may be used to initialized construction of vectors - * by data gathering. We start with zero-length and use either the {@link - * #ArrayRealVector(ArrayRealVector, ArrayRealVector)} constructor - * or one of the {@code append} method ({@link #append(double)}, - * {@link #append(ArrayRealVector)}) to gather data into this vector. - */ - public ArrayRealVector() { - data = new double[0]; - } - - /** - * Construct a vector of zeroes. - * - * @param size Size of the vector. - */ - public ArrayRealVector(int size) { - data = new double[size]; - } - - /** - * Construct a vector with preset values. - * - * @param size Size of the vector - * @param preset All entries will be set with this value. - */ - public ArrayRealVector(int size, double preset) { - data = new double[size]; - Arrays.fill(data, preset); - } - - /** - * Construct a vector from an array, copying the input array. - * - * @param d Array. - */ - public ArrayRealVector(double[] d) { - data = d.clone(); - } - - /** - * Create a new ArrayRealVector using the input array as the underlying - * data array. - * If an array is built specially in order to be embedded in a - * ArrayRealVector and not used directly, the {@code copyArray} may be - * set to {@code false}. This will prevent the copying and improve - * performance as no new array will be built and no data will be copied. - * - * @param d Data for the new vector. - * @param copyArray if {@code true}, the input array will be copied, - * otherwise it will be referenced. - * @throws NullArgumentException if {@code d} is {@code null}. - * @see #ArrayRealVector(double[]) - */ - public ArrayRealVector(double[] d, boolean copyArray) - throws NullArgumentException { - if (d == null) { - throw new NullArgumentException(); - } - data = copyArray ? d.clone() : d; - } - - /** - * Construct a vector from part of a array. - * - * @param d Array. - * @param pos Position of first entry. - * @param size Number of entries to copy. - * @throws NullArgumentException if {@code d} is {@code null}. - * @throws NumberIsTooLargeException if the size of {@code d} is less - * than {@code pos + size}. - */ - public ArrayRealVector(double[] d, int pos, int size) - throws NullArgumentException, NumberIsTooLargeException { - if (d == null) { - throw new NullArgumentException(); - } - if (d.length < pos + size) { - throw new NumberIsTooLargeException(pos + size, d.length, true); - } - data = new double[size]; - System.arraycopy(d, pos, data, 0, size); - } - - /** - * Construct a vector from an array. - * - * @param d Array of {@code Double}s. - */ - public ArrayRealVector(Double[] d) { - data = new double[d.length]; - for (int i = 0; i < d.length; i++) { - data[i] = d[i].doubleValue(); - } - } - - /** - * Construct a vector from part of an array. - * - * @param d Array. - * @param pos Position of first entry. - * @param size Number of entries to copy. - * @throws NullArgumentException if {@code d} is {@code null}. - * @throws NumberIsTooLargeException if the size of {@code d} is less - * than {@code pos + size}. - */ - public ArrayRealVector(Double[] d, int pos, int size) - throws NullArgumentException, NumberIsTooLargeException { - if (d == null) { - throw new NullArgumentException(); - } - if (d.length < pos + size) { - throw new NumberIsTooLargeException(pos + size, d.length, true); - } - data = new double[size]; - for (int i = pos; i < pos + size; i++) { - data[i - pos] = d[i].doubleValue(); - } - } - - /** - * Construct a vector from another vector, using a deep copy. - * - * @param v vector to copy. - * @throws NullArgumentException if {@code v} is {@code null}. - */ - public ArrayRealVector(RealVector v) throws NullArgumentException { - if (v == null) { - throw new NullArgumentException(); - } - data = new double[v.getDimension()]; - for (int i = 0; i < data.length; ++i) { - data[i] = v.getEntry(i); - } - } - - /** - * Construct a vector from another vector, using a deep copy. - * - * @param v Vector to copy. - * @throws NullArgumentException if {@code v} is {@code null}. - */ - public ArrayRealVector(ArrayRealVector v) throws NullArgumentException { - this(v, true); - } - - /** - * Construct a vector from another vector. - * - * @param v Vector to copy. - * @param deep If {@code true} perform a deep copy, otherwise perform a - * shallow copy. - */ - public ArrayRealVector(ArrayRealVector v, boolean deep) { - data = deep ? v.data.clone() : v.data; - } - - /** - * Construct a vector by appending one vector to another vector. - * @param v1 First vector (will be put in front of the new vector). - * @param v2 Second vector (will be put at back of the new vector). - */ - public ArrayRealVector(ArrayRealVector v1, ArrayRealVector v2) { - data = new double[v1.data.length + v2.data.length]; - System.arraycopy(v1.data, 0, data, 0, v1.data.length); - System.arraycopy(v2.data, 0, data, v1.data.length, v2.data.length); - } - - /** - * Construct a vector by appending one vector to another vector. - * @param v1 First vector (will be put in front of the new vector). - * @param v2 Second vector (will be put at back of the new vector). - */ - public ArrayRealVector(ArrayRealVector v1, RealVector v2) { - final int l1 = v1.data.length; - final int l2 = v2.getDimension(); - data = new double[l1 + l2]; - System.arraycopy(v1.data, 0, data, 0, l1); - for (int i = 0; i < l2; ++i) { - data[l1 + i] = v2.getEntry(i); - } - } - - /** - * Construct a vector by appending one vector to another vector. - * @param v1 First vector (will be put in front of the new vector). - * @param v2 Second vector (will be put at back of the new vector). - */ - public ArrayRealVector(RealVector v1, ArrayRealVector v2) { - final int l1 = v1.getDimension(); - final int l2 = v2.data.length; - data = new double[l1 + l2]; - for (int i = 0; i < l1; ++i) { - data[i] = v1.getEntry(i); - } - System.arraycopy(v2.data, 0, data, l1, l2); - } - - /** - * Construct a vector by appending one vector to another vector. - * @param v1 First vector (will be put in front of the new vector). - * @param v2 Second vector (will be put at back of the new vector). - */ - public ArrayRealVector(ArrayRealVector v1, double[] v2) { - final int l1 = v1.getDimension(); - final int l2 = v2.length; - data = new double[l1 + l2]; - System.arraycopy(v1.data, 0, data, 0, l1); - System.arraycopy(v2, 0, data, l1, l2); - } - - /** - * Construct a vector by appending one vector to another vector. - * @param v1 First vector (will be put in front of the new vector). - * @param v2 Second vector (will be put at back of the new vector). - */ - public ArrayRealVector(double[] v1, ArrayRealVector v2) { - final int l1 = v1.length; - final int l2 = v2.getDimension(); - data = new double[l1 + l2]; - System.arraycopy(v1, 0, data, 0, l1); - System.arraycopy(v2.data, 0, data, l1, l2); - } - - /** - * Construct a vector by appending one vector to another vector. - * @param v1 first vector (will be put in front of the new vector) - * @param v2 second vector (will be put at back of the new vector) - */ - public ArrayRealVector(double[] v1, double[] v2) { - final int l1 = v1.length; - final int l2 = v2.length; - data = new double[l1 + l2]; - System.arraycopy(v1, 0, data, 0, l1); - System.arraycopy(v2, 0, data, l1, l2); - } - - /** {@inheritDoc} */ - @Override - public ArrayRealVector copy() { - return new ArrayRealVector(this, true); - } - - /** {@inheritDoc} */ - @Override - public ArrayRealVector add(RealVector v) - throws DimensionMismatchException { - if (v instanceof ArrayRealVector) { - final double[] vData = ((ArrayRealVector) v).data; - final int dim = vData.length; - checkVectorDimensions(dim); - ArrayRealVector result = new ArrayRealVector(dim); - double[] resultData = result.data; - for (int i = 0; i < dim; i++) { - resultData[i] = data[i] + vData[i]; - } - return result; - } else { - checkVectorDimensions(v); - double[] out = data.clone(); - Iterator it = v.iterator(); - while (it.hasNext()) { - final Entry e = it.next(); - out[e.getIndex()] += e.getValue(); - } - return new ArrayRealVector(out, false); - } - } - - /** {@inheritDoc} */ - @Override - public ArrayRealVector subtract(RealVector v) - throws DimensionMismatchException { - if (v instanceof ArrayRealVector) { - final double[] vData = ((ArrayRealVector) v).data; - final int dim = vData.length; - checkVectorDimensions(dim); - ArrayRealVector result = new ArrayRealVector(dim); - double[] resultData = result.data; - for (int i = 0; i < dim; i++) { - resultData[i] = data[i] - vData[i]; - } - return result; - } else { - checkVectorDimensions(v); - double[] out = data.clone(); - Iterator it = v.iterator(); - while (it.hasNext()) { - final Entry e = it.next(); - out[e.getIndex()] -= e.getValue(); - } - return new ArrayRealVector(out, false); - } - } - - /** {@inheritDoc} */ - @Override - public ArrayRealVector map(UnivariateFunction function) { - return copy().mapToSelf(function); - } - - /** {@inheritDoc} */ - @Override - public ArrayRealVector mapToSelf(UnivariateFunction function) { - for (int i = 0; i < data.length; i++) { - data[i] = function.value(data[i]); - } - return this; - } - - /** {@inheritDoc} */ - @Override - public RealVector mapAddToSelf(double d) { - for (int i = 0; i < data.length; i++) { - data[i] += d; - } - return this; - } - - /** {@inheritDoc} */ - @Override - public RealVector mapSubtractToSelf(double d) { - for (int i = 0; i < data.length; i++) { - data[i] -= d; - } - return this; - } - - /** {@inheritDoc} */ - @Override - public RealVector mapMultiplyToSelf(double d) { - for (int i = 0; i < data.length; i++) { - data[i] *= d; - } - return this; - } - - /** {@inheritDoc} */ - @Override - public RealVector mapDivideToSelf(double d) { - for (int i = 0; i < data.length; i++) { - data[i] /= d; - } - return this; - } - - /** {@inheritDoc} */ - @Override - public ArrayRealVector ebeMultiply(RealVector v) - throws DimensionMismatchException { - if (v instanceof ArrayRealVector) { - final double[] vData = ((ArrayRealVector) v).data; - final int dim = vData.length; - checkVectorDimensions(dim); - ArrayRealVector result = new ArrayRealVector(dim); - double[] resultData = result.data; - for (int i = 0; i < dim; i++) { - resultData[i] = data[i] * vData[i]; - } - return result; - } else { - checkVectorDimensions(v); - double[] out = data.clone(); - for (int i = 0; i < data.length; i++) { - out[i] *= v.getEntry(i); - } - return new ArrayRealVector(out, false); - } - } - - /** {@inheritDoc} */ - @Override - public ArrayRealVector ebeDivide(RealVector v) - throws DimensionMismatchException { - if (v instanceof ArrayRealVector) { - final double[] vData = ((ArrayRealVector) v).data; - final int dim = vData.length; - checkVectorDimensions(dim); - ArrayRealVector result = new ArrayRealVector(dim); - double[] resultData = result.data; - for (int i = 0; i < dim; i++) { - resultData[i] = data[i] / vData[i]; - } - return result; - } else { - checkVectorDimensions(v); - double[] out = data.clone(); - for (int i = 0; i < data.length; i++) { - out[i] /= v.getEntry(i); - } - return new ArrayRealVector(out, false); - } - } - - /** - * Get a reference to the underlying data array. - * This method does not make a fresh copy of the underlying data. - * - * @return the array of entries. - */ - public double[] getDataRef() { - return data; - } - - /** {@inheritDoc} */ - @Override - public double dotProduct(RealVector v) throws DimensionMismatchException { - if (v instanceof ArrayRealVector) { - final double[] vData = ((ArrayRealVector) v).data; - checkVectorDimensions(vData.length); - double dot = 0; - for (int i = 0; i < data.length; i++) { - dot += data[i] * vData[i]; - } - return dot; - } - return super.dotProduct(v); - } - - /** {@inheritDoc} */ - @Override - public double getNorm() { - double sum = 0; - for (double a : data) { - sum += a * a; - } - return FastMath.sqrt(sum); - } - - /** {@inheritDoc} */ - @Override - public double getL1Norm() { - double sum = 0; - for (double a : data) { - sum += FastMath.abs(a); - } - return sum; - } - - /** {@inheritDoc} */ - @Override - public double getLInfNorm() { - double max = 0; - for (double a : data) { - max = FastMath.max(max, FastMath.abs(a)); - } - return max; - } - - /** {@inheritDoc} */ - @Override - public double getDistance(RealVector v) throws DimensionMismatchException { - if (v instanceof ArrayRealVector) { - final double[] vData = ((ArrayRealVector) v).data; - checkVectorDimensions(vData.length); - double sum = 0; - for (int i = 0; i < data.length; ++i) { - final double delta = data[i] - vData[i]; - sum += delta * delta; - } - return FastMath.sqrt(sum); - } else { - checkVectorDimensions(v); - double sum = 0; - for (int i = 0; i < data.length; ++i) { - final double delta = data[i] - v.getEntry(i); - sum += delta * delta; - } - return FastMath.sqrt(sum); - } - } - - /** {@inheritDoc} */ - @Override - public double getL1Distance(RealVector v) - throws DimensionMismatchException { - if (v instanceof ArrayRealVector) { - final double[] vData = ((ArrayRealVector) v).data; - checkVectorDimensions(vData.length); - double sum = 0; - for (int i = 0; i < data.length; ++i) { - final double delta = data[i] - vData[i]; - sum += FastMath.abs(delta); - } - return sum; - } else { - checkVectorDimensions(v); - double sum = 0; - for (int i = 0; i < data.length; ++i) { - final double delta = data[i] - v.getEntry(i); - sum += FastMath.abs(delta); - } - return sum; - } - } - - /** {@inheritDoc} */ - @Override - public double getLInfDistance(RealVector v) - throws DimensionMismatchException { - if (v instanceof ArrayRealVector) { - final double[] vData = ((ArrayRealVector) v).data; - checkVectorDimensions(vData.length); - double max = 0; - for (int i = 0; i < data.length; ++i) { - final double delta = data[i] - vData[i]; - max = FastMath.max(max, FastMath.abs(delta)); - } - return max; - } else { - checkVectorDimensions(v); - double max = 0; - for (int i = 0; i < data.length; ++i) { - final double delta = data[i] - v.getEntry(i); - max = FastMath.max(max, FastMath.abs(delta)); - } - return max; - } - } - - /** {@inheritDoc} */ - @Override - public RealMatrix outerProduct(RealVector v) { - if (v instanceof ArrayRealVector) { - final double[] vData = ((ArrayRealVector) v).data; - final int m = data.length; - final int n = vData.length; - final RealMatrix out = MatrixUtils.createRealMatrix(m, n); - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - out.setEntry(i, j, data[i] * vData[j]); - } - } - return out; - } else { - final int m = data.length; - final int n = v.getDimension(); - final RealMatrix out = MatrixUtils.createRealMatrix(m, n); - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - out.setEntry(i, j, data[i] * v.getEntry(j)); - } - } - return out; - } - } - - /** {@inheritDoc} */ - @Override - public double getEntry(int index) throws OutOfRangeException { - try { - return data[index]; - } catch (IndexOutOfBoundsException e) { - throw new OutOfRangeException(LocalizedFormats.INDEX, index, 0, - getDimension() - 1); - } - } - - /** {@inheritDoc} */ - @Override - public int getDimension() { - return data.length; - } - - /** {@inheritDoc} */ - @Override - public RealVector append(RealVector v) { - try { - return new ArrayRealVector(this, (ArrayRealVector) v); - } catch (ClassCastException cce) { - return new ArrayRealVector(this, v); - } - } - - /** - * Construct a vector by appending a vector to this vector. - * - * @param v Vector to append to this one. - * @return a new vector. - */ - public ArrayRealVector append(ArrayRealVector v) { - return new ArrayRealVector(this, v); - } - - /** {@inheritDoc} */ - @Override - public RealVector append(double in) { - final double[] out = new double[data.length + 1]; - System.arraycopy(data, 0, out, 0, data.length); - out[data.length] = in; - return new ArrayRealVector(out, false); - } - - /** {@inheritDoc} */ - @Override - public RealVector getSubVector(int index, int n) - throws OutOfRangeException, NotPositiveException { - if (n < 0) { - throw new NotPositiveException(LocalizedFormats.NUMBER_OF_ELEMENTS_SHOULD_BE_POSITIVE, n); - } - ArrayRealVector out = new ArrayRealVector(n); - try { - System.arraycopy(data, index, out.data, 0, n); - } catch (IndexOutOfBoundsException e) { - checkIndex(index); - checkIndex(index + n - 1); - } - return out; - } - - /** {@inheritDoc} */ - @Override - public void setEntry(int index, double value) throws OutOfRangeException { - try { - data[index] = value; - } catch (IndexOutOfBoundsException e) { - checkIndex(index); - } - } - - /** {@inheritDoc} */ - @Override - public void addToEntry(int index, double increment) - throws OutOfRangeException { - try { - data[index] += increment; - } catch(IndexOutOfBoundsException e){ - throw new OutOfRangeException(LocalizedFormats.INDEX, - index, 0, data.length - 1); - } - } - - /** {@inheritDoc} */ - @Override - public void setSubVector(int index, RealVector v) - throws OutOfRangeException { - if (v instanceof ArrayRealVector) { - setSubVector(index, ((ArrayRealVector) v).data); - } else { - try { - for (int i = index; i < index + v.getDimension(); ++i) { - data[i] = v.getEntry(i - index); - } - } catch (IndexOutOfBoundsException e) { - checkIndex(index); - checkIndex(index + v.getDimension() - 1); - } - } - } - - /** - * Set a set of consecutive elements. - * - * @param index Index of first element to be set. - * @param v Vector containing the values to set. - * @throws OutOfRangeException if the index is inconsistent with the vector - * size. - */ - public void setSubVector(int index, double[] v) - throws OutOfRangeException { - try { - System.arraycopy(v, 0, data, index, v.length); - } catch (IndexOutOfBoundsException e) { - checkIndex(index); - checkIndex(index + v.length - 1); - } - } - - /** {@inheritDoc} */ - @Override - public void set(double value) { - Arrays.fill(data, value); - } - - /** {@inheritDoc} */ - @Override - public double[] toArray(){ - return data.clone(); - } - - /** {@inheritDoc} */ - @Override - public String toString(){ - return DEFAULT_FORMAT.format(this); - } - - /** - * Check if instance and specified vectors have the same dimension. - * - * @param v Vector to compare instance with. - * @throws DimensionMismatchException if the vectors do not - * have the same dimension. - */ - @Override - protected void checkVectorDimensions(RealVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - } - - /** - * Check if instance dimension is equal to some expected value. - * - * @param n Expected dimension. - * @throws DimensionMismatchException if the dimension is - * inconsistent with vector size. - */ - @Override - protected void checkVectorDimensions(int n) - throws DimensionMismatchException { - if (data.length != n) { - throw new DimensionMismatchException(data.length, n); - } - } - - /** - * Check if any coordinate of this vector is {@code NaN}. - * - * @return {@code true} if any coordinate of this vector is {@code NaN}, - * {@code false} otherwise. - */ - @Override - public boolean isNaN() { - for (double v : data) { - if (Double.isNaN(v)) { - return true; - } - } - return false; - } - - /** - * Check whether any coordinate of this vector is infinite and none - * are {@code NaN}. - * - * @return {@code true} if any coordinate of this vector is infinite and - * none are {@code NaN}, {@code false} otherwise. - */ - @Override - public boolean isInfinite() { - if (isNaN()) { - return false; - } - - for (double v : data) { - if (Double.isInfinite(v)) { - return true; - } - } - - return false; - } - - /** {@inheritDoc} */ - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - - if (!(other instanceof RealVector)) { - return false; - } - - RealVector rhs = (RealVector) other; - if (data.length != rhs.getDimension()) { - return false; - } - - if (rhs.isNaN()) { - return this.isNaN(); - } - - for (int i = 0; i < data.length; ++i) { - if (data[i] != rhs.getEntry(i)) { - return false; - } - } - return true; - } - - /** - * {@inheritDoc} All {@code NaN} values have the same hash code. - */ - @Override - public int hashCode() { - if (isNaN()) { - return 9; - } - return MathUtils.hash(data); - } - - /** {@inheritDoc} */ - @Override - public ArrayRealVector combine(double a, double b, RealVector y) - throws DimensionMismatchException { - return copy().combineToSelf(a, b, y); - } - - /** {@inheritDoc} */ - @Override - public ArrayRealVector combineToSelf(double a, double b, RealVector y) - throws DimensionMismatchException { - if (y instanceof ArrayRealVector) { - final double[] yData = ((ArrayRealVector) y).data; - checkVectorDimensions(yData.length); - for (int i = 0; i < this.data.length; i++) { - data[i] = a * data[i] + b * yData[i]; - } - } else { - checkVectorDimensions(y); - for (int i = 0; i < this.data.length; i++) { - data[i] = a * data[i] + b * y.getEntry(i); - } - } - return this; - } - - /** {@inheritDoc} */ - @Override - public double walkInDefaultOrder(final RealVectorPreservingVisitor visitor) { - visitor.start(data.length, 0, data.length - 1); - for (int i = 0; i < data.length; i++) { - visitor.visit(i, data[i]); - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInDefaultOrder(final RealVectorPreservingVisitor visitor, - final int start, final int end) throws NumberIsTooSmallException, - OutOfRangeException { - checkIndices(start, end); - visitor.start(data.length, start, end); - for (int i = start; i <= end; i++) { - visitor.visit(i, data[i]); - } - return visitor.end(); - } - - /** - * {@inheritDoc} - * - * In this implementation, the optimized order is the default order. - */ - @Override - public double walkInOptimizedOrder(final RealVectorPreservingVisitor visitor) { - return walkInDefaultOrder(visitor); - } - - /** - * {@inheritDoc} - * - * In this implementation, the optimized order is the default order. - */ - @Override - public double walkInOptimizedOrder(final RealVectorPreservingVisitor visitor, - final int start, final int end) throws NumberIsTooSmallException, - OutOfRangeException { - return walkInDefaultOrder(visitor, start, end); - } - - /** {@inheritDoc} */ - @Override - public double walkInDefaultOrder(final RealVectorChangingVisitor visitor) { - visitor.start(data.length, 0, data.length - 1); - for (int i = 0; i < data.length; i++) { - data[i] = visitor.visit(i, data[i]); - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInDefaultOrder(final RealVectorChangingVisitor visitor, - final int start, final int end) throws NumberIsTooSmallException, - OutOfRangeException { - checkIndices(start, end); - visitor.start(data.length, start, end); - for (int i = start; i <= end; i++) { - data[i] = visitor.visit(i, data[i]); - } - return visitor.end(); - } - - /** - * {@inheritDoc} - * - * In this implementation, the optimized order is the default order. - */ - @Override - public double walkInOptimizedOrder(final RealVectorChangingVisitor visitor) { - return walkInDefaultOrder(visitor); - } - - /** - * {@inheritDoc} - * - * In this implementation, the optimized order is the default order. - */ - @Override - public double walkInOptimizedOrder(final RealVectorChangingVisitor visitor, - final int start, final int end) throws NumberIsTooSmallException, - OutOfRangeException { - return walkInDefaultOrder(visitor, start, end); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/BiDiagonalTransformer.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/BiDiagonalTransformer.java deleted file mode 100644 index 3e9e71a7f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/BiDiagonalTransformer.java +++ /dev/null @@ -1,380 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.util.FastMath; - - -/** - * Class transforming any matrix to bi-diagonal shape. - *

Any m × n matrix A can be written as the product of three matrices: - * A = U × B × VT with U an m × m orthogonal matrix, - * B an m × n bi-diagonal matrix (lower diagonal if m < n, upper diagonal - * otherwise), and V an n × n orthogonal matrix.

- *

Transformation to bi-diagonal shape is often not a goal by itself, but it is - * an intermediate step in more general decomposition algorithms like {@link - * SingularValueDecomposition Singular Value Decomposition}. This class is therefore - * intended for internal use by the library and is not public. As a consequence of - * this explicitly limited scope, many methods directly returns references to - * internal arrays, not copies.

- * @since 2.0 - */ -class BiDiagonalTransformer { - - /** Householder vectors. */ - private final double householderVectors[][]; - - /** Main diagonal. */ - private final double[] main; - - /** Secondary diagonal. */ - private final double[] secondary; - - /** Cached value of U. */ - private RealMatrix cachedU; - - /** Cached value of B. */ - private RealMatrix cachedB; - - /** Cached value of V. */ - private RealMatrix cachedV; - - /** - * Build the transformation to bi-diagonal shape of a matrix. - * @param matrix the matrix to transform. - */ - BiDiagonalTransformer(RealMatrix matrix) { - - final int m = matrix.getRowDimension(); - final int n = matrix.getColumnDimension(); - final int p = FastMath.min(m, n); - householderVectors = matrix.getData(); - main = new double[p]; - secondary = new double[p - 1]; - cachedU = null; - cachedB = null; - cachedV = null; - - // transform matrix - if (m >= n) { - transformToUpperBiDiagonal(); - } else { - transformToLowerBiDiagonal(); - } - - } - - /** - * Returns the matrix U of the transform. - *

U is an orthogonal matrix, i.e. its transpose is also its inverse.

- * @return the U matrix - */ - public RealMatrix getU() { - - if (cachedU == null) { - - final int m = householderVectors.length; - final int n = householderVectors[0].length; - final int p = main.length; - final int diagOffset = (m >= n) ? 0 : 1; - final double[] diagonal = (m >= n) ? main : secondary; - double[][] ua = new double[m][m]; - - // fill up the part of the matrix not affected by Householder transforms - for (int k = m - 1; k >= p; --k) { - ua[k][k] = 1; - } - - // build up first part of the matrix by applying Householder transforms - for (int k = p - 1; k >= diagOffset; --k) { - final double[] hK = householderVectors[k]; - ua[k][k] = 1; - if (hK[k - diagOffset] != 0.0) { - for (int j = k; j < m; ++j) { - double alpha = 0; - for (int i = k; i < m; ++i) { - alpha -= ua[i][j] * householderVectors[i][k - diagOffset]; - } - alpha /= diagonal[k - diagOffset] * hK[k - diagOffset]; - - for (int i = k; i < m; ++i) { - ua[i][j] += -alpha * householderVectors[i][k - diagOffset]; - } - } - } - } - if (diagOffset > 0) { - ua[0][0] = 1; - } - cachedU = MatrixUtils.createRealMatrix(ua); - } - - // return the cached matrix - return cachedU; - - } - - /** - * Returns the bi-diagonal matrix B of the transform. - * @return the B matrix - */ - public RealMatrix getB() { - - if (cachedB == null) { - - final int m = householderVectors.length; - final int n = householderVectors[0].length; - double[][] ba = new double[m][n]; - for (int i = 0; i < main.length; ++i) { - ba[i][i] = main[i]; - if (m < n) { - if (i > 0) { - ba[i][i-1] = secondary[i - 1]; - } - } else { - if (i < main.length - 1) { - ba[i][i+1] = secondary[i]; - } - } - } - cachedB = MatrixUtils.createRealMatrix(ba); - } - - // return the cached matrix - return cachedB; - - } - - /** - * Returns the matrix V of the transform. - *

V is an orthogonal matrix, i.e. its transpose is also its inverse.

- * @return the V matrix - */ - public RealMatrix getV() { - - if (cachedV == null) { - - final int m = householderVectors.length; - final int n = householderVectors[0].length; - final int p = main.length; - final int diagOffset = (m >= n) ? 1 : 0; - final double[] diagonal = (m >= n) ? secondary : main; - double[][] va = new double[n][n]; - - // fill up the part of the matrix not affected by Householder transforms - for (int k = n - 1; k >= p; --k) { - va[k][k] = 1; - } - - // build up first part of the matrix by applying Householder transforms - for (int k = p - 1; k >= diagOffset; --k) { - final double[] hK = householderVectors[k - diagOffset]; - va[k][k] = 1; - if (hK[k] != 0.0) { - for (int j = k; j < n; ++j) { - double beta = 0; - for (int i = k; i < n; ++i) { - beta -= va[i][j] * hK[i]; - } - beta /= diagonal[k - diagOffset] * hK[k]; - - for (int i = k; i < n; ++i) { - va[i][j] += -beta * hK[i]; - } - } - } - } - if (diagOffset > 0) { - va[0][0] = 1; - } - cachedV = MatrixUtils.createRealMatrix(va); - } - - // return the cached matrix - return cachedV; - - } - - /** - * Get the Householder vectors of the transform. - *

Note that since this class is only intended for internal use, - * it returns directly a reference to its internal arrays, not a copy.

- * @return the main diagonal elements of the B matrix - */ - double[][] getHouseholderVectorsRef() { - return householderVectors; - } - - /** - * Get the main diagonal elements of the matrix B of the transform. - *

Note that since this class is only intended for internal use, - * it returns directly a reference to its internal arrays, not a copy.

- * @return the main diagonal elements of the B matrix - */ - double[] getMainDiagonalRef() { - return main; - } - - /** - * Get the secondary diagonal elements of the matrix B of the transform. - *

Note that since this class is only intended for internal use, - * it returns directly a reference to its internal arrays, not a copy.

- * @return the secondary diagonal elements of the B matrix - */ - double[] getSecondaryDiagonalRef() { - return secondary; - } - - /** - * Check if the matrix is transformed to upper bi-diagonal. - * @return true if the matrix is transformed to upper bi-diagonal - */ - boolean isUpperBiDiagonal() { - return householderVectors.length >= householderVectors[0].length; - } - - /** - * Transform original matrix to upper bi-diagonal form. - *

Transformation is done using alternate Householder transforms - * on columns and rows.

- */ - private void transformToUpperBiDiagonal() { - - final int m = householderVectors.length; - final int n = householderVectors[0].length; - for (int k = 0; k < n; k++) { - - //zero-out a column - double xNormSqr = 0; - for (int i = k; i < m; ++i) { - final double c = householderVectors[i][k]; - xNormSqr += c * c; - } - final double[] hK = householderVectors[k]; - final double a = (hK[k] > 0) ? -FastMath.sqrt(xNormSqr) : FastMath.sqrt(xNormSqr); - main[k] = a; - if (a != 0.0) { - hK[k] -= a; - for (int j = k + 1; j < n; ++j) { - double alpha = 0; - for (int i = k; i < m; ++i) { - final double[] hI = householderVectors[i]; - alpha -= hI[j] * hI[k]; - } - alpha /= a * householderVectors[k][k]; - for (int i = k; i < m; ++i) { - final double[] hI = householderVectors[i]; - hI[j] -= alpha * hI[k]; - } - } - } - - if (k < n - 1) { - //zero-out a row - xNormSqr = 0; - for (int j = k + 1; j < n; ++j) { - final double c = hK[j]; - xNormSqr += c * c; - } - final double b = (hK[k + 1] > 0) ? -FastMath.sqrt(xNormSqr) : FastMath.sqrt(xNormSqr); - secondary[k] = b; - if (b != 0.0) { - hK[k + 1] -= b; - for (int i = k + 1; i < m; ++i) { - final double[] hI = householderVectors[i]; - double beta = 0; - for (int j = k + 1; j < n; ++j) { - beta -= hI[j] * hK[j]; - } - beta /= b * hK[k + 1]; - for (int j = k + 1; j < n; ++j) { - hI[j] -= beta * hK[j]; - } - } - } - } - - } - } - - /** - * Transform original matrix to lower bi-diagonal form. - *

Transformation is done using alternate Householder transforms - * on rows and columns.

- */ - private void transformToLowerBiDiagonal() { - - final int m = householderVectors.length; - final int n = householderVectors[0].length; - for (int k = 0; k < m; k++) { - - //zero-out a row - final double[] hK = householderVectors[k]; - double xNormSqr = 0; - for (int j = k; j < n; ++j) { - final double c = hK[j]; - xNormSqr += c * c; - } - final double a = (hK[k] > 0) ? -FastMath.sqrt(xNormSqr) : FastMath.sqrt(xNormSqr); - main[k] = a; - if (a != 0.0) { - hK[k] -= a; - for (int i = k + 1; i < m; ++i) { - final double[] hI = householderVectors[i]; - double alpha = 0; - for (int j = k; j < n; ++j) { - alpha -= hI[j] * hK[j]; - } - alpha /= a * householderVectors[k][k]; - for (int j = k; j < n; ++j) { - hI[j] -= alpha * hK[j]; - } - } - } - - if (k < m - 1) { - //zero-out a column - final double[] hKp1 = householderVectors[k + 1]; - xNormSqr = 0; - for (int i = k + 1; i < m; ++i) { - final double c = householderVectors[i][k]; - xNormSqr += c * c; - } - final double b = (hKp1[k] > 0) ? -FastMath.sqrt(xNormSqr) : FastMath.sqrt(xNormSqr); - secondary[k] = b; - if (b != 0.0) { - hKp1[k] -= b; - for (int j = k + 1; j < n; ++j) { - double beta = 0; - for (int i = k + 1; i < m; ++i) { - final double[] hI = householderVectors[i]; - beta -= hI[j] * hI[k]; - } - beta /= b * hKp1[k]; - for (int i = k + 1; i < m; ++i) { - final double[] hI = householderVectors[i]; - hI[j] -= beta * hI[k]; - } - } - } - } - - } - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/BlockFieldMatrix.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/BlockFieldMatrix.java deleted file mode 100644 index 03417a3d2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/BlockFieldMatrix.java +++ /dev/null @@ -1,1591 +0,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. - */ - -package org.apache.commons.math4.linear; - -import java.io.Serializable; - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - -/** - * Cache-friendly implementation of FieldMatrix using a flat arrays to store - * square blocks of the matrix. - *

- * This implementation is specially designed to be cache-friendly. Square blocks are - * stored as small arrays and allow efficient traversal of data both in row major direction - * and columns major direction, one block at a time. This greatly increases performances - * for algorithms that use crossed directions loops like multiplication or transposition. - *

- *

- * The size of square blocks is a static parameter. It may be tuned according to the cache - * size of the target computer processor. As a rule of thumbs, it should be the largest - * value that allows three blocks to be simultaneously cached (this is necessary for example - * for matrix multiplication). The default value is to use 36x36 blocks. - *

- *

- * The regular blocks represent {@link #BLOCK_SIZE} x {@link #BLOCK_SIZE} squares. Blocks - * at right hand side and bottom side which may be smaller to fit matrix dimensions. The square - * blocks are flattened in row major order in single dimension arrays which are therefore - * {@link #BLOCK_SIZE}2 elements long for regular blocks. The blocks are themselves - * organized in row major order. - *

- *

- * As an example, for a block size of 36x36, a 100x60 matrix would be stored in 6 blocks. - * Block 0 would be a Field[1296] array holding the upper left 36x36 square, block 1 would be - * a Field[1296] array holding the upper center 36x36 square, block 2 would be a Field[1008] - * array holding the upper right 36x28 rectangle, block 3 would be a Field[864] array holding - * the lower left 24x36 rectangle, block 4 would be a Field[864] array holding the lower center - * 24x36 rectangle and block 5 would be a Field[672] array holding the lower right 24x28 - * rectangle. - *

- *

- * The layout complexity overhead versus simple mapping of matrices to java - * arrays is negligible for small matrices (about 1%). The gain from cache efficiency leads - * to up to 3-fold improvements for matrices of moderate to large size. - *

- * @param the type of the field elements - * @since 2.0 - */ -public class BlockFieldMatrix> extends AbstractFieldMatrix implements Serializable { - /** Block size. */ - public static final int BLOCK_SIZE = 36; - /** Serializable version identifier. */ - private static final long serialVersionUID = -4602336630143123183L; - /** Blocks of matrix entries. */ - private final T blocks[][]; - /** Number of rows of the matrix. */ - private final int rows; - /** Number of columns of the matrix. */ - private final int columns; - /** Number of block rows of the matrix. */ - private final int blockRows; - /** Number of block columns of the matrix. */ - private final int blockColumns; - - /** - * Create a new matrix with the supplied row and column dimensions. - * - * @param field Field to which the elements belong. - * @param rows Number of rows in the new matrix. - * @param columns Number of columns in the new matrix. - * @throws NotStrictlyPositiveException if row or column dimension is not - * positive. - */ - public BlockFieldMatrix(final Field field, final int rows, - final int columns) - throws NotStrictlyPositiveException { - super(field, rows, columns); - this.rows = rows; - this.columns = columns; - - // number of blocks - blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE; - blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE; - - // allocate storage blocks, taking care of smaller ones at right and bottom - blocks = createBlocksLayout(field, rows, columns); - } - - /** - * Create a new dense matrix copying entries from raw layout data. - *

The input array must already be in raw layout.

- *

Calling this constructor is equivalent to call: - * {@code matrix = new BlockFieldMatrix(getField(), rawData.length, rawData[0].length, - * toBlocksLayout(rawData), false);} - * - * @param rawData Data for the new matrix, in raw layout. - * @throws DimensionMismatchException if the {@code blockData} shape is - * inconsistent with block layout. - * @see #BlockFieldMatrix(int, int, FieldElement[][], boolean) - */ - public BlockFieldMatrix(final T[][] rawData) - throws DimensionMismatchException { - this(rawData.length, rawData[0].length, toBlocksLayout(rawData), false); - } - - /** - * Create a new dense matrix copying entries from block layout data. - *

The input array must already be in blocks layout.

- * @param rows the number of rows in the new matrix - * @param columns the number of columns in the new matrix - * @param blockData data for new matrix - * @param copyArray if true, the input array will be copied, otherwise - * it will be referenced - * - * @throws DimensionMismatchException if the {@code blockData} shape is - * inconsistent with block layout. - * @throws NotStrictlyPositiveException if row or column dimension is not - * positive. - * @see #createBlocksLayout(Field, int, int) - * @see #toBlocksLayout(FieldElement[][]) - * @see #BlockFieldMatrix(FieldElement[][]) - */ - public BlockFieldMatrix(final int rows, final int columns, - final T[][] blockData, final boolean copyArray) - throws DimensionMismatchException, NotStrictlyPositiveException { - super(extractField(blockData), rows, columns); - this.rows = rows; - this.columns = columns; - - // number of blocks - blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE; - blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE; - - if (copyArray) { - // allocate storage blocks, taking care of smaller ones at right and bottom - blocks = MathArrays.buildArray(getField(), blockRows * blockColumns, -1); - } else { - // reference existing array - blocks = blockData; - } - - int index = 0; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int iHeight = blockHeight(iBlock); - for (int jBlock = 0; jBlock < blockColumns; ++jBlock, ++index) { - if (blockData[index].length != iHeight * blockWidth(jBlock)) { - throw new DimensionMismatchException(blockData[index].length, - iHeight * blockWidth(jBlock)); - } - if (copyArray) { - blocks[index] = blockData[index].clone(); - } - } - } - } - - /** - * Convert a data array from raw layout to blocks layout. - *

- * Raw layout is the straightforward layout where element at row i and - * column j is in array element rawData[i][j]. Blocks layout - * is the layout used in {@link BlockFieldMatrix} instances, where the matrix - * is split in square blocks (except at right and bottom side where blocks may - * be rectangular to fit matrix size) and each block is stored in a flattened - * one-dimensional array. - *

- *

- * This method creates an array in blocks layout from an input array in raw layout. - * It can be used to provide the array argument of the {@link - * #BlockFieldMatrix(int, int, FieldElement[][], boolean)} - * constructor. - *

- * @param Type of the field elements. - * @param rawData Data array in raw layout. - * @return a new data array containing the same entries but in blocks layout - * @throws DimensionMismatchException if {@code rawData} is not rectangular - * (not all rows have the same length). - * @see #createBlocksLayout(Field, int, int) - * @see #BlockFieldMatrix(int, int, FieldElement[][], boolean) - */ - public static > T[][] toBlocksLayout(final T[][] rawData) - throws DimensionMismatchException { - - final int rows = rawData.length; - final int columns = rawData[0].length; - final int blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE; - final int blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE; - - // safety checks - for (int i = 0; i < rawData.length; ++i) { - final int length = rawData[i].length; - if (length != columns) { - throw new DimensionMismatchException(columns, length); - } - } - - // convert array - final Field field = extractField(rawData); - final T[][] blocks = MathArrays.buildArray(field, blockRows * blockColumns, -1); - int blockIndex = 0; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - final int iHeight = pEnd - pStart; - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - final int jWidth = qEnd - qStart; - - // allocate new block - final T[] block = MathArrays.buildArray(field, iHeight * jWidth); - blocks[blockIndex] = block; - - // copy data - int index = 0; - for (int p = pStart; p < pEnd; ++p) { - System.arraycopy(rawData[p], qStart, block, index, jWidth); - index += jWidth; - } - - ++blockIndex; - } - } - - return blocks; - } - - /** - * Create a data array in blocks layout. - *

- * This method can be used to create the array argument of the {@link - * #BlockFieldMatrix(int, int, FieldElement[][], boolean)} - * constructor. - *

- * @param Type of the field elements. - * @param field Field to which the elements belong. - * @param rows Number of rows in the new matrix. - * @param columns Number of columns in the new matrix. - * @return a new data array in blocks layout. - * @see #toBlocksLayout(FieldElement[][]) - * @see #BlockFieldMatrix(int, int, FieldElement[][], boolean) - */ - public static > T[][] createBlocksLayout(final Field field, - final int rows, final int columns) { - final int blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE; - final int blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE; - - final T[][] blocks = MathArrays.buildArray(field, blockRows * blockColumns, -1); - int blockIndex = 0; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - final int iHeight = pEnd - pStart; - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - final int jWidth = qEnd - qStart; - blocks[blockIndex] = MathArrays.buildArray(field, iHeight * jWidth); - ++blockIndex; - } - } - - return blocks; - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix createMatrix(final int rowDimension, - final int columnDimension) - throws NotStrictlyPositiveException { - return new BlockFieldMatrix<>(getField(), rowDimension, - columnDimension); - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix copy() { - - // create an empty matrix - BlockFieldMatrix copied = new BlockFieldMatrix<>(getField(), rows, columns); - - // copy the blocks - for (int i = 0; i < blocks.length; ++i) { - System.arraycopy(blocks[i], 0, copied.blocks[i], 0, blocks[i].length); - } - - return copied; - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix add(final FieldMatrix m) - throws MatrixDimensionMismatchException { - try { - return add((BlockFieldMatrix) m); - } catch (ClassCastException cce) { - - // safety check - checkAdditionCompatible(m); - - final BlockFieldMatrix out = new BlockFieldMatrix<>(getField(), rows, columns); - - // perform addition block-wise, to ensure good cache behavior - int blockIndex = 0; - for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) { - for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) { - - // perform addition on the current block - final T[] outBlock = out.blocks[blockIndex]; - final T[] tBlock = blocks[blockIndex]; - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - int k = 0; - for (int p = pStart; p < pEnd; ++p) { - for (int q = qStart; q < qEnd; ++q) { - outBlock[k] = tBlock[k].add(m.getEntry(p, q)); - ++k; - } - } - - // go to next block - ++blockIndex; - - } - } - - return out; - } - } - - /** - * Compute the sum of {@code this} and {@code m}. - * - * @param m matrix to be added - * @return {@code this + m} - * @throws MatrixDimensionMismatchException if {@code m} is not the same - * size as {@code this} - */ - public BlockFieldMatrix add(final BlockFieldMatrix m) - throws MatrixDimensionMismatchException { - - // safety check - checkAdditionCompatible(m); - - final BlockFieldMatrix out = new BlockFieldMatrix<>(getField(), rows, columns); - - // perform addition block-wise, to ensure good cache behavior - for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) { - final T[] outBlock = out.blocks[blockIndex]; - final T[] tBlock = blocks[blockIndex]; - final T[] mBlock = m.blocks[blockIndex]; - for (int k = 0; k < outBlock.length; ++k) { - outBlock[k] = tBlock[k].add(mBlock[k]); - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix subtract(final FieldMatrix m) - throws MatrixDimensionMismatchException { - try { - return subtract((BlockFieldMatrix) m); - } catch (ClassCastException cce) { - - // safety check - checkSubtractionCompatible(m); - - final BlockFieldMatrix out = new BlockFieldMatrix<>(getField(), rows, columns); - - // perform subtraction block-wise, to ensure good cache behavior - int blockIndex = 0; - for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) { - for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) { - - // perform subtraction on the current block - final T[] outBlock = out.blocks[blockIndex]; - final T[] tBlock = blocks[blockIndex]; - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - int k = 0; - for (int p = pStart; p < pEnd; ++p) { - for (int q = qStart; q < qEnd; ++q) { - outBlock[k] = tBlock[k].subtract(m.getEntry(p, q)); - ++k; - } - } - - // go to next block - ++blockIndex; - - } - } - - return out; - } - } - - /** - * Compute {@code this - m}. - * - * @param m matrix to be subtracted - * @return {@code this - m} - * @throws MatrixDimensionMismatchException if {@code m} is not the same - * size as {@code this} - */ - public BlockFieldMatrix subtract(final BlockFieldMatrix m) throws MatrixDimensionMismatchException { - // safety check - checkSubtractionCompatible(m); - - final BlockFieldMatrix out = new BlockFieldMatrix<>(getField(), rows, columns); - - // perform subtraction block-wise, to ensure good cache behavior - for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) { - final T[] outBlock = out.blocks[blockIndex]; - final T[] tBlock = blocks[blockIndex]; - final T[] mBlock = m.blocks[blockIndex]; - for (int k = 0; k < outBlock.length; ++k) { - outBlock[k] = tBlock[k].subtract(mBlock[k]); - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix scalarAdd(final T d) { - final BlockFieldMatrix out = new BlockFieldMatrix<>(getField(), rows, columns); - - // perform subtraction block-wise, to ensure good cache behavior - for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) { - final T[] outBlock = out.blocks[blockIndex]; - final T[] tBlock = blocks[blockIndex]; - for (int k = 0; k < outBlock.length; ++k) { - outBlock[k] = tBlock[k].add(d); - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix scalarMultiply(final T d) { - - final BlockFieldMatrix out = new BlockFieldMatrix<>(getField(), rows, columns); - - // perform subtraction block-wise, to ensure good cache behavior - for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) { - final T[] outBlock = out.blocks[blockIndex]; - final T[] tBlock = blocks[blockIndex]; - for (int k = 0; k < outBlock.length; ++k) { - outBlock[k] = tBlock[k].multiply(d); - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix multiply(final FieldMatrix m) - throws DimensionMismatchException { - try { - return multiply((BlockFieldMatrix) m); - } catch (ClassCastException cce) { - - // safety check - checkMultiplicationCompatible(m); - - final BlockFieldMatrix out = new BlockFieldMatrix<>(getField(), rows, m.getColumnDimension()); - final T zero = getField().getZero(); - - // perform multiplication block-wise, to ensure good cache behavior - int blockIndex = 0; - for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) { - - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - - for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) { - - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, m.getColumnDimension()); - - // select current block - final T[] outBlock = out.blocks[blockIndex]; - - // perform multiplication on current block - for (int kBlock = 0; kBlock < blockColumns; ++kBlock) { - final int kWidth = blockWidth(kBlock); - final T[] tBlock = blocks[iBlock * blockColumns + kBlock]; - final int rStart = kBlock * BLOCK_SIZE; - int k = 0; - for (int p = pStart; p < pEnd; ++p) { - final int lStart = (p - pStart) * kWidth; - final int lEnd = lStart + kWidth; - for (int q = qStart; q < qEnd; ++q) { - T sum = zero; - int r = rStart; - for (int l = lStart; l < lEnd; ++l) { - sum = sum.add(tBlock[l].multiply(m.getEntry(r, q))); - ++r; - } - outBlock[k] = outBlock[k].add(sum); - ++k; - } - } - } - - // go to next block - ++blockIndex; - - } - } - - return out; - } - } - - /** - * Returns the result of postmultiplying {@code this} by {@code m}. - * - * @param m matrix to postmultiply by - * @return {@code this * m} - * @throws DimensionMismatchException if the matrices are not compatible. - */ - public BlockFieldMatrix multiply(BlockFieldMatrix m) - throws DimensionMismatchException { - - // safety check - checkMultiplicationCompatible(m); - - final BlockFieldMatrix out = new BlockFieldMatrix<>(getField(), rows, m.columns); - final T zero = getField().getZero(); - - // perform multiplication block-wise, to ensure good cache behavior - int blockIndex = 0; - for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) { - - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - - for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) { - final int jWidth = out.blockWidth(jBlock); - final int jWidth2 = jWidth + jWidth; - final int jWidth3 = jWidth2 + jWidth; - final int jWidth4 = jWidth3 + jWidth; - - // select current block - final T[] outBlock = out.blocks[blockIndex]; - - // perform multiplication on current block - for (int kBlock = 0; kBlock < blockColumns; ++kBlock) { - final int kWidth = blockWidth(kBlock); - final T[] tBlock = blocks[iBlock * blockColumns + kBlock]; - final T[] mBlock = m.blocks[kBlock * m.blockColumns + jBlock]; - int k = 0; - for (int p = pStart; p < pEnd; ++p) { - final int lStart = (p - pStart) * kWidth; - final int lEnd = lStart + kWidth; - for (int nStart = 0; nStart < jWidth; ++nStart) { - T sum = zero; - int l = lStart; - int n = nStart; - while (l < lEnd - 3) { - sum = sum. - add(tBlock[l].multiply(mBlock[n])). - add(tBlock[l + 1].multiply(mBlock[n + jWidth])). - add(tBlock[l + 2].multiply(mBlock[n + jWidth2])). - add(tBlock[l + 3].multiply(mBlock[n + jWidth3])); - l += 4; - n += jWidth4; - } - while (l < lEnd) { - sum = sum.add(tBlock[l++].multiply(mBlock[n])); - n += jWidth; - } - outBlock[k] = outBlock[k].add(sum); - ++k; - } - } - } - - // go to next block - ++blockIndex; - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public T[][] getData() { - - final T[][] data = MathArrays.buildArray(getField(), getRowDimension(), getColumnDimension()); - final int lastColumns = columns - (blockColumns - 1) * BLOCK_SIZE; - - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - int regularPos = 0; - int lastPos = 0; - for (int p = pStart; p < pEnd; ++p) { - final T[] dataP = data[p]; - int blockIndex = iBlock * blockColumns; - int dataPos = 0; - for (int jBlock = 0; jBlock < blockColumns - 1; ++jBlock) { - System.arraycopy(blocks[blockIndex++], regularPos, dataP, dataPos, BLOCK_SIZE); - dataPos += BLOCK_SIZE; - } - System.arraycopy(blocks[blockIndex], lastPos, dataP, dataPos, lastColumns); - regularPos += BLOCK_SIZE; - lastPos += lastColumns; - } - } - - return data; - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix getSubMatrix(final int startRow, final int endRow, - final int startColumn, - final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - // safety checks - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); - - // create the output matrix - final BlockFieldMatrix out = - new BlockFieldMatrix<>(getField(), endRow - startRow + 1, endColumn - startColumn + 1); - - // compute blocks shifts - final int blockStartRow = startRow / BLOCK_SIZE; - final int rowsShift = startRow % BLOCK_SIZE; - final int blockStartColumn = startColumn / BLOCK_SIZE; - final int columnsShift = startColumn % BLOCK_SIZE; - - // perform extraction block-wise, to ensure good cache behavior - int pBlock = blockStartRow; - for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) { - final int iHeight = out.blockHeight(iBlock); - int qBlock = blockStartColumn; - for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) { - final int jWidth = out.blockWidth(jBlock); - - // handle one block of the output matrix - final int outIndex = iBlock * out.blockColumns + jBlock; - final T[] outBlock = out.blocks[outIndex]; - final int index = pBlock * blockColumns + qBlock; - final int width = blockWidth(qBlock); - - final int heightExcess = iHeight + rowsShift - BLOCK_SIZE; - final int widthExcess = jWidth + columnsShift - BLOCK_SIZE; - if (heightExcess > 0) { - // the submatrix block spans on two blocks rows from the original matrix - if (widthExcess > 0) { - // the submatrix block spans on two blocks columns from the original matrix - final int width2 = blockWidth(qBlock + 1); - copyBlockPart(blocks[index], width, - rowsShift, BLOCK_SIZE, - columnsShift, BLOCK_SIZE, - outBlock, jWidth, 0, 0); - copyBlockPart(blocks[index + 1], width2, - rowsShift, BLOCK_SIZE, - 0, widthExcess, - outBlock, jWidth, 0, jWidth - widthExcess); - copyBlockPart(blocks[index + blockColumns], width, - 0, heightExcess, - columnsShift, BLOCK_SIZE, - outBlock, jWidth, iHeight - heightExcess, 0); - copyBlockPart(blocks[index + blockColumns + 1], width2, - 0, heightExcess, - 0, widthExcess, - outBlock, jWidth, iHeight - heightExcess, jWidth - widthExcess); - } else { - // the submatrix block spans on one block column from the original matrix - copyBlockPart(blocks[index], width, - rowsShift, BLOCK_SIZE, - columnsShift, jWidth + columnsShift, - outBlock, jWidth, 0, 0); - copyBlockPart(blocks[index + blockColumns], width, - 0, heightExcess, - columnsShift, jWidth + columnsShift, - outBlock, jWidth, iHeight - heightExcess, 0); - } - } else { - // the submatrix block spans on one block row from the original matrix - if (widthExcess > 0) { - // the submatrix block spans on two blocks columns from the original matrix - final int width2 = blockWidth(qBlock + 1); - copyBlockPart(blocks[index], width, - rowsShift, iHeight + rowsShift, - columnsShift, BLOCK_SIZE, - outBlock, jWidth, 0, 0); - copyBlockPart(blocks[index + 1], width2, - rowsShift, iHeight + rowsShift, - 0, widthExcess, - outBlock, jWidth, 0, jWidth - widthExcess); - } else { - // the submatrix block spans on one block column from the original matrix - copyBlockPart(blocks[index], width, - rowsShift, iHeight + rowsShift, - columnsShift, jWidth + columnsShift, - outBlock, jWidth, 0, 0); - } - } - ++qBlock; - } - ++pBlock; - } - - return out; - } - - /** - * Copy a part of a block into another one - *

This method can be called only when the specified part fits in both - * blocks, no verification is done here.

- * @param srcBlock source block - * @param srcWidth source block width ({@link #BLOCK_SIZE} or smaller) - * @param srcStartRow start row in the source block - * @param srcEndRow end row (exclusive) in the source block - * @param srcStartColumn start column in the source block - * @param srcEndColumn end column (exclusive) in the source block - * @param dstBlock destination block - * @param dstWidth destination block width ({@link #BLOCK_SIZE} or smaller) - * @param dstStartRow start row in the destination block - * @param dstStartColumn start column in the destination block - */ - private void copyBlockPart(final T[] srcBlock, final int srcWidth, - final int srcStartRow, final int srcEndRow, - final int srcStartColumn, final int srcEndColumn, - final T[] dstBlock, final int dstWidth, - final int dstStartRow, final int dstStartColumn) { - final int length = srcEndColumn - srcStartColumn; - int srcPos = srcStartRow * srcWidth + srcStartColumn; - int dstPos = dstStartRow * dstWidth + dstStartColumn; - for (int srcRow = srcStartRow; srcRow < srcEndRow; ++srcRow) { - System.arraycopy(srcBlock, srcPos, dstBlock, dstPos, length); - srcPos += srcWidth; - dstPos += dstWidth; - } - } - - /** {@inheritDoc} */ - @Override - public void setSubMatrix(final T[][] subMatrix, final int row, - final int column) - throws DimensionMismatchException, OutOfRangeException, - NoDataException, NullArgumentException { - // safety checks - MathUtils.checkNotNull(subMatrix); - final int refLength = subMatrix[0].length; - if (refLength == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN); - } - final int endRow = row + subMatrix.length - 1; - final int endColumn = column + refLength - 1; - checkSubMatrixIndex(row, endRow, column, endColumn); - for (final T[] subRow : subMatrix) { - if (subRow.length != refLength) { - throw new DimensionMismatchException(refLength, subRow.length); - } - } - - // compute blocks bounds - final int blockStartRow = row / BLOCK_SIZE; - final int blockEndRow = (endRow + BLOCK_SIZE) / BLOCK_SIZE; - final int blockStartColumn = column / BLOCK_SIZE; - final int blockEndColumn = (endColumn + BLOCK_SIZE) / BLOCK_SIZE; - - // perform copy block-wise, to ensure good cache behavior - for (int iBlock = blockStartRow; iBlock < blockEndRow; ++iBlock) { - final int iHeight = blockHeight(iBlock); - final int firstRow = iBlock * BLOCK_SIZE; - final int iStart = FastMath.max(row, firstRow); - final int iEnd = FastMath.min(endRow + 1, firstRow + iHeight); - - for (int jBlock = blockStartColumn; jBlock < blockEndColumn; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final int firstColumn = jBlock * BLOCK_SIZE; - final int jStart = FastMath.max(column, firstColumn); - final int jEnd = FastMath.min(endColumn + 1, firstColumn + jWidth); - final int jLength = jEnd - jStart; - - // handle one block, row by row - final T[] block = blocks[iBlock * blockColumns + jBlock]; - for (int i = iStart; i < iEnd; ++i) { - System.arraycopy(subMatrix[i - row], jStart - column, - block, (i - firstRow) * jWidth + (jStart - firstColumn), - jLength); - } - - } - } - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix getRowMatrix(final int row) - throws OutOfRangeException { - checkRowIndex(row); - final BlockFieldMatrix out = new BlockFieldMatrix<>(getField(), 1, columns); - - // perform copy block-wise, to ensure good cache behavior - final int iBlock = row / BLOCK_SIZE; - final int iRow = row - iBlock * BLOCK_SIZE; - int outBlockIndex = 0; - int outIndex = 0; - T[] outBlock = out.blocks[outBlockIndex]; - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final T[] block = blocks[iBlock * blockColumns + jBlock]; - final int available = outBlock.length - outIndex; - if (jWidth > available) { - System.arraycopy(block, iRow * jWidth, outBlock, outIndex, available); - outBlock = out.blocks[++outBlockIndex]; - System.arraycopy(block, iRow * jWidth, outBlock, 0, jWidth - available); - outIndex = jWidth - available; - } else { - System.arraycopy(block, iRow * jWidth, outBlock, outIndex, jWidth); - outIndex += jWidth; - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public void setRowMatrix(final int row, final FieldMatrix matrix) - throws MatrixDimensionMismatchException, OutOfRangeException { - try { - setRowMatrix(row, (BlockFieldMatrix) matrix); - } catch (ClassCastException cce) { - super.setRowMatrix(row, matrix); - } - } - - /** - * Sets the entries in row number row - * as a row matrix. Row indices start at 0. - * - * @param row the row to be set - * @param matrix row matrix (must have one row and the same number of columns - * as the instance) - * @throws MatrixDimensionMismatchException if the matrix dimensions do - * not match one instance row. - * @throws OutOfRangeException if the specified row index is invalid. - */ - public void setRowMatrix(final int row, final BlockFieldMatrix matrix) - throws MatrixDimensionMismatchException, OutOfRangeException { - checkRowIndex(row); - final int nCols = getColumnDimension(); - if ((matrix.getRowDimension() != 1) || - (matrix.getColumnDimension() != nCols)) { - throw new MatrixDimensionMismatchException(matrix.getRowDimension(), - matrix.getColumnDimension(), - 1, nCols); - } - - // perform copy block-wise, to ensure good cache behavior - final int iBlock = row / BLOCK_SIZE; - final int iRow = row - iBlock * BLOCK_SIZE; - int mBlockIndex = 0; - int mIndex = 0; - T[] mBlock = matrix.blocks[mBlockIndex]; - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final T[] block = blocks[iBlock * blockColumns + jBlock]; - final int available = mBlock.length - mIndex; - if (jWidth > available) { - System.arraycopy(mBlock, mIndex, block, iRow * jWidth, available); - mBlock = matrix.blocks[++mBlockIndex]; - System.arraycopy(mBlock, 0, block, iRow * jWidth, jWidth - available); - mIndex = jWidth - available; - } else { - System.arraycopy(mBlock, mIndex, block, iRow * jWidth, jWidth); - mIndex += jWidth; - } - } - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix getColumnMatrix(final int column) - throws OutOfRangeException { - checkColumnIndex(column); - final BlockFieldMatrix out = new BlockFieldMatrix<>(getField(), rows, 1); - - // perform copy block-wise, to ensure good cache behavior - final int jBlock = column / BLOCK_SIZE; - final int jColumn = column - jBlock * BLOCK_SIZE; - final int jWidth = blockWidth(jBlock); - int outBlockIndex = 0; - int outIndex = 0; - T[] outBlock = out.blocks[outBlockIndex]; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int iHeight = blockHeight(iBlock); - final T[] block = blocks[iBlock * blockColumns + jBlock]; - for (int i = 0; i < iHeight; ++i) { - if (outIndex >= outBlock.length) { - outBlock = out.blocks[++outBlockIndex]; - outIndex = 0; - } - outBlock[outIndex++] = block[i * jWidth + jColumn]; - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public void setColumnMatrix(final int column, final FieldMatrix matrix) - throws MatrixDimensionMismatchException, OutOfRangeException { - try { - setColumnMatrix(column, (BlockFieldMatrix) matrix); - } catch (ClassCastException cce) { - super.setColumnMatrix(column, matrix); - } - } - - /** - * Sets the entries in column number {@code column} - * as a column matrix. Column indices start at 0. - * - * @param column Column to be set. - * @param matrix Column matrix (must have one column and the same number of rows - * as the instance). - * @throws MatrixDimensionMismatchException if the matrix dimensions do - * not match one instance column. - * @throws OutOfRangeException if the specified column index is invalid. - */ - void setColumnMatrix(final int column, final BlockFieldMatrix matrix) - throws MatrixDimensionMismatchException, OutOfRangeException { - checkColumnIndex(column); - final int nRows = getRowDimension(); - if ((matrix.getRowDimension() != nRows) || - (matrix.getColumnDimension() != 1)) { - throw new MatrixDimensionMismatchException(matrix.getRowDimension(), - matrix.getColumnDimension(), - nRows, 1); - } - - // perform copy block-wise, to ensure good cache behavior - final int jBlock = column / BLOCK_SIZE; - final int jColumn = column - jBlock * BLOCK_SIZE; - final int jWidth = blockWidth(jBlock); - int mBlockIndex = 0; - int mIndex = 0; - T[] mBlock = matrix.blocks[mBlockIndex]; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int iHeight = blockHeight(iBlock); - final T[] block = blocks[iBlock * blockColumns + jBlock]; - for (int i = 0; i < iHeight; ++i) { - if (mIndex >= mBlock.length) { - mBlock = matrix.blocks[++mBlockIndex]; - mIndex = 0; - } - block[i * jWidth + jColumn] = mBlock[mIndex++]; - } - } - } - - /** {@inheritDoc} */ - @Override - public FieldVector getRowVector(final int row) - throws OutOfRangeException { - checkRowIndex(row); - final T[] outData = MathArrays.buildArray(getField(), columns); - - // perform copy block-wise, to ensure good cache behavior - final int iBlock = row / BLOCK_SIZE; - final int iRow = row - iBlock * BLOCK_SIZE; - int outIndex = 0; - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final T[] block = blocks[iBlock * blockColumns + jBlock]; - System.arraycopy(block, iRow * jWidth, outData, outIndex, jWidth); - outIndex += jWidth; - } - - return new ArrayFieldVector<>(getField(), outData, false); - } - - /** {@inheritDoc} */ - @Override - public void setRowVector(final int row, final FieldVector vector) - throws MatrixDimensionMismatchException, OutOfRangeException { - try { - setRow(row, ((ArrayFieldVector) vector).getDataRef()); - } catch (ClassCastException cce) { - super.setRowVector(row, vector); - } - } - - /** {@inheritDoc} */ - @Override - public FieldVector getColumnVector(final int column) - throws OutOfRangeException { - checkColumnIndex(column); - final T[] outData = MathArrays.buildArray(getField(), rows); - - // perform copy block-wise, to ensure good cache behavior - final int jBlock = column / BLOCK_SIZE; - final int jColumn = column - jBlock * BLOCK_SIZE; - final int jWidth = blockWidth(jBlock); - int outIndex = 0; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int iHeight = blockHeight(iBlock); - final T[] block = blocks[iBlock * blockColumns + jBlock]; - for (int i = 0; i < iHeight; ++i) { - outData[outIndex++] = block[i * jWidth + jColumn]; - } - } - - return new ArrayFieldVector<>(getField(), outData, false); - } - - /** {@inheritDoc} */ - @Override - public void setColumnVector(final int column, final FieldVector vector) - throws OutOfRangeException, MatrixDimensionMismatchException { - try { - setColumn(column, ((ArrayFieldVector) vector).getDataRef()); - } catch (ClassCastException cce) { - super.setColumnVector(column, vector); - } - } - - /** {@inheritDoc} */ - @Override - public T[] getRow(final int row) throws OutOfRangeException { - checkRowIndex(row); - final T[] out = MathArrays.buildArray(getField(), columns); - - // perform copy block-wise, to ensure good cache behavior - final int iBlock = row / BLOCK_SIZE; - final int iRow = row - iBlock * BLOCK_SIZE; - int outIndex = 0; - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final T[] block = blocks[iBlock * blockColumns + jBlock]; - System.arraycopy(block, iRow * jWidth, out, outIndex, jWidth); - outIndex += jWidth; - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public void setRow(final int row, final T[] array) - throws OutOfRangeException, MatrixDimensionMismatchException { - checkRowIndex(row); - final int nCols = getColumnDimension(); - if (array.length != nCols) { - throw new MatrixDimensionMismatchException(1, array.length, 1, nCols); - } - - // perform copy block-wise, to ensure good cache behavior - final int iBlock = row / BLOCK_SIZE; - final int iRow = row - iBlock * BLOCK_SIZE; - int outIndex = 0; - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final T[] block = blocks[iBlock * blockColumns + jBlock]; - System.arraycopy(array, outIndex, block, iRow * jWidth, jWidth); - outIndex += jWidth; - } - } - - /** {@inheritDoc} */ - @Override - public T[] getColumn(final int column) throws OutOfRangeException { - checkColumnIndex(column); - final T[] out = MathArrays.buildArray(getField(), rows); - - // perform copy block-wise, to ensure good cache behavior - final int jBlock = column / BLOCK_SIZE; - final int jColumn = column - jBlock * BLOCK_SIZE; - final int jWidth = blockWidth(jBlock); - int outIndex = 0; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int iHeight = blockHeight(iBlock); - final T[] block = blocks[iBlock * blockColumns + jBlock]; - for (int i = 0; i < iHeight; ++i) { - out[outIndex++] = block[i * jWidth + jColumn]; - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public void setColumn(final int column, final T[] array) - throws MatrixDimensionMismatchException, OutOfRangeException { - checkColumnIndex(column); - final int nRows = getRowDimension(); - if (array.length != nRows) { - throw new MatrixDimensionMismatchException(array.length, 1, nRows, 1); - } - - // perform copy block-wise, to ensure good cache behavior - final int jBlock = column / BLOCK_SIZE; - final int jColumn = column - jBlock * BLOCK_SIZE; - final int jWidth = blockWidth(jBlock); - int outIndex = 0; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int iHeight = blockHeight(iBlock); - final T[] block = blocks[iBlock * blockColumns + jBlock]; - for (int i = 0; i < iHeight; ++i) { - block[i * jWidth + jColumn] = array[outIndex++]; - } - } - } - - /** {@inheritDoc} */ - @Override - public T getEntry(final int row, final int column) - throws OutOfRangeException { - checkRowIndex(row); - checkColumnIndex(column); - - final int iBlock = row / BLOCK_SIZE; - final int jBlock = column / BLOCK_SIZE; - final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) + - (column - jBlock * BLOCK_SIZE); - - return blocks[iBlock * blockColumns + jBlock][k]; - } - - /** {@inheritDoc} */ - @Override - public void setEntry(final int row, final int column, final T value) - throws OutOfRangeException { - checkRowIndex(row); - checkColumnIndex(column); - - final int iBlock = row / BLOCK_SIZE; - final int jBlock = column / BLOCK_SIZE; - final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) + - (column - jBlock * BLOCK_SIZE); - - blocks[iBlock * blockColumns + jBlock][k] = value; - } - - /** {@inheritDoc} */ - @Override - public void addToEntry(final int row, final int column, final T increment) - throws OutOfRangeException { - checkRowIndex(row); - checkColumnIndex(column); - - final int iBlock = row / BLOCK_SIZE; - final int jBlock = column / BLOCK_SIZE; - final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) + - (column - jBlock * BLOCK_SIZE); - final T[] blockIJ = blocks[iBlock * blockColumns + jBlock]; - - blockIJ[k] = blockIJ[k].add(increment); - } - - /** {@inheritDoc} */ - @Override - public void multiplyEntry(final int row, final int column, final T factor) - throws OutOfRangeException { - checkRowIndex(row); - checkColumnIndex(column); - - final int iBlock = row / BLOCK_SIZE; - final int jBlock = column / BLOCK_SIZE; - final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) + - (column - jBlock * BLOCK_SIZE); - final T[] blockIJ = blocks[iBlock * blockColumns + jBlock]; - - blockIJ[k] = blockIJ[k].multiply(factor); - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix transpose() { - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - final BlockFieldMatrix out = new BlockFieldMatrix<>(getField(), nCols, nRows); - - // perform transpose block-wise, to ensure good cache behavior - int blockIndex = 0; - for (int iBlock = 0; iBlock < blockColumns; ++iBlock) { - for (int jBlock = 0; jBlock < blockRows; ++jBlock) { - - // transpose current block - final T[] outBlock = out.blocks[blockIndex]; - final T[] tBlock = blocks[jBlock * blockColumns + iBlock]; - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, columns); - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, rows); - int k = 0; - for (int p = pStart; p < pEnd; ++p) { - final int lInc = pEnd - pStart; - int l = p - pStart; - for (int q = qStart; q < qEnd; ++q) { - outBlock[k] = tBlock[l]; - ++k; - l+= lInc; - } - } - - // go to next block - ++blockIndex; - - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public int getRowDimension() { - return rows; - } - - /** {@inheritDoc} */ - @Override - public int getColumnDimension() { - return columns; - } - - /** {@inheritDoc} */ - @Override - public T[] operate(final T[] v) throws DimensionMismatchException { - if (v.length != columns) { - throw new DimensionMismatchException(v.length, columns); - } - final T[] out = MathArrays.buildArray(getField(), rows); - final T zero = getField().getZero(); - - // perform multiplication block-wise, to ensure good cache behavior - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final T[] block = blocks[iBlock * blockColumns + jBlock]; - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - int k = 0; - for (int p = pStart; p < pEnd; ++p) { - T sum = zero; - int q = qStart; - while (q < qEnd - 3) { - sum = sum. - add(block[k].multiply(v[q])). - add(block[k + 1].multiply(v[q + 1])). - add(block[k + 2].multiply(v[q + 2])). - add(block[k + 3].multiply(v[q + 3])); - k += 4; - q += 4; - } - while (q < qEnd) { - sum = sum.add(block[k++].multiply(v[q++])); - } - out[p] = out[p].add(sum); - } - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public T[] preMultiply(final T[] v) throws DimensionMismatchException { - - if (v.length != rows) { - throw new DimensionMismatchException(v.length, rows); - } - final T[] out = MathArrays.buildArray(getField(), columns); - final T zero = getField().getZero(); - - // perform multiplication block-wise, to ensure good cache behavior - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final int jWidth2 = jWidth + jWidth; - final int jWidth3 = jWidth2 + jWidth; - final int jWidth4 = jWidth3 + jWidth; - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final T[] block = blocks[iBlock * blockColumns + jBlock]; - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - for (int q = qStart; q < qEnd; ++q) { - int k = q - qStart; - T sum = zero; - int p = pStart; - while (p < pEnd - 3) { - sum = sum. - add(block[k].multiply(v[p])). - add(block[k + jWidth].multiply(v[p + 1])). - add(block[k + jWidth2].multiply(v[p + 2])). - add(block[k + jWidth3].multiply(v[p + 3])); - k += jWidth4; - p += 4; - } - while (p < pEnd) { - sum = sum.add(block[k].multiply(v[p++])); - k += jWidth; - } - out[q] = out[q].add(sum); - } - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public T walkInRowOrder(final FieldMatrixChangingVisitor visitor) { - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - for (int p = pStart; p < pEnd; ++p) { - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - final T[] block = blocks[iBlock * blockColumns + jBlock]; - int k = (p - pStart) * jWidth; - for (int q = qStart; q < qEnd; ++q) { - block[k] = visitor.visit(p, q, block[k]); - ++k; - } - } - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInRowOrder(final FieldMatrixPreservingVisitor visitor) { - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - for (int p = pStart; p < pEnd; ++p) { - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - final T[] block = blocks[iBlock * blockColumns + jBlock]; - int k = (p - pStart) * jWidth; - for (int q = qStart; q < qEnd; ++q) { - visitor.visit(p, q, block[k]); - ++k; - } - } - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInRowOrder(final FieldMatrixChangingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); - visitor.start(rows, columns, startRow, endRow, startColumn, endColumn); - for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) { - final int p0 = iBlock * BLOCK_SIZE; - final int pStart = FastMath.max(startRow, p0); - final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow); - for (int p = pStart; p < pEnd; ++p) { - for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final int q0 = jBlock * BLOCK_SIZE; - final int qStart = FastMath.max(startColumn, q0); - final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn); - final T[] block = blocks[iBlock * blockColumns + jBlock]; - int k = (p - p0) * jWidth + qStart - q0; - for (int q = qStart; q < qEnd; ++q) { - block[k] = visitor.visit(p, q, block[k]); - ++k; - } - } - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInRowOrder(final FieldMatrixPreservingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); - visitor.start(rows, columns, startRow, endRow, startColumn, endColumn); - for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) { - final int p0 = iBlock * BLOCK_SIZE; - final int pStart = FastMath.max(startRow, p0); - final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow); - for (int p = pStart; p < pEnd; ++p) { - for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final int q0 = jBlock * BLOCK_SIZE; - final int qStart = FastMath.max(startColumn, q0); - final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn); - final T[] block = blocks[iBlock * blockColumns + jBlock]; - int k = (p - p0) * jWidth + qStart - q0; - for (int q = qStart; q < qEnd; ++q) { - visitor.visit(p, q, block[k]); - ++k; - } - } - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInOptimizedOrder(final FieldMatrixChangingVisitor visitor) { - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - int blockIndex = 0; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - final T[] block = blocks[blockIndex]; - int k = 0; - for (int p = pStart; p < pEnd; ++p) { - for (int q = qStart; q < qEnd; ++q) { - block[k] = visitor.visit(p, q, block[k]); - ++k; - } - } - ++blockIndex; - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInOptimizedOrder(final FieldMatrixPreservingVisitor visitor) { - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - int blockIndex = 0; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - final T[] block = blocks[blockIndex]; - int k = 0; - for (int p = pStart; p < pEnd; ++p) { - for (int q = qStart; q < qEnd; ++q) { - visitor.visit(p, q, block[k]); - ++k; - } - } - ++blockIndex; - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInOptimizedOrder(final FieldMatrixChangingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); - visitor.start(rows, columns, startRow, endRow, startColumn, endColumn); - for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) { - final int p0 = iBlock * BLOCK_SIZE; - final int pStart = FastMath.max(startRow, p0); - final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow); - for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final int q0 = jBlock * BLOCK_SIZE; - final int qStart = FastMath.max(startColumn, q0); - final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn); - final T[] block = blocks[iBlock * blockColumns + jBlock]; - for (int p = pStart; p < pEnd; ++p) { - int k = (p - p0) * jWidth + qStart - q0; - for (int q = qStart; q < qEnd; ++q) { - block[k] = visitor.visit(p, q, block[k]); - ++k; - } - } - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public T walkInOptimizedOrder(final FieldMatrixPreservingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - checkSubMatrixIndex(startRow, endRow, startColumn, endColumn); - visitor.start(rows, columns, startRow, endRow, startColumn, endColumn); - for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) { - final int p0 = iBlock * BLOCK_SIZE; - final int pStart = FastMath.max(startRow, p0); - final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow); - for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final int q0 = jBlock * BLOCK_SIZE; - final int qStart = FastMath.max(startColumn, q0); - final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn); - final T[] block = blocks[iBlock * blockColumns + jBlock]; - for (int p = pStart; p < pEnd; ++p) { - int k = (p - p0) * jWidth + qStart - q0; - for (int q = qStart; q < qEnd; ++q) { - visitor.visit(p, q, block[k]); - ++k; - } - } - } - } - return visitor.end(); - } - - /** - * Get the height of a block. - * @param blockRow row index (in block sense) of the block - * @return height (number of rows) of the block - */ - private int blockHeight(final int blockRow) { - return (blockRow == blockRows - 1) ? rows - blockRow * BLOCK_SIZE : BLOCK_SIZE; - } - - /** - * Get the width of a block. - * @param blockColumn column index (in block sense) of the block - * @return width (number of columns) of the block - */ - private int blockWidth(final int blockColumn) { - return (blockColumn == blockColumns - 1) ? columns - blockColumn * BLOCK_SIZE : BLOCK_SIZE; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/BlockRealMatrix.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/BlockRealMatrix.java deleted file mode 100644 index 20192aded..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/BlockRealMatrix.java +++ /dev/null @@ -1,1580 +0,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. - */ - -package org.apache.commons.math4.linear; - -import java.io.Serializable; -import java.util.Arrays; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathUtils; - -/** - * Cache-friendly implementation of RealMatrix using a flat arrays to store - * square blocks of the matrix. - *

- * This implementation is specially designed to be cache-friendly. Square blocks are - * stored as small arrays and allow efficient traversal of data both in row major direction - * and columns major direction, one block at a time. This greatly increases performances - * for algorithms that use crossed directions loops like multiplication or transposition. - *

- *

- * The size of square blocks is a static parameter. It may be tuned according to the cache - * size of the target computer processor. As a rule of thumbs, it should be the largest - * value that allows three blocks to be simultaneously cached (this is necessary for example - * for matrix multiplication). The default value is to use 52x52 blocks which is well suited - * for processors with 64k L1 cache (one block holds 2704 values or 21632 bytes). This value - * could be lowered to 36x36 for processors with 32k L1 cache. - *

- *

- * The regular blocks represent {@link #BLOCK_SIZE} x {@link #BLOCK_SIZE} squares. Blocks - * at right hand side and bottom side which may be smaller to fit matrix dimensions. The square - * blocks are flattened in row major order in single dimension arrays which are therefore - * {@link #BLOCK_SIZE}2 elements long for regular blocks. The blocks are themselves - * organized in row major order. - *

- *

- * As an example, for a block size of 52x52, a 100x60 matrix would be stored in 4 blocks. - * Block 0 would be a double[2704] array holding the upper left 52x52 square, block 1 would be - * a double[416] array holding the upper right 52x8 rectangle, block 2 would be a double[2496] - * array holding the lower left 48x52 rectangle and block 3 would be a double[384] array - * holding the lower right 48x8 rectangle. - *

- *

- * The layout complexity overhead versus simple mapping of matrices to java - * arrays is negligible for small matrices (about 1%). The gain from cache efficiency leads - * to up to 3-fold improvements for matrices of moderate to large size. - *

- * @since 2.0 - */ -public class BlockRealMatrix extends AbstractRealMatrix implements Serializable { - /** Block size. */ - public static final int BLOCK_SIZE = 52; - /** Serializable version identifier */ - private static final long serialVersionUID = 4991895511313664478L; - /** Blocks of matrix entries. */ - private final double blocks[][]; - /** Number of rows of the matrix. */ - private final int rows; - /** Number of columns of the matrix. */ - private final int columns; - /** Number of block rows of the matrix. */ - private final int blockRows; - /** Number of block columns of the matrix. */ - private final int blockColumns; - - /** - * Create a new matrix with the supplied row and column dimensions. - * - * @param rows the number of rows in the new matrix - * @param columns the number of columns in the new matrix - * @throws NotStrictlyPositiveException if row or column dimension is not - * positive. - */ - public BlockRealMatrix(final int rows, final int columns) - throws NotStrictlyPositiveException { - super(rows, columns); - this.rows = rows; - this.columns = columns; - - // number of blocks - blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE; - blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE; - - // allocate storage blocks, taking care of smaller ones at right and bottom - blocks = createBlocksLayout(rows, columns); - } - - /** - * Create a new dense matrix copying entries from raw layout data. - *

The input array must already be in raw layout.

- *

Calling this constructor is equivalent to call: - *

matrix = new BlockRealMatrix(rawData.length, rawData[0].length,
-     *                                   toBlocksLayout(rawData), false);
- * - * @param rawData data for new matrix, in raw layout - * @throws DimensionMismatchException if the shape of {@code blockData} is - * inconsistent with block layout. - * @throws NotStrictlyPositiveException if row or column dimension is not - * positive. - * @see #BlockRealMatrix(int, int, double[][], boolean) - */ - public BlockRealMatrix(final double[][] rawData) - throws DimensionMismatchException, NotStrictlyPositiveException { - this(rawData.length, rawData[0].length, toBlocksLayout(rawData), false); - } - - /** - * Create a new dense matrix copying entries from block layout data. - *

The input array must already be in blocks layout.

- * - * @param rows Number of rows in the new matrix. - * @param columns Number of columns in the new matrix. - * @param blockData data for new matrix - * @param copyArray Whether the input array will be copied or referenced. - * @throws DimensionMismatchException if the shape of {@code blockData} is - * inconsistent with block layout. - * @throws NotStrictlyPositiveException if row or column dimension is not - * positive. - * @see #createBlocksLayout(int, int) - * @see #toBlocksLayout(double[][]) - * @see #BlockRealMatrix(double[][]) - */ - public BlockRealMatrix(final int rows, final int columns, - final double[][] blockData, final boolean copyArray) - throws DimensionMismatchException, NotStrictlyPositiveException { - super(rows, columns); - this.rows = rows; - this.columns = columns; - - // number of blocks - blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE; - blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE; - - if (copyArray) { - // allocate storage blocks, taking care of smaller ones at right and bottom - blocks = new double[blockRows * blockColumns][]; - } else { - // reference existing array - blocks = blockData; - } - - int index = 0; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int iHeight = blockHeight(iBlock); - for (int jBlock = 0; jBlock < blockColumns; ++jBlock, ++index) { - if (blockData[index].length != iHeight * blockWidth(jBlock)) { - throw new DimensionMismatchException(blockData[index].length, - iHeight * blockWidth(jBlock)); - } - if (copyArray) { - blocks[index] = blockData[index].clone(); - } - } - } - } - - /** - * Convert a data array from raw layout to blocks layout. - *

- * Raw layout is the straightforward layout where element at row i and - * column j is in array element rawData[i][j]. Blocks layout - * is the layout used in {@link BlockRealMatrix} instances, where the matrix - * is split in square blocks (except at right and bottom side where blocks may - * be rectangular to fit matrix size) and each block is stored in a flattened - * one-dimensional array. - *

- *

- * This method creates an array in blocks layout from an input array in raw layout. - * It can be used to provide the array argument of the {@link - * #BlockRealMatrix(int, int, double[][], boolean)} constructor. - *

- * @param rawData Data array in raw layout. - * @return a new data array containing the same entries but in blocks layout. - * @throws DimensionMismatchException if {@code rawData} is not rectangular. - * @see #createBlocksLayout(int, int) - * @see #BlockRealMatrix(int, int, double[][], boolean) - */ - public static double[][] toBlocksLayout(final double[][] rawData) - throws DimensionMismatchException { - final int rows = rawData.length; - final int columns = rawData[0].length; - final int blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE; - final int blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE; - - // safety checks - for (int i = 0; i < rawData.length; ++i) { - final int length = rawData[i].length; - if (length != columns) { - throw new DimensionMismatchException(columns, length); - } - } - - // convert array - final double[][] blocks = new double[blockRows * blockColumns][]; - int blockIndex = 0; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - final int iHeight = pEnd - pStart; - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - final int jWidth = qEnd - qStart; - - // allocate new block - final double[] block = new double[iHeight * jWidth]; - blocks[blockIndex] = block; - - // copy data - int index = 0; - for (int p = pStart; p < pEnd; ++p) { - System.arraycopy(rawData[p], qStart, block, index, jWidth); - index += jWidth; - } - ++blockIndex; - } - } - - return blocks; - } - - /** - * Create a data array in blocks layout. - *

- * This method can be used to create the array argument of the {@link - * #BlockRealMatrix(int, int, double[][], boolean)} constructor. - *

- * @param rows Number of rows in the new matrix. - * @param columns Number of columns in the new matrix. - * @return a new data array in blocks layout. - * @see #toBlocksLayout(double[][]) - * @see #BlockRealMatrix(int, int, double[][], boolean) - */ - public static double[][] createBlocksLayout(final int rows, final int columns) { - final int blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE; - final int blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE; - - final double[][] blocks = new double[blockRows * blockColumns][]; - int blockIndex = 0; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - final int iHeight = pEnd - pStart; - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - final int jWidth = qEnd - qStart; - blocks[blockIndex] = new double[iHeight * jWidth]; - ++blockIndex; - } - } - - return blocks; - } - - /** {@inheritDoc} */ - @Override - public BlockRealMatrix createMatrix(final int rowDimension, - final int columnDimension) - throws NotStrictlyPositiveException { - return new BlockRealMatrix(rowDimension, columnDimension); - } - - /** {@inheritDoc} */ - @Override - public BlockRealMatrix copy() { - // create an empty matrix - BlockRealMatrix copied = new BlockRealMatrix(rows, columns); - - // copy the blocks - for (int i = 0; i < blocks.length; ++i) { - System.arraycopy(blocks[i], 0, copied.blocks[i], 0, blocks[i].length); - } - - return copied; - } - - /** {@inheritDoc} */ - @Override - public BlockRealMatrix add(final RealMatrix m) - throws MatrixDimensionMismatchException { - try { - return add((BlockRealMatrix) m); - } catch (ClassCastException cce) { - // safety check - MatrixUtils.checkAdditionCompatible(this, m); - - final BlockRealMatrix out = new BlockRealMatrix(rows, columns); - - // perform addition block-wise, to ensure good cache behavior - int blockIndex = 0; - for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) { - for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) { - - // perform addition on the current block - final double[] outBlock = out.blocks[blockIndex]; - final double[] tBlock = blocks[blockIndex]; - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - int k = 0; - for (int p = pStart; p < pEnd; ++p) { - for (int q = qStart; q < qEnd; ++q) { - outBlock[k] = tBlock[k] + m.getEntry(p, q); - ++k; - } - } - // go to next block - ++blockIndex; - } - } - - return out; - } - } - - /** - * Compute the sum of this matrix and {@code m}. - * - * @param m Matrix to be added. - * @return {@code this} + m. - * @throws MatrixDimensionMismatchException if {@code m} is not the same - * size as this matrix. - */ - public BlockRealMatrix add(final BlockRealMatrix m) - throws MatrixDimensionMismatchException { - // safety check - MatrixUtils.checkAdditionCompatible(this, m); - - final BlockRealMatrix out = new BlockRealMatrix(rows, columns); - - // perform addition block-wise, to ensure good cache behavior - for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) { - final double[] outBlock = out.blocks[blockIndex]; - final double[] tBlock = blocks[blockIndex]; - final double[] mBlock = m.blocks[blockIndex]; - for (int k = 0; k < outBlock.length; ++k) { - outBlock[k] = tBlock[k] + mBlock[k]; - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public BlockRealMatrix subtract(final RealMatrix m) - throws MatrixDimensionMismatchException { - try { - return subtract((BlockRealMatrix) m); - } catch (ClassCastException cce) { - // safety check - MatrixUtils.checkSubtractionCompatible(this, m); - - final BlockRealMatrix out = new BlockRealMatrix(rows, columns); - - // perform subtraction block-wise, to ensure good cache behavior - int blockIndex = 0; - for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) { - for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) { - - // perform subtraction on the current block - final double[] outBlock = out.blocks[blockIndex]; - final double[] tBlock = blocks[blockIndex]; - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - int k = 0; - for (int p = pStart; p < pEnd; ++p) { - for (int q = qStart; q < qEnd; ++q) { - outBlock[k] = tBlock[k] - m.getEntry(p, q); - ++k; - } - } - // go to next block - ++blockIndex; - } - } - - return out; - } - } - - /** - * Subtract {@code m} from this matrix. - * - * @param m Matrix to be subtracted. - * @return {@code this} - m. - * @throws MatrixDimensionMismatchException if {@code m} is not the - * same size as this matrix. - */ - public BlockRealMatrix subtract(final BlockRealMatrix m) - throws MatrixDimensionMismatchException { - // safety check - MatrixUtils.checkSubtractionCompatible(this, m); - - final BlockRealMatrix out = new BlockRealMatrix(rows, columns); - - // perform subtraction block-wise, to ensure good cache behavior - for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) { - final double[] outBlock = out.blocks[blockIndex]; - final double[] tBlock = blocks[blockIndex]; - final double[] mBlock = m.blocks[blockIndex]; - for (int k = 0; k < outBlock.length; ++k) { - outBlock[k] = tBlock[k] - mBlock[k]; - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public BlockRealMatrix scalarAdd(final double d) { - - final BlockRealMatrix out = new BlockRealMatrix(rows, columns); - - // perform subtraction block-wise, to ensure good cache behavior - for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) { - final double[] outBlock = out.blocks[blockIndex]; - final double[] tBlock = blocks[blockIndex]; - for (int k = 0; k < outBlock.length; ++k) { - outBlock[k] = tBlock[k] + d; - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public RealMatrix scalarMultiply(final double d) { - final BlockRealMatrix out = new BlockRealMatrix(rows, columns); - - // perform subtraction block-wise, to ensure good cache behavior - for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) { - final double[] outBlock = out.blocks[blockIndex]; - final double[] tBlock = blocks[blockIndex]; - for (int k = 0; k < outBlock.length; ++k) { - outBlock[k] = tBlock[k] * d; - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public BlockRealMatrix multiply(final RealMatrix m) - throws DimensionMismatchException { - try { - return multiply((BlockRealMatrix) m); - } catch (ClassCastException cce) { - // safety check - MatrixUtils.checkMultiplicationCompatible(this, m); - - final BlockRealMatrix out = new BlockRealMatrix(rows, m.getColumnDimension()); - - // perform multiplication block-wise, to ensure good cache behavior - int blockIndex = 0; - for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) { - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - - for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) { - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, m.getColumnDimension()); - - // select current block - final double[] outBlock = out.blocks[blockIndex]; - - // perform multiplication on current block - for (int kBlock = 0; kBlock < blockColumns; ++kBlock) { - final int kWidth = blockWidth(kBlock); - final double[] tBlock = blocks[iBlock * blockColumns + kBlock]; - final int rStart = kBlock * BLOCK_SIZE; - int k = 0; - for (int p = pStart; p < pEnd; ++p) { - final int lStart = (p - pStart) * kWidth; - final int lEnd = lStart + kWidth; - for (int q = qStart; q < qEnd; ++q) { - double sum = 0; - int r = rStart; - for (int l = lStart; l < lEnd; ++l) { - sum += tBlock[l] * m.getEntry(r, q); - ++r; - } - outBlock[k] += sum; - ++k; - } - } - } - // go to next block - ++blockIndex; - } - } - - return out; - } - } - - /** - * Returns the result of postmultiplying this by {@code m}. - * - * @param m Matrix to postmultiply by. - * @return {@code this} * m. - * @throws DimensionMismatchException if the matrices are not compatible. - */ - public BlockRealMatrix multiply(BlockRealMatrix m) - throws DimensionMismatchException { - // safety check - MatrixUtils.checkMultiplicationCompatible(this, m); - - final BlockRealMatrix out = new BlockRealMatrix(rows, m.columns); - - // perform multiplication block-wise, to ensure good cache behavior - int blockIndex = 0; - for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) { - - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - - for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) { - final int jWidth = out.blockWidth(jBlock); - final int jWidth2 = jWidth + jWidth; - final int jWidth3 = jWidth2 + jWidth; - final int jWidth4 = jWidth3 + jWidth; - - // select current block - final double[] outBlock = out.blocks[blockIndex]; - - // perform multiplication on current block - for (int kBlock = 0; kBlock < blockColumns; ++kBlock) { - final int kWidth = blockWidth(kBlock); - final double[] tBlock = blocks[iBlock * blockColumns + kBlock]; - final double[] mBlock = m.blocks[kBlock * m.blockColumns + jBlock]; - int k = 0; - for (int p = pStart; p < pEnd; ++p) { - final int lStart = (p - pStart) * kWidth; - final int lEnd = lStart + kWidth; - for (int nStart = 0; nStart < jWidth; ++nStart) { - double sum = 0; - int l = lStart; - int n = nStart; - while (l < lEnd - 3) { - sum += tBlock[l] * mBlock[n] + - tBlock[l + 1] * mBlock[n + jWidth] + - tBlock[l + 2] * mBlock[n + jWidth2] + - tBlock[l + 3] * mBlock[n + jWidth3]; - l += 4; - n += jWidth4; - } - while (l < lEnd) { - sum += tBlock[l++] * mBlock[n]; - n += jWidth; - } - outBlock[k] += sum; - ++k; - } - } - } - // go to next block - ++blockIndex; - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public double[][] getData() { - final double[][] data = new double[getRowDimension()][getColumnDimension()]; - final int lastColumns = columns - (blockColumns - 1) * BLOCK_SIZE; - - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - int regularPos = 0; - int lastPos = 0; - for (int p = pStart; p < pEnd; ++p) { - final double[] dataP = data[p]; - int blockIndex = iBlock * blockColumns; - int dataPos = 0; - for (int jBlock = 0; jBlock < blockColumns - 1; ++jBlock) { - System.arraycopy(blocks[blockIndex++], regularPos, dataP, dataPos, BLOCK_SIZE); - dataPos += BLOCK_SIZE; - } - System.arraycopy(blocks[blockIndex], lastPos, dataP, dataPos, lastColumns); - regularPos += BLOCK_SIZE; - lastPos += lastColumns; - } - } - - return data; - } - - /** {@inheritDoc} */ - @Override - public double getNorm() { - final double[] colSums = new double[BLOCK_SIZE]; - double maxColSum = 0; - for (int jBlock = 0; jBlock < blockColumns; jBlock++) { - final int jWidth = blockWidth(jBlock); - Arrays.fill(colSums, 0, jWidth, 0.0); - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int iHeight = blockHeight(iBlock); - final double[] block = blocks[iBlock * blockColumns + jBlock]; - for (int j = 0; j < jWidth; ++j) { - double sum = 0; - for (int i = 0; i < iHeight; ++i) { - sum += FastMath.abs(block[i * jWidth + j]); - } - colSums[j] += sum; - } - } - for (int j = 0; j < jWidth; ++j) { - maxColSum = FastMath.max(maxColSum, colSums[j]); - } - } - return maxColSum; - } - - /** {@inheritDoc} */ - @Override - public double getFrobeniusNorm() { - double sum2 = 0; - for (int blockIndex = 0; blockIndex < blocks.length; ++blockIndex) { - for (final double entry : blocks[blockIndex]) { - sum2 += entry * entry; - } - } - return FastMath.sqrt(sum2); - } - - /** {@inheritDoc} */ - @Override - public BlockRealMatrix getSubMatrix(final int startRow, final int endRow, - final int startColumn, - final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - // safety checks - MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); - - // create the output matrix - final BlockRealMatrix out = - new BlockRealMatrix(endRow - startRow + 1, endColumn - startColumn + 1); - - // compute blocks shifts - final int blockStartRow = startRow / BLOCK_SIZE; - final int rowsShift = startRow % BLOCK_SIZE; - final int blockStartColumn = startColumn / BLOCK_SIZE; - final int columnsShift = startColumn % BLOCK_SIZE; - - // perform extraction block-wise, to ensure good cache behavior - int pBlock = blockStartRow; - for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) { - final int iHeight = out.blockHeight(iBlock); - int qBlock = blockStartColumn; - for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) { - final int jWidth = out.blockWidth(jBlock); - - // handle one block of the output matrix - final int outIndex = iBlock * out.blockColumns + jBlock; - final double[] outBlock = out.blocks[outIndex]; - final int index = pBlock * blockColumns + qBlock; - final int width = blockWidth(qBlock); - - final int heightExcess = iHeight + rowsShift - BLOCK_SIZE; - final int widthExcess = jWidth + columnsShift - BLOCK_SIZE; - if (heightExcess > 0) { - // the submatrix block spans on two blocks rows from the original matrix - if (widthExcess > 0) { - // the submatrix block spans on two blocks columns from the original matrix - final int width2 = blockWidth(qBlock + 1); - copyBlockPart(blocks[index], width, - rowsShift, BLOCK_SIZE, - columnsShift, BLOCK_SIZE, - outBlock, jWidth, 0, 0); - copyBlockPart(blocks[index + 1], width2, - rowsShift, BLOCK_SIZE, - 0, widthExcess, - outBlock, jWidth, 0, jWidth - widthExcess); - copyBlockPart(blocks[index + blockColumns], width, - 0, heightExcess, - columnsShift, BLOCK_SIZE, - outBlock, jWidth, iHeight - heightExcess, 0); - copyBlockPart(blocks[index + blockColumns + 1], width2, - 0, heightExcess, - 0, widthExcess, - outBlock, jWidth, iHeight - heightExcess, jWidth - widthExcess); - } else { - // the submatrix block spans on one block column from the original matrix - copyBlockPart(blocks[index], width, - rowsShift, BLOCK_SIZE, - columnsShift, jWidth + columnsShift, - outBlock, jWidth, 0, 0); - copyBlockPart(blocks[index + blockColumns], width, - 0, heightExcess, - columnsShift, jWidth + columnsShift, - outBlock, jWidth, iHeight - heightExcess, 0); - } - } else { - // the submatrix block spans on one block row from the original matrix - if (widthExcess > 0) { - // the submatrix block spans on two blocks columns from the original matrix - final int width2 = blockWidth(qBlock + 1); - copyBlockPart(blocks[index], width, - rowsShift, iHeight + rowsShift, - columnsShift, BLOCK_SIZE, - outBlock, jWidth, 0, 0); - copyBlockPart(blocks[index + 1], width2, - rowsShift, iHeight + rowsShift, - 0, widthExcess, - outBlock, jWidth, 0, jWidth - widthExcess); - } else { - // the submatrix block spans on one block column from the original matrix - copyBlockPart(blocks[index], width, - rowsShift, iHeight + rowsShift, - columnsShift, jWidth + columnsShift, - outBlock, jWidth, 0, 0); - } - } - ++qBlock; - } - ++pBlock; - } - - return out; - } - - /** - * Copy a part of a block into another one - *

This method can be called only when the specified part fits in both - * blocks, no verification is done here.

- * @param srcBlock source block - * @param srcWidth source block width ({@link #BLOCK_SIZE} or smaller) - * @param srcStartRow start row in the source block - * @param srcEndRow end row (exclusive) in the source block - * @param srcStartColumn start column in the source block - * @param srcEndColumn end column (exclusive) in the source block - * @param dstBlock destination block - * @param dstWidth destination block width ({@link #BLOCK_SIZE} or smaller) - * @param dstStartRow start row in the destination block - * @param dstStartColumn start column in the destination block - */ - private void copyBlockPart(final double[] srcBlock, final int srcWidth, - final int srcStartRow, final int srcEndRow, - final int srcStartColumn, final int srcEndColumn, - final double[] dstBlock, final int dstWidth, - final int dstStartRow, final int dstStartColumn) { - final int length = srcEndColumn - srcStartColumn; - int srcPos = srcStartRow * srcWidth + srcStartColumn; - int dstPos = dstStartRow * dstWidth + dstStartColumn; - for (int srcRow = srcStartRow; srcRow < srcEndRow; ++srcRow) { - System.arraycopy(srcBlock, srcPos, dstBlock, dstPos, length); - srcPos += srcWidth; - dstPos += dstWidth; - } - } - - /** {@inheritDoc} */ - @Override - public void setSubMatrix(final double[][] subMatrix, final int row, - final int column) - throws OutOfRangeException, NoDataException, NullArgumentException, - DimensionMismatchException { - // safety checks - MathUtils.checkNotNull(subMatrix); - final int refLength = subMatrix[0].length; - if (refLength == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN); - } - final int endRow = row + subMatrix.length - 1; - final int endColumn = column + refLength - 1; - MatrixUtils.checkSubMatrixIndex(this, row, endRow, column, endColumn); - for (final double[] subRow : subMatrix) { - if (subRow.length != refLength) { - throw new DimensionMismatchException(refLength, subRow.length); - } - } - - // compute blocks bounds - final int blockStartRow = row / BLOCK_SIZE; - final int blockEndRow = (endRow + BLOCK_SIZE) / BLOCK_SIZE; - final int blockStartColumn = column / BLOCK_SIZE; - final int blockEndColumn = (endColumn + BLOCK_SIZE) / BLOCK_SIZE; - - // perform copy block-wise, to ensure good cache behavior - for (int iBlock = blockStartRow; iBlock < blockEndRow; ++iBlock) { - final int iHeight = blockHeight(iBlock); - final int firstRow = iBlock * BLOCK_SIZE; - final int iStart = FastMath.max(row, firstRow); - final int iEnd = FastMath.min(endRow + 1, firstRow + iHeight); - - for (int jBlock = blockStartColumn; jBlock < blockEndColumn; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final int firstColumn = jBlock * BLOCK_SIZE; - final int jStart = FastMath.max(column, firstColumn); - final int jEnd = FastMath.min(endColumn + 1, firstColumn + jWidth); - final int jLength = jEnd - jStart; - - // handle one block, row by row - final double[] block = blocks[iBlock * blockColumns + jBlock]; - for (int i = iStart; i < iEnd; ++i) { - System.arraycopy(subMatrix[i - row], jStart - column, - block, (i - firstRow) * jWidth + (jStart - firstColumn), - jLength); - } - - } - } - } - - /** {@inheritDoc} */ - @Override - public BlockRealMatrix getRowMatrix(final int row) - throws OutOfRangeException { - MatrixUtils.checkRowIndex(this, row); - final BlockRealMatrix out = new BlockRealMatrix(1, columns); - - // perform copy block-wise, to ensure good cache behavior - final int iBlock = row / BLOCK_SIZE; - final int iRow = row - iBlock * BLOCK_SIZE; - int outBlockIndex = 0; - int outIndex = 0; - double[] outBlock = out.blocks[outBlockIndex]; - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final double[] block = blocks[iBlock * blockColumns + jBlock]; - final int available = outBlock.length - outIndex; - if (jWidth > available) { - System.arraycopy(block, iRow * jWidth, outBlock, outIndex, available); - outBlock = out.blocks[++outBlockIndex]; - System.arraycopy(block, iRow * jWidth, outBlock, 0, jWidth - available); - outIndex = jWidth - available; - } else { - System.arraycopy(block, iRow * jWidth, outBlock, outIndex, jWidth); - outIndex += jWidth; - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public void setRowMatrix(final int row, final RealMatrix matrix) - throws OutOfRangeException, MatrixDimensionMismatchException { - try { - setRowMatrix(row, (BlockRealMatrix) matrix); - } catch (ClassCastException cce) { - super.setRowMatrix(row, matrix); - } - } - - /** - * Sets the entries in row number row - * as a row matrix. Row indices start at 0. - * - * @param row the row to be set - * @param matrix row matrix (must have one row and the same number of columns - * as the instance) - * @throws OutOfRangeException if the specified row index is invalid. - * @throws MatrixDimensionMismatchException if the matrix dimensions do - * not match one instance row. - */ - public void setRowMatrix(final int row, final BlockRealMatrix matrix) - throws OutOfRangeException, MatrixDimensionMismatchException { - MatrixUtils.checkRowIndex(this, row); - final int nCols = getColumnDimension(); - if ((matrix.getRowDimension() != 1) || - (matrix.getColumnDimension() != nCols)) { - throw new MatrixDimensionMismatchException(matrix.getRowDimension(), - matrix.getColumnDimension(), - 1, nCols); - } - - // perform copy block-wise, to ensure good cache behavior - final int iBlock = row / BLOCK_SIZE; - final int iRow = row - iBlock * BLOCK_SIZE; - int mBlockIndex = 0; - int mIndex = 0; - double[] mBlock = matrix.blocks[mBlockIndex]; - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final double[] block = blocks[iBlock * blockColumns + jBlock]; - final int available = mBlock.length - mIndex; - if (jWidth > available) { - System.arraycopy(mBlock, mIndex, block, iRow * jWidth, available); - mBlock = matrix.blocks[++mBlockIndex]; - System.arraycopy(mBlock, 0, block, iRow * jWidth, jWidth - available); - mIndex = jWidth - available; - } else { - System.arraycopy(mBlock, mIndex, block, iRow * jWidth, jWidth); - mIndex += jWidth; - } - } - } - - /** {@inheritDoc} */ - @Override - public BlockRealMatrix getColumnMatrix(final int column) - throws OutOfRangeException { - MatrixUtils.checkColumnIndex(this, column); - final BlockRealMatrix out = new BlockRealMatrix(rows, 1); - - // perform copy block-wise, to ensure good cache behavior - final int jBlock = column / BLOCK_SIZE; - final int jColumn = column - jBlock * BLOCK_SIZE; - final int jWidth = blockWidth(jBlock); - int outBlockIndex = 0; - int outIndex = 0; - double[] outBlock = out.blocks[outBlockIndex]; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int iHeight = blockHeight(iBlock); - final double[] block = blocks[iBlock * blockColumns + jBlock]; - for (int i = 0; i < iHeight; ++i) { - if (outIndex >= outBlock.length) { - outBlock = out.blocks[++outBlockIndex]; - outIndex = 0; - } - outBlock[outIndex++] = block[i * jWidth + jColumn]; - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public void setColumnMatrix(final int column, final RealMatrix matrix) - throws OutOfRangeException, MatrixDimensionMismatchException { - try { - setColumnMatrix(column, (BlockRealMatrix) matrix); - } catch (ClassCastException cce) { - super.setColumnMatrix(column, matrix); - } - } - - /** - * Sets the entries in column number column - * as a column matrix. Column indices start at 0. - * - * @param column the column to be set - * @param matrix column matrix (must have one column and the same number of rows - * as the instance) - * @throws OutOfRangeException if the specified column index is invalid. - * @throws MatrixDimensionMismatchException if the matrix dimensions do - * not match one instance column. - */ - void setColumnMatrix(final int column, final BlockRealMatrix matrix) - throws OutOfRangeException, MatrixDimensionMismatchException { - MatrixUtils.checkColumnIndex(this, column); - final int nRows = getRowDimension(); - if ((matrix.getRowDimension() != nRows) || - (matrix.getColumnDimension() != 1)) { - throw new MatrixDimensionMismatchException(matrix.getRowDimension(), - matrix.getColumnDimension(), - nRows, 1); - } - - // perform copy block-wise, to ensure good cache behavior - final int jBlock = column / BLOCK_SIZE; - final int jColumn = column - jBlock * BLOCK_SIZE; - final int jWidth = blockWidth(jBlock); - int mBlockIndex = 0; - int mIndex = 0; - double[] mBlock = matrix.blocks[mBlockIndex]; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int iHeight = blockHeight(iBlock); - final double[] block = blocks[iBlock * blockColumns + jBlock]; - for (int i = 0; i < iHeight; ++i) { - if (mIndex >= mBlock.length) { - mBlock = matrix.blocks[++mBlockIndex]; - mIndex = 0; - } - block[i * jWidth + jColumn] = mBlock[mIndex++]; - } - } - } - - /** {@inheritDoc} */ - @Override - public RealVector getRowVector(final int row) - throws OutOfRangeException { - MatrixUtils.checkRowIndex(this, row); - final double[] outData = new double[columns]; - - // perform copy block-wise, to ensure good cache behavior - final int iBlock = row / BLOCK_SIZE; - final int iRow = row - iBlock * BLOCK_SIZE; - int outIndex = 0; - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final double[] block = blocks[iBlock * blockColumns + jBlock]; - System.arraycopy(block, iRow * jWidth, outData, outIndex, jWidth); - outIndex += jWidth; - } - - return new ArrayRealVector(outData, false); - } - - /** {@inheritDoc} */ - @Override - public void setRowVector(final int row, final RealVector vector) - throws OutOfRangeException, MatrixDimensionMismatchException { - try { - setRow(row, ((ArrayRealVector) vector).getDataRef()); - } catch (ClassCastException cce) { - super.setRowVector(row, vector); - } - } - - /** {@inheritDoc} */ - @Override - public RealVector getColumnVector(final int column) - throws OutOfRangeException { - MatrixUtils.checkColumnIndex(this, column); - final double[] outData = new double[rows]; - - // perform copy block-wise, to ensure good cache behavior - final int jBlock = column / BLOCK_SIZE; - final int jColumn = column - jBlock * BLOCK_SIZE; - final int jWidth = blockWidth(jBlock); - int outIndex = 0; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int iHeight = blockHeight(iBlock); - final double[] block = blocks[iBlock * blockColumns + jBlock]; - for (int i = 0; i < iHeight; ++i) { - outData[outIndex++] = block[i * jWidth + jColumn]; - } - } - - return new ArrayRealVector(outData, false); - } - - /** {@inheritDoc} */ - @Override - public void setColumnVector(final int column, final RealVector vector) - throws OutOfRangeException, MatrixDimensionMismatchException { - try { - setColumn(column, ((ArrayRealVector) vector).getDataRef()); - } catch (ClassCastException cce) { - super.setColumnVector(column, vector); - } - } - - /** {@inheritDoc} */ - @Override - public double[] getRow(final int row) throws OutOfRangeException { - MatrixUtils.checkRowIndex(this, row); - final double[] out = new double[columns]; - - // perform copy block-wise, to ensure good cache behavior - final int iBlock = row / BLOCK_SIZE; - final int iRow = row - iBlock * BLOCK_SIZE; - int outIndex = 0; - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final double[] block = blocks[iBlock * blockColumns + jBlock]; - System.arraycopy(block, iRow * jWidth, out, outIndex, jWidth); - outIndex += jWidth; - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public void setRow(final int row, final double[] array) - throws OutOfRangeException, MatrixDimensionMismatchException { - MatrixUtils.checkRowIndex(this, row); - final int nCols = getColumnDimension(); - if (array.length != nCols) { - throw new MatrixDimensionMismatchException(1, array.length, 1, nCols); - } - - // perform copy block-wise, to ensure good cache behavior - final int iBlock = row / BLOCK_SIZE; - final int iRow = row - iBlock * BLOCK_SIZE; - int outIndex = 0; - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final double[] block = blocks[iBlock * blockColumns + jBlock]; - System.arraycopy(array, outIndex, block, iRow * jWidth, jWidth); - outIndex += jWidth; - } - } - - /** {@inheritDoc} */ - @Override - public double[] getColumn(final int column) throws OutOfRangeException { - MatrixUtils.checkColumnIndex(this, column); - final double[] out = new double[rows]; - - // perform copy block-wise, to ensure good cache behavior - final int jBlock = column / BLOCK_SIZE; - final int jColumn = column - jBlock * BLOCK_SIZE; - final int jWidth = blockWidth(jBlock); - int outIndex = 0; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int iHeight = blockHeight(iBlock); - final double[] block = blocks[iBlock * blockColumns + jBlock]; - for (int i = 0; i < iHeight; ++i) { - out[outIndex++] = block[i * jWidth + jColumn]; - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public void setColumn(final int column, final double[] array) - throws OutOfRangeException, MatrixDimensionMismatchException { - MatrixUtils.checkColumnIndex(this, column); - final int nRows = getRowDimension(); - if (array.length != nRows) { - throw new MatrixDimensionMismatchException(array.length, 1, nRows, 1); - } - - // perform copy block-wise, to ensure good cache behavior - final int jBlock = column / BLOCK_SIZE; - final int jColumn = column - jBlock * BLOCK_SIZE; - final int jWidth = blockWidth(jBlock); - int outIndex = 0; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int iHeight = blockHeight(iBlock); - final double[] block = blocks[iBlock * blockColumns + jBlock]; - for (int i = 0; i < iHeight; ++i) { - block[i * jWidth + jColumn] = array[outIndex++]; - } - } - } - - /** {@inheritDoc} */ - @Override - public double getEntry(final int row, final int column) - throws OutOfRangeException { - MatrixUtils.checkMatrixIndex(this, row, column); - final int iBlock = row / BLOCK_SIZE; - final int jBlock = column / BLOCK_SIZE; - final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) + - (column - jBlock * BLOCK_SIZE); - return blocks[iBlock * blockColumns + jBlock][k]; - } - - /** {@inheritDoc} */ - @Override - public void setEntry(final int row, final int column, final double value) - throws OutOfRangeException { - MatrixUtils.checkMatrixIndex(this, row, column); - final int iBlock = row / BLOCK_SIZE; - final int jBlock = column / BLOCK_SIZE; - final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) + - (column - jBlock * BLOCK_SIZE); - blocks[iBlock * blockColumns + jBlock][k] = value; - } - - /** {@inheritDoc} */ - @Override - public void addToEntry(final int row, final int column, - final double increment) - throws OutOfRangeException { - MatrixUtils.checkMatrixIndex(this, row, column); - final int iBlock = row / BLOCK_SIZE; - final int jBlock = column / BLOCK_SIZE; - final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) + - (column - jBlock * BLOCK_SIZE); - blocks[iBlock * blockColumns + jBlock][k] += increment; - } - - /** {@inheritDoc} */ - @Override - public void multiplyEntry(final int row, final int column, - final double factor) - throws OutOfRangeException { - MatrixUtils.checkMatrixIndex(this, row, column); - final int iBlock = row / BLOCK_SIZE; - final int jBlock = column / BLOCK_SIZE; - final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) + - (column - jBlock * BLOCK_SIZE); - blocks[iBlock * blockColumns + jBlock][k] *= factor; - } - - /** {@inheritDoc} */ - @Override - public BlockRealMatrix transpose() { - final int nRows = getRowDimension(); - final int nCols = getColumnDimension(); - final BlockRealMatrix out = new BlockRealMatrix(nCols, nRows); - - // perform transpose block-wise, to ensure good cache behavior - int blockIndex = 0; - for (int iBlock = 0; iBlock < blockColumns; ++iBlock) { - for (int jBlock = 0; jBlock < blockRows; ++jBlock) { - // transpose current block - final double[] outBlock = out.blocks[blockIndex]; - final double[] tBlock = blocks[jBlock * blockColumns + iBlock]; - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, columns); - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, rows); - int k = 0; - for (int p = pStart; p < pEnd; ++p) { - final int lInc = pEnd - pStart; - int l = p - pStart; - for (int q = qStart; q < qEnd; ++q) { - outBlock[k] = tBlock[l]; - ++k; - l+= lInc; - } - } - // go to next block - ++blockIndex; - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public int getRowDimension() { - return rows; - } - - /** {@inheritDoc} */ - @Override - public int getColumnDimension() { - return columns; - } - - /** {@inheritDoc} */ - @Override - public double[] operate(final double[] v) - throws DimensionMismatchException { - if (v.length != columns) { - throw new DimensionMismatchException(v.length, columns); - } - final double[] out = new double[rows]; - - // perform multiplication block-wise, to ensure good cache behavior - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final double[] block = blocks[iBlock * blockColumns + jBlock]; - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - int k = 0; - for (int p = pStart; p < pEnd; ++p) { - double sum = 0; - int q = qStart; - while (q < qEnd - 3) { - sum += block[k] * v[q] + - block[k + 1] * v[q + 1] + - block[k + 2] * v[q + 2] + - block[k + 3] * v[q + 3]; - k += 4; - q += 4; - } - while (q < qEnd) { - sum += block[k++] * v[q++]; - } - out[p] += sum; - } - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public double[] preMultiply(final double[] v) - throws DimensionMismatchException { - if (v.length != rows) { - throw new DimensionMismatchException(v.length, rows); - } - final double[] out = new double[columns]; - - // perform multiplication block-wise, to ensure good cache behavior - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final int jWidth2 = jWidth + jWidth; - final int jWidth3 = jWidth2 + jWidth; - final int jWidth4 = jWidth3 + jWidth; - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final double[] block = blocks[iBlock * blockColumns + jBlock]; - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - for (int q = qStart; q < qEnd; ++q) { - int k = q - qStart; - double sum = 0; - int p = pStart; - while (p < pEnd - 3) { - sum += block[k] * v[p] + - block[k + jWidth] * v[p + 1] + - block[k + jWidth2] * v[p + 2] + - block[k + jWidth3] * v[p + 3]; - k += jWidth4; - p += 4; - } - while (p < pEnd) { - sum += block[k] * v[p++]; - k += jWidth; - } - out[q] += sum; - } - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public double walkInRowOrder(final RealMatrixChangingVisitor visitor) { - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - for (int p = pStart; p < pEnd; ++p) { - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - final double[] block = blocks[iBlock * blockColumns + jBlock]; - int k = (p - pStart) * jWidth; - for (int q = qStart; q < qEnd; ++q) { - block[k] = visitor.visit(p, q, block[k]); - ++k; - } - } - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInRowOrder(final RealMatrixPreservingVisitor visitor) { - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - for (int p = pStart; p < pEnd; ++p) { - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - final double[] block = blocks[iBlock * blockColumns + jBlock]; - int k = (p - pStart) * jWidth; - for (int q = qStart; q < qEnd; ++q) { - visitor.visit(p, q, block[k]); - ++k; - } - } - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInRowOrder(final RealMatrixChangingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); - visitor.start(rows, columns, startRow, endRow, startColumn, endColumn); - for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) { - final int p0 = iBlock * BLOCK_SIZE; - final int pStart = FastMath.max(startRow, p0); - final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow); - for (int p = pStart; p < pEnd; ++p) { - for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final int q0 = jBlock * BLOCK_SIZE; - final int qStart = FastMath.max(startColumn, q0); - final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn); - final double[] block = blocks[iBlock * blockColumns + jBlock]; - int k = (p - p0) * jWidth + qStart - q0; - for (int q = qStart; q < qEnd; ++q) { - block[k] = visitor.visit(p, q, block[k]); - ++k; - } - } - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInRowOrder(final RealMatrixPreservingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); - visitor.start(rows, columns, startRow, endRow, startColumn, endColumn); - for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) { - final int p0 = iBlock * BLOCK_SIZE; - final int pStart = FastMath.max(startRow, p0); - final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow); - for (int p = pStart; p < pEnd; ++p) { - for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final int q0 = jBlock * BLOCK_SIZE; - final int qStart = FastMath.max(startColumn, q0); - final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn); - final double[] block = blocks[iBlock * blockColumns + jBlock]; - int k = (p - p0) * jWidth + qStart - q0; - for (int q = qStart; q < qEnd; ++q) { - visitor.visit(p, q, block[k]); - ++k; - } - } - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInOptimizedOrder(final RealMatrixChangingVisitor visitor) { - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - int blockIndex = 0; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - final double[] block = blocks[blockIndex]; - int k = 0; - for (int p = pStart; p < pEnd; ++p) { - for (int q = qStart; q < qEnd; ++q) { - block[k] = visitor.visit(p, q, block[k]); - ++k; - } - } - ++blockIndex; - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInOptimizedOrder(final RealMatrixPreservingVisitor visitor) { - visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); - int blockIndex = 0; - for (int iBlock = 0; iBlock < blockRows; ++iBlock) { - final int pStart = iBlock * BLOCK_SIZE; - final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); - for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { - final int qStart = jBlock * BLOCK_SIZE; - final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); - final double[] block = blocks[blockIndex]; - int k = 0; - for (int p = pStart; p < pEnd; ++p) { - for (int q = qStart; q < qEnd; ++q) { - visitor.visit(p, q, block[k]); - ++k; - } - } - ++blockIndex; - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInOptimizedOrder(final RealMatrixChangingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, - final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); - visitor.start(rows, columns, startRow, endRow, startColumn, endColumn); - for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) { - final int p0 = iBlock * BLOCK_SIZE; - final int pStart = FastMath.max(startRow, p0); - final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow); - for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final int q0 = jBlock * BLOCK_SIZE; - final int qStart = FastMath.max(startColumn, q0); - final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn); - final double[] block = blocks[iBlock * blockColumns + jBlock]; - for (int p = pStart; p < pEnd; ++p) { - int k = (p - p0) * jWidth + qStart - q0; - for (int q = qStart; q < qEnd; ++q) { - block[k] = visitor.visit(p, q, block[k]); - ++k; - } - } - } - } - return visitor.end(); - } - - /** {@inheritDoc} */ - @Override - public double walkInOptimizedOrder(final RealMatrixPreservingVisitor visitor, - final int startRow, final int endRow, - final int startColumn, - final int endColumn) - throws OutOfRangeException, NumberIsTooSmallException { - MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); - visitor.start(rows, columns, startRow, endRow, startColumn, endColumn); - for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) { - final int p0 = iBlock * BLOCK_SIZE; - final int pStart = FastMath.max(startRow, p0); - final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow); - for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) { - final int jWidth = blockWidth(jBlock); - final int q0 = jBlock * BLOCK_SIZE; - final int qStart = FastMath.max(startColumn, q0); - final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn); - final double[] block = blocks[iBlock * blockColumns + jBlock]; - for (int p = pStart; p < pEnd; ++p) { - int k = (p - p0) * jWidth + qStart - q0; - for (int q = qStart; q < qEnd; ++q) { - visitor.visit(p, q, block[k]); - ++k; - } - } - } - } - return visitor.end(); - } - - /** - * Get the height of a block. - * @param blockRow row index (in block sense) of the block - * @return height (number of rows) of the block - */ - private int blockHeight(final int blockRow) { - return (blockRow == blockRows - 1) ? rows - blockRow * BLOCK_SIZE : BLOCK_SIZE; - } - - /** - * Get the width of a block. - * @param blockColumn column index (in block sense) of the block - * @return width (number of columns) of the block - */ - private int blockWidth(final int blockColumn) { - return (blockColumn == blockColumns - 1) ? columns - blockColumn * BLOCK_SIZE : BLOCK_SIZE; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/CholeskyDecomposition.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/CholeskyDecomposition.java deleted file mode 100644 index 06bbc8342..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/CholeskyDecomposition.java +++ /dev/null @@ -1,314 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.util.FastMath; - - -/** - * Calculates the Cholesky decomposition of a matrix. - *

The Cholesky decomposition of a real symmetric positive-definite - * matrix A consists of a lower triangular matrix L with same size such - * that: A = LLT. In a sense, this is the square root of A.

- *

This class is based on the class with similar name from the - * JAMA library, with the - * following changes:

- *
    - *
  • a {@link #getLT() getLT} method has been added,
  • - *
  • the {@code isspd} method has been removed, since the constructor of - * this class throws a {@link NonPositiveDefiniteMatrixException} when a - * matrix cannot be decomposed,
  • - *
  • a {@link #getDeterminant() getDeterminant} method has been added,
  • - *
  • the {@code solve} method has been replaced by a {@link #getSolver() - * getSolver} method and the equivalent method provided by the returned - * {@link DecompositionSolver}.
  • - *
- * - * @see MathWorld - * @see Wikipedia - * @since 2.0 (changed to concrete class in 3.0) - */ -public class CholeskyDecomposition { - /** - * Default threshold above which off-diagonal elements are considered too different - * and matrix not symmetric. - */ - public static final double DEFAULT_RELATIVE_SYMMETRY_THRESHOLD = 1.0e-15; - /** - * Default threshold below which diagonal elements are considered null - * and matrix not positive definite. - */ - public static final double DEFAULT_ABSOLUTE_POSITIVITY_THRESHOLD = 1.0e-10; - /** Row-oriented storage for LT matrix data. */ - private final double[][] lTData; - /** Cached value of L. */ - private RealMatrix cachedL; - /** Cached value of LT. */ - private RealMatrix cachedLT; - - /** - * Calculates the Cholesky decomposition of the given matrix. - *

- * Calling this constructor is equivalent to call {@link - * #CholeskyDecomposition(RealMatrix, double, double)} with the - * thresholds set to the default values {@link - * #DEFAULT_RELATIVE_SYMMETRY_THRESHOLD} and {@link - * #DEFAULT_ABSOLUTE_POSITIVITY_THRESHOLD} - *

- * @param matrix the matrix to decompose - * @throws NonSquareMatrixException if the matrix is not square. - * @throws NonSymmetricMatrixException if the matrix is not symmetric. - * @throws NonPositiveDefiniteMatrixException if the matrix is not - * strictly positive definite. - * @see #CholeskyDecomposition(RealMatrix, double, double) - * @see #DEFAULT_RELATIVE_SYMMETRY_THRESHOLD - * @see #DEFAULT_ABSOLUTE_POSITIVITY_THRESHOLD - */ - public CholeskyDecomposition(final RealMatrix matrix) { - this(matrix, DEFAULT_RELATIVE_SYMMETRY_THRESHOLD, - DEFAULT_ABSOLUTE_POSITIVITY_THRESHOLD); - } - - /** - * Calculates the Cholesky decomposition of the given matrix. - * @param matrix the matrix to decompose - * @param relativeSymmetryThreshold threshold above which off-diagonal - * elements are considered too different and matrix not symmetric - * @param absolutePositivityThreshold threshold below which diagonal - * elements are considered null and matrix not positive definite - * @throws NonSquareMatrixException if the matrix is not square. - * @throws NonSymmetricMatrixException if the matrix is not symmetric. - * @throws NonPositiveDefiniteMatrixException if the matrix is not - * strictly positive definite. - * @see #CholeskyDecomposition(RealMatrix) - * @see #DEFAULT_RELATIVE_SYMMETRY_THRESHOLD - * @see #DEFAULT_ABSOLUTE_POSITIVITY_THRESHOLD - */ - public CholeskyDecomposition(final RealMatrix matrix, - final double relativeSymmetryThreshold, - final double absolutePositivityThreshold) { - if (!matrix.isSquare()) { - throw new NonSquareMatrixException(matrix.getRowDimension(), - matrix.getColumnDimension()); - } - - final int order = matrix.getRowDimension(); - lTData = matrix.getData(); - cachedL = null; - cachedLT = null; - - // check the matrix before transformation - for (int i = 0; i < order; ++i) { - final double[] lI = lTData[i]; - - // check off-diagonal elements (and reset them to 0) - for (int j = i + 1; j < order; ++j) { - final double[] lJ = lTData[j]; - final double lIJ = lI[j]; - final double lJI = lJ[i]; - final double maxDelta = - relativeSymmetryThreshold * FastMath.max(FastMath.abs(lIJ), FastMath.abs(lJI)); - if (FastMath.abs(lIJ - lJI) > maxDelta) { - throw new NonSymmetricMatrixException(i, j, relativeSymmetryThreshold); - } - lJ[i] = 0; - } - } - - // transform the matrix - for (int i = 0; i < order; ++i) { - - final double[] ltI = lTData[i]; - - // check diagonal element - if (ltI[i] <= absolutePositivityThreshold) { - throw new NonPositiveDefiniteMatrixException(ltI[i], i, absolutePositivityThreshold); - } - - ltI[i] = FastMath.sqrt(ltI[i]); - final double inverse = 1.0 / ltI[i]; - - for (int q = order - 1; q > i; --q) { - ltI[q] *= inverse; - final double[] ltQ = lTData[q]; - for (int p = q; p < order; ++p) { - ltQ[p] -= ltI[q] * ltI[p]; - } - } - } - } - - /** - * Returns the matrix L of the decomposition. - *

L is an lower-triangular matrix

- * @return the L matrix - */ - public RealMatrix getL() { - if (cachedL == null) { - cachedL = getLT().transpose(); - } - return cachedL; - } - - /** - * Returns the transpose of the matrix L of the decomposition. - *

LT is an upper-triangular matrix

- * @return the transpose of the matrix L of the decomposition - */ - public RealMatrix getLT() { - - if (cachedLT == null) { - cachedLT = MatrixUtils.createRealMatrix(lTData); - } - - // return the cached matrix - return cachedLT; - } - - /** - * Return the determinant of the matrix - * @return determinant of the matrix - */ - public double getDeterminant() { - double determinant = 1.0; - for (int i = 0; i < lTData.length; ++i) { - double lTii = lTData[i][i]; - determinant *= lTii * lTii; - } - return determinant; - } - - /** - * Get a solver for finding the A × X = B solution in least square sense. - * @return a solver - */ - public DecompositionSolver getSolver() { - return new Solver(lTData); - } - - /** Specialized solver. */ - private static class Solver implements DecompositionSolver { - /** Row-oriented storage for LT matrix data. */ - private final double[][] lTData; - - /** - * Build a solver from decomposed matrix. - * @param lTData row-oriented storage for LT matrix data - */ - private Solver(final double[][] lTData) { - this.lTData = lTData; - } - - /** {@inheritDoc} */ - @Override - public boolean isNonSingular() { - // if we get this far, the matrix was positive definite, hence non-singular - return true; - } - - /** {@inheritDoc} */ - @Override - public RealVector solve(final RealVector b) { - final int m = lTData.length; - if (b.getDimension() != m) { - throw new DimensionMismatchException(b.getDimension(), m); - } - - final double[] x = b.toArray(); - - // Solve LY = b - for (int j = 0; j < m; j++) { - final double[] lJ = lTData[j]; - x[j] /= lJ[j]; - final double xJ = x[j]; - for (int i = j + 1; i < m; i++) { - x[i] -= xJ * lJ[i]; - } - } - - // Solve LTX = Y - for (int j = m - 1; j >= 0; j--) { - x[j] /= lTData[j][j]; - final double xJ = x[j]; - for (int i = 0; i < j; i++) { - x[i] -= xJ * lTData[i][j]; - } - } - - return new ArrayRealVector(x, false); - } - - /** {@inheritDoc} */ - @Override - public RealMatrix solve(RealMatrix b) { - final int m = lTData.length; - if (b.getRowDimension() != m) { - throw new DimensionMismatchException(b.getRowDimension(), m); - } - - final int nColB = b.getColumnDimension(); - final double[][] x = b.getData(); - - // Solve LY = b - for (int j = 0; j < m; j++) { - final double[] lJ = lTData[j]; - final double lJJ = lJ[j]; - final double[] xJ = x[j]; - for (int k = 0; k < nColB; ++k) { - xJ[k] /= lJJ; - } - for (int i = j + 1; i < m; i++) { - final double[] xI = x[i]; - final double lJI = lJ[i]; - for (int k = 0; k < nColB; ++k) { - xI[k] -= xJ[k] * lJI; - } - } - } - - // Solve LTX = Y - for (int j = m - 1; j >= 0; j--) { - final double lJJ = lTData[j][j]; - final double[] xJ = x[j]; - for (int k = 0; k < nColB; ++k) { - xJ[k] /= lJJ; - } - for (int i = 0; i < j; i++) { - final double[] xI = x[i]; - final double lIJ = lTData[i][j]; - for (int k = 0; k < nColB; ++k) { - xI[k] -= xJ[k] * lIJ; - } - } - } - - return new Array2DRowRealMatrix(x); - } - - /** - * Get the inverse of the decomposed matrix. - * - * @return the inverse matrix. - */ - @Override - public RealMatrix getInverse() { - return solve(MatrixUtils.createRealIdentityMatrix(lTData.length)); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/ConjugateGradient.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/ConjugateGradient.java deleted file mode 100644 index f6a46d613..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/ConjugateGradient.java +++ /dev/null @@ -1,234 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.util.ExceptionContext; -import org.apache.commons.math4.util.IterationManager; - -/** - *

- * This is an implementation of the conjugate gradient method for - * {@link RealLinearOperator}. It follows closely the template by Barrett et al. (1994) (figure 2.5). The linear system at - * hand is A · x = b, and the residual is r = b - A · x. - *

- *

Default stopping criterion

- *

- * A default stopping criterion is implemented. The iterations stop when || r || - * ≤ δ || b ||, where b is the right-hand side vector, r the current - * estimate of the residual, and δ a user-specified tolerance. It should - * be noted that r is the so-called updated residual, which might - * differ from the true residual due to rounding-off errors (see e.g. Strakos and Tichy, 2002). - *

- *

Iteration count

- *

- * In the present context, an iteration should be understood as one evaluation - * of the matrix-vector product A · x. The initialization phase therefore - * counts as one iteration. - *

- *

Exception context

- *

- * Besides standard {@link DimensionMismatchException}, this class might throw - * {@link NonPositiveDefiniteOperatorException} if the linear operator or - * the preconditioner are not positive definite. In this case, the - * {@link ExceptionContext} provides some more information - *

    - *
  • key {@code "operator"} points to the offending linear operator, say L,
  • - *
  • key {@code "vector"} points to the offending vector, say x, such that - * xT · L · x < 0.
  • - *
- * - *

References

- *
- *
Barret et al. (1994)
- *
R. Barrett, M. Berry, T. F. Chan, J. Demmel, J. M. Donato, J. Dongarra, - * V. Eijkhout, R. Pozo, C. Romine and H. Van der Vorst, - * - * Templates for the Solution of Linear Systems: Building Blocks for Iterative - * Methods, SIAM
- *
Strakos and Tichy (2002)
- *
Z. Strakos and P. Tichy, - * On error estimation in the conjugate gradient method and why it works - * in finite precision computations, Electronic Transactions on - * Numerical Analysis 13: 56-80, 2002
- *
- * - * @since 3.0 - */ -public class ConjugateGradient - extends PreconditionedIterativeLinearSolver { - - /** Key for the exception context. */ - public static final String OPERATOR = "operator"; - - /** Key for the exception context. */ - public static final String VECTOR = "vector"; - - /** - * {@code true} if positive-definiteness of matrix and preconditioner should - * be checked. - */ - private boolean check; - - /** The value of δ, for the default stopping criterion. */ - private final double delta; - - /** - * Creates a new instance of this class, with default - * stopping criterion. - * - * @param maxIterations the maximum number of iterations - * @param delta the δ parameter for the default stopping criterion - * @param check {@code true} if positive definiteness of both matrix and - * preconditioner should be checked - */ - public ConjugateGradient(final int maxIterations, final double delta, - final boolean check) { - super(maxIterations); - this.delta = delta; - this.check = check; - } - - /** - * Creates a new instance of this class, with default - * stopping criterion and custom iteration manager. - * - * @param manager the custom iteration manager - * @param delta the δ parameter for the default stopping criterion - * @param check {@code true} if positive definiteness of both matrix and - * preconditioner should be checked - * @throws NullArgumentException if {@code manager} is {@code null} - */ - public ConjugateGradient(final IterationManager manager, - final double delta, final boolean check) - throws NullArgumentException { - super(manager); - this.delta = delta; - this.check = check; - } - - /** - * Returns {@code true} if positive-definiteness should be checked for both - * matrix and preconditioner. - * - * @return {@code true} if the tests are to be performed - */ - public final boolean getCheck() { - return check; - } - - /** - * {@inheritDoc} - * - * @throws NonPositiveDefiniteOperatorException if {@code a} or {@code m} is - * not positive definite - */ - @Override - public RealVector solveInPlace(final RealLinearOperator a, - final RealLinearOperator m, - final RealVector b, - final RealVector x0) - throws NullArgumentException, NonPositiveDefiniteOperatorException, - NonSquareOperatorException, DimensionMismatchException, - MaxCountExceededException { - checkParameters(a, m, b, x0); - final IterationManager manager = getIterationManager(); - // Initialization of default stopping criterion - manager.resetIterationCount(); - final double rmax = delta * b.getNorm(); - final RealVector bro = RealVector.unmodifiableRealVector(b); - - // Initialization phase counts as one iteration. - manager.incrementIterationCount(); - // p and x are constructed as copies of x0, since presumably, the type - // of x is optimized for the calculation of the matrix-vector product - // A.x. - final RealVector x = x0; - final RealVector xro = RealVector.unmodifiableRealVector(x); - final RealVector p = x.copy(); - RealVector q = a.operate(p); - - final RealVector r = b.combine(1, -1, q); - final RealVector rro = RealVector.unmodifiableRealVector(r); - double rnorm = r.getNorm(); - RealVector z; - if (m == null) { - z = r; - } else { - z = null; - } - IterativeLinearSolverEvent evt; - evt = new DefaultIterativeLinearSolverEvent(this, - manager.getIterations(), xro, bro, rro, rnorm); - manager.fireInitializationEvent(evt); - if (rnorm <= rmax) { - manager.fireTerminationEvent(evt); - return x; - } - double rhoPrev = 0.; - while (true) { - manager.incrementIterationCount(); - evt = new DefaultIterativeLinearSolverEvent(this, - manager.getIterations(), xro, bro, rro, rnorm); - manager.fireIterationStartedEvent(evt); - if (m != null) { - z = m.operate(r); - } - final double rhoNext = r.dotProduct(z); - if (check && (rhoNext <= 0.)) { - final NonPositiveDefiniteOperatorException e; - e = new NonPositiveDefiniteOperatorException(); - final ExceptionContext context = e.getContext(); - context.setValue(OPERATOR, m); - context.setValue(VECTOR, r); - throw e; - } - if (manager.getIterations() == 2) { - p.setSubVector(0, z); - } else { - p.combineToSelf(rhoNext / rhoPrev, 1., z); - } - q = a.operate(p); - final double pq = p.dotProduct(q); - if (check && (pq <= 0.)) { - final NonPositiveDefiniteOperatorException e; - e = new NonPositiveDefiniteOperatorException(); - final ExceptionContext context = e.getContext(); - context.setValue(OPERATOR, a); - context.setValue(VECTOR, p); - throw e; - } - final double alpha = rhoNext / pq; - x.combineToSelf(1., alpha, p); - r.combineToSelf(1., -alpha, q); - rhoPrev = rhoNext; - rnorm = r.getNorm(); - evt = new DefaultIterativeLinearSolverEvent(this, - manager.getIterations(), xro, bro, rro, rnorm); - manager.fireIterationPerformedEvent(evt); - if (rnorm <= rmax) { - manager.fireTerminationEvent(evt); - return x; - } - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DecompositionSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DecompositionSolver.java deleted file mode 100644 index a0dfadb5f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DecompositionSolver.java +++ /dev/null @@ -1,97 +0,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. - */ - -package org.apache.commons.math4.linear; - -/** - * Interface handling decomposition algorithms that can solve A × X = B. - *

- * Decomposition algorithms decompose an A matrix has a product of several specific - * matrices from which they can solve A × X = B in least squares sense: they find X - * such that ||A × X - B|| is minimal. - *

- * Some solvers like {@link LUDecomposition} can only find the solution for - * square matrices and when the solution is an exact linear solution, i.e. when - * ||A × X - B|| is exactly 0. Other solvers can also find solutions - * with non-square matrix A and with non-null minimal norm. If an exact linear - * solution exists it is also the minimal norm solution. - * - * @since 2.0 - */ -public interface DecompositionSolver { - - /** - * Solve the linear equation A × X = B for matrices A. - *

- * The A matrix is implicit, it is provided by the underlying - * decomposition algorithm. - * - * @param b right-hand side of the equation A × X = B - * @return a vector X that minimizes the two norm of A × X - B - * @throws org.apache.commons.math4.exception.DimensionMismatchException - * if the matrices dimensions do not match. - * @throws SingularMatrixException if the decomposed matrix is singular. - */ - RealVector solve(final RealVector b) throws SingularMatrixException; - - /** - * Solve the linear equation A × X = B for matrices A. - *

- * The A matrix is implicit, it is provided by the underlying - * decomposition algorithm. - * - * @param b right-hand side of the equation A × X = B - * @return a matrix X that minimizes the two norm of A × X - B - * @throws org.apache.commons.math4.exception.DimensionMismatchException - * if the matrices dimensions do not match. - * @throws SingularMatrixException if the decomposed matrix is singular. - */ - RealMatrix solve(final RealMatrix b) throws SingularMatrixException; - - /** - * Check if the decomposed matrix is non-singular. - * @return true if the decomposed matrix is non-singular. - */ - boolean isNonSingular(); - - /** - * Get the pseudo-inverse - * of the decomposed matrix. - *

- * This is equal to the inverse of the decomposed matrix, if such an inverse exists. - *

- * If no such inverse exists, then the result has properties that resemble that of an inverse. - *

- * In particular, in this case, if the decomposed matrix is A, then the system of equations - * \( A x = b \) may have no solutions, or many. If it has no solutions, then the pseudo-inverse - * \( A^+ \) gives the "closest" solution \( z = A^+ b \), meaning \( \left \| A z - b \right \|_2 \) - * is minimized. If there are many solutions, then \( z = A^+ b \) is the smallest solution, - * meaning \( \left \| z \right \|_2 \) is minimized. - *

- * Note however that some decompositions cannot compute a pseudo-inverse for all matrices. - * For example, the {@link LUDecomposition} is not defined for non-square matrices to begin - * with. The {@link QRDecomposition} can operate on non-square matrices, but will throw - * {@link SingularMatrixException} if the decomposed matrix is singular. Refer to the javadoc - * of specific decomposition implementations for more details. - * - * @return pseudo-inverse matrix (which is the inverse, if it exists), - * if the decomposition can pseudo-invert the decomposed matrix - * @throws SingularMatrixException if the decomposed matrix is singular and the decomposition - * can not compute a pseudo-inverse - */ - RealMatrix getInverse() throws SingularMatrixException; -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DefaultFieldMatrixChangingVisitor.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DefaultFieldMatrixChangingVisitor.java deleted file mode 100644 index a9abded51..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DefaultFieldMatrixChangingVisitor.java +++ /dev/null @@ -1,61 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.FieldElement; - -/** - * Default implementation of the {@link FieldMatrixChangingVisitor} interface. - *

- * This class is a convenience to create custom visitors without defining all - * methods. This class provides default implementations that do nothing. - *

- * - * @param the type of the field elements - * @since 2.0 - */ -public class DefaultFieldMatrixChangingVisitor> - implements FieldMatrixChangingVisitor { - /** Zero element of the field. */ - private final T zero; - - /** Build a new instance. - * @param zero additive identity of the field - */ - public DefaultFieldMatrixChangingVisitor(final T zero) { - this.zero = zero; - } - - /** {@inheritDoc} */ - @Override - public void start(int rows, int columns, - int startRow, int endRow, int startColumn, int endColumn) { - } - - /** {@inheritDoc} */ - @Override - public T visit(int row, int column, T value) { - return value; - } - - /** {@inheritDoc} */ - @Override - public T end() { - return zero; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DefaultFieldMatrixPreservingVisitor.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DefaultFieldMatrixPreservingVisitor.java deleted file mode 100644 index ab924b9eb..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DefaultFieldMatrixPreservingVisitor.java +++ /dev/null @@ -1,59 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.FieldElement; - -/** - * Default implementation of the {@link FieldMatrixPreservingVisitor} interface. - *

- * This class is a convenience to create custom visitors without defining all - * methods. This class provides default implementations that do nothing. - *

- * - * @param the type of the field elements - * @since 2.0 - */ -public class DefaultFieldMatrixPreservingVisitor> - implements FieldMatrixPreservingVisitor { - /** Zero element of the field. */ - private final T zero; - - /** Build a new instance. - * @param zero additive identity of the field - */ - public DefaultFieldMatrixPreservingVisitor(final T zero) { - this.zero = zero; - } - - /** {@inheritDoc} */ - @Override - public void start(int rows, int columns, - int startRow, int endRow, int startColumn, int endColumn) { - } - - /** {@inheritDoc} */ - @Override - public void visit(int row, int column, T value) {} - - /** {@inheritDoc} */ - @Override - public T end() { - return zero; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DefaultIterativeLinearSolverEvent.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DefaultIterativeLinearSolverEvent.java deleted file mode 100644 index 4c4b7f7dd..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DefaultIterativeLinearSolverEvent.java +++ /dev/null @@ -1,143 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.MathUnsupportedOperationException; - -/** - * A default concrete implementation of the abstract class - * {@link IterativeLinearSolverEvent}. - * - */ -public class DefaultIterativeLinearSolverEvent extends IterativeLinearSolverEvent { - - /** */ - private static final long serialVersionUID = 20120129L; - - /** The right-hand side vector. */ - private final RealVector b; - - /** The current estimate of the residual. */ - private final RealVector r; - - /** The current estimate of the norm of the residual. */ - private final double rnorm; - - /** The current estimate of the solution. */ - private final RealVector x; - - /** - * Creates a new instance of this class. This implementation does - * not deep copy the specified vectors {@code x}, {@code b}, - * {@code r}. Therefore the user must make sure that these vectors are - * either unmodifiable views or deep copies of the same vectors actually - * used by the {@code source}. Failure to do so may compromise subsequent - * iterations of the {@code source}. If the residual vector {@code r} is - * {@code null}, then {@link #getResidual()} throws a - * {@link MathUnsupportedOperationException}, and - * {@link #providesResidual()} returns {@code false}. - * - * @param source the iterative solver which fired this event - * @param iterations the number of iterations performed at the time - * {@code this} event is created - * @param x the current estimate of the solution - * @param b the right-hand side vector - * @param r the current estimate of the residual (can be {@code null}) - * @param rnorm the norm of the current estimate of the residual - */ - public DefaultIterativeLinearSolverEvent(final Object source, final int iterations, - final RealVector x, final RealVector b, final RealVector r, - final double rnorm) { - super(source, iterations); - this.x = x; - this.b = b; - this.r = r; - this.rnorm = rnorm; - } - - /** - * Creates a new instance of this class. This implementation does - * not deep copy the specified vectors {@code x}, {@code b}. - * Therefore the user must make sure that these vectors are either - * unmodifiable views or deep copies of the same vectors actually used by - * the {@code source}. Failure to do so may compromise subsequent iterations - * of the {@code source}. Callling {@link #getResidual()} on instances - * returned by this constructor throws a - * {@link MathUnsupportedOperationException}, while - * {@link #providesResidual()} returns {@code false}. - * - * @param source the iterative solver which fired this event - * @param iterations the number of iterations performed at the time - * {@code this} event is created - * @param x the current estimate of the solution - * @param b the right-hand side vector - * @param rnorm the norm of the current estimate of the residual - */ - public DefaultIterativeLinearSolverEvent(final Object source, final int iterations, - final RealVector x, final RealVector b, final double rnorm) { - super(source, iterations); - this.x = x; - this.b = b; - this.r = null; - this.rnorm = rnorm; - } - - /** {@inheritDoc} */ - @Override - public double getNormOfResidual() { - return rnorm; - } - - /** - * {@inheritDoc} - * - * This implementation throws an {@link MathUnsupportedOperationException} - * if no residual vector {@code r} was provided at construction time. - */ - @Override - public RealVector getResidual() { - if (r != null) { - return r; - } - throw new MathUnsupportedOperationException(); - } - - /** {@inheritDoc} */ - @Override - public RealVector getRightHandSideVector() { - return b; - } - - /** {@inheritDoc} */ - @Override - public RealVector getSolution() { - return x; - } - - /** - * {@inheritDoc} - * - * This implementation returns {@code true} if a non-{@code null} value was - * specified for the residual vector {@code r} at construction time. - * - * @return {@code true} if {@code r != null} - */ - @Override - public boolean providesResidual() { - return r != null; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DefaultRealMatrixChangingVisitor.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DefaultRealMatrixChangingVisitor.java deleted file mode 100644 index 0e091bb80..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DefaultRealMatrixChangingVisitor.java +++ /dev/null @@ -1,47 +0,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. - */ - -package org.apache.commons.math4.linear; - -/** - * Default implementation of the {@link RealMatrixChangingVisitor} interface. - *

- * This class is a convenience to create custom visitors without defining all - * methods. This class provides default implementations that do nothing. - *

- * - * @since 2.0 - */ -public class DefaultRealMatrixChangingVisitor implements RealMatrixChangingVisitor { - /** {@inheritDoc} */ - @Override - public void start(int rows, int columns, - int startRow, int endRow, int startColumn, int endColumn) { - } - - /** {@inheritDoc} */ - @Override - public double visit(int row, int column, double value) { - return value; - } - - /** {@inheritDoc} */ - @Override - public double end() { - return 0; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DefaultRealMatrixPreservingVisitor.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DefaultRealMatrixPreservingVisitor.java deleted file mode 100644 index 7e5c3acfb..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DefaultRealMatrixPreservingVisitor.java +++ /dev/null @@ -1,45 +0,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. - */ - -package org.apache.commons.math4.linear; - -/** - * Default implementation of the {@link RealMatrixPreservingVisitor} interface. - *

- * This class is a convenience to create custom visitors without defining all - * methods. This class provides default implementations that do nothing. - *

- * - * @since 2.0 - */ -public class DefaultRealMatrixPreservingVisitor implements RealMatrixPreservingVisitor { - /** {@inheritDoc} */ - @Override - public void start(int rows, int columns, - int startRow, int endRow, int startColumn, int endColumn) { - } - - /** {@inheritDoc} */ - @Override - public void visit(int row, int column, double value) {} - - /** {@inheritDoc} */ - @Override - public double end() { - return 0; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DiagonalMatrix.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DiagonalMatrix.java deleted file mode 100644 index d85052947..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/DiagonalMatrix.java +++ /dev/null @@ -1,370 +0,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. - */ -package org.apache.commons.math4.linear; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathUtils; -import org.apache.commons.numbers.core.Precision; - -/** - * Implementation of a diagonal matrix. - * - * @since 3.1.1 - */ -public class DiagonalMatrix extends AbstractRealMatrix - implements Serializable { - /** Serializable version identifier. */ - private static final long serialVersionUID = 20121229L; - /** Entries of the diagonal. */ - private final double[] data; - - /** - * Creates a matrix with the supplied dimension. - * - * @param dimension Number of rows and columns in the new matrix. - * @throws NotStrictlyPositiveException if the dimension is - * not positive. - */ - public DiagonalMatrix(final int dimension) - throws NotStrictlyPositiveException { - super(dimension, dimension); - data = new double[dimension]; - } - - /** - * Creates a matrix using the input array as the underlying data. - *
- * The input array is copied, not referenced. - * - * @param d Data for the new matrix. - */ - public DiagonalMatrix(final double[] d) { - this(d, true); - } - - /** - * Creates a matrix using the input array as the underlying data. - *
- * If an array is created specially in order to be embedded in a - * this instance and not used directly, the {@code copyArray} may be - * set to {@code false}. - * This will prevent the copying and improve performance as no new - * array will be built and no data will be copied. - * - * @param d Data for new matrix. - * @param copyArray if {@code true}, the input array will be copied, - * otherwise it will be referenced. - * @exception NullArgumentException if d is null - */ - public DiagonalMatrix(final double[] d, final boolean copyArray) - throws NullArgumentException { - MathUtils.checkNotNull(d); - data = copyArray ? d.clone() : d; - } - - /** - * {@inheritDoc} - * - * @throws DimensionMismatchException if the requested dimensions are not equal. - */ - @Override - public RealMatrix createMatrix(final int rowDimension, - final int columnDimension) - throws NotStrictlyPositiveException, - DimensionMismatchException { - if (rowDimension != columnDimension) { - throw new DimensionMismatchException(rowDimension, columnDimension); - } - - return new DiagonalMatrix(rowDimension); - } - - /** {@inheritDoc} */ - @Override - public RealMatrix copy() { - return new DiagonalMatrix(data); - } - - /** - * Compute the sum of {@code this} and {@code m}. - * - * @param m Matrix to be added. - * @return {@code this + m}. - * @throws MatrixDimensionMismatchException if {@code m} is not the same - * size as {@code this}. - */ - public DiagonalMatrix add(final DiagonalMatrix m) - throws MatrixDimensionMismatchException { - // Safety check. - MatrixUtils.checkAdditionCompatible(this, m); - - final int dim = getRowDimension(); - final double[] outData = new double[dim]; - for (int i = 0; i < dim; i++) { - outData[i] = data[i] + m.data[i]; - } - - return new DiagonalMatrix(outData, false); - } - - /** - * Returns {@code this} minus {@code m}. - * - * @param m Matrix to be subtracted. - * @return {@code this - m} - * @throws MatrixDimensionMismatchException if {@code m} is not the same - * size as {@code this}. - */ - public DiagonalMatrix subtract(final DiagonalMatrix m) - throws MatrixDimensionMismatchException { - MatrixUtils.checkSubtractionCompatible(this, m); - - final int dim = getRowDimension(); - final double[] outData = new double[dim]; - for (int i = 0; i < dim; i++) { - outData[i] = data[i] - m.data[i]; - } - - return new DiagonalMatrix(outData, false); - } - - /** - * Returns the result of postmultiplying {@code this} by {@code m}. - * - * @param m matrix to postmultiply by - * @return {@code this * m} - * @throws DimensionMismatchException if - * {@code columnDimension(this) != rowDimension(m)} - */ - public DiagonalMatrix multiply(final DiagonalMatrix m) - throws DimensionMismatchException { - MatrixUtils.checkMultiplicationCompatible(this, m); - - final int dim = getRowDimension(); - final double[] outData = new double[dim]; - for (int i = 0; i < dim; i++) { - outData[i] = data[i] * m.data[i]; - } - - return new DiagonalMatrix(outData, false); - } - - /** - * Returns the result of postmultiplying {@code this} by {@code m}. - * - * @param m matrix to postmultiply by - * @return {@code this * m} - * @throws DimensionMismatchException if - * {@code columnDimension(this) != rowDimension(m)} - */ - @Override - public RealMatrix multiply(final RealMatrix m) - throws DimensionMismatchException { - if (m instanceof DiagonalMatrix) { - return multiply((DiagonalMatrix) m); - } else { - MatrixUtils.checkMultiplicationCompatible(this, m); - final int nRows = m.getRowDimension(); - final int nCols = m.getColumnDimension(); - final double[][] product = new double[nRows][nCols]; - for (int r = 0; r < nRows; r++) { - for (int c = 0; c < nCols; c++) { - product[r][c] = data[r] * m.getEntry(r, c); - } - } - return new Array2DRowRealMatrix(product, false); - } - } - - /** {@inheritDoc} */ - @Override - public double[][] getData() { - final int dim = getRowDimension(); - final double[][] out = new double[dim][dim]; - - for (int i = 0; i < dim; i++) { - out[i][i] = data[i]; - } - - return out; - } - - /** - * Gets a reference to the underlying data array. - * - * @return 1-dimensional array of entries. - */ - public double[] getDataRef() { - return data; - } - - /** {@inheritDoc} */ - @Override - public double getEntry(final int row, final int column) - throws OutOfRangeException { - MatrixUtils.checkMatrixIndex(this, row, column); - return row == column ? data[row] : 0; - } - - /** {@inheritDoc} - * @throws NumberIsTooLargeException if {@code row != column} and value is non-zero. - */ - @Override - public void setEntry(final int row, final int column, final double value) - throws OutOfRangeException, NumberIsTooLargeException { - if (row == column) { - MatrixUtils.checkRowIndex(this, row); - data[row] = value; - } else { - ensureZero(value); - } - } - - /** {@inheritDoc} - * @throws NumberIsTooLargeException if {@code row != column} and increment is non-zero. - */ - @Override - public void addToEntry(final int row, - final int column, - final double increment) - throws OutOfRangeException, NumberIsTooLargeException { - if (row == column) { - MatrixUtils.checkRowIndex(this, row); - data[row] += increment; - } else { - ensureZero(increment); - } - } - - /** {@inheritDoc} */ - @Override - public void multiplyEntry(final int row, - final int column, - final double factor) - throws OutOfRangeException { - // we don't care about non-diagonal elements for multiplication - if (row == column) { - MatrixUtils.checkRowIndex(this, row); - data[row] *= factor; - } - } - - /** {@inheritDoc} */ - @Override - public int getRowDimension() { - return data.length; - } - - /** {@inheritDoc} */ - @Override - public int getColumnDimension() { - return data.length; - } - - /** {@inheritDoc} */ - @Override - public double[] operate(final double[] v) - throws DimensionMismatchException { - return multiply(new DiagonalMatrix(v, false)).getDataRef(); - } - - /** {@inheritDoc} */ - @Override - public double[] preMultiply(final double[] v) - throws DimensionMismatchException { - return operate(v); - } - - /** {@inheritDoc} */ - @Override - public RealVector preMultiply(final RealVector v) throws DimensionMismatchException { - final double[] vectorData; - if (v instanceof ArrayRealVector) { - vectorData = ((ArrayRealVector) v).getDataRef(); - } else { - vectorData = v.toArray(); - } - return MatrixUtils.createRealVector(preMultiply(vectorData)); - } - - /** Ensure a value is zero. - * @param value value to check - * @exception NumberIsTooLargeException if value is not zero - */ - private void ensureZero(final double value) throws NumberIsTooLargeException { - if (!Precision.equals(0.0, value, 1)) { - throw new NumberIsTooLargeException(FastMath.abs(value), 0, true); - } - } - - /** - * Computes the inverse of this diagonal matrix. - *

- * Note: this method will use a singularity threshold of 0, - * use {@link #inverse(double)} if a different threshold is needed. - * - * @return the inverse of {@code m} - * @throws SingularMatrixException if the matrix is singular - * @since 3.3 - */ - public DiagonalMatrix inverse() throws SingularMatrixException { - return inverse(0); - } - - /** - * Computes the inverse of this diagonal matrix. - * - * @param threshold Singularity threshold. - * @return the inverse of {@code m} - * @throws SingularMatrixException if the matrix is singular - * @since 3.3 - */ - public DiagonalMatrix inverse(double threshold) throws SingularMatrixException { - if (isSingular(threshold)) { - throw new SingularMatrixException(); - } - - final double[] result = new double[data.length]; - for (int i = 0; i < data.length; i++) { - result[i] = 1.0 / data[i]; - } - return new DiagonalMatrix(result, false); - } - - /** Returns whether this diagonal matrix is singular, i.e. any diagonal entry - * is equal to {@code 0} within the given threshold. - * - * @param threshold Singularity threshold. - * @return {@code true} if the matrix is singular, {@code false} otherwise - * @since 3.3 - */ - public boolean isSingular(double threshold) { - for (int i = 0; i < data.length; i++) { - if (Precision.equals(data[i], 0.0, threshold)) { - return true; - } - } - return false; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/EigenDecomposition.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/EigenDecomposition.java deleted file mode 100644 index 4517c5cc6..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/EigenDecomposition.java +++ /dev/null @@ -1,942 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.numbers.complex.Complex; -import org.apache.commons.numbers.core.Precision; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.MathUnsupportedOperationException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; - -/** - * Calculates the eigen decomposition of a real matrix. - *

- * The eigen decomposition of matrix A is a set of two matrices: - * V and D such that A = V × D × VT. - * A, V and D are all m × m matrices. - *

- * This class is similar in spirit to the {@code EigenvalueDecomposition} - * class from the JAMA - * library, with the following changes: - *

    - *
  • a {@link #getVT() getVt} method has been added,
  • - *
  • two {@link #getRealEigenvalue(int) getRealEigenvalue} and - * {@link #getImagEigenvalue(int) getImagEigenvalue} methods to pick up a - * single eigenvalue have been added,
  • - *
  • a {@link #getEigenvector(int) getEigenvector} method to pick up a - * single eigenvector has been added,
  • - *
  • a {@link #getDeterminant() getDeterminant} method has been added.
  • - *
  • a {@link #getSolver() getSolver} method has been added.
  • - *
- *

- * As of 3.1, this class supports general real matrices (both symmetric and non-symmetric): - *

- * If A is symmetric, then A = V*D*V' where the eigenvalue matrix D is diagonal - * and the eigenvector matrix V is orthogonal, i.e. - * {@code A = V.multiply(D.multiply(V.transpose()))} and - * {@code V.multiply(V.transpose())} equals the identity matrix. - *

- *

- * If A is not symmetric, then the eigenvalue matrix D is block diagonal with the real - * eigenvalues in 1-by-1 blocks and any complex eigenvalues, lambda + i*mu, in 2-by-2 - * blocks: - *

- *    [lambda, mu    ]
- *    [   -mu, lambda]
- * 
- * The columns of V represent the eigenvectors in the sense that {@code A*V = V*D}, - * i.e. A.multiply(V) equals V.multiply(D). - * The matrix V may be badly conditioned, or even singular, so the validity of the - * equation {@code A = V*D*inverse(V)} depends upon the condition of V. - *

- * This implementation is based on the paper by A. Drubrulle, R.S. Martin and - * J.H. Wilkinson "The Implicit QL Algorithm" in Wilksinson and Reinsch (1971) - * Handbook for automatic computation, vol. 2, Linear algebra, Springer-Verlag, - * New-York. - * - * @see MathWorld - * @see Wikipedia - * @since 2.0 (changed to concrete class in 3.0) - */ -public class EigenDecomposition { - /** Internally used epsilon criteria. */ - private static final double EPSILON = 1e-12; - /** Maximum number of iterations accepted in the implicit QL transformation */ - private static final byte MAX_ITER = 30; - /** Main diagonal of the tridiagonal matrix. */ - private double[] main; - /** Secondary diagonal of the tridiagonal matrix. */ - private double[] secondary; - /** - * Transformer to tridiagonal (may be null if matrix is already - * tridiagonal). - */ - private TriDiagonalTransformer transformer; - /** Real part of the realEigenvalues. */ - private double[] realEigenvalues; - /** Imaginary part of the realEigenvalues. */ - private double[] imagEigenvalues; - /** Eigenvectors. */ - private ArrayRealVector[] eigenvectors; - /** Cached value of V. */ - private RealMatrix cachedV; - /** Cached value of D. */ - private RealMatrix cachedD; - /** Cached value of Vt. */ - private RealMatrix cachedVt; - /** Whether the matrix is symmetric. */ - private final boolean isSymmetric; - - /** - * Calculates the eigen decomposition of the given real matrix. - *

- * Supports decomposition of a general matrix since 3.1. - * - * @param matrix Matrix to decompose. - * @throws MaxCountExceededException if the algorithm fails to converge. - * @throws MathArithmeticException if the decomposition of a general matrix - * results in a matrix with zero norm - * @since 3.1 - */ - public EigenDecomposition(final RealMatrix matrix) - throws MathArithmeticException { - final double symTol = 10 * matrix.getRowDimension() * matrix.getColumnDimension() * Precision.EPSILON; - isSymmetric = MatrixUtils.isSymmetric(matrix, symTol); - if (isSymmetric) { - transformToTridiagonal(matrix); - findEigenVectors(transformer.getQ().getData()); - } else { - final SchurTransformer t = transformToSchur(matrix); - findEigenVectorsFromSchur(t); - } - } - - /** - * Calculates the eigen decomposition of the symmetric tridiagonal - * matrix. The Householder matrix is assumed to be the identity matrix. - * - * @param main Main diagonal of the symmetric tridiagonal form. - * @param secondary Secondary of the tridiagonal form. - * @throws MaxCountExceededException if the algorithm fails to converge. - * @since 3.1 - */ - public EigenDecomposition(final double[] main, final double[] secondary) { - isSymmetric = true; - this.main = main.clone(); - this.secondary = secondary.clone(); - transformer = null; - final int size = main.length; - final double[][] z = new double[size][size]; - for (int i = 0; i < size; i++) { - z[i][i] = 1.0; - } - findEigenVectors(z); - } - - /** - * Gets the matrix V of the decomposition. - * V is an orthogonal matrix, i.e. its transpose is also its inverse. - * The columns of V are the eigenvectors of the original matrix. - * No assumption is made about the orientation of the system axes formed - * by the columns of V (e.g. in a 3-dimension space, V can form a left- - * or right-handed system). - * - * @return the V matrix. - */ - public RealMatrix getV() { - - if (cachedV == null) { - final int m = eigenvectors.length; - cachedV = MatrixUtils.createRealMatrix(m, m); - for (int k = 0; k < m; ++k) { - cachedV.setColumnVector(k, eigenvectors[k]); - } - } - // return the cached matrix - return cachedV; - } - - /** - * Gets the block diagonal matrix D of the decomposition. - * D is a block diagonal matrix. - * Real eigenvalues are on the diagonal while complex values are on - * 2x2 blocks { {real +imaginary}, {-imaginary, real} }. - * - * @return the D matrix. - * - * @see #getRealEigenvalues() - * @see #getImagEigenvalues() - */ - public RealMatrix getD() { - - if (cachedD == null) { - // cache the matrix for subsequent calls - cachedD = MatrixUtils.createRealMatrixWithDiagonal(realEigenvalues); - - for (int i = 0; i < imagEigenvalues.length; i++) { - if (Precision.compareTo(imagEigenvalues[i], 0.0, EPSILON) > 0) { - cachedD.setEntry(i, i+1, imagEigenvalues[i]); - } else if (Precision.compareTo(imagEigenvalues[i], 0.0, EPSILON) < 0) { - cachedD.setEntry(i, i-1, imagEigenvalues[i]); - } - } - } - return cachedD; - } - - /** - * Gets the transpose of the matrix V of the decomposition. - * V is an orthogonal matrix, i.e. its transpose is also its inverse. - * The columns of V are the eigenvectors of the original matrix. - * No assumption is made about the orientation of the system axes formed - * by the columns of V (e.g. in a 3-dimension space, V can form a left- - * or right-handed system). - * - * @return the transpose of the V matrix. - */ - public RealMatrix getVT() { - - if (cachedVt == null) { - final int m = eigenvectors.length; - cachedVt = MatrixUtils.createRealMatrix(m, m); - for (int k = 0; k < m; ++k) { - cachedVt.setRowVector(k, eigenvectors[k]); - } - } - - // return the cached matrix - return cachedVt; - } - - /** - * Returns whether the calculated eigen values are complex or real. - *

The method performs a zero check for each element of the - * {@link #getImagEigenvalues()} array and returns {@code true} if any - * element is not equal to zero. - * - * @return {@code true} if the eigen values are complex, {@code false} otherwise - * @since 3.1 - */ - public boolean hasComplexEigenvalues() { - for (int i = 0; i < imagEigenvalues.length; i++) { - if (!Precision.equals(imagEigenvalues[i], 0.0, EPSILON)) { - return true; - } - } - return false; - } - - /** - * Gets a copy of the real parts of the eigenvalues of the original matrix. - * - * @return a copy of the real parts of the eigenvalues of the original matrix. - * - * @see #getD() - * @see #getRealEigenvalue(int) - * @see #getImagEigenvalues() - */ - public double[] getRealEigenvalues() { - return realEigenvalues.clone(); - } - - /** - * Returns the real part of the ith eigenvalue of the original - * matrix. - * - * @param i index of the eigenvalue (counting from 0) - * @return real part of the ith eigenvalue of the original - * matrix. - * - * @see #getD() - * @see #getRealEigenvalues() - * @see #getImagEigenvalue(int) - */ - public double getRealEigenvalue(final int i) { - return realEigenvalues[i]; - } - - /** - * Gets a copy of the imaginary parts of the eigenvalues of the original - * matrix. - * - * @return a copy of the imaginary parts of the eigenvalues of the original - * matrix. - * - * @see #getD() - * @see #getImagEigenvalue(int) - * @see #getRealEigenvalues() - */ - public double[] getImagEigenvalues() { - return imagEigenvalues.clone(); - } - - /** - * Gets the imaginary part of the ith eigenvalue of the original - * matrix. - * - * @param i Index of the eigenvalue (counting from 0). - * @return the imaginary part of the ith eigenvalue of the original - * matrix. - * - * @see #getD() - * @see #getImagEigenvalues() - * @see #getRealEigenvalue(int) - */ - public double getImagEigenvalue(final int i) { - return imagEigenvalues[i]; - } - - /** - * Gets a copy of the ith eigenvector of the original matrix. - * - * @param i Index of the eigenvector (counting from 0). - * @return a copy of the ith eigenvector of the original matrix. - * @see #getD() - */ - public RealVector getEigenvector(final int i) { - return eigenvectors[i].copy(); - } - - /** - * Computes the determinant of the matrix. - * - * @return the determinant of the matrix. - */ - public double getDeterminant() { - double determinant = 1; - for (double lambda : realEigenvalues) { - determinant *= lambda; - } - return determinant; - } - - /** - * Computes the square-root of the matrix. - * This implementation assumes that the matrix is symmetric and positive - * definite. - * - * @return the square-root of the matrix. - * @throws MathUnsupportedOperationException if the matrix is not - * symmetric or not positive definite. - * @since 3.1 - */ - public RealMatrix getSquareRoot() { - if (!isSymmetric) { - throw new MathUnsupportedOperationException(); - } - - final double[] sqrtEigenValues = new double[realEigenvalues.length]; - for (int i = 0; i < realEigenvalues.length; i++) { - final double eigen = realEigenvalues[i]; - if (eigen <= 0) { - throw new MathUnsupportedOperationException(); - } - sqrtEigenValues[i] = FastMath.sqrt(eigen); - } - final RealMatrix sqrtEigen = MatrixUtils.createRealDiagonalMatrix(sqrtEigenValues); - final RealMatrix v = getV(); - final RealMatrix vT = getVT(); - - return v.multiply(sqrtEigen).multiply(vT); - } - - /** - * Gets a solver for finding the A × X = B solution in exact - * linear sense. - *

- * Since 3.1, eigen decomposition of a general matrix is supported, - * but the {@link DecompositionSolver} only supports real eigenvalues. - * - * @return a solver - * @throws MathUnsupportedOperationException if the decomposition resulted in - * complex eigenvalues - */ - public DecompositionSolver getSolver() { - if (hasComplexEigenvalues()) { - throw new MathUnsupportedOperationException(); - } - return new Solver(realEigenvalues, imagEigenvalues, eigenvectors); - } - - /** Specialized solver. */ - private static class Solver implements DecompositionSolver { - /** Real part of the realEigenvalues. */ - private final double[] realEigenvalues; - /** Imaginary part of the realEigenvalues. */ - private final double[] imagEigenvalues; - /** Eigenvectors. */ - private final ArrayRealVector[] eigenvectors; - - /** - * Builds a solver from decomposed matrix. - * - * @param realEigenvalues Real parts of the eigenvalues. - * @param imagEigenvalues Imaginary parts of the eigenvalues. - * @param eigenvectors Eigenvectors. - */ - private Solver(final double[] realEigenvalues, - final double[] imagEigenvalues, - final ArrayRealVector[] eigenvectors) { - this.realEigenvalues = realEigenvalues; - this.imagEigenvalues = imagEigenvalues; - this.eigenvectors = eigenvectors; - } - - /** - * Solves the linear equation A × X = B for symmetric matrices A. - *

- * This method only finds exact linear solutions, i.e. solutions for - * which ||A × X - B|| is exactly 0. - *

- * - * @param b Right-hand side of the equation A × X = B. - * @return a Vector X that minimizes the two norm of A × X - B. - * - * @throws DimensionMismatchException if the matrices dimensions do not match. - * @throws SingularMatrixException if the decomposed matrix is singular. - */ - @Override - public RealVector solve(final RealVector b) { - if (!isNonSingular()) { - throw new SingularMatrixException(); - } - - final int m = realEigenvalues.length; - if (b.getDimension() != m) { - throw new DimensionMismatchException(b.getDimension(), m); - } - - final double[] bp = new double[m]; - for (int i = 0; i < m; ++i) { - final ArrayRealVector v = eigenvectors[i]; - final double[] vData = v.getDataRef(); - final double s = v.dotProduct(b) / realEigenvalues[i]; - for (int j = 0; j < m; ++j) { - bp[j] += s * vData[j]; - } - } - - return new ArrayRealVector(bp, false); - } - - /** {@inheritDoc} */ - @Override - public RealMatrix solve(RealMatrix b) { - - if (!isNonSingular()) { - throw new SingularMatrixException(); - } - - final int m = realEigenvalues.length; - if (b.getRowDimension() != m) { - throw new DimensionMismatchException(b.getRowDimension(), m); - } - - final int nColB = b.getColumnDimension(); - final double[][] bp = new double[m][nColB]; - final double[] tmpCol = new double[m]; - for (int k = 0; k < nColB; ++k) { - for (int i = 0; i < m; ++i) { - tmpCol[i] = b.getEntry(i, k); - bp[i][k] = 0; - } - for (int i = 0; i < m; ++i) { - final ArrayRealVector v = eigenvectors[i]; - final double[] vData = v.getDataRef(); - double s = 0; - for (int j = 0; j < m; ++j) { - s += v.getEntry(j) * tmpCol[j]; - } - s /= realEigenvalues[i]; - for (int j = 0; j < m; ++j) { - bp[j][k] += s * vData[j]; - } - } - } - - return new Array2DRowRealMatrix(bp, false); - - } - - /** - * Checks whether the decomposed matrix is non-singular. - * - * @return true if the decomposed matrix is non-singular. - */ - @Override - public boolean isNonSingular() { - double largestEigenvalueNorm = 0.0; - // Looping over all values (in case they are not sorted in decreasing - // order of their norm). - for (int i = 0; i < realEigenvalues.length; ++i) { - largestEigenvalueNorm = FastMath.max(largestEigenvalueNorm, eigenvalueNorm(i)); - } - // Corner case: zero matrix, all exactly 0 eigenvalues - if (largestEigenvalueNorm == 0.0) { - return false; - } - for (int i = 0; i < realEigenvalues.length; ++i) { - // Looking for eigenvalues that are 0, where we consider anything much much smaller - // than the largest eigenvalue to be effectively 0. - if (Precision.equals(eigenvalueNorm(i) / largestEigenvalueNorm, 0, EPSILON)) { - return false; - } - } - return true; - } - - /** - * @param i which eigenvalue to find the norm of - * @return the norm of ith (complex) eigenvalue. - */ - private double eigenvalueNorm(int i) { - final double re = realEigenvalues[i]; - final double im = imagEigenvalues[i]; - return FastMath.sqrt(re * re + im * im); - } - - /** - * Get the inverse of the decomposed matrix. - * - * @return the inverse matrix. - * @throws SingularMatrixException if the decomposed matrix is singular. - */ - @Override - public RealMatrix getInverse() { - if (!isNonSingular()) { - throw new SingularMatrixException(); - } - - final int m = realEigenvalues.length; - final double[][] invData = new double[m][m]; - - for (int i = 0; i < m; ++i) { - final double[] invI = invData[i]; - for (int j = 0; j < m; ++j) { - double invIJ = 0; - for (int k = 0; k < m; ++k) { - final double[] vK = eigenvectors[k].getDataRef(); - invIJ += vK[i] * vK[j] / realEigenvalues[k]; - } - invI[j] = invIJ; - } - } - return MatrixUtils.createRealMatrix(invData); - } - } - - /** - * Transforms the matrix to tridiagonal form. - * - * @param matrix Matrix to transform. - */ - private void transformToTridiagonal(final RealMatrix matrix) { - // transform the matrix to tridiagonal - transformer = new TriDiagonalTransformer(matrix); - main = transformer.getMainDiagonalRef(); - secondary = transformer.getSecondaryDiagonalRef(); - } - - /** - * Find eigenvalues and eigenvectors (Dubrulle et al., 1971) - * - * @param householderMatrix Householder matrix of the transformation - * to tridiagonal form. - */ - private void findEigenVectors(final double[][] householderMatrix) { - final double[][]z = householderMatrix.clone(); - final int n = main.length; - realEigenvalues = new double[n]; - imagEigenvalues = new double[n]; - final double[] e = new double[n]; - for (int i = 0; i < n - 1; i++) { - realEigenvalues[i] = main[i]; - e[i] = secondary[i]; - } - realEigenvalues[n - 1] = main[n - 1]; - e[n - 1] = 0; - - // Determine the largest main and secondary value in absolute term. - double maxAbsoluteValue = 0; - for (int i = 0; i < n; i++) { - if (FastMath.abs(realEigenvalues[i]) > maxAbsoluteValue) { - maxAbsoluteValue = FastMath.abs(realEigenvalues[i]); - } - if (FastMath.abs(e[i]) > maxAbsoluteValue) { - maxAbsoluteValue = FastMath.abs(e[i]); - } - } - // Make null any main and secondary value too small to be significant - if (maxAbsoluteValue != 0) { - for (int i=0; i < n; i++) { - if (FastMath.abs(realEigenvalues[i]) <= Precision.EPSILON * maxAbsoluteValue) { - realEigenvalues[i] = 0; - } - if (FastMath.abs(e[i]) <= Precision.EPSILON * maxAbsoluteValue) { - e[i]=0; - } - } - } - - for (int j = 0; j < n; j++) { - int its = 0; - int m; - do { - for (m = j; m < n - 1; m++) { - double delta = FastMath.abs(realEigenvalues[m]) + - FastMath.abs(realEigenvalues[m + 1]); - if (FastMath.abs(e[m]) + delta == delta) { - break; - } - } - if (m != j) { - if (its == MAX_ITER) { - throw new MaxCountExceededException(LocalizedFormats.CONVERGENCE_FAILED, - MAX_ITER); - } - its++; - double q = (realEigenvalues[j + 1] - realEigenvalues[j]) / (2 * e[j]); - double t = FastMath.sqrt(1 + q * q); - if (q < 0.0) { - q = realEigenvalues[m] - realEigenvalues[j] + e[j] / (q - t); - } else { - q = realEigenvalues[m] - realEigenvalues[j] + e[j] / (q + t); - } - double u = 0.0; - double s = 1.0; - double c = 1.0; - int i; - for (i = m - 1; i >= j; i--) { - double p = s * e[i]; - double h = c * e[i]; - if (FastMath.abs(p) >= FastMath.abs(q)) { - c = q / p; - t = FastMath.sqrt(c * c + 1.0); - e[i + 1] = p * t; - s = 1.0 / t; - c *= s; - } else { - s = p / q; - t = FastMath.sqrt(s * s + 1.0); - e[i + 1] = q * t; - c = 1.0 / t; - s *= c; - } - if (e[i + 1] == 0.0) { - realEigenvalues[i + 1] -= u; - e[m] = 0.0; - break; - } - q = realEigenvalues[i + 1] - u; - t = (realEigenvalues[i] - q) * s + 2.0 * c * h; - u = s * t; - realEigenvalues[i + 1] = q + u; - q = c * t - h; - for (int ia = 0; ia < n; ia++) { - p = z[ia][i + 1]; - z[ia][i + 1] = s * z[ia][i] + c * p; - z[ia][i] = c * z[ia][i] - s * p; - } - } - if (t == 0.0 && i >= j) { - continue; - } - realEigenvalues[j] -= u; - e[j] = q; - e[m] = 0.0; - } - } while (m != j); - } - - //Sort the eigen values (and vectors) in increase order - for (int i = 0; i < n; i++) { - int k = i; - double p = realEigenvalues[i]; - for (int j = i + 1; j < n; j++) { - if (realEigenvalues[j] > p) { - k = j; - p = realEigenvalues[j]; - } - } - if (k != i) { - realEigenvalues[k] = realEigenvalues[i]; - realEigenvalues[i] = p; - for (int j = 0; j < n; j++) { - p = z[j][i]; - z[j][i] = z[j][k]; - z[j][k] = p; - } - } - } - - // Determine the largest eigen value in absolute term. - maxAbsoluteValue = 0; - for (int i = 0; i < n; i++) { - if (FastMath.abs(realEigenvalues[i]) > maxAbsoluteValue) { - maxAbsoluteValue=FastMath.abs(realEigenvalues[i]); - } - } - // Make null any eigen value too small to be significant - if (maxAbsoluteValue != 0.0) { - for (int i=0; i < n; i++) { - if (FastMath.abs(realEigenvalues[i]) < Precision.EPSILON * maxAbsoluteValue) { - realEigenvalues[i] = 0; - } - } - } - eigenvectors = new ArrayRealVector[n]; - final double[] tmp = new double[n]; - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { - tmp[j] = z[j][i]; - } - eigenvectors[i] = new ArrayRealVector(tmp); - } - } - - /** - * Transforms the matrix to Schur form and calculates the eigenvalues. - * - * @param matrix Matrix to transform. - * @return the {@link SchurTransformer Shur transform} for this matrix - */ - private SchurTransformer transformToSchur(final RealMatrix matrix) { - final SchurTransformer schurTransform = new SchurTransformer(matrix); - final double[][] matT = schurTransform.getT().getData(); - - realEigenvalues = new double[matT.length]; - imagEigenvalues = new double[matT.length]; - - for (int i = 0; i < realEigenvalues.length; i++) { - if (i == (realEigenvalues.length - 1) || - Precision.equals(matT[i + 1][i], 0.0, EPSILON)) { - realEigenvalues[i] = matT[i][i]; - } else { - final double x = matT[i + 1][i + 1]; - final double p = 0.5 * (matT[i][i] - x); - final double z = FastMath.sqrt(FastMath.abs(p * p + matT[i + 1][i] * matT[i][i + 1])); - realEigenvalues[i] = x + p; - imagEigenvalues[i] = z; - realEigenvalues[i + 1] = x + p; - imagEigenvalues[i + 1] = -z; - i++; - } - } - return schurTransform; - } - - /** - * Performs a division of two complex numbers. - * - * @param xr real part of the first number - * @param xi imaginary part of the first number - * @param yr real part of the second number - * @param yi imaginary part of the second number - * @return result of the complex division - */ - private Complex cdiv(final double xr, final double xi, - final double yr, final double yi) { - return Complex.ofCartesian(xr, xi).divide(Complex.ofCartesian(yr, yi)); - } - - /** - * Find eigenvectors from a matrix transformed to Schur form. - * - * @param schur the schur transformation of the matrix - * @throws MathArithmeticException if the Schur form has a norm of zero - */ - private void findEigenVectorsFromSchur(final SchurTransformer schur) - throws MathArithmeticException { - final double[][] matrixT = schur.getT().getData(); - final double[][] matrixP = schur.getP().getData(); - - final int n = matrixT.length; - - // compute matrix norm - double norm = 0.0; - for (int i = 0; i < n; i++) { - for (int j = FastMath.max(i - 1, 0); j < n; j++) { - norm += FastMath.abs(matrixT[i][j]); - } - } - - // we can not handle a matrix with zero norm - if (Precision.equals(norm, 0.0, EPSILON)) { - throw new MathArithmeticException(LocalizedFormats.ZERO_NORM); - } - - // Backsubstitute to find vectors of upper triangular form - - double r = 0.0; - double s = 0.0; - double z = 0.0; - - for (int idx = n - 1; idx >= 0; idx--) { - double p = realEigenvalues[idx]; - double q = imagEigenvalues[idx]; - - if (Precision.equals(q, 0.0)) { - // Real vector - int l = idx; - matrixT[idx][idx] = 1.0; - for (int i = idx - 1; i >= 0; i--) { - double w = matrixT[i][i] - p; - r = 0.0; - for (int j = l; j <= idx; j++) { - r += matrixT[i][j] * matrixT[j][idx]; - } - if (Precision.compareTo(imagEigenvalues[i], 0.0, EPSILON) < 0) { - z = w; - s = r; - } else { - l = i; - if (Precision.equals(imagEigenvalues[i], 0.0)) { - if (w != 0.0) { - matrixT[i][idx] = -r / w; - } else { - matrixT[i][idx] = -r / (Precision.EPSILON * norm); - } - } else { - // Solve real equations - double x = matrixT[i][i + 1]; - double y = matrixT[i + 1][i]; - q = (realEigenvalues[i] - p) * (realEigenvalues[i] - p) + - imagEigenvalues[i] * imagEigenvalues[i]; - double t = (x * s - z * r) / q; - matrixT[i][idx] = t; - if (FastMath.abs(x) > FastMath.abs(z)) { - matrixT[i + 1][idx] = (-r - w * t) / x; - } else { - matrixT[i + 1][idx] = (-s - y * t) / z; - } - } - - // Overflow control - double t = FastMath.abs(matrixT[i][idx]); - if ((Precision.EPSILON * t) * t > 1) { - for (int j = i; j <= idx; j++) { - matrixT[j][idx] /= t; - } - } - } - } - } else if (q < 0.0) { - // Complex vector - int l = idx - 1; - - // Last vector component imaginary so matrix is triangular - if (FastMath.abs(matrixT[idx][idx - 1]) > FastMath.abs(matrixT[idx - 1][idx])) { - matrixT[idx - 1][idx - 1] = q / matrixT[idx][idx - 1]; - matrixT[idx - 1][idx] = -(matrixT[idx][idx] - p) / matrixT[idx][idx - 1]; - } else { - final Complex result = cdiv(0.0, -matrixT[idx - 1][idx], - matrixT[idx - 1][idx - 1] - p, q); - matrixT[idx - 1][idx - 1] = result.getReal(); - matrixT[idx - 1][idx] = result.getImaginary(); - } - - matrixT[idx][idx - 1] = 0.0; - matrixT[idx][idx] = 1.0; - - for (int i = idx - 2; i >= 0; i--) { - double ra = 0.0; - double sa = 0.0; - for (int j = l; j <= idx; j++) { - ra += matrixT[i][j] * matrixT[j][idx - 1]; - sa += matrixT[i][j] * matrixT[j][idx]; - } - double w = matrixT[i][i] - p; - - if (Precision.compareTo(imagEigenvalues[i], 0.0, EPSILON) < 0) { - z = w; - r = ra; - s = sa; - } else { - l = i; - if (Precision.equals(imagEigenvalues[i], 0.0)) { - final Complex c = cdiv(-ra, -sa, w, q); - matrixT[i][idx - 1] = c.getReal(); - matrixT[i][idx] = c.getImaginary(); - } else { - // Solve complex equations - double x = matrixT[i][i + 1]; - double y = matrixT[i + 1][i]; - double vr = (realEigenvalues[i] - p) * (realEigenvalues[i] - p) + - imagEigenvalues[i] * imagEigenvalues[i] - q * q; - final double vi = (realEigenvalues[i] - p) * 2.0 * q; - if (Precision.equals(vr, 0.0) && Precision.equals(vi, 0.0)) { - vr = Precision.EPSILON * norm * - (FastMath.abs(w) + FastMath.abs(q) + FastMath.abs(x) + - FastMath.abs(y) + FastMath.abs(z)); - } - final Complex c = cdiv(x * r - z * ra + q * sa, - x * s - z * sa - q * ra, vr, vi); - matrixT[i][idx - 1] = c.getReal(); - matrixT[i][idx] = c.getImaginary(); - - if (FastMath.abs(x) > (FastMath.abs(z) + FastMath.abs(q))) { - matrixT[i + 1][idx - 1] = (-ra - w * matrixT[i][idx - 1] + - q * matrixT[i][idx]) / x; - matrixT[i + 1][idx] = (-sa - w * matrixT[i][idx] - - q * matrixT[i][idx - 1]) / x; - } else { - final Complex c2 = cdiv(-r - y * matrixT[i][idx - 1], - -s - y * matrixT[i][idx], z, q); - matrixT[i + 1][idx - 1] = c2.getReal(); - matrixT[i + 1][idx] = c2.getImaginary(); - } - } - - // Overflow control - double t = FastMath.max(FastMath.abs(matrixT[i][idx - 1]), - FastMath.abs(matrixT[i][idx])); - if ((Precision.EPSILON * t) * t > 1) { - for (int j = i; j <= idx; j++) { - matrixT[j][idx - 1] /= t; - matrixT[j][idx] /= t; - } - } - } - } - } - } - - // Back transformation to get eigenvectors of original matrix - for (int j = n - 1; j >= 0; j--) { - for (int i = 0; i <= n - 1; i++) { - z = 0.0; - for (int k = 0; k <= FastMath.min(j, n - 1); k++) { - z += matrixP[i][k] * matrixT[k][j]; - } - matrixP[i][j] = z; - } - } - - eigenvectors = new ArrayRealVector[n]; - final double[] tmp = new double[n]; - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { - tmp[j] = matrixP[j][i]; - } - eigenvectors[i] = new ArrayRealVector(tmp); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldDecompositionSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldDecompositionSolver.java deleted file mode 100644 index 92f95d51f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldDecompositionSolver.java +++ /dev/null @@ -1,75 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.FieldElement; - - -/** - * Interface handling decomposition algorithms that can solve A × X = B. - *

Decomposition algorithms decompose an A matrix has a product of several specific - * matrices from which they can solve A × X = B in least squares sense: they find X - * such that ||A × X - B|| is minimal.

- *

Some solvers like {@link FieldLUDecomposition} can only find the solution for - * square matrices and when the solution is an exact linear solution, i.e. when - * ||A × X - B|| is exactly 0. Other solvers can also find solutions - * with non-square matrix A and with non-null minimal norm. If an exact linear - * solution exists it is also the minimal norm solution.

- * - * @param the type of the field elements - * @since 2.0 - */ -public interface FieldDecompositionSolver> { - - /** Solve the linear equation A × X = B for matrices A. - *

The A matrix is implicit, it is provided by the underlying - * decomposition algorithm.

- * @param b right-hand side of the equation A × X = B - * @return a vector X that minimizes the two norm of A × X - B - * @throws org.apache.commons.math4.exception.DimensionMismatchException - * if the matrices dimensions do not match. - * @throws SingularMatrixException - * if the decomposed matrix is singular. - */ - FieldVector solve(final FieldVector b); - - /** Solve the linear equation A × X = B for matrices A. - *

The A matrix is implicit, it is provided by the underlying - * decomposition algorithm.

- * @param b right-hand side of the equation A × X = B - * @return a matrix X that minimizes the two norm of A × X - B - * @throws org.apache.commons.math4.exception.DimensionMismatchException - * if the matrices dimensions do not match. - * @throws SingularMatrixException - * if the decomposed matrix is singular. - */ - FieldMatrix solve(final FieldMatrix b); - - /** - * Check if the decomposed matrix is non-singular. - * @return true if the decomposed matrix is non-singular - */ - boolean isNonSingular(); - - /** Get the inverse (or pseudo-inverse) of the decomposed matrix. - * @return inverse matrix - * @throws SingularMatrixException - * if the decomposed matrix is singular. - */ - FieldMatrix getInverse(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldLUDecomposition.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldLUDecomposition.java deleted file mode 100644 index e733f42bf..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldLUDecomposition.java +++ /dev/null @@ -1,450 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.util.MathArrays; - -/** - * Calculates the LUP-decomposition of a square matrix. - *

The LUP-decomposition of a matrix A consists of three matrices - * L, U and P that satisfy: PA = LU, L is lower triangular, and U is - * upper triangular and P is a permutation matrix. All matrices are - * m×m.

- *

Since {@link FieldElement field elements} do not provide an ordering - * operator, the permutation matrix is computed here only in order to avoid - * a zero pivot element, no attempt is done to get the largest pivot - * element.

- *

This class is based on the class with similar name from the - * JAMA library.

- *
    - *
  • a {@link #getP() getP} method has been added,
  • - *
  • the {@code det} method has been renamed as {@link #getDeterminant() - * getDeterminant},
  • - *
  • the {@code getDoublePivot} method has been removed (but the int based - * {@link #getPivot() getPivot} method has been kept),
  • - *
  • the {@code solve} and {@code isNonSingular} methods have been replaced - * by a {@link #getSolver() getSolver} method and the equivalent methods - * provided by the returned {@link DecompositionSolver}.
  • - *
- * - * @param the type of the field elements - * @see MathWorld - * @see Wikipedia - * @since 2.0 (changed to concrete class in 3.0) - */ -public class FieldLUDecomposition> { - - /** Field to which the elements belong. */ - private final Field field; - - /** Entries of LU decomposition. */ - private T[][] lu; - - /** Pivot permutation associated with LU decomposition. */ - private int[] pivot; - - /** Parity of the permutation associated with the LU decomposition. */ - private boolean even; - - /** Singularity indicator. */ - private boolean singular; - - /** Cached value of L. */ - private FieldMatrix cachedL; - - /** Cached value of U. */ - private FieldMatrix cachedU; - - /** Cached value of P. */ - private FieldMatrix cachedP; - - /** - * Calculates the LU-decomposition of the given matrix. - * @param matrix The matrix to decompose. - * @throws NonSquareMatrixException if matrix is not square - */ - public FieldLUDecomposition(FieldMatrix matrix) { - if (!matrix.isSquare()) { - throw new NonSquareMatrixException(matrix.getRowDimension(), - matrix.getColumnDimension()); - } - - final int m = matrix.getColumnDimension(); - field = matrix.getField(); - lu = matrix.getData(); - pivot = new int[m]; - cachedL = null; - cachedU = null; - cachedP = null; - - // Initialize permutation array and parity - for (int row = 0; row < m; row++) { - pivot[row] = row; - } - even = true; - singular = false; - - // Loop over columns - for (int col = 0; col < m; col++) { - - T sum = field.getZero(); - - // upper - for (int row = 0; row < col; row++) { - final T[] luRow = lu[row]; - sum = luRow[col]; - for (int i = 0; i < row; i++) { - sum = sum.subtract(luRow[i].multiply(lu[i][col])); - } - luRow[col] = sum; - } - - // lower - int nonZero = col; // permutation row - for (int row = col; row < m; row++) { - final T[] luRow = lu[row]; - sum = luRow[col]; - for (int i = 0; i < col; i++) { - sum = sum.subtract(luRow[i].multiply(lu[i][col])); - } - luRow[col] = sum; - - if (lu[nonZero][col].equals(field.getZero())) { - // try to select a better permutation choice - ++nonZero; - } - } - - // Singularity check - if (nonZero >= m) { - singular = true; - return; - } - - // Pivot if necessary - if (nonZero != col) { - T tmp = field.getZero(); - for (int i = 0; i < m; i++) { - tmp = lu[nonZero][i]; - lu[nonZero][i] = lu[col][i]; - lu[col][i] = tmp; - } - int temp = pivot[nonZero]; - pivot[nonZero] = pivot[col]; - pivot[col] = temp; - even = !even; - } - - // Divide the lower elements by the "winning" diagonal elt. - final T luDiag = lu[col][col]; - for (int row = col + 1; row < m; row++) { - final T[] luRow = lu[row]; - luRow[col] = luRow[col].divide(luDiag); - } - } - - } - - /** - * Returns the matrix L of the decomposition. - *

L is a lower-triangular matrix

- * @return the L matrix (or null if decomposed matrix is singular) - */ - public FieldMatrix getL() { - if ((cachedL == null) && !singular) { - final int m = pivot.length; - cachedL = new Array2DRowFieldMatrix<>(field, m, m); - for (int i = 0; i < m; ++i) { - final T[] luI = lu[i]; - for (int j = 0; j < i; ++j) { - cachedL.setEntry(i, j, luI[j]); - } - cachedL.setEntry(i, i, field.getOne()); - } - } - return cachedL; - } - - /** - * Returns the matrix U of the decomposition. - *

U is an upper-triangular matrix

- * @return the U matrix (or null if decomposed matrix is singular) - */ - public FieldMatrix getU() { - if ((cachedU == null) && !singular) { - final int m = pivot.length; - cachedU = new Array2DRowFieldMatrix<>(field, m, m); - for (int i = 0; i < m; ++i) { - final T[] luI = lu[i]; - for (int j = i; j < m; ++j) { - cachedU.setEntry(i, j, luI[j]); - } - } - } - return cachedU; - } - - /** - * Returns the P rows permutation matrix. - *

P is a sparse matrix with exactly one element set to 1.0 in - * each row and each column, all other elements being set to 0.0.

- *

The positions of the 1 elements are given by the {@link #getPivot() - * pivot permutation vector}.

- * @return the P rows permutation matrix (or null if decomposed matrix is singular) - * @see #getPivot() - */ - public FieldMatrix getP() { - if ((cachedP == null) && !singular) { - final int m = pivot.length; - cachedP = new Array2DRowFieldMatrix<>(field, m, m); - for (int i = 0; i < m; ++i) { - cachedP.setEntry(i, pivot[i], field.getOne()); - } - } - return cachedP; - } - - /** - * Returns the pivot permutation vector. - * @return the pivot permutation vector - * @see #getP() - */ - public int[] getPivot() { - return pivot.clone(); - } - - /** - * Return the determinant of the matrix. - * @return determinant of the matrix - */ - public T getDeterminant() { - if (singular) { - return field.getZero(); - } else { - final int m = pivot.length; - T determinant = even ? field.getOne() : field.getZero().subtract(field.getOne()); - for (int i = 0; i < m; i++) { - determinant = determinant.multiply(lu[i][i]); - } - return determinant; - } - } - - /** - * Get a solver for finding the A × X = B solution in exact linear sense. - * @return a solver - */ - public FieldDecompositionSolver getSolver() { - return new Solver<>(field, lu, pivot, singular); - } - - /** Specialized solver. - * @param the type of the field elements - */ - private static class Solver> implements FieldDecompositionSolver { - - /** Field to which the elements belong. */ - private final Field field; - - /** Entries of LU decomposition. */ - private final T[][] lu; - - /** Pivot permutation associated with LU decomposition. */ - private final int[] pivot; - - /** Singularity indicator. */ - private final boolean singular; - - /** - * Build a solver from decomposed matrix. - * @param field field to which the matrix elements belong - * @param lu entries of LU decomposition - * @param pivot pivot permutation associated with LU decomposition - * @param singular singularity indicator - */ - private Solver(final Field field, final T[][] lu, - final int[] pivot, final boolean singular) { - this.field = field; - this.lu = lu; - this.pivot = pivot; - this.singular = singular; - } - - /** {@inheritDoc} */ - @Override - public boolean isNonSingular() { - return !singular; - } - - /** {@inheritDoc} */ - @Override - public FieldVector solve(FieldVector b) { - try { - return solve((ArrayFieldVector) b); - } catch (ClassCastException cce) { - - final int m = pivot.length; - if (b.getDimension() != m) { - throw new DimensionMismatchException(b.getDimension(), m); - } - if (singular) { - throw new SingularMatrixException(); - } - - // Apply permutations to b - final T[] bp = MathArrays.buildArray(field, m); - for (int row = 0; row < m; row++) { - bp[row] = b.getEntry(pivot[row]); - } - - // Solve LY = b - for (int col = 0; col < m; col++) { - final T bpCol = bp[col]; - for (int i = col + 1; i < m; i++) { - bp[i] = bp[i].subtract(bpCol.multiply(lu[i][col])); - } - } - - // Solve UX = Y - for (int col = m - 1; col >= 0; col--) { - bp[col] = bp[col].divide(lu[col][col]); - final T bpCol = bp[col]; - for (int i = 0; i < col; i++) { - bp[i] = bp[i].subtract(bpCol.multiply(lu[i][col])); - } - } - - return new ArrayFieldVector<>(field, bp, false); - - } - } - - /** Solve the linear equation A × X = B. - *

The A matrix is implicit here. It is

- * @param b right-hand side of the equation A × X = B - * @return a vector X such that A × X = B - * @throws DimensionMismatchException if the matrices dimensions do not match. - * @throws SingularMatrixException if the decomposed matrix is singular. - */ - public ArrayFieldVector solve(ArrayFieldVector b) { - final int m = pivot.length; - final int length = b.getDimension(); - if (length != m) { - throw new DimensionMismatchException(length, m); - } - if (singular) { - throw new SingularMatrixException(); - } - - // Apply permutations to b - final T[] bp = MathArrays.buildArray(field, m); - for (int row = 0; row < m; row++) { - bp[row] = b.getEntry(pivot[row]); - } - - // Solve LY = b - for (int col = 0; col < m; col++) { - final T bpCol = bp[col]; - for (int i = col + 1; i < m; i++) { - bp[i] = bp[i].subtract(bpCol.multiply(lu[i][col])); - } - } - - // Solve UX = Y - for (int col = m - 1; col >= 0; col--) { - bp[col] = bp[col].divide(lu[col][col]); - final T bpCol = bp[col]; - for (int i = 0; i < col; i++) { - bp[i] = bp[i].subtract(bpCol.multiply(lu[i][col])); - } - } - - return new ArrayFieldVector<>(bp, false); - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix solve(FieldMatrix b) { - final int m = pivot.length; - if (b.getRowDimension() != m) { - throw new DimensionMismatchException(b.getRowDimension(), m); - } - if (singular) { - throw new SingularMatrixException(); - } - - final int nColB = b.getColumnDimension(); - - // Apply permutations to b - final T[][] bp = MathArrays.buildArray(field, m, nColB); - for (int row = 0; row < m; row++) { - final T[] bpRow = bp[row]; - final int pRow = pivot[row]; - for (int col = 0; col < nColB; col++) { - bpRow[col] = b.getEntry(pRow, col); - } - } - - // Solve LY = b - for (int col = 0; col < m; col++) { - final T[] bpCol = bp[col]; - for (int i = col + 1; i < m; i++) { - final T[] bpI = bp[i]; - final T luICol = lu[i][col]; - for (int j = 0; j < nColB; j++) { - bpI[j] = bpI[j].subtract(bpCol[j].multiply(luICol)); - } - } - } - - // Solve UX = Y - for (int col = m - 1; col >= 0; col--) { - final T[] bpCol = bp[col]; - final T luDiag = lu[col][col]; - for (int j = 0; j < nColB; j++) { - bpCol[j] = bpCol[j].divide(luDiag); - } - for (int i = 0; i < col; i++) { - final T[] bpI = bp[i]; - final T luICol = lu[i][col]; - for (int j = 0; j < nColB; j++) { - bpI[j] = bpI[j].subtract(bpCol[j].multiply(luICol)); - } - } - } - - return new Array2DRowFieldMatrix<>(field, bp, false); - - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix getInverse() { - final int m = pivot.length; - final T one = field.getOne(); - FieldMatrix identity = new Array2DRowFieldMatrix<>(field, m, m); - for (int i = 0; i < m; ++i) { - identity.setEntry(i, i, one); - } - return solve(identity); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldMatrix.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldMatrix.java deleted file mode 100644 index 16f529a03..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldMatrix.java +++ /dev/null @@ -1,814 +0,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. - */ - -package org.apache.commons.math4.linear; - - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.OutOfRangeException; - -/** - * Interface defining field-valued matrix with basic algebraic operations. - *

- * Matrix element indexing is 0-based -- e.g., getEntry(0, 0) - * returns the element in the first row, first column of the matrix.

- * - * @param the type of the field elements - */ -public interface FieldMatrix> extends AnyMatrix { - /** - * Get the type of field elements of the matrix. - * - * @return the type of field elements of the matrix. - */ - Field getField(); - - /** - * Create a new {@code FieldMatrix} of the same type as the instance with - * the supplied row and column dimensions. - * - * @param rowDimension the number of rows in the new matrix - * @param columnDimension the number of columns in the new matrix - * @return a new matrix of the same type as the instance - * @throws NotStrictlyPositiveException if row or column dimension is not - * positive. - * @since 2.0 - */ - FieldMatrix createMatrix(final int rowDimension, final int columnDimension) - throws NotStrictlyPositiveException; - - /** - * Make a (deep) copy of this. - * - * @return a copy of this matrix. - */ - FieldMatrix copy(); - - /** - * Compute the sum of this and m. - * - * @param m Matrix to be added. - * @return {@code this} + {@code m}. - * @throws MatrixDimensionMismatchException if {@code m} is not the same - * size as {@code this} matrix. - */ - FieldMatrix add(FieldMatrix m) throws MatrixDimensionMismatchException; - - /** - * Subtract {@code m} from this matrix. - * - * @param m Matrix to be subtracted. - * @return {@code this} - {@code m}. - * @throws MatrixDimensionMismatchException if {@code m} is not the same - * size as {@code this} matrix. - */ - FieldMatrix subtract(FieldMatrix m) throws MatrixDimensionMismatchException; - - /** - * Increment each entry of this matrix. - * - * @param d Value to be added to each entry. - * @return {@code d} + {@code this}. - */ - FieldMatrix scalarAdd(T d); - - /** - * Multiply each entry by {@code d}. - * - * @param d Value to multiply all entries by. - * @return {@code d} * {@code this}. - */ - FieldMatrix scalarMultiply(T d); - - /** - * Postmultiply this matrix by {@code m}. - * - * @param m Matrix to postmultiply by. - * @return {@code this} * {@code m}. - * @throws DimensionMismatchException if the number of columns of - * {@code this} matrix is not equal to the number of rows of matrix - * {@code m}. - */ - FieldMatrix multiply(FieldMatrix m) throws DimensionMismatchException; - - /** - * Premultiply this matrix by {@code m}. - * - * @param m Matrix to premultiply by. - * @return {@code m} * {@code this}. - * @throws DimensionMismatchException if the number of columns of {@code m} - * differs from the number of rows of {@code this} matrix. - */ - FieldMatrix preMultiply(FieldMatrix m) throws DimensionMismatchException; - - /** - * Returns the result multiplying this with itself p times. - * Depending on the type of the field elements, T, instability for high - * powers might occur. - * - * @param p raise this to power p - * @return this^p - * @throws NotPositiveException if {@code p < 0} - * @throws NonSquareMatrixException if {@code this matrix} is not square - */ - FieldMatrix power(final int p) throws NonSquareMatrixException, - NotPositiveException; - - /** - * Returns matrix entries as a two-dimensional array. - * - * @return a 2-dimensional array of entries. - */ - T[][] getData(); - - /** - * Get a submatrix. Rows and columns are indicated - * counting from 0 to n - 1. - * - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index (inclusive) - * @return the matrix containing the data of the specified rows and columns. - * @throws NumberIsTooSmallException is {@code endRow < startRow} of - * {@code endColumn < startColumn}. - * @throws OutOfRangeException if the indices are not valid. - */ - FieldMatrix getSubMatrix(int startRow, int endRow, int startColumn, int endColumn) - throws NumberIsTooSmallException, OutOfRangeException; - - /** - * Get a submatrix. Rows and columns are indicated - * counting from 0 to n - 1. - * - * @param selectedRows Array of row indices. - * @param selectedColumns Array of column indices. - * @return the matrix containing the data in the - * specified rows and columns. - * @throws NoDataException if {@code selectedRows} or - * {@code selectedColumns} is empty - * @throws NullArgumentException if {@code selectedRows} or - * {@code selectedColumns} is {@code null}. - * @throws OutOfRangeException if row or column selections are not valid. - */ - FieldMatrix getSubMatrix(int[] selectedRows, int[] selectedColumns) - throws NoDataException, NullArgumentException, OutOfRangeException; - - /** - * Copy a submatrix. Rows and columns are 0-based. The designated submatrix - * is copied into the top left portion of the destination array. - * - * @param startRow Initial row index. - * @param endRow Final row index (inclusive). - * @param startColumn Initial column index. - * @param endColumn Final column index (inclusive). - * @param destination The array where the submatrix data should be copied - * (if larger than rows/columns counts, only the upper-left part will be modified). - * @throws MatrixDimensionMismatchException if the dimensions of - * {@code destination} are not large enough to hold the submatrix. - * @throws NumberIsTooSmallException if {@code endRow < startRow} or - * {@code endColumn < startColumn}. - * @throws OutOfRangeException if the indices are not valid. - */ - void copySubMatrix(int startRow, int endRow, int startColumn, int endColumn, - T[][] destination) - throws MatrixDimensionMismatchException, NumberIsTooSmallException, - OutOfRangeException; - - /** - * Copy a submatrix. Rows and columns are indicated - * counting from 0 to n - 1. - * - * @param selectedRows Array of row indices. - * @param selectedColumns Array of column indices. - * @param destination Arrays where the submatrix data should be copied - * (if larger than rows/columns counts, only the upper-left part will be used) - * @throws MatrixDimensionMismatchException if the dimensions of - * {@code destination} do not match those of {@code this}. - * @throws NoDataException if {@code selectedRows} or - * {@code selectedColumns} is empty - * @throws NullArgumentException if {@code selectedRows} or - * {@code selectedColumns} is {@code null}. - * @throws OutOfRangeException if the indices are not valid. - */ - void copySubMatrix(int[] selectedRows, int[] selectedColumns, T[][] destination) - throws MatrixDimensionMismatchException, NoDataException, NullArgumentException, - OutOfRangeException; - - /** - * Replace the submatrix starting at {@code (row, column)} using data in the - * input {@code subMatrix} array. Indexes are 0-based. - *

- * Example:
- * Starting with - * - *

-     * 1  2  3  4
-     * 5  6  7  8
-     * 9  0  1  2
-     * 
- * - * and subMatrix = {{3, 4} {5,6}}, invoking - * setSubMatrix(subMatrix,1,1)) will result in - * - *
-     * 1  2  3  4
-     * 5  3  4  8
-     * 9  5  6  2
-     * 
- * - * - * @param subMatrix Array containing the submatrix replacement data. - * @param row Row coordinate of the top-left element to be replaced. - * @param column Column coordinate of the top-left element to be replaced. - * @throws OutOfRangeException if {@code subMatrix} does not fit into this - * matrix from element in {@code (row, column)}. - * @throws NoDataException if a row or column of {@code subMatrix} is empty. - * @throws DimensionMismatchException if {@code subMatrix} is not - * rectangular (not all rows have the same length). - * @throws NullArgumentException if {@code subMatrix} is {@code null}. - * @since 2.0 - */ - void setSubMatrix(T[][] subMatrix, int row, int column) - throws DimensionMismatchException, OutOfRangeException, - NoDataException, NullArgumentException; - - /** - * Get the entries in row number {@code row} - * as a row matrix. - * - * @param row Row to be fetched. - * @return a row matrix. - * @throws OutOfRangeException if the specified row index is invalid. - */ - FieldMatrix getRowMatrix(int row) throws OutOfRangeException; - - /** - * Set the entries in row number {@code row} - * as a row matrix. - * - * @param row Row to be set. - * @param matrix Row matrix (must have one row and the same number - * of columns as the instance). - * @throws OutOfRangeException if the specified row index is invalid. - * @throws MatrixDimensionMismatchException - * if the matrix dimensions do not match one instance row. - */ - void setRowMatrix(int row, FieldMatrix matrix) - throws MatrixDimensionMismatchException, OutOfRangeException; - - /** - * Get the entries in column number {@code column} - * as a column matrix. - * - * @param column Column to be fetched. - * @return a column matrix. - * @throws OutOfRangeException if the specified column index is invalid. - */ - FieldMatrix getColumnMatrix(int column) throws OutOfRangeException; - - /** - * Set the entries in column number {@code column} - * as a column matrix. - * - * @param column Column to be set. - * @param matrix column matrix (must have one column and the same - * number of rows as the instance). - * @throws OutOfRangeException if the specified column index is invalid. - * @throws MatrixDimensionMismatchException if the matrix dimensions do - * not match one instance column. - */ - void setColumnMatrix(int column, FieldMatrix matrix) - throws MatrixDimensionMismatchException, OutOfRangeException; - - /** - * Get the entries in row number {@code row} - * as a vector. - * - * @param row Row to be fetched - * @return a row vector. - * @throws OutOfRangeException if the specified row index is invalid. - */ - FieldVector getRowVector(int row) throws OutOfRangeException; - - /** - * Set the entries in row number {@code row} - * as a vector. - * - * @param row Row to be set. - * @param vector row vector (must have the same number of columns - * as the instance). - * @throws OutOfRangeException if the specified row index is invalid. - * @throws MatrixDimensionMismatchException if the vector dimension does not - * match one instance row. - */ - void setRowVector(int row, FieldVector vector) - throws MatrixDimensionMismatchException, OutOfRangeException; - - /** - * Returns the entries in column number {@code column} - * as a vector. - * - * @param column Column to be fetched. - * @return a column vector. - * @throws OutOfRangeException if the specified column index is invalid. - */ - FieldVector getColumnVector(int column) throws OutOfRangeException; - - /** - * Set the entries in column number {@code column} - * as a vector. - * - * @param column Column to be set. - * @param vector Column vector (must have the same number of rows - * as the instance). - * @throws OutOfRangeException if the specified column index is invalid. - * @throws MatrixDimensionMismatchException if the vector dimension does not - * match one instance column. - */ - void setColumnVector(int column, FieldVector vector) - throws MatrixDimensionMismatchException, OutOfRangeException; - - /** - * Get the entries in row number {@code row} as an array. - * - * @param row Row to be fetched. - * @return array of entries in the row. - * @throws OutOfRangeException if the specified row index is not valid. - */ - T[] getRow(int row) throws OutOfRangeException; - - /** - * Set the entries in row number {@code row} - * as a row matrix. - * - * @param row Row to be set. - * @param array Row matrix (must have the same number of columns as - * the instance). - * @throws OutOfRangeException if the specified row index is invalid. - * @throws MatrixDimensionMismatchException if the array size does not match - * one instance row. - */ - void setRow(int row, T[] array) throws MatrixDimensionMismatchException, - OutOfRangeException; - - /** - * Get the entries in column number {@code col} as an array. - * - * @param column the column to be fetched - * @return array of entries in the column - * @throws OutOfRangeException if the specified column index is not valid. - */ - T[] getColumn(int column) throws OutOfRangeException; - - /** - * Set the entries in column number {@code column} - * as a column matrix. - * - * @param column the column to be set - * @param array column array (must have the same number of rows as the instance) - * @throws OutOfRangeException if the specified column index is invalid. - * @throws MatrixDimensionMismatchException if the array size does not match - * one instance column. - */ - void setColumn(int column, T[] array) throws MatrixDimensionMismatchException, - OutOfRangeException; - - /** - * Returns the entry in the specified row and column. - * - * @param row row location of entry to be fetched - * @param column column location of entry to be fetched - * @return matrix entry in row,column - * @throws OutOfRangeException if the row or column index is not valid. - */ - T getEntry(int row, int column) throws OutOfRangeException; - - /** - * Set the entry in the specified row and column. - * - * @param row row location of entry to be set - * @param column column location of entry to be set - * @param value matrix entry to be set in row,column - * @throws OutOfRangeException if the row or column index is not valid. - * @since 2.0 - */ - void setEntry(int row, int column, T value) throws OutOfRangeException; - - /** - * Change an entry in the specified row and column. - * - * @param row Row location of entry to be set. - * @param column Column location of entry to be set. - * @param increment Value to add to the current matrix entry in - * {@code (row, column)}. - * @throws OutOfRangeException if the row or column index is not valid. - * @since 2.0 - */ - void addToEntry(int row, int column, T increment) throws OutOfRangeException; - - /** - * Change an entry in the specified row and column. - * - * @param row Row location of entry to be set. - * @param column Column location of entry to be set. - * @param factor Multiplication factor for the current matrix entry - * in {@code (row,column)} - * @throws OutOfRangeException if the row or column index is not valid. - * @since 2.0 - */ - void multiplyEntry(int row, int column, T factor) throws OutOfRangeException; - - /** - * Returns the transpose of this matrix. - * - * @return transpose matrix - */ - FieldMatrix transpose(); - - /** - * Returns the - * trace of the matrix (the sum of the elements on the main diagonal). - * - * @return trace - * @throws NonSquareMatrixException if the matrix is not square. - */ - T getTrace() throws NonSquareMatrixException; - - /** - * Returns the result of multiplying this by the vector {@code v}. - * - * @param v the vector to operate on - * @return {@code this * v} - * @throws DimensionMismatchException if the number of columns of - * {@code this} matrix is not equal to the size of the vector {@code v}. - */ - T[] operate(T[] v) throws DimensionMismatchException; - - /** - * Returns the result of multiplying this by the vector {@code v}. - * - * @param v the vector to operate on - * @return {@code this * v} - * @throws DimensionMismatchException if the number of columns of - * {@code this} matrix is not equal to the size of the vector {@code v}. - */ - FieldVector operate(FieldVector v) throws DimensionMismatchException; - - /** - * Returns the (row) vector result of premultiplying this by the vector - * {@code v}. - * - * @param v the row vector to premultiply by - * @return {@code v * this} - * @throws DimensionMismatchException if the number of rows of {@code this} - * matrix is not equal to the size of the vector {@code v} - */ - T[] preMultiply(T[] v) throws DimensionMismatchException; - - /** - * Returns the (row) vector result of premultiplying this by the vector - * {@code v}. - * - * @param v the row vector to premultiply by - * @return {@code v * this} - * @throws DimensionMismatchException if the number of rows of {@code this} - * matrix is not equal to the size of the vector {@code v} - */ - FieldVector preMultiply(FieldVector v) throws DimensionMismatchException; - - /** - * Visit (and possibly change) all matrix entries in row order. - *

Row order starts at upper left and iterating through all elements - * of a row from left to right before going to the leftmost element - * of the next row.

- * @param visitor visitor used to process all matrix entries - * @see #walkInRowOrder(FieldMatrixPreservingVisitor) - * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link FieldMatrixChangingVisitor#end()} at the end - * of the walk - */ - T walkInRowOrder(FieldMatrixChangingVisitor visitor); - - /** - * Visit (but don't change) all matrix entries in row order. - *

Row order starts at upper left and iterating through all elements - * of a row from left to right before going to the leftmost element - * of the next row.

- * @param visitor visitor used to process all matrix entries - * @see #walkInRowOrder(FieldMatrixChangingVisitor) - * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link FieldMatrixPreservingVisitor#end()} at the end - * of the walk - */ - T walkInRowOrder(FieldMatrixPreservingVisitor visitor); - - /** - * Visit (and possibly change) some matrix entries in row order. - *

Row order starts at upper left and iterating through all elements - * of a row from left to right before going to the leftmost element - * of the next row.

- * @param visitor visitor used to process all matrix entries - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index - * @throws OutOfRangeException if the indices are not valid. - * @throws NumberIsTooSmallException if {@code endRow < startRow} or - * {@code endColumn < startColumn}. - * @see #walkInRowOrder(FieldMatrixChangingVisitor) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link FieldMatrixChangingVisitor#end()} at the end - * of the walk - */ - T walkInRowOrder(FieldMatrixChangingVisitor visitor, - int startRow, int endRow, int startColumn, int endColumn) - throws OutOfRangeException, NumberIsTooSmallException; - - /** - * Visit (but don't change) some matrix entries in row order. - *

Row order starts at upper left and iterating through all elements - * of a row from left to right before going to the leftmost element - * of the next row.

- * @param visitor visitor used to process all matrix entries - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index - * @throws OutOfRangeException if the indices are not valid. - * @throws NumberIsTooSmallException if {@code endRow < startRow} or - * {@code endColumn < startColumn}. - * @see #walkInRowOrder(FieldMatrixChangingVisitor) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor) - * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link FieldMatrixPreservingVisitor#end()} at the end - * of the walk - */ - T walkInRowOrder(FieldMatrixPreservingVisitor visitor, - int startRow, int endRow, int startColumn, int endColumn) - throws OutOfRangeException, NumberIsTooSmallException; - - /** - * Visit (and possibly change) all matrix entries in column order. - *

Column order starts at upper left and iterating through all elements - * of a column from top to bottom before going to the topmost element - * of the next column.

- * @param visitor visitor used to process all matrix entries - * @see #walkInRowOrder(FieldMatrixChangingVisitor) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor) - * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link FieldMatrixChangingVisitor#end()} at the end - * of the walk - */ - T walkInColumnOrder(FieldMatrixChangingVisitor visitor); - - /** - * Visit (but don't change) all matrix entries in column order. - *

Column order starts at upper left and iterating through all elements - * of a column from top to bottom before going to the topmost element - * of the next column.

- * @param visitor visitor used to process all matrix entries - * @see #walkInRowOrder(FieldMatrixChangingVisitor) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor) - * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link FieldMatrixPreservingVisitor#end()} at the end - * of the walk - */ - T walkInColumnOrder(FieldMatrixPreservingVisitor visitor); - - /** - * Visit (and possibly change) some matrix entries in column order. - *

Column order starts at upper left and iterating through all elements - * of a column from top to bottom before going to the topmost element - * of the next column.

- * @param visitor visitor used to process all matrix entries - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index - * @throws NumberIsTooSmallException if {@code endRow < startRow} or - * {@code endColumn < startColumn}. - * @throws OutOfRangeException if the indices are not valid. - * @see #walkInRowOrder(FieldMatrixChangingVisitor) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor) - * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link FieldMatrixChangingVisitor#end()} at the end - * of the walk - */ - T walkInColumnOrder(FieldMatrixChangingVisitor visitor, - int startRow, int endRow, int startColumn, int endColumn) - throws NumberIsTooSmallException, OutOfRangeException; - - /** - * Visit (but don't change) some matrix entries in column order. - *

Column order starts at upper left and iterating through all elements - * of a column from top to bottom before going to the topmost element - * of the next column.

- * @param visitor visitor used to process all matrix entries - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index - * @throws NumberIsTooSmallException if {@code endRow < startRow} or - * {@code endColumn < startColumn}. - * @throws OutOfRangeException if the indices are not valid. - * @see #walkInRowOrder(FieldMatrixChangingVisitor) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor) - * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link FieldMatrixPreservingVisitor#end()} at the end - * of the walk - */ - T walkInColumnOrder(FieldMatrixPreservingVisitor visitor, - int startRow, int endRow, int startColumn, int endColumn) - throws NumberIsTooSmallException, OutOfRangeException; - - /** - * Visit (and possibly change) all matrix entries using the fastest possible order. - *

The fastest walking order depends on the exact matrix class. It may be - * different from traditional row or column orders.

- * @param visitor visitor used to process all matrix entries - * @see #walkInRowOrder(FieldMatrixChangingVisitor) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor) - * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link FieldMatrixChangingVisitor#end()} at the end - * of the walk - */ - T walkInOptimizedOrder(FieldMatrixChangingVisitor visitor); - - /** - * Visit (but don't change) all matrix entries using the fastest possible order. - *

The fastest walking order depends on the exact matrix class. It may be - * different from traditional row or column orders.

- * @param visitor visitor used to process all matrix entries - * @see #walkInRowOrder(FieldMatrixChangingVisitor) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor) - * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link FieldMatrixPreservingVisitor#end()} at the end - * of the walk - */ - T walkInOptimizedOrder(FieldMatrixPreservingVisitor visitor); - - /** - * Visit (and possibly change) some matrix entries using the fastest possible order. - *

The fastest walking order depends on the exact matrix class. It may be - * different from traditional row or column orders.

- * @param visitor visitor used to process all matrix entries - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index (inclusive) - * @throws NumberIsTooSmallException if {@code endRow < startRow} or - * {@code endColumn < startColumn}. - * @throws OutOfRangeException if the indices are not valid. - * @see #walkInRowOrder(FieldMatrixChangingVisitor) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor) - * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link FieldMatrixChangingVisitor#end()} at the end - * of the walk - */ - T walkInOptimizedOrder(FieldMatrixChangingVisitor visitor, - int startRow, int endRow, int startColumn, int endColumn) - throws NumberIsTooSmallException, OutOfRangeException; - - /** - * Visit (but don't change) some matrix entries using the fastest possible order. - *

The fastest walking order depends on the exact matrix class. It may be - * different from traditional row or column orders.

- * @param visitor visitor used to process all matrix entries - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index (inclusive) - * @throws NumberIsTooSmallException if {@code endRow < startRow} or - * {@code endColumn < startColumn}. - * @throws OutOfRangeException if the indices are not valid. - * @see #walkInRowOrder(FieldMatrixChangingVisitor) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor) - * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) - * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) - * @return the value returned by {@link FieldMatrixPreservingVisitor#end()} at the end - * of the walk - */ - T walkInOptimizedOrder(FieldMatrixPreservingVisitor visitor, - int startRow, int endRow, int startColumn, int endColumn) - throws NumberIsTooSmallException, OutOfRangeException; -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldMatrixChangingVisitor.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldMatrixChangingVisitor.java deleted file mode 100644 index 53c965f24..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldMatrixChangingVisitor.java +++ /dev/null @@ -1,57 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.FieldElement; - -/** - * Interface defining a visitor for matrix entries. - * - * @param the type of the field elements - * @since 2.0 - */ -public interface FieldMatrixChangingVisitor> { - /** - * Start visiting a matrix. - *

This method is called once before any entry of the matrix is visited.

- * @param rows number of rows of the matrix - * @param columns number of columns of the matrix - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index (inclusive) - */ - void start(int rows, int columns, - int startRow, int endRow, int startColumn, int endColumn); - - /** - * Visit one matrix entry. - * @param row row index of the entry - * @param column column index of the entry - * @param value current value of the entry - * @return the new value to be set for the entry - */ - T visit(int row, int column, T value); - - /** - * End visiting a matrix. - *

This method is called once after all entries of the matrix have been visited.

- * @return the value that the walkInXxxOrder must return - */ - T end(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldMatrixPreservingVisitor.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldMatrixPreservingVisitor.java deleted file mode 100644 index 3b46933bf..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldMatrixPreservingVisitor.java +++ /dev/null @@ -1,56 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.FieldElement; - -/** - * Interface defining a visitor for matrix entries. - * - * @param the type of the field elements - * @since 2.0 - */ -public interface FieldMatrixPreservingVisitor> { - /** - * Start visiting a matrix. - *

This method is called once before any entry of the matrix is visited.

- * @param rows number of rows of the matrix - * @param columns number of columns of the matrix - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index (inclusive) - */ - void start(int rows, int columns, - int startRow, int endRow, int startColumn, int endColumn); - - /** - * Visit one matrix entry. - * @param row row index of the entry - * @param column column index of the entry - * @param value current value of the entry - */ - void visit(int row, int column, T value); - - /** - * End visiting a matrix. - *

This method is called once after all entries of the matrix have been visited.

- * @return the value that the walkInXxxOrder must return - */ - T end(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldVector.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldVector.java deleted file mode 100644 index 2e4544b64..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldVector.java +++ /dev/null @@ -1,290 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.OutOfRangeException; - -/** - * Interface defining a field-valued vector with basic algebraic operations. - *

- * vector element indexing is 0-based -- e.g., getEntry(0) - * returns the first element of the vector. - *

- *

- * The various mapXxx and mapXxxToSelf methods operate - * on vectors element-wise, i.e. they perform the same operation (adding a scalar, - * applying a function ...) on each element in turn. The mapXxx - * versions create a new vector to hold the result and do not change the instance. - * The mapXxxToSelf versions use the instance itself to store the - * results, so the instance is changed by these methods. In both cases, the result - * vector is returned by the methods, this allows to use the fluent API - * style, like this: - *

- *
- *   RealVector result = v.mapAddToSelf(3.0).mapTanToSelf().mapSquareToSelf();
- * 
- *

- * Note that as almost all operations on {@link FieldElement} throw {@link - * NullArgumentException} when operating on a null element, it is the responsibility - * of FieldVector implementations to make sure no null elements - * are inserted into the vector. This must be done in all constructors and - * all setters. - *

- * - * @param the type of the field elements - * @since 2.0 - */ -public interface FieldVector> { - - /** - * Get the type of field elements of the vector. - * @return type of field elements of the vector - */ - Field getField(); - - /** - * Returns a (deep) copy of this. - * @return vector copy - */ - FieldVector copy(); - - /** - * Compute the sum of {@code this} and {@code v}. - * @param v vector to be added - * @return {@code this + v} - * @throws DimensionMismatchException if {@code v} is not the same size as {@code this} - */ - FieldVector add(FieldVector v) throws DimensionMismatchException; - - /** - * Compute {@code this} minus {@code v}. - * @param v vector to be subtracted - * @return {@code this - v} - * @throws DimensionMismatchException if {@code v} is not the same size as {@code this} - */ - FieldVector subtract(FieldVector v) throws DimensionMismatchException; - - /** - * Map an addition operation to each entry. - * @param d value to be added to each entry - * @return {@code this + d} - * @throws NullArgumentException if {@code d} is {@code null}. - */ - FieldVector mapAdd(T d) throws NullArgumentException; - - /** - * Map an addition operation to each entry. - *

The instance is changed by this method.

- * @param d value to be added to each entry - * @return for convenience, return {@code this} - * @throws NullArgumentException if {@code d} is {@code null}. - */ - FieldVector mapAddToSelf(T d) throws NullArgumentException; - - /** - * Map a subtraction operation to each entry. - * @param d value to be subtracted to each entry - * @return {@code this - d} - * @throws NullArgumentException if {@code d} is {@code null} - */ - FieldVector mapSubtract(T d) throws NullArgumentException; - - /** - * Map a subtraction operation to each entry. - *

The instance is changed by this method.

- * @param d value to be subtracted to each entry - * @return for convenience, return {@code this} - * @throws NullArgumentException if {@code d} is {@code null} - */ - FieldVector mapSubtractToSelf(T d) throws NullArgumentException; - - /** - * Map a multiplication operation to each entry. - * @param d value to multiply all entries by - * @return {@code this * d} - * @throws NullArgumentException if {@code d} is {@code null}. - */ - FieldVector mapMultiply(T d) throws NullArgumentException; - - /** - * Map a multiplication operation to each entry. - *

The instance is changed by this method.

- * @param d value to multiply all entries by - * @return for convenience, return {@code this} - * @throws NullArgumentException if {@code d} is {@code null}. - */ - FieldVector mapMultiplyToSelf(T d) throws NullArgumentException; - - /** - * Map a division operation to each entry. - * @param d value to divide all entries by - * @return {@code this / d} - * @throws NullArgumentException if {@code d} is {@code null}. - * @throws MathArithmeticException if {@code d} is zero. - */ - FieldVector mapDivide(T d) - throws NullArgumentException, MathArithmeticException; - - /** - * Map a division operation to each entry. - *

The instance is changed by this method.

- * @param d value to divide all entries by - * @return for convenience, return {@code this} - * @throws NullArgumentException if {@code d} is {@code null}. - * @throws MathArithmeticException if {@code d} is zero. - */ - FieldVector mapDivideToSelf(T d) - throws NullArgumentException, MathArithmeticException; - - /** - * Map the 1/x function to each entry. - * @return a vector containing the result of applying the function to each entry. - * @throws MathArithmeticException if one of the entries is zero. - */ - FieldVector mapInv() throws MathArithmeticException; - - /** - * Map the 1/x function to each entry. - *

The instance is changed by this method.

- * @return for convenience, return {@code this} - * @throws MathArithmeticException if one of the entries is zero. - */ - FieldVector mapInvToSelf() throws MathArithmeticException; - - /** - * Element-by-element multiplication. - * @param v vector by which instance elements must be multiplied - * @return a vector containing {@code this[i] * v[i]} for all {@code i} - * @throws DimensionMismatchException if {@code v} is not the same size as {@code this} - */ - FieldVector ebeMultiply(FieldVector v) - throws DimensionMismatchException; - - /** - * Element-by-element division. - * @param v vector by which instance elements must be divided - * @return a vector containing {@code this[i] / v[i]} for all {@code i} - * @throws DimensionMismatchException if {@code v} is not the same size as {@code this} - * @throws MathArithmeticException if one entry of {@code v} is zero. - */ - FieldVector ebeDivide(FieldVector v) - throws DimensionMismatchException, MathArithmeticException; - - /** - * Compute the dot product. - * @param v vector with which dot product should be computed - * @return the scalar dot product of {@code this} and {@code v} - * @throws DimensionMismatchException if {@code v} is not the same size as {@code this} - */ - T dotProduct(FieldVector v) throws DimensionMismatchException; - - /** - * Find the orthogonal projection of this vector onto another vector. - * @param v vector onto which {@code this} must be projected - * @return projection of {@code this} onto {@code v} - * @throws DimensionMismatchException if {@code v} is not the same size as {@code this} - * @throws MathArithmeticException if {@code v} is the null vector. - */ - FieldVector projection(FieldVector v) - throws DimensionMismatchException, MathArithmeticException; - - /** - * Compute the outer product. - * @param v vector with which outer product should be computed - * @return the matrix outer product between instance and v - */ - FieldMatrix outerProduct(FieldVector v); - - /** - * Returns the entry in the specified index. - * - * @param index Index location of entry to be fetched. - * @return the vector entry at {@code index}. - * @throws OutOfRangeException if the index is not valid. - * @see #setEntry(int, FieldElement) - */ - T getEntry(int index) throws OutOfRangeException; - - /** - * Set a single element. - * @param index element index. - * @param value new value for the element. - * @throws OutOfRangeException if the index is not valid. - * @see #getEntry(int) - */ - void setEntry(int index, T value) throws OutOfRangeException; - - /** - * Returns the size of the vector. - * @return size - */ - int getDimension(); - - /** - * Construct a vector by appending a vector to this vector. - * @param v vector to append to this one. - * @return a new vector - */ - FieldVector append(FieldVector v); - - /** - * Construct a vector by appending a T to this vector. - * @param d T to append. - * @return a new vector - */ - FieldVector append(T d); - - /** - * Get a subvector from consecutive elements. - * @param index index of first element. - * @param n number of elements to be retrieved. - * @return a vector containing n elements. - * @throws OutOfRangeException if the index is not valid. - * @throws NotPositiveException if the number of elements if not positive. - */ - FieldVector getSubVector(int index, int n) - throws OutOfRangeException, NotPositiveException; - - /** - * Set a set of consecutive elements. - * @param index index of first element to be set. - * @param v vector containing the values to set. - * @throws OutOfRangeException if the index is not valid. - */ - void setSubVector(int index, FieldVector v) throws OutOfRangeException; - - /** - * Set all elements to a single value. - * @param value single value to set for all elements - */ - void set(T value); - - /** - * Convert the vector to a T array. - *

The array is independent from vector data, it's elements - * are copied.

- * @return array containing a copy of vector elements - */ - T[] toArray(); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldVectorChangingVisitor.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldVectorChangingVisitor.java deleted file mode 100644 index 2938d43d3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldVectorChangingVisitor.java +++ /dev/null @@ -1,56 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.FieldElement; - -/** - * This interface defines a visitor for the entries of a vector. Visitors - * implementing this interface may alter the entries of the vector being - * visited. - * - * @param the type of the field elements - * @since 3.3 - */ -public interface FieldVectorChangingVisitor> { - /** - * Start visiting a vector. This method is called once, before any entry - * of the vector is visited. - * - * @param dimension the size of the vector - * @param start the index of the first entry to be visited - * @param end the index of the last entry to be visited (inclusive) - */ - void start(int dimension, int start, int end); - - /** - * Visit one entry of the vector. - * - * @param index the index of the entry being visited - * @param value the value of the entry being visited - * @return the new value of the entry being visited - */ - T visit(int index, T value); - - /** - * End visiting a vector. This method is called once, after all entries of - * the vector have been visited. - * - * @return the value returned after visiting all entries - */ - T end(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldVectorPreservingVisitor.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldVectorPreservingVisitor.java deleted file mode 100644 index 9ad4384f3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/FieldVectorPreservingVisitor.java +++ /dev/null @@ -1,55 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.FieldElement; - -/** - * This interface defines a visitor for the entries of a vector. Visitors - * implementing this interface do not alter the entries of the vector being - * visited. - * - * @param the type of the field elements - * @since 3.3 - */ -public interface FieldVectorPreservingVisitor> { - /** - * Start visiting a vector. This method is called once, before any entry - * of the vector is visited. - * - * @param dimension the size of the vector - * @param start the index of the first entry to be visited - * @param end the index of the last entry to be visited (inclusive) - */ - void start(int dimension, int start, int end); - - /** - * Visit one entry of the vector. - * - * @param index the index of the entry being visited - * @param value the value of the entry being visited - */ - void visit(int index, T value); - - /** - * End visiting a vector. This method is called once, after all entries of - * the vector have been visited. - * - * @return the value returned after visiting all entries - */ - T end(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/HessenbergTransformer.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/HessenbergTransformer.java deleted file mode 100644 index c10c41a15..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/HessenbergTransformer.java +++ /dev/null @@ -1,232 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.numbers.core.Precision; - -/** - * Class transforming a general real matrix to Hessenberg form. - *

A m × m matrix A can be written as the product of three matrices: A = P - * × H × PT with P an orthogonal matrix and H a Hessenberg - * matrix. Both P and H are m × m matrices.

- *

Transformation to Hessenberg form is often not a goal by itself, but it is an - * intermediate step in more general decomposition algorithms like - * {@link EigenDecomposition eigen decomposition}. This class is therefore - * intended for internal use by the library and is not public. As a consequence - * of this explicitly limited scope, many methods directly returns references to - * internal arrays, not copies.

- *

This class is based on the method orthes in class EigenvalueDecomposition - * from the JAMA library.

- * - * @see MathWorld - * @see Householder Transformations - * @since 3.1 - */ -class HessenbergTransformer { - /** Householder vectors. */ - private final double householderVectors[][]; - /** Temporary storage vector. */ - private final double ort[]; - /** Cached value of P. */ - private RealMatrix cachedP; - /** Cached value of Pt. */ - private RealMatrix cachedPt; - /** Cached value of H. */ - private RealMatrix cachedH; - - /** - * Build the transformation to Hessenberg form of a general matrix. - * - * @param matrix matrix to transform - * @throws NonSquareMatrixException if the matrix is not square - */ - HessenbergTransformer(final RealMatrix matrix) { - if (!matrix.isSquare()) { - throw new NonSquareMatrixException(matrix.getRowDimension(), - matrix.getColumnDimension()); - } - - final int m = matrix.getRowDimension(); - householderVectors = matrix.getData(); - ort = new double[m]; - cachedP = null; - cachedPt = null; - cachedH = null; - - // transform matrix - transform(); - } - - /** - * Returns the matrix P of the transform. - *

P is an orthogonal matrix, i.e. its inverse is also its transpose.

- * - * @return the P matrix - */ - public RealMatrix getP() { - if (cachedP == null) { - final int n = householderVectors.length; - final int high = n - 1; - final double[][] pa = new double[n][n]; - - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { - pa[i][j] = (i == j) ? 1 : 0; - } - } - - for (int m = high - 1; m >= 1; m--) { - if (householderVectors[m][m - 1] != 0.0) { - for (int i = m + 1; i <= high; i++) { - ort[i] = householderVectors[i][m - 1]; - } - - for (int j = m; j <= high; j++) { - double g = 0.0; - - for (int i = m; i <= high; i++) { - g += ort[i] * pa[i][j]; - } - - // Double division avoids possible underflow - g = (g / ort[m]) / householderVectors[m][m - 1]; - - for (int i = m; i <= high; i++) { - pa[i][j] += g * ort[i]; - } - } - } - } - - cachedP = MatrixUtils.createRealMatrix(pa); - } - return cachedP; - } - - /** - * Returns the transpose of the matrix P of the transform. - *

P is an orthogonal matrix, i.e. its inverse is also its transpose.

- * - * @return the transpose of the P matrix - */ - public RealMatrix getPT() { - if (cachedPt == null) { - cachedPt = getP().transpose(); - } - - // return the cached matrix - return cachedPt; - } - - /** - * Returns the Hessenberg matrix H of the transform. - * - * @return the H matrix - */ - public RealMatrix getH() { - if (cachedH == null) { - final int m = householderVectors.length; - final double[][] h = new double[m][m]; - for (int i = 0; i < m; ++i) { - if (i > 0) { - // copy the entry of the lower sub-diagonal - h[i][i - 1] = householderVectors[i][i - 1]; - } - - // copy upper triangular part of the matrix - for (int j = i; j < m; ++j) { - h[i][j] = householderVectors[i][j]; - } - } - cachedH = MatrixUtils.createRealMatrix(h); - } - - // return the cached matrix - return cachedH; - } - - /** - * Get the Householder vectors of the transform. - *

Note that since this class is only intended for internal use, it returns - * directly a reference to its internal arrays, not a copy.

- * - * @return the main diagonal elements of the B matrix - */ - double[][] getHouseholderVectorsRef() { - return householderVectors; - } - - /** - * Transform original matrix to Hessenberg form. - *

Transformation is done using Householder transforms.

- */ - private void transform() { - final int n = householderVectors.length; - final int high = n - 1; - - for (int m = 1; m <= high - 1; m++) { - // Scale column. - double scale = 0; - for (int i = m; i <= high; i++) { - scale += FastMath.abs(householderVectors[i][m - 1]); - } - - if (!Precision.equals(scale, 0)) { - // Compute Householder transformation. - double h = 0; - for (int i = high; i >= m; i--) { - ort[i] = householderVectors[i][m - 1] / scale; - h += ort[i] * ort[i]; - } - final double g = (ort[m] > 0) ? -FastMath.sqrt(h) : FastMath.sqrt(h); - - h -= ort[m] * g; - ort[m] -= g; - - // Apply Householder similarity transformation - // H = (I - u*u' / h) * H * (I - u*u' / h) - - for (int j = m; j < n; j++) { - double f = 0; - for (int i = high; i >= m; i--) { - f += ort[i] * householderVectors[i][j]; - } - f /= h; - for (int i = m; i <= high; i++) { - householderVectors[i][j] -= f * ort[i]; - } - } - - for (int i = 0; i <= high; i++) { - double f = 0; - for (int j = high; j >= m; j--) { - f += ort[j] * householderVectors[i][j]; - } - f /= h; - for (int j = m; j <= high; j++) { - householderVectors[i][j] -= f * ort[j]; - } - } - - ort[m] = scale * ort[m]; - householderVectors[m][m - 1] = scale * g; - } - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/IllConditionedOperatorException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/IllConditionedOperatorException.java deleted file mode 100644 index a90b3d1d3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/IllConditionedOperatorException.java +++ /dev/null @@ -1,42 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * An exception to be thrown when the condition number of a - * {@link RealLinearOperator} is too high. - * - * @since 3.0 - */ -public class IllConditionedOperatorException - extends MathIllegalArgumentException { - /** Serializable version Id. */ - private static final long serialVersionUID = -7883263944530490135L; - - /** - * Creates a new instance of this class. - * - * @param cond An estimate of the condition number of the offending linear - * operator. - */ - public IllConditionedOperatorException(final double cond) { - super(LocalizedFormats.ILL_CONDITIONED_OPERATOR, cond); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/IterativeLinearSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/IterativeLinearSolver.java deleted file mode 100644 index 877d48b63..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/IterativeLinearSolver.java +++ /dev/null @@ -1,173 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.util.IterationManager; -import org.apache.commons.math4.util.MathUtils; - -/** - * This abstract class defines an iterative solver for the linear system A - * · x = b. In what follows, the residual r is defined as r = b - * - A · x, where A is the linear operator of the linear system, b is the - * right-hand side vector, and x the current estimate of the solution. - * - * @since 3.0 - */ -public abstract class IterativeLinearSolver { - - /** The object in charge of managing the iterations. */ - private final IterationManager manager; - - /** - * Creates a new instance of this class, with default iteration manager. - * - * @param maxIterations the maximum number of iterations - */ - public IterativeLinearSolver(final int maxIterations) { - this.manager = new IterationManager(maxIterations); - } - - /** - * Creates a new instance of this class, with custom iteration manager. - * - * @param manager the custom iteration manager - * @throws NullArgumentException if {@code manager} is {@code null} - */ - public IterativeLinearSolver(final IterationManager manager) - throws NullArgumentException { - MathUtils.checkNotNull(manager); - this.manager = manager; - } - - /** - * Performs all dimension checks on the parameters of - * {@link #solve(RealLinearOperator, RealVector, RealVector) solve} and - * {@link #solveInPlace(RealLinearOperator, RealVector, RealVector) solveInPlace}, - * and throws an exception if one of the checks fails. - * - * @param a the linear operator A of the system - * @param b the right-hand side vector - * @param x0 the initial guess of the solution - * @throws NullArgumentException if one of the parameters is {@code null} - * @throws NonSquareOperatorException if {@code a} is not square - * @throws DimensionMismatchException if {@code b} or {@code x0} have - * dimensions inconsistent with {@code a} - */ - protected static void checkParameters(final RealLinearOperator a, - final RealVector b, final RealVector x0) throws - NullArgumentException, NonSquareOperatorException, - DimensionMismatchException { - MathUtils.checkNotNull(a); - MathUtils.checkNotNull(b); - MathUtils.checkNotNull(x0); - if (a.getRowDimension() != a.getColumnDimension()) { - throw new NonSquareOperatorException(a.getRowDimension(), - a.getColumnDimension()); - } - if (b.getDimension() != a.getRowDimension()) { - throw new DimensionMismatchException(b.getDimension(), - a.getRowDimension()); - } - if (x0.getDimension() != a.getColumnDimension()) { - throw new DimensionMismatchException(x0.getDimension(), - a.getColumnDimension()); - } - } - - /** - * Returns the iteration manager attached to this solver. - * - * @return the manager - */ - public IterationManager getIterationManager() { - return manager; - } - - /** - * Returns an estimate of the solution to the linear system A · x = - * b. - * - * @param a the linear operator A of the system - * @param b the right-hand side vector - * @return a new vector containing the solution - * @throws NullArgumentException if one of the parameters is {@code null} - * @throws NonSquareOperatorException if {@code a} is not square - * @throws DimensionMismatchException if {@code b} has dimensions - * inconsistent with {@code a} - * @throws MaxCountExceededException at exhaustion of the iteration count, - * unless a custom - * {@link org.apache.commons.math4.util.Incrementor.MaxCountExceededCallback callback} - * has been set at construction of the {@link IterationManager} - */ - public RealVector solve(final RealLinearOperator a, final RealVector b) - throws NullArgumentException, NonSquareOperatorException, - DimensionMismatchException, MaxCountExceededException { - MathUtils.checkNotNull(a); - final RealVector x = new ArrayRealVector(a.getColumnDimension()); - x.set(0.); - return solveInPlace(a, b, x); - } - - /** - * Returns an estimate of the solution to the linear system A · x = - * b. - * - * @param a the linear operator A of the system - * @param b the right-hand side vector - * @param x0 the initial guess of the solution - * @return a new vector containing the solution - * @throws NullArgumentException if one of the parameters is {@code null} - * @throws NonSquareOperatorException if {@code a} is not square - * @throws DimensionMismatchException if {@code b} or {@code x0} have - * dimensions inconsistent with {@code a} - * @throws MaxCountExceededException at exhaustion of the iteration count, - * unless a custom - * {@link org.apache.commons.math4.util.Incrementor.MaxCountExceededCallback callback} - * has been set at construction of the {@link IterationManager} - */ - public RealVector solve(RealLinearOperator a, RealVector b, RealVector x0) - throws NullArgumentException, NonSquareOperatorException, - DimensionMismatchException, MaxCountExceededException { - MathUtils.checkNotNull(x0); - return solveInPlace(a, b, x0.copy()); - } - - /** - * Returns an estimate of the solution to the linear system A · x = - * b. The solution is computed in-place (initial guess is modified). - * - * @param a the linear operator A of the system - * @param b the right-hand side vector - * @param x0 initial guess of the solution - * @return a reference to {@code x0} (shallow copy) updated with the - * solution - * @throws NullArgumentException if one of the parameters is {@code null} - * @throws NonSquareOperatorException if {@code a} is not square - * @throws DimensionMismatchException if {@code b} or {@code x0} have - * dimensions inconsistent with {@code a} - * @throws MaxCountExceededException at exhaustion of the iteration count, - * unless a custom - * {@link org.apache.commons.math4.util.Incrementor.MaxCountExceededCallback callback} - * has been set at construction of the {@link IterationManager} - */ - public abstract RealVector solveInPlace(RealLinearOperator a, RealVector b, - RealVector x0) throws NullArgumentException, NonSquareOperatorException, - DimensionMismatchException, MaxCountExceededException; -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/IterativeLinearSolverEvent.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/IterativeLinearSolverEvent.java deleted file mode 100644 index 94b47efa5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/IterativeLinearSolverEvent.java +++ /dev/null @@ -1,115 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.MathUnsupportedOperationException; -import org.apache.commons.math4.util.IterationEvent; - -/** - * This is the base class for all events occurring during the iterations of a - * {@link IterativeLinearSolver}. - * - * @since 3.0 - */ -public abstract class IterativeLinearSolverEvent - extends IterationEvent { - /** Serialization identifier. */ - private static final long serialVersionUID = 20120129L; - - /** - * Creates a new instance of this class. - * - * @param source the iterative algorithm on which the event initially - * occurred - * @param iterations the number of iterations performed at the time - * {@code this} event is created - */ - public IterativeLinearSolverEvent(final Object source, final int iterations) { - super(source, iterations); - } - - /** - * Returns the current right-hand side of the linear system to be solved. - * This method should return an unmodifiable view, or a deep copy of the - * actual right-hand side vector, in order not to compromise subsequent - * iterations of the source {@link IterativeLinearSolver}. - * - * @return the right-hand side vector, b - */ - public abstract RealVector getRightHandSideVector(); - - /** - * Returns the norm of the residual. The returned value is not required to - * be exact. Instead, the norm of the so-called updated - * residual (if available) should be returned. For example, the - * {@link ConjugateGradient conjugate gradient} method computes a sequence - * of residuals, the norm of which is cheap to compute. However, due to - * accumulation of round-off errors, this residual might differ from the - * true residual after some iterations. See e.g. A. Greenbaum and - * Z. Strakos, Predicting the Behavior of Finite Precision Lanzos and - * Conjugate Gradient Computations, Technical Report 538, Department of - * Computer Science, New York University, 1991 (available - * here). - * - * @return the norm of the residual, ||r|| - */ - public abstract double getNormOfResidual(); - - /** - *

- * Returns the residual. This is an optional operation, as all iterative - * linear solvers do not provide cheap estimate of the updated residual - * vector, in which case - *

- *
    - *
  • this method should throw a - * {@link MathUnsupportedOperationException},
  • - *
  • {@link #providesResidual()} returns {@code false}.
  • - *
- *

- * The default implementation throws a - * {@link MathUnsupportedOperationException}. If this method is overriden, - * then {@link #providesResidual()} should be overriden as well. - *

- * - * @return the updated residual, r - */ - public RealVector getResidual() { - throw new MathUnsupportedOperationException(); - } - - /** - * Returns the current estimate of the solution to the linear system to be - * solved. This method should return an unmodifiable view, or a deep copy of - * the actual current solution, in order not to compromise subsequent - * iterations of the source {@link IterativeLinearSolver}. - * - * @return the solution, x - */ - public abstract RealVector getSolution(); - - /** - * Returns {@code true} if {@link #getResidual()} is supported. The default - * implementation returns {@code false}. - * - * @return {@code false} if {@link #getResidual()} throws a - * {@link MathUnsupportedOperationException} - */ - public boolean providesResidual() { - return false; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/JacobiPreconditioner.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/JacobiPreconditioner.java deleted file mode 100644 index 63d70c369..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/JacobiPreconditioner.java +++ /dev/null @@ -1,135 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.analysis.function.Sqrt; -import org.apache.commons.math4.util.MathArrays; - -/** - * This class implements the standard Jacobi (diagonal) preconditioner. For a - * matrix Aij, this preconditioner is - * M = diag(1 / A11, 1 / A22, …). - * - * @since 3.0 - */ -public class JacobiPreconditioner extends RealLinearOperator { - - /** The diagonal coefficients of the preconditioner. */ - private final ArrayRealVector diag; - - /** - * Creates a new instance of this class. - * - * @param diag the diagonal coefficients of the linear operator to be - * preconditioned - * @param deep {@code true} if a deep copy of the above array should be - * performed - */ - public JacobiPreconditioner(final double[] diag, final boolean deep) { - this.diag = new ArrayRealVector(diag, deep); - } - - /** - * Creates a new instance of this class. This method extracts the diagonal - * coefficients of the specified linear operator. If {@code a} does not - * extend {@link AbstractRealMatrix}, then the coefficients of the - * underlying matrix are not accessible, coefficient extraction is made by - * matrix-vector products with the basis vectors (and might therefore take - * some time). With matrices, direct entry access is carried out. - * - * @param a the linear operator for which the preconditioner should be built - * @return the diagonal preconditioner made of the inverse of the diagonal - * coefficients of the specified linear operator - * @throws NonSquareOperatorException if {@code a} is not square - */ - public static JacobiPreconditioner create(final RealLinearOperator a) - throws NonSquareOperatorException { - final int n = a.getColumnDimension(); - if (a.getRowDimension() != n) { - throw new NonSquareOperatorException(a.getRowDimension(), n); - } - final double[] diag = new double[n]; - if (a instanceof AbstractRealMatrix) { - final AbstractRealMatrix m = (AbstractRealMatrix) a; - for (int i = 0; i < n; i++) { - diag[i] = m.getEntry(i, i); - } - } else { - final ArrayRealVector x = new ArrayRealVector(n); - for (int i = 0; i < n; i++) { - x.set(0.); - x.setEntry(i, 1.); - diag[i] = a.operate(x).getEntry(i); - } - } - return new JacobiPreconditioner(diag, false); - } - - /** {@inheritDoc} */ - @Override - public int getColumnDimension() { - return diag.getDimension(); - } - - /** {@inheritDoc} */ - @Override - public int getRowDimension() { - return diag.getDimension(); - } - - /** {@inheritDoc} */ - @Override - public RealVector operate(final RealVector x) { - // Dimension check is carried out by ebeDivide - return new ArrayRealVector(MathArrays.ebeDivide(x.toArray(), - diag.toArray()), - false); - } - - /** - * Returns the square root of {@code this} diagonal operator. More - * precisely, this method returns - * P = diag(1 / √A11, 1 / √A22, …). - * - * @return the square root of {@code this} preconditioner - * @since 3.1 - */ - public RealLinearOperator sqrt() { - final RealVector sqrtDiag = diag.map(new Sqrt()); - return new RealLinearOperator() { - /** {@inheritDoc} */ - @Override - public RealVector operate(final RealVector x) { - return new ArrayRealVector(MathArrays.ebeDivide(x.toArray(), - sqrtDiag.toArray()), - false); - } - - /** {@inheritDoc} */ - @Override - public int getRowDimension() { - return sqrtDiag.getDimension(); - } - - /** {@inheritDoc} */ - @Override - public int getColumnDimension() { - return sqrtDiag.getDimension(); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/LUDecomposition.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/LUDecomposition.java deleted file mode 100644 index 06884441e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/LUDecomposition.java +++ /dev/null @@ -1,394 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.util.FastMath; - -/** - * Calculates the LUP-decomposition of a square matrix. - *

The LUP-decomposition of a matrix A consists of three matrices L, U and - * P that satisfy: P×A = L×U. L is lower triangular (with unit - * diagonal terms), U is upper triangular and P is a permutation matrix. All - * matrices are m×m.

- *

As shown by the presence of the P matrix, this decomposition is - * implemented using partial pivoting.

- *

This class is based on the class with similar name from the - * JAMA library.

- *
    - *
  • a {@link #getP() getP} method has been added,
  • - *
  • the {@code det} method has been renamed as {@link #getDeterminant() - * getDeterminant},
  • - *
  • the {@code getDoublePivot} method has been removed (but the int based - * {@link #getPivot() getPivot} method has been kept),
  • - *
  • the {@code solve} and {@code isNonSingular} methods have been replaced - * by a {@link #getSolver() getSolver} method and the equivalent methods - * provided by the returned {@link DecompositionSolver}.
  • - *
- * - * @see MathWorld - * @see Wikipedia - * @since 2.0 (changed to concrete class in 3.0) - */ -public class LUDecomposition { - /** Default bound to determine effective singularity in LU decomposition. */ - private static final double DEFAULT_TOO_SMALL = 1e-11; - /** Entries of LU decomposition. */ - private final double[][] lu; - /** Pivot permutation associated with LU decomposition. */ - private final int[] pivot; - /** Parity of the permutation associated with the LU decomposition. */ - private boolean even; - /** Singularity indicator. */ - private boolean singular; - /** Cached value of L. */ - private RealMatrix cachedL; - /** Cached value of U. */ - private RealMatrix cachedU; - /** Cached value of P. */ - private RealMatrix cachedP; - - /** - * Calculates the LU-decomposition of the given matrix. - * This constructor uses 1e-11 as default value for the singularity - * threshold. - * - * @param matrix Matrix to decompose. - * @throws NonSquareMatrixException if matrix is not square. - */ - public LUDecomposition(RealMatrix matrix) { - this(matrix, DEFAULT_TOO_SMALL); - } - - /** - * Calculates the LU-decomposition of the given matrix. - * @param matrix The matrix to decompose. - * @param singularityThreshold threshold (based on partial row norm) - * under which a matrix is considered singular - * @throws NonSquareMatrixException if matrix is not square - */ - public LUDecomposition(RealMatrix matrix, double singularityThreshold) { - if (!matrix.isSquare()) { - throw new NonSquareMatrixException(matrix.getRowDimension(), - matrix.getColumnDimension()); - } - - final int m = matrix.getColumnDimension(); - lu = matrix.getData(); - pivot = new int[m]; - cachedL = null; - cachedU = null; - cachedP = null; - - // Initialize permutation array and parity - for (int row = 0; row < m; row++) { - pivot[row] = row; - } - even = true; - singular = false; - - // Loop over columns - for (int col = 0; col < m; col++) { - - // upper - for (int row = 0; row < col; row++) { - final double[] luRow = lu[row]; - double sum = luRow[col]; - for (int i = 0; i < row; i++) { - sum -= luRow[i] * lu[i][col]; - } - luRow[col] = sum; - } - - // lower - int max = col; // permutation row - double largest = Double.NEGATIVE_INFINITY; - for (int row = col; row < m; row++) { - final double[] luRow = lu[row]; - double sum = luRow[col]; - for (int i = 0; i < col; i++) { - sum -= luRow[i] * lu[i][col]; - } - luRow[col] = sum; - - // maintain best permutation choice - if (FastMath.abs(sum) > largest) { - largest = FastMath.abs(sum); - max = row; - } - } - - // Singularity check - if (FastMath.abs(lu[max][col]) < singularityThreshold) { - singular = true; - return; - } - - // Pivot if necessary - if (max != col) { - double tmp = 0; - final double[] luMax = lu[max]; - final double[] luCol = lu[col]; - for (int i = 0; i < m; i++) { - tmp = luMax[i]; - luMax[i] = luCol[i]; - luCol[i] = tmp; - } - int temp = pivot[max]; - pivot[max] = pivot[col]; - pivot[col] = temp; - even = !even; - } - - // Divide the lower elements by the "winning" diagonal elt. - final double luDiag = lu[col][col]; - for (int row = col + 1; row < m; row++) { - lu[row][col] /= luDiag; - } - } - } - - /** - * Returns the matrix L of the decomposition. - *

L is a lower-triangular matrix

- * @return the L matrix (or null if decomposed matrix is singular) - */ - public RealMatrix getL() { - if ((cachedL == null) && !singular) { - final int m = pivot.length; - cachedL = MatrixUtils.createRealMatrix(m, m); - for (int i = 0; i < m; ++i) { - final double[] luI = lu[i]; - for (int j = 0; j < i; ++j) { - cachedL.setEntry(i, j, luI[j]); - } - cachedL.setEntry(i, i, 1.0); - } - } - return cachedL; - } - - /** - * Returns the matrix U of the decomposition. - *

U is an upper-triangular matrix

- * @return the U matrix (or null if decomposed matrix is singular) - */ - public RealMatrix getU() { - if ((cachedU == null) && !singular) { - final int m = pivot.length; - cachedU = MatrixUtils.createRealMatrix(m, m); - for (int i = 0; i < m; ++i) { - final double[] luI = lu[i]; - for (int j = i; j < m; ++j) { - cachedU.setEntry(i, j, luI[j]); - } - } - } - return cachedU; - } - - /** - * Returns the P rows permutation matrix. - *

P is a sparse matrix with exactly one element set to 1.0 in - * each row and each column, all other elements being set to 0.0.

- *

The positions of the 1 elements are given by the {@link #getPivot() - * pivot permutation vector}.

- * @return the P rows permutation matrix (or null if decomposed matrix is singular) - * @see #getPivot() - */ - public RealMatrix getP() { - if ((cachedP == null) && !singular) { - final int m = pivot.length; - cachedP = MatrixUtils.createRealMatrix(m, m); - for (int i = 0; i < m; ++i) { - cachedP.setEntry(i, pivot[i], 1.0); - } - } - return cachedP; - } - - /** - * Returns the pivot permutation vector. - * @return the pivot permutation vector - * @see #getP() - */ - public int[] getPivot() { - return pivot.clone(); - } - - /** - * Return the determinant of the matrix - * @return determinant of the matrix - */ - public double getDeterminant() { - if (singular) { - return 0; - } else { - final int m = pivot.length; - double determinant = even ? 1 : -1; - for (int i = 0; i < m; i++) { - determinant *= lu[i][i]; - } - return determinant; - } - } - - /** - * Get a solver for finding the A × X = B solution in exact linear - * sense. - * @return a solver - */ - public DecompositionSolver getSolver() { - return new Solver(lu, pivot, singular); - } - - /** Specialized solver. */ - private static class Solver implements DecompositionSolver { - - /** Entries of LU decomposition. */ - private final double[][] lu; - - /** Pivot permutation associated with LU decomposition. */ - private final int[] pivot; - - /** Singularity indicator. */ - private final boolean singular; - - /** - * Build a solver from decomposed matrix. - * @param lu entries of LU decomposition - * @param pivot pivot permutation associated with LU decomposition - * @param singular singularity indicator - */ - private Solver(final double[][] lu, final int[] pivot, final boolean singular) { - this.lu = lu; - this.pivot = pivot; - this.singular = singular; - } - - /** {@inheritDoc} */ - @Override - public boolean isNonSingular() { - return !singular; - } - - /** {@inheritDoc} */ - @Override - public RealVector solve(RealVector b) { - final int m = pivot.length; - if (b.getDimension() != m) { - throw new DimensionMismatchException(b.getDimension(), m); - } - if (singular) { - throw new SingularMatrixException(); - } - - final double[] bp = new double[m]; - - // Apply permutations to b - for (int row = 0; row < m; row++) { - bp[row] = b.getEntry(pivot[row]); - } - - // Solve LY = b - for (int col = 0; col < m; col++) { - final double bpCol = bp[col]; - for (int i = col + 1; i < m; i++) { - bp[i] -= bpCol * lu[i][col]; - } - } - - // Solve UX = Y - for (int col = m - 1; col >= 0; col--) { - bp[col] /= lu[col][col]; - final double bpCol = bp[col]; - for (int i = 0; i < col; i++) { - bp[i] -= bpCol * lu[i][col]; - } - } - - return new ArrayRealVector(bp, false); - } - - /** {@inheritDoc} */ - @Override - public RealMatrix solve(RealMatrix b) { - - final int m = pivot.length; - if (b.getRowDimension() != m) { - throw new DimensionMismatchException(b.getRowDimension(), m); - } - if (singular) { - throw new SingularMatrixException(); - } - - final int nColB = b.getColumnDimension(); - - // Apply permutations to b - final double[][] bp = new double[m][nColB]; - for (int row = 0; row < m; row++) { - final double[] bpRow = bp[row]; - final int pRow = pivot[row]; - for (int col = 0; col < nColB; col++) { - bpRow[col] = b.getEntry(pRow, col); - } - } - - // Solve LY = b - for (int col = 0; col < m; col++) { - final double[] bpCol = bp[col]; - for (int i = col + 1; i < m; i++) { - final double[] bpI = bp[i]; - final double luICol = lu[i][col]; - for (int j = 0; j < nColB; j++) { - bpI[j] -= bpCol[j] * luICol; - } - } - } - - // Solve UX = Y - for (int col = m - 1; col >= 0; col--) { - final double[] bpCol = bp[col]; - final double luDiag = lu[col][col]; - for (int j = 0; j < nColB; j++) { - bpCol[j] /= luDiag; - } - for (int i = 0; i < col; i++) { - final double[] bpI = bp[i]; - final double luICol = lu[i][col]; - for (int j = 0; j < nColB; j++) { - bpI[j] -= bpCol[j] * luICol; - } - } - } - - return new Array2DRowRealMatrix(bp, false); - } - - /** - * Get the inverse of the decomposed matrix. - * - * @return the inverse matrix. - * @throws SingularMatrixException if the decomposed matrix is singular. - */ - @Override - public RealMatrix getInverse() { - return solve(MatrixUtils.createRealIdentityMatrix(pivot.length)); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/MatrixDimensionMismatchException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/MatrixDimensionMismatchException.java deleted file mode 100644 index ff3928e15..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/MatrixDimensionMismatchException.java +++ /dev/null @@ -1,73 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.MultiDimensionMismatchException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when either the number of rows or the number of - * columns of a matrix do not match the expected values. - * - * @since 3.0 - */ -public class MatrixDimensionMismatchException extends MultiDimensionMismatchException { - /** Serializable version Id. */ - private static final long serialVersionUID = -8415396756375798143L; - - /** - * Construct an exception from the mismatched dimensions. - * - * @param wrongRowDim Wrong row dimension. - * @param wrongColDim Wrong column dimension. - * @param expectedRowDim Expected row dimension. - * @param expectedColDim Expected column dimension. - */ - public MatrixDimensionMismatchException(int wrongRowDim, - int wrongColDim, - int expectedRowDim, - int expectedColDim) { - super(LocalizedFormats.DIMENSIONS_MISMATCH_2x2, - new Integer[] { wrongRowDim, wrongColDim }, - new Integer[] { expectedRowDim, expectedColDim }); - } - - /** - * @return the expected row dimension. - */ - public int getWrongRowDimension() { - return getWrongDimension(0); - } - /** - * @return the expected row dimension. - */ - public int getExpectedRowDimension() { - return getExpectedDimension(0); - } - /** - * @return the wrong column dimension. - */ - public int getWrongColumnDimension() { - return getWrongDimension(1); - } - /** - * @return the expected column dimension. - */ - public int getExpectedColumnDimension() { - return getExpectedDimension(1); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/MatrixUtils.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/MatrixUtils.java deleted file mode 100644 index bff4359f5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/MatrixUtils.java +++ /dev/null @@ -1,1133 +0,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. - */ - -package org.apache.commons.math4.linear; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.util.Arrays; - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.ZeroException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.fraction.BigFraction; -import org.apache.commons.math4.fraction.Fraction; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; -import org.apache.commons.numbers.core.Precision; - -/** - * A collection of static methods that operate on or return matrices. - * - */ -public class MatrixUtils { - - /** - * The default format for {@link RealMatrix} objects. - * @since 3.1 - */ - public static final RealMatrixFormat DEFAULT_FORMAT = RealMatrixFormat.getInstance(); - - /** - * A format for {@link RealMatrix} objects compatible with octave. - * @since 3.1 - */ - public static final RealMatrixFormat OCTAVE_FORMAT = new RealMatrixFormat("[", "]", "", "", "; ", ", "); - - /** - * Private constructor. - */ - private MatrixUtils() { - super(); - } - - /** - * Returns a {@link RealMatrix} with specified dimensions. - *

The type of matrix returned depends on the dimension. Below - * 212 elements (i.e. 4096 elements or 64×64 for a - * square matrix) which can be stored in a 32kB array, a {@link - * Array2DRowRealMatrix} instance is built. Above this threshold a {@link - * BlockRealMatrix} instance is built.

- *

The matrix elements are all set to 0.0.

- * @param rows number of rows of the matrix - * @param columns number of columns of the matrix - * @return RealMatrix with specified dimensions - * @see #createRealMatrix(double[][]) - */ - public static RealMatrix createRealMatrix(final int rows, final int columns) { - return (rows * columns <= 4096) ? - new Array2DRowRealMatrix(rows, columns) : new BlockRealMatrix(rows, columns); - } - - /** - * Returns a {@link FieldMatrix} with specified dimensions. - *

The type of matrix returned depends on the dimension. Below - * 212 elements (i.e. 4096 elements or 64×64 for a - * square matrix), a {@link FieldMatrix} instance is built. Above - * this threshold a {@link BlockFieldMatrix} instance is built.

- *

The matrix elements are all set to field.getZero().

- * @param the type of the field elements - * @param field field to which the matrix elements belong - * @param rows number of rows of the matrix - * @param columns number of columns of the matrix - * @return FieldMatrix with specified dimensions - * @see #createFieldMatrix(FieldElement[][]) - * @since 2.0 - */ - public static > FieldMatrix createFieldMatrix(final Field field, - final int rows, - final int columns) { - return (rows * columns <= 4096) ? - new Array2DRowFieldMatrix<>(field, rows, columns) : new BlockFieldMatrix<>(field, rows, columns); - } - - /** - * Returns a {@link RealMatrix} whose entries are the values in the - * the input array. - *

The type of matrix returned depends on the dimension. Below - * 212 elements (i.e. 4096 elements or 64×64 for a - * square matrix) which can be stored in a 32kB array, a {@link - * Array2DRowRealMatrix} instance is built. Above this threshold a {@link - * BlockRealMatrix} instance is built.

- *

The input array is copied, not referenced.

- * - * @param data input array - * @return RealMatrix containing the values of the array - * @throws DimensionMismatchException - * if {@code data} is not rectangular (not all rows have the same length). - * @throws NoDataException if a row or column is empty. - * @throws NullArgumentException if either {@code data} or {@code data[0]} - * is {@code null}. - * @throws DimensionMismatchException if {@code data} is not rectangular. - * @see #createRealMatrix(int, int) - */ - public static RealMatrix createRealMatrix(double[][] data) - throws NullArgumentException, DimensionMismatchException, - NoDataException { - if (data == null || - data[0] == null) { - throw new NullArgumentException(); - } - return (data.length * data[0].length <= 4096) ? - new Array2DRowRealMatrix(data) : new BlockRealMatrix(data); - } - - /** - * Returns a {@link FieldMatrix} whose entries are the values in the - * the input array. - *

The type of matrix returned depends on the dimension. Below - * 212 elements (i.e. 4096 elements or 64×64 for a - * square matrix), a {@link FieldMatrix} instance is built. Above - * this threshold a {@link BlockFieldMatrix} instance is built.

- *

The input array is copied, not referenced.

- * @param the type of the field elements - * @param data input array - * @return a matrix containing the values of the array. - * @throws DimensionMismatchException - * if {@code data} is not rectangular (not all rows have the same length). - * @throws NoDataException if a row or column is empty. - * @throws NullArgumentException if either {@code data} or {@code data[0]} - * is {@code null}. - * @see #createFieldMatrix(Field, int, int) - * @since 2.0 - */ - public static > FieldMatrix createFieldMatrix(T[][] data) - throws DimensionMismatchException, NoDataException, NullArgumentException { - if (data == null || - data[0] == null) { - throw new NullArgumentException(); - } - return (data.length * data[0].length <= 4096) ? - new Array2DRowFieldMatrix<>(data) : new BlockFieldMatrix<>(data); - } - - /** - * Returns dimension x dimension identity matrix. - * - * @param dimension dimension of identity matrix to generate - * @return identity matrix - * @throws IllegalArgumentException if dimension is not positive - * @since 1.1 - */ - public static RealMatrix createRealIdentityMatrix(int dimension) { - final RealMatrix m = createRealMatrix(dimension, dimension); - for (int i = 0; i < dimension; ++i) { - m.setEntry(i, i, 1.0); - } - return m; - } - - /** - * Returns dimension x dimension identity matrix. - * - * @param the type of the field elements - * @param field field to which the elements belong - * @param dimension dimension of identity matrix to generate - * @return identity matrix - * @throws IllegalArgumentException if dimension is not positive - * @since 2.0 - */ - public static > FieldMatrix - createFieldIdentityMatrix(final Field field, final int dimension) { - final T zero = field.getZero(); - final T one = field.getOne(); - final T[][] d = MathArrays.buildArray(field, dimension, dimension); - for (int row = 0; row < dimension; row++) { - final T[] dRow = d[row]; - Arrays.fill(dRow, zero); - dRow[row] = one; - } - return new Array2DRowFieldMatrix<>(field, d, false); - } - - /** - * Creates a diagonal matrix with the specified diagonal elements. - * - * @param diagonal Diagonal elements of the matrix. - * The array elements will be copied. - * @return a diagonal matrix instance. - * - * @see #createRealMatrixWithDiagonal(double[]) - * @since 2.0 - */ - public static DiagonalMatrix createRealDiagonalMatrix(final double[] diagonal) { - return new DiagonalMatrix(diagonal, true); - } - - /** - * Creates a dense matrix with the specified diagonal elements. - * - * @param diagonal Diagonal elements of the matrix. - * @return a matrix instance. - * - * @see #createRealDiagonalMatrix(double[]) - * @since 4.0 - */ - public static RealMatrix createRealMatrixWithDiagonal(final double[] diagonal) { - final int size = diagonal.length; - final RealMatrix m = createRealMatrix(size, size); - for (int i = 0; i < size; i++) { - m.setEntry(i, i, diagonal[i]); - } - return m; - } - - /** - * Returns a diagonal matrix with specified elements. - * - * @param the type of the field elements - * @param diagonal diagonal elements of the matrix (the array elements - * will be copied) - * @return diagonal matrix - * @since 2.0 - */ - public static > FieldMatrix - createFieldDiagonalMatrix(final T[] diagonal) { - final FieldMatrix m = - createFieldMatrix(diagonal[0].getField(), diagonal.length, diagonal.length); - for (int i = 0; i < diagonal.length; ++i) { - m.setEntry(i, i, diagonal[i]); - } - return m; - } - - /** - * Creates a {@link RealVector} using the data from the input array. - * - * @param data the input data - * @return a data.length RealVector - * @throws NoDataException if {@code data} is empty. - * @throws NullArgumentException if {@code data} is {@code null}. - */ - public static RealVector createRealVector(double[] data) - throws NoDataException, NullArgumentException { - if (data == null) { - throw new NullArgumentException(); - } - return new ArrayRealVector(data, true); - } - - /** - * Creates a {@link FieldVector} using the data from the input array. - * - * @param the type of the field elements - * @param data the input data - * @return a data.length FieldVector - * @throws NoDataException if {@code data} is empty. - * @throws NullArgumentException if {@code data} is {@code null}. - * @throws ZeroException if {@code data} has 0 elements - */ - public static > FieldVector createFieldVector(final T[] data) - throws NoDataException, NullArgumentException, ZeroException { - if (data == null) { - throw new NullArgumentException(); - } - if (data.length == 0) { - throw new ZeroException(LocalizedFormats.VECTOR_MUST_HAVE_AT_LEAST_ONE_ELEMENT); - } - return new ArrayFieldVector<>(data[0].getField(), data, true); - } - - /** - * Create a row {@link RealMatrix} using the data from the input - * array. - * - * @param rowData the input row data - * @return a 1 x rowData.length RealMatrix - * @throws NoDataException if {@code rowData} is empty. - * @throws NullArgumentException if {@code rowData} is {@code null}. - */ - public static RealMatrix createRowRealMatrix(double[] rowData) - throws NoDataException, NullArgumentException { - if (rowData == null) { - throw new NullArgumentException(); - } - final int nCols = rowData.length; - final RealMatrix m = createRealMatrix(1, nCols); - for (int i = 0; i < nCols; ++i) { - m.setEntry(0, i, rowData[i]); - } - return m; - } - - /** - * Create a row {@link FieldMatrix} using the data from the input - * array. - * - * @param the type of the field elements - * @param rowData the input row data - * @return a 1 x rowData.length FieldMatrix - * @throws NoDataException if {@code rowData} is empty. - * @throws NullArgumentException if {@code rowData} is {@code null}. - */ - public static > FieldMatrix - createRowFieldMatrix(final T[] rowData) - throws NoDataException, NullArgumentException { - if (rowData == null) { - throw new NullArgumentException(); - } - final int nCols = rowData.length; - if (nCols == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN); - } - final FieldMatrix m = createFieldMatrix(rowData[0].getField(), 1, nCols); - for (int i = 0; i < nCols; ++i) { - m.setEntry(0, i, rowData[i]); - } - return m; - } - - /** - * Creates a column {@link RealMatrix} using the data from the input - * array. - * - * @param columnData the input column data - * @return a columnData x 1 RealMatrix - * @throws NoDataException if {@code columnData} is empty. - * @throws NullArgumentException if {@code columnData} is {@code null}. - */ - public static RealMatrix createColumnRealMatrix(double[] columnData) - throws NoDataException, NullArgumentException { - if (columnData == null) { - throw new NullArgumentException(); - } - final int nRows = columnData.length; - final RealMatrix m = createRealMatrix(nRows, 1); - for (int i = 0; i < nRows; ++i) { - m.setEntry(i, 0, columnData[i]); - } - return m; - } - - /** - * Creates a column {@link FieldMatrix} using the data from the input - * array. - * - * @param the type of the field elements - * @param columnData the input column data - * @return a columnData x 1 FieldMatrix - * @throws NoDataException if {@code data} is empty. - * @throws NullArgumentException if {@code columnData} is {@code null}. - */ - public static > FieldMatrix - createColumnFieldMatrix(final T[] columnData) - throws NoDataException, NullArgumentException { - if (columnData == null) { - throw new NullArgumentException(); - } - final int nRows = columnData.length; - if (nRows == 0) { - throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW); - } - final FieldMatrix m = createFieldMatrix(columnData[0].getField(), nRows, 1); - for (int i = 0; i < nRows; ++i) { - m.setEntry(i, 0, columnData[i]); - } - return m; - } - - /** - * Checks whether a matrix is symmetric, within a given relative tolerance. - * - * @param matrix Matrix to check. - * @param relativeTolerance Tolerance of the symmetry check. - * @param raiseException If {@code true}, an exception will be raised if - * the matrix is not symmetric. - * @return {@code true} if {@code matrix} is symmetric. - * @throws NonSquareMatrixException if the matrix is not square. - * @throws NonSymmetricMatrixException if the matrix is not symmetric. - */ - private static boolean isSymmetricInternal(RealMatrix matrix, - double relativeTolerance, - boolean raiseException) { - final int rows = matrix.getRowDimension(); - if (rows != matrix.getColumnDimension()) { - if (raiseException) { - throw new NonSquareMatrixException(rows, matrix.getColumnDimension()); - } else { - return false; - } - } - for (int i = 0; i < rows; i++) { - for (int j = i + 1; j < rows; j++) { - final double mij = matrix.getEntry(i, j); - final double mji = matrix.getEntry(j, i); - if (FastMath.abs(mij - mji) > - FastMath.max(FastMath.abs(mij), FastMath.abs(mji)) * relativeTolerance) { - if (raiseException) { - throw new NonSymmetricMatrixException(i, j, relativeTolerance); - } else { - return false; - } - } - } - } - return true; - } - - /** - * Checks whether a matrix is symmetric. - * - * @param matrix Matrix to check. - * @param eps Relative tolerance. - * @throws NonSquareMatrixException if the matrix is not square. - * @throws NonSymmetricMatrixException if the matrix is not symmetric. - * @since 3.1 - */ - public static void checkSymmetric(RealMatrix matrix, - double eps) { - isSymmetricInternal(matrix, eps, true); - } - - /** - * Checks whether a matrix is symmetric. - * - * @param matrix Matrix to check. - * @param eps Relative tolerance. - * @return {@code true} if {@code matrix} is symmetric. - * @since 3.1 - */ - public static boolean isSymmetric(RealMatrix matrix, - double eps) { - return isSymmetricInternal(matrix, eps, false); - } - - /** - * Check if matrix indices are valid. - * - * @param m Matrix. - * @param row Row index to check. - * @param column Column index to check. - * @throws OutOfRangeException if {@code row} or {@code column} is not - * a valid index. - */ - public static void checkMatrixIndex(final AnyMatrix m, - final int row, final int column) - throws OutOfRangeException { - checkRowIndex(m, row); - checkColumnIndex(m, column); - } - - /** - * Check if a row index is valid. - * - * @param m Matrix. - * @param row Row index to check. - * @throws OutOfRangeException if {@code row} is not a valid index. - */ - public static void checkRowIndex(final AnyMatrix m, final int row) - throws OutOfRangeException { - if (row < 0 || - row >= m.getRowDimension()) { - throw new OutOfRangeException(LocalizedFormats.ROW_INDEX, - row, 0, m.getRowDimension() - 1); - } - } - - /** - * Check if a column index is valid. - * - * @param m Matrix. - * @param column Column index to check. - * @throws OutOfRangeException if {@code column} is not a valid index. - */ - public static void checkColumnIndex(final AnyMatrix m, final int column) - throws OutOfRangeException { - if (column < 0 || column >= m.getColumnDimension()) { - throw new OutOfRangeException(LocalizedFormats.COLUMN_INDEX, - column, 0, m.getColumnDimension() - 1); - } - } - - /** - * Check if submatrix ranges indices are valid. - * Rows and columns are indicated counting from 0 to {@code n - 1}. - * - * @param m Matrix. - * @param startRow Initial row index. - * @param endRow Final row index. - * @param startColumn Initial column index. - * @param endColumn Final column index. - * @throws OutOfRangeException if the indices are invalid. - * @throws NumberIsTooSmallException if {@code endRow < startRow} or - * {@code endColumn < startColumn}. - */ - public static void checkSubMatrixIndex(final AnyMatrix m, - final int startRow, final int endRow, - final int startColumn, final int endColumn) - throws NumberIsTooSmallException, OutOfRangeException { - checkRowIndex(m, startRow); - checkRowIndex(m, endRow); - if (endRow < startRow) { - throw new NumberIsTooSmallException(LocalizedFormats.INITIAL_ROW_AFTER_FINAL_ROW, - endRow, startRow, false); - } - - checkColumnIndex(m, startColumn); - checkColumnIndex(m, endColumn); - if (endColumn < startColumn) { - throw new NumberIsTooSmallException(LocalizedFormats.INITIAL_COLUMN_AFTER_FINAL_COLUMN, - endColumn, startColumn, false); - } - - - } - - /** - * Check if submatrix ranges indices are valid. - * Rows and columns are indicated counting from 0 to n-1. - * - * @param m Matrix. - * @param selectedRows Array of row indices. - * @param selectedColumns Array of column indices. - * @throws NullArgumentException if {@code selectedRows} or - * {@code selectedColumns} are {@code null}. - * @throws NoDataException if the row or column selections are empty (zero - * length). - * @throws OutOfRangeException if row or column selections are not valid. - */ - public static void checkSubMatrixIndex(final AnyMatrix m, - final int[] selectedRows, - final int[] selectedColumns) - throws NoDataException, NullArgumentException, OutOfRangeException { - if (selectedRows == null) { - throw new NullArgumentException(); - } - if (selectedColumns == null) { - throw new NullArgumentException(); - } - if (selectedRows.length == 0) { - throw new NoDataException(LocalizedFormats.EMPTY_SELECTED_ROW_INDEX_ARRAY); - } - if (selectedColumns.length == 0) { - throw new NoDataException(LocalizedFormats.EMPTY_SELECTED_COLUMN_INDEX_ARRAY); - } - - for (final int row : selectedRows) { - checkRowIndex(m, row); - } - for (final int column : selectedColumns) { - checkColumnIndex(m, column); - } - } - - /** - * Check if matrices are addition compatible. - * - * @param left Left hand side matrix. - * @param right Right hand side matrix. - * @throws MatrixDimensionMismatchException if the matrices are not addition - * compatible. - */ - public static void checkAdditionCompatible(final AnyMatrix left, final AnyMatrix right) - throws MatrixDimensionMismatchException { - if ((left.getRowDimension() != right.getRowDimension()) || - (left.getColumnDimension() != right.getColumnDimension())) { - throw new MatrixDimensionMismatchException(left.getRowDimension(), left.getColumnDimension(), - right.getRowDimension(), right.getColumnDimension()); - } - } - - /** - * Check if matrices are subtraction compatible - * - * @param left Left hand side matrix. - * @param right Right hand side matrix. - * @throws MatrixDimensionMismatchException if the matrices are not addition - * compatible. - */ - public static void checkSubtractionCompatible(final AnyMatrix left, final AnyMatrix right) - throws MatrixDimensionMismatchException { - if ((left.getRowDimension() != right.getRowDimension()) || - (left.getColumnDimension() != right.getColumnDimension())) { - throw new MatrixDimensionMismatchException(left.getRowDimension(), left.getColumnDimension(), - right.getRowDimension(), right.getColumnDimension()); - } - } - - /** - * Check if matrices are multiplication compatible - * - * @param left Left hand side matrix. - * @param right Right hand side matrix. - * @throws DimensionMismatchException if matrices are not multiplication - * compatible. - */ - public static void checkMultiplicationCompatible(final AnyMatrix left, final AnyMatrix right) - throws DimensionMismatchException { - - if (left.getColumnDimension() != right.getRowDimension()) { - throw new DimensionMismatchException(left.getColumnDimension(), - right.getRowDimension()); - } - } - - /** - * Convert a {@link FieldMatrix}/{@link Fraction} matrix to a {@link RealMatrix}. - * @param m Matrix to convert. - * @return the converted matrix. - */ - public static Array2DRowRealMatrix fractionMatrixToRealMatrix(final FieldMatrix m) { - final FractionMatrixConverter converter = new FractionMatrixConverter(); - m.walkInOptimizedOrder(converter); - return converter.getConvertedMatrix(); - } - - /** Converter for {@link FieldMatrix}/{@link Fraction}. */ - private static class FractionMatrixConverter extends DefaultFieldMatrixPreservingVisitor { - /** Converted array. */ - private double[][] data; - /** Simple constructor. */ - FractionMatrixConverter() { - super(Fraction.ZERO); - } - - /** {@inheritDoc} */ - @Override - public void start(int rows, int columns, - int startRow, int endRow, int startColumn, int endColumn) { - data = new double[rows][columns]; - } - - /** {@inheritDoc} */ - @Override - public void visit(int row, int column, Fraction value) { - data[row][column] = value.doubleValue(); - } - - /** - * Get the converted matrix. - * - * @return the converted matrix. - */ - Array2DRowRealMatrix getConvertedMatrix() { - return new Array2DRowRealMatrix(data, false); - } - - } - - /** - * Convert a {@link FieldMatrix}/{@link BigFraction} matrix to a {@link RealMatrix}. - * - * @param m Matrix to convert. - * @return the converted matrix. - */ - public static Array2DRowRealMatrix bigFractionMatrixToRealMatrix(final FieldMatrix m) { - final BigFractionMatrixConverter converter = new BigFractionMatrixConverter(); - m.walkInOptimizedOrder(converter); - return converter.getConvertedMatrix(); - } - - /** Converter for {@link FieldMatrix}/{@link BigFraction}. */ - private static class BigFractionMatrixConverter extends DefaultFieldMatrixPreservingVisitor { - /** Converted array. */ - private double[][] data; - /** Simple constructor. */ - BigFractionMatrixConverter() { - super(BigFraction.ZERO); - } - - /** {@inheritDoc} */ - @Override - public void start(int rows, int columns, - int startRow, int endRow, int startColumn, int endColumn) { - data = new double[rows][columns]; - } - - /** {@inheritDoc} */ - @Override - public void visit(int row, int column, BigFraction value) { - data[row][column] = value.doubleValue(); - } - - /** - * Get the converted matrix. - * - * @return the converted matrix. - */ - Array2DRowRealMatrix getConvertedMatrix() { - return new Array2DRowRealMatrix(data, false); - } - } - - /** Serialize a {@link RealVector}. - *

- * This method is intended to be called from within a private - * writeObject method (after a call to - * oos.defaultWriteObject()) in a class that has a - * {@link RealVector} field, which should be declared transient. - * This way, the default handling does not serialize the vector (the {@link - * RealVector} interface is not serializable by default) but this method does - * serialize it specifically. - *

- *

- * The following example shows how a simple class with a name and a real vector - * should be written: - *


-     * public class NamedVector implements Serializable {
-     *
-     *     private final String name;
-     *     private final transient RealVector coefficients;
-     *
-     *     // omitted constructors, getters ...
-     *
-     *     private void writeObject(ObjectOutputStream oos) throws IOException {
-     *         oos.defaultWriteObject();  // takes care of name field
-     *         MatrixUtils.serializeRealVector(coefficients, oos);
-     *     }
-     *
-     *     private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
-     *         ois.defaultReadObject();  // takes care of name field
-     *         MatrixUtils.deserializeRealVector(this, "coefficients", ois);
-     *     }
-     *
-     * }
-     * 
- * - * @param vector real vector to serialize - * @param oos stream where the real vector should be written - * @exception IOException if object cannot be written to stream - * @see #deserializeRealVector(Object, String, ObjectInputStream) - */ - public static void serializeRealVector(final RealVector vector, - final ObjectOutputStream oos) - throws IOException { - final int n = vector.getDimension(); - oos.writeInt(n); - for (int i = 0; i < n; ++i) { - oos.writeDouble(vector.getEntry(i)); - } - } - - /** Deserialize a {@link RealVector} field in a class. - *

- * This method is intended to be called from within a private - * readObject method (after a call to - * ois.defaultReadObject()) in a class that has a - * {@link RealVector} field, which should be declared transient. - * This way, the default handling does not deserialize the vector (the {@link - * RealVector} interface is not serializable by default) but this method does - * deserialize it specifically. - *

- * @param instance instance in which the field must be set up - * @param fieldName name of the field within the class (may be private and final) - * @param ois stream from which the real vector should be read - * @exception ClassNotFoundException if a class in the stream cannot be found - * @exception IOException if object cannot be read from the stream - * @see #serializeRealVector(RealVector, ObjectOutputStream) - */ - public static void deserializeRealVector(final Object instance, - final String fieldName, - final ObjectInputStream ois) - throws ClassNotFoundException, IOException { - try { - - // read the vector data - final int n = ois.readInt(); - final double[] data = new double[n]; - for (int i = 0; i < n; ++i) { - data[i] = ois.readDouble(); - } - - // create the instance - final RealVector vector = new ArrayRealVector(data, false); - - // set up the field - final java.lang.reflect.Field f = - instance.getClass().getDeclaredField(fieldName); - f.setAccessible(true); - f.set(instance, vector); - - } catch (NoSuchFieldException nsfe) { - IOException ioe = new IOException(); - ioe.initCause(nsfe); - throw ioe; - } catch (IllegalAccessException iae) { - IOException ioe = new IOException(); - ioe.initCause(iae); - throw ioe; - } - - } - - /** Serialize a {@link RealMatrix}. - *

- * This method is intended to be called from within a private - * writeObject method (after a call to - * oos.defaultWriteObject()) in a class that has a - * {@link RealMatrix} field, which should be declared transient. - * This way, the default handling does not serialize the matrix (the {@link - * RealMatrix} interface is not serializable by default) but this method does - * serialize it specifically. - *

- *

- * The following example shows how a simple class with a name and a real matrix - * should be written: - *


-     * public class NamedMatrix implements Serializable {
-     *
-     *     private final String name;
-     *     private final transient RealMatrix coefficients;
-     *
-     *     // omitted constructors, getters ...
-     *
-     *     private void writeObject(ObjectOutputStream oos) throws IOException {
-     *         oos.defaultWriteObject();  // takes care of name field
-     *         MatrixUtils.serializeRealMatrix(coefficients, oos);
-     *     }
-     *
-     *     private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
-     *         ois.defaultReadObject();  // takes care of name field
-     *         MatrixUtils.deserializeRealMatrix(this, "coefficients", ois);
-     *     }
-     *
-     * }
-     * 
- * - * @param matrix real matrix to serialize - * @param oos stream where the real matrix should be written - * @exception IOException if object cannot be written to stream - * @see #deserializeRealMatrix(Object, String, ObjectInputStream) - */ - public static void serializeRealMatrix(final RealMatrix matrix, - final ObjectOutputStream oos) - throws IOException { - final int n = matrix.getRowDimension(); - final int m = matrix.getColumnDimension(); - oos.writeInt(n); - oos.writeInt(m); - for (int i = 0; i < n; ++i) { - for (int j = 0; j < m; ++j) { - oos.writeDouble(matrix.getEntry(i, j)); - } - } - } - - /** Deserialize a {@link RealMatrix} field in a class. - *

- * This method is intended to be called from within a private - * readObject method (after a call to - * ois.defaultReadObject()) in a class that has a - * {@link RealMatrix} field, which should be declared transient. - * This way, the default handling does not deserialize the matrix (the {@link - * RealMatrix} interface is not serializable by default) but this method does - * deserialize it specifically. - *

- * @param instance instance in which the field must be set up - * @param fieldName name of the field within the class (may be private and final) - * @param ois stream from which the real matrix should be read - * @exception ClassNotFoundException if a class in the stream cannot be found - * @exception IOException if object cannot be read from the stream - * @see #serializeRealMatrix(RealMatrix, ObjectOutputStream) - */ - public static void deserializeRealMatrix(final Object instance, - final String fieldName, - final ObjectInputStream ois) - throws ClassNotFoundException, IOException { - try { - - // read the matrix data - final int n = ois.readInt(); - final int m = ois.readInt(); - final double[][] data = new double[n][m]; - for (int i = 0; i < n; ++i) { - final double[] dataI = data[i]; - for (int j = 0; j < m; ++j) { - dataI[j] = ois.readDouble(); - } - } - - // create the instance - final RealMatrix matrix = new Array2DRowRealMatrix(data, false); - - // set up the field - final java.lang.reflect.Field f = - instance.getClass().getDeclaredField(fieldName); - f.setAccessible(true); - f.set(instance, matrix); - - } catch (NoSuchFieldException nsfe) { - IOException ioe = new IOException(); - ioe.initCause(nsfe); - throw ioe; - } catch (IllegalAccessException iae) { - IOException ioe = new IOException(); - ioe.initCause(iae); - throw ioe; - } - } - - /**Solve a system of composed of a Lower Triangular Matrix - * {@link RealMatrix}. - *

- * This method is called to solve systems of equations which are - * of the lower triangular form. The matrix {@link RealMatrix} - * is assumed, though not checked, to be in lower triangular form. - * The vector {@link RealVector} is overwritten with the solution. - * The matrix is checked that it is square and its dimensions match - * the length of the vector. - *

- * @param rm RealMatrix which is lower triangular - * @param b RealVector this is overwritten - * @throws DimensionMismatchException if the matrix and vector are not - * conformable - * @throws NonSquareMatrixException if the matrix {@code rm} is not square - * @throws MathArithmeticException if the absolute value of one of the diagonal - * coefficient of {@code rm} is lower than {@link Precision#SAFE_MIN} - */ - public static void solveLowerTriangularSystem(RealMatrix rm, RealVector b) - throws DimensionMismatchException, MathArithmeticException, - NonSquareMatrixException { - if ((rm == null) || (b == null) || ( rm.getRowDimension() != b.getDimension())) { - throw new DimensionMismatchException( - (rm == null) ? 0 : rm.getRowDimension(), - (b == null) ? 0 : b.getDimension()); - } - if( rm.getColumnDimension() != rm.getRowDimension() ){ - throw new NonSquareMatrixException(rm.getRowDimension(), - rm.getColumnDimension()); - } - int rows = rm.getRowDimension(); - for( int i = 0 ; i < rows ; i++ ){ - double diag = rm.getEntry(i, i); - if( FastMath.abs(diag) < Precision.SAFE_MIN ){ - throw new MathArithmeticException(LocalizedFormats.ZERO_DENOMINATOR); - } - double bi = b.getEntry(i)/diag; - b.setEntry(i, bi ); - for( int j = i+1; j< rows; j++ ){ - b.setEntry(j, b.getEntry(j)-bi*rm.getEntry(j,i) ); - } - } - } - - /** Solver a system composed of an Upper Triangular Matrix - * {@link RealMatrix}. - *

- * This method is called to solve systems of equations which are - * of the lower triangular form. The matrix {@link RealMatrix} - * is assumed, though not checked, to be in upper triangular form. - * The vector {@link RealVector} is overwritten with the solution. - * The matrix is checked that it is square and its dimensions match - * the length of the vector. - *

- * @param rm RealMatrix which is upper triangular - * @param b RealVector this is overwritten - * @throws DimensionMismatchException if the matrix and vector are not - * conformable - * @throws NonSquareMatrixException if the matrix {@code rm} is not - * square - * @throws MathArithmeticException if the absolute value of one of the diagonal - * coefficient of {@code rm} is lower than {@link Precision#SAFE_MIN} - */ - public static void solveUpperTriangularSystem(RealMatrix rm, RealVector b) - throws DimensionMismatchException, MathArithmeticException, - NonSquareMatrixException { - if ((rm == null) || (b == null) || ( rm.getRowDimension() != b.getDimension())) { - throw new DimensionMismatchException( - (rm == null) ? 0 : rm.getRowDimension(), - (b == null) ? 0 : b.getDimension()); - } - if( rm.getColumnDimension() != rm.getRowDimension() ){ - throw new NonSquareMatrixException(rm.getRowDimension(), - rm.getColumnDimension()); - } - int rows = rm.getRowDimension(); - for( int i = rows-1 ; i >-1 ; i-- ){ - double diag = rm.getEntry(i, i); - if( FastMath.abs(diag) < Precision.SAFE_MIN ){ - throw new MathArithmeticException(LocalizedFormats.ZERO_DENOMINATOR); - } - double bi = b.getEntry(i)/diag; - b.setEntry(i, bi ); - for( int j = i-1; j>-1; j-- ){ - b.setEntry(j, b.getEntry(j)-bi*rm.getEntry(j,i) ); - } - } - } - - /** - * Computes the inverse of the given matrix by splitting it into - * 4 sub-matrices. - * - * @param m Matrix whose inverse must be computed. - * @param splitIndex Index that determines the "split" line and - * column. - * The element corresponding to this index will part of the - * upper-left sub-matrix. - * @return the inverse of {@code m}. - * @throws NonSquareMatrixException if {@code m} is not square. - */ - public static RealMatrix blockInverse(RealMatrix m, - int splitIndex) { - final int n = m.getRowDimension(); - if (m.getColumnDimension() != n) { - throw new NonSquareMatrixException(m.getRowDimension(), - m.getColumnDimension()); - } - - final int splitIndex1 = splitIndex + 1; - - final RealMatrix a = m.getSubMatrix(0, splitIndex, 0, splitIndex); - final RealMatrix b = m.getSubMatrix(0, splitIndex, splitIndex1, n - 1); - final RealMatrix c = m.getSubMatrix(splitIndex1, n - 1, 0, splitIndex); - final RealMatrix d = m.getSubMatrix(splitIndex1, n - 1, splitIndex1, n - 1); - - final SingularValueDecomposition aDec = new SingularValueDecomposition(a); - final DecompositionSolver aSolver = aDec.getSolver(); - if (!aSolver.isNonSingular()) { - throw new SingularMatrixException(); - } - final RealMatrix aInv = aSolver.getInverse(); - - final SingularValueDecomposition dDec = new SingularValueDecomposition(d); - final DecompositionSolver dSolver = dDec.getSolver(); - if (!dSolver.isNonSingular()) { - throw new SingularMatrixException(); - } - final RealMatrix dInv = dSolver.getInverse(); - - final RealMatrix tmp1 = a.subtract(b.multiply(dInv).multiply(c)); - final SingularValueDecomposition tmp1Dec = new SingularValueDecomposition(tmp1); - final DecompositionSolver tmp1Solver = tmp1Dec.getSolver(); - if (!tmp1Solver.isNonSingular()) { - throw new SingularMatrixException(); - } - final RealMatrix result00 = tmp1Solver.getInverse(); - - final RealMatrix tmp2 = d.subtract(c.multiply(aInv).multiply(b)); - final SingularValueDecomposition tmp2Dec = new SingularValueDecomposition(tmp2); - final DecompositionSolver tmp2Solver = tmp2Dec.getSolver(); - if (!tmp2Solver.isNonSingular()) { - throw new SingularMatrixException(); - } - final RealMatrix result11 = tmp2Solver.getInverse(); - - final RealMatrix result01 = aInv.multiply(b).multiply(result11).scalarMultiply(-1); - final RealMatrix result10 = dInv.multiply(c).multiply(result00).scalarMultiply(-1); - - final RealMatrix result = new Array2DRowRealMatrix(n, n); - result.setSubMatrix(result00.getData(), 0, 0); - result.setSubMatrix(result01.getData(), 0, splitIndex1); - result.setSubMatrix(result10.getData(), splitIndex1, 0); - result.setSubMatrix(result11.getData(), splitIndex1, splitIndex1); - - return result; - } - - /** - * Computes the inverse of the given matrix. - *

- * By default, the inverse of the matrix is computed using the QR-decomposition, - * unless a more efficient method can be determined for the input matrix. - *

- * Note: this method will use a singularity threshold of 0, - * use {@link #inverse(RealMatrix, double)} if a different threshold is needed. - * - * @param matrix Matrix whose inverse shall be computed - * @return the inverse of {@code matrix} - * @throws NullArgumentException if {@code matrix} is {@code null} - * @throws SingularMatrixException if m is singular - * @throws NonSquareMatrixException if matrix is not square - * @since 3.3 - */ - public static RealMatrix inverse(RealMatrix matrix) - throws NullArgumentException, SingularMatrixException, NonSquareMatrixException { - return inverse(matrix, 0); - } - - /** - * Computes the inverse of the given matrix. - *

- * By default, the inverse of the matrix is computed using the QR-decomposition, - * unless a more efficient method can be determined for the input matrix. - * - * @param matrix Matrix whose inverse shall be computed - * @param threshold Singularity threshold - * @return the inverse of {@code m} - * @throws NullArgumentException if {@code matrix} is {@code null} - * @throws SingularMatrixException if matrix is singular - * @throws NonSquareMatrixException if matrix is not square - * @since 3.3 - */ - public static RealMatrix inverse(RealMatrix matrix, double threshold) - throws NullArgumentException, SingularMatrixException, NonSquareMatrixException { - - MathUtils.checkNotNull(matrix); - - if (!matrix.isSquare()) { - throw new NonSquareMatrixException(matrix.getRowDimension(), - matrix.getColumnDimension()); - } - - if (matrix instanceof DiagonalMatrix) { - return ((DiagonalMatrix) matrix).inverse(threshold); - } else { - QRDecomposition decomposition = new QRDecomposition(matrix, threshold); - return decomposition.getSolver().getInverse(); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonPositiveDefiniteMatrixException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonPositiveDefiniteMatrixException.java deleted file mode 100644 index fffacc627..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonPositiveDefiniteMatrixException.java +++ /dev/null @@ -1,73 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.util.ExceptionContext; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when a positive definite matrix is expected. - * - * @since 3.0 - */ -public class NonPositiveDefiniteMatrixException extends NumberIsTooSmallException { - /** Serializable version Id. */ - private static final long serialVersionUID = 1641613838113738061L; - /** Index (diagonal element). */ - private final int index; - /** Threshold. */ - private final double threshold; - - /** - * Construct an exception. - * - * @param wrong Value that fails the positivity check. - * @param index Row (and column) index. - * @param threshold Absolute positivity threshold. - */ - public NonPositiveDefiniteMatrixException(double wrong, - int index, - double threshold) { - super(wrong, threshold, false); - this.index = index; - this.threshold = threshold; - - final ExceptionContext context = getContext(); - context.addMessage(LocalizedFormats.NOT_POSITIVE_DEFINITE_MATRIX); - context.addMessage(LocalizedFormats.ARRAY_ELEMENT, wrong, index); - } - - /** - * @return the row index. - */ - public int getRow() { - return index; - } - /** - * @return the column index. - */ - public int getColumn() { - return index; - } - /** - * @return the absolute positivity threshold. - */ - public double getThreshold() { - return threshold; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonPositiveDefiniteOperatorException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonPositiveDefiniteOperatorException.java deleted file mode 100644 index 4390d4710..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonPositiveDefiniteOperatorException.java +++ /dev/null @@ -1,43 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when a symmetric, definite positive - * {@link RealLinearOperator} is expected. - * Since the coefficients of the matrix are not accessible, the most - * general definition is used to check that {@code A} is not positive - * definite, i.e. there exists {@code x} such that {@code x' A x <= 0}. - * In the terminology of this exception, {@code A} is the "offending" - * linear operator and {@code x} the "offending" vector. - * - * @since 3.0 - */ -public class NonPositiveDefiniteOperatorException - extends MathIllegalArgumentException { - /** Serializable version Id. */ - private static final long serialVersionUID = 917034489420549847L; - - /** Creates a new instance of this class. */ - public NonPositiveDefiniteOperatorException() { - super(LocalizedFormats.NON_POSITIVE_DEFINITE_OPERATOR); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonSelfAdjointOperatorException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonSelfAdjointOperatorException.java deleted file mode 100644 index 4f9cc0d32..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonSelfAdjointOperatorException.java +++ /dev/null @@ -1,46 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when a self-adjoint {@link RealLinearOperator} - * is expected. - * Since the coefficients of the matrix are not accessible, the most - * general definition is used to check that A is not self-adjoint, i.e. - * there exist x and y such as {@code | x' A y - y' A x | >= eps}, - * where {@code eps} is a user-specified tolerance, and {@code x'} - * denotes the transpose of {@code x}. - * In the terminology of this exception, {@code A} is the "offending" - * linear operator, {@code x} and {@code y} are the first and second - * "offending" vectors, respectively. - * - * @since 3.0 - */ -public class NonSelfAdjointOperatorException - extends MathIllegalArgumentException { - /** Serializable version Id. */ - private static final long serialVersionUID = 1784999305030258247L; - - /** Creates a new instance of this class. */ - public NonSelfAdjointOperatorException() { - super(LocalizedFormats.NON_SELF_ADJOINT_OPERATOR); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonSquareMatrixException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonSquareMatrixException.java deleted file mode 100644 index 635439153..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonSquareMatrixException.java +++ /dev/null @@ -1,41 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when a square matrix is expected. - * - * @since 3.0 - */ -public class NonSquareMatrixException extends DimensionMismatchException { - /** Serializable version Id. */ - private static final long serialVersionUID = -660069396594485772L; - - /** - * Construct an exception from the mismatched dimensions. - * - * @param wrong Row dimension. - * @param expected Column dimension. - */ - public NonSquareMatrixException(int wrong, - int expected) { - super(LocalizedFormats.NON_SQUARE_MATRIX, wrong, expected); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonSquareOperatorException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonSquareOperatorException.java deleted file mode 100644 index e325cf4d1..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonSquareOperatorException.java +++ /dev/null @@ -1,40 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when a square linear operator is expected. - * - * @since 3.0 - */ -public class NonSquareOperatorException extends DimensionMismatchException { - /** Serializable version Id. */ - private static final long serialVersionUID = -4145007524150846242L; - - /** - * Construct an exception from the mismatched dimensions. - * - * @param wrong Row dimension. - * @param expected Column dimension. - */ - public NonSquareOperatorException(int wrong, int expected) { - super(LocalizedFormats.NON_SQUARE_OPERATOR, wrong, expected); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonSymmetricMatrixException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonSymmetricMatrixException.java deleted file mode 100644 index 23280e988..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/NonSymmetricMatrixException.java +++ /dev/null @@ -1,71 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when a symmetric matrix is expected. - * - * @since 3.0 - */ -public class NonSymmetricMatrixException extends MathIllegalArgumentException { - /** Serializable version Id. */ - private static final long serialVersionUID = -7518495577824189882L; - /** Row. */ - private final int row; - /** Column. */ - private final int column; - /** Threshold. */ - private final double threshold; - - /** - * Construct an exception. - * - * @param row Row index. - * @param column Column index. - * @param threshold Relative symmetry threshold. - */ - public NonSymmetricMatrixException(int row, - int column, - double threshold) { - super(LocalizedFormats.NON_SYMMETRIC_MATRIX, row, column, threshold); - this.row = row; - this.column = column; - this.threshold = threshold; - } - - /** - * @return the row index of the entry. - */ - public int getRow() { - return row; - } - /** - * @return the column index of the entry. - */ - public int getColumn() { - return column; - } - /** - * @return the relative symmetry threshold. - */ - public double getThreshold() { - return threshold; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/OpenMapRealMatrix.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/OpenMapRealMatrix.java deleted file mode 100644 index a8382eb44..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/OpenMapRealMatrix.java +++ /dev/null @@ -1,310 +0,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. - */ - -package org.apache.commons.math4.linear; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.util.OpenIntToDoubleHashMap; - -/** - * Sparse matrix implementation based on an open addressed map. - * - *

- * Caveat: This implementation assumes that, for any {@code x}, - * the equality {@code x * 0d == 0d} holds. But it is is not true for - * {@code NaN}. Moreover, zero entries will lose their sign. - * Some operations (that involve {@code NaN} and/or infinities) may - * thus give incorrect results. - *

- * @since 2.0 - */ -public class OpenMapRealMatrix extends AbstractRealMatrix - implements SparseRealMatrix, Serializable { - /** Serializable version identifier. */ - private static final long serialVersionUID = -5962461716457143437L; - /** Number of rows of the matrix. */ - private final int rows; - /** Number of columns of the matrix. */ - private final int columns; - /** Storage for (sparse) matrix elements. */ - private final OpenIntToDoubleHashMap entries; - - /** - * Build a sparse matrix with the supplied row and column dimensions. - * - * @param rowDimension Number of rows of the matrix. - * @param columnDimension Number of columns of the matrix. - * @throws NotStrictlyPositiveException if row or column dimension is not - * positive. - * @throws NumberIsTooLargeException if the total number of entries of the - * matrix is larger than {@code Integer.MAX_VALUE}. - */ - public OpenMapRealMatrix(int rowDimension, int columnDimension) - throws NotStrictlyPositiveException, NumberIsTooLargeException { - super(rowDimension, columnDimension); - long lRow = rowDimension; - long lCol = columnDimension; - if (lRow * lCol >= Integer.MAX_VALUE) { - throw new NumberIsTooLargeException(lRow * lCol, Integer.MAX_VALUE, false); - } - this.rows = rowDimension; - this.columns = columnDimension; - this.entries = new OpenIntToDoubleHashMap(0.0); - } - - /** - * Build a matrix by copying another one. - * - * @param matrix matrix to copy. - */ - public OpenMapRealMatrix(OpenMapRealMatrix matrix) { - this.rows = matrix.rows; - this.columns = matrix.columns; - this.entries = new OpenIntToDoubleHashMap(matrix.entries); - } - - /** {@inheritDoc} */ - @Override - public OpenMapRealMatrix copy() { - return new OpenMapRealMatrix(this); - } - - /** - * {@inheritDoc} - * - * @throws NumberIsTooLargeException if the total number of entries of the - * matrix is larger than {@code Integer.MAX_VALUE}. - */ - @Override - public OpenMapRealMatrix createMatrix(int rowDimension, int columnDimension) - throws NotStrictlyPositiveException, NumberIsTooLargeException { - return new OpenMapRealMatrix(rowDimension, columnDimension); - } - - /** {@inheritDoc} */ - @Override - public int getColumnDimension() { - return columns; - } - - /** - * Compute the sum of this matrix and {@code m}. - * - * @param m Matrix to be added. - * @return {@code this} + {@code m}. - * @throws MatrixDimensionMismatchException if {@code m} is not the same - * size as {@code this}. - */ - public OpenMapRealMatrix add(OpenMapRealMatrix m) - throws MatrixDimensionMismatchException { - - MatrixUtils.checkAdditionCompatible(this, m); - - final OpenMapRealMatrix out = new OpenMapRealMatrix(this); - for (OpenIntToDoubleHashMap.Iterator iterator = m.entries.iterator(); iterator.hasNext();) { - iterator.advance(); - final int row = iterator.key() / columns; - final int col = iterator.key() - row * columns; - out.setEntry(row, col, getEntry(row, col) + iterator.value()); - } - - return out; - - } - - /** {@inheritDoc} */ - @Override - public OpenMapRealMatrix subtract(final RealMatrix m) - throws MatrixDimensionMismatchException { - try { - return subtract((OpenMapRealMatrix) m); - } catch (ClassCastException cce) { - return (OpenMapRealMatrix) super.subtract(m); - } - } - - /** - * Subtract {@code m} from this matrix. - * - * @param m Matrix to be subtracted. - * @return {@code this} - {@code m}. - * @throws MatrixDimensionMismatchException if {@code m} is not the same - * size as {@code this}. - */ - public OpenMapRealMatrix subtract(OpenMapRealMatrix m) - throws MatrixDimensionMismatchException { - MatrixUtils.checkAdditionCompatible(this, m); - - final OpenMapRealMatrix out = new OpenMapRealMatrix(this); - for (OpenIntToDoubleHashMap.Iterator iterator = m.entries.iterator(); iterator.hasNext();) { - iterator.advance(); - final int row = iterator.key() / columns; - final int col = iterator.key() - row * columns; - out.setEntry(row, col, getEntry(row, col) - iterator.value()); - } - - return out; - } - - /** - * {@inheritDoc} - * - * @throws NumberIsTooLargeException if {@code m} is an - * {@code OpenMapRealMatrix}, and the total number of entries of the product - * is larger than {@code Integer.MAX_VALUE}. - */ - @Override - public RealMatrix multiply(final RealMatrix m) - throws DimensionMismatchException, NumberIsTooLargeException { - try { - return multiply((OpenMapRealMatrix) m); - } catch (ClassCastException cce) { - - MatrixUtils.checkMultiplicationCompatible(this, m); - - final int outCols = m.getColumnDimension(); - final BlockRealMatrix out = new BlockRealMatrix(rows, outCols); - for (OpenIntToDoubleHashMap.Iterator iterator = entries.iterator(); iterator.hasNext();) { - iterator.advance(); - final double value = iterator.value(); - final int key = iterator.key(); - final int i = key / columns; - final int k = key % columns; - for (int j = 0; j < outCols; ++j) { - out.addToEntry(i, j, value * m.getEntry(k, j)); - } - } - - return out; - } - } - - /** - * Postmultiply this matrix by {@code m}. - * - * @param m Matrix to postmultiply by. - * @return {@code this} * {@code m}. - * @throws DimensionMismatchException if the number of rows of {@code m} - * differ from the number of columns of {@code this} matrix. - * @throws NumberIsTooLargeException if the total number of entries of the - * product is larger than {@code Integer.MAX_VALUE}. - */ - public OpenMapRealMatrix multiply(OpenMapRealMatrix m) - throws DimensionMismatchException, NumberIsTooLargeException { - // Safety check. - MatrixUtils.checkMultiplicationCompatible(this, m); - - final int outCols = m.getColumnDimension(); - OpenMapRealMatrix out = new OpenMapRealMatrix(rows, outCols); - for (OpenIntToDoubleHashMap.Iterator iterator = entries.iterator(); iterator.hasNext();) { - iterator.advance(); - final double value = iterator.value(); - final int key = iterator.key(); - final int i = key / columns; - final int k = key % columns; - for (int j = 0; j < outCols; ++j) { - final int rightKey = m.computeKey(k, j); - if (m.entries.containsKey(rightKey)) { - final int outKey = out.computeKey(i, j); - final double outValue = - out.entries.get(outKey) + value * m.entries.get(rightKey); - if (outValue == 0.0) { - out.entries.remove(outKey); - } else { - out.entries.put(outKey, outValue); - } - } - } - } - - return out; - } - - /** {@inheritDoc} */ - @Override - public double getEntry(int row, int column) throws OutOfRangeException { - MatrixUtils.checkRowIndex(this, row); - MatrixUtils.checkColumnIndex(this, column); - return entries.get(computeKey(row, column)); - } - - /** {@inheritDoc} */ - @Override - public int getRowDimension() { - return rows; - } - - /** {@inheritDoc} */ - @Override - public void setEntry(int row, int column, double value) - throws OutOfRangeException { - MatrixUtils.checkRowIndex(this, row); - MatrixUtils.checkColumnIndex(this, column); - if (value == 0.0) { - entries.remove(computeKey(row, column)); - } else { - entries.put(computeKey(row, column), value); - } - } - - /** {@inheritDoc} */ - @Override - public void addToEntry(int row, int column, double increment) - throws OutOfRangeException { - MatrixUtils.checkRowIndex(this, row); - MatrixUtils.checkColumnIndex(this, column); - final int key = computeKey(row, column); - final double value = entries.get(key) + increment; - if (value == 0.0) { - entries.remove(key); - } else { - entries.put(key, value); - } - } - - /** {@inheritDoc} */ - @Override - public void multiplyEntry(int row, int column, double factor) - throws OutOfRangeException { - MatrixUtils.checkRowIndex(this, row); - MatrixUtils.checkColumnIndex(this, column); - final int key = computeKey(row, column); - final double value = entries.get(key) * factor; - if (value == 0.0) { - entries.remove(key); - } else { - entries.put(key, value); - } - } - - /** - * Compute the key to access a matrix element - * @param row row index of the matrix element - * @param column column index of the matrix element - * @return key within the map to access the matrix element - */ - private int computeKey(int row, int column) { - return row * columns + column; - } - - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/OpenMapRealVector.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/OpenMapRealVector.java deleted file mode 100644 index 48136d9c2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/OpenMapRealVector.java +++ /dev/null @@ -1,812 +0,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. - */ -package org.apache.commons.math4.linear; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.OpenIntToDoubleHashMap; -import org.apache.commons.math4.util.OpenIntToDoubleHashMap.Iterator; - -/** - * This class implements the {@link RealVector} interface with a - * {@link OpenIntToDoubleHashMap} backing store. - *

- * Caveat: This implementation assumes that, for any {@code x}, - * the equality {@code x * 0d == 0d} holds. But it is is not true for - * {@code NaN}. Moreover, zero entries will lose their sign. - * Some operations (that involve {@code NaN} and/or infinities) may - * thus give incorrect results, like multiplications, divisions or - * functions mapping. - *

- * @since 2.0 - */ -public class OpenMapRealVector extends SparseRealVector - implements Serializable { - /** Default Tolerance for having a value considered zero. */ - public static final double DEFAULT_ZERO_TOLERANCE = 1.0e-12; - /** Serializable version identifier. */ - private static final long serialVersionUID = 8772222695580707260L; - /** Entries of the vector. */ - private final OpenIntToDoubleHashMap entries; - /** Dimension of the vector. */ - private final int virtualSize; - /** Tolerance for having a value considered zero. */ - private final double epsilon; - - /** - * Build a 0-length vector. - * Zero-length vectors may be used to initialized construction of vectors - * by data gathering. We start with zero-length and use either the {@link - * #OpenMapRealVector(OpenMapRealVector, int)} constructor - * or one of the {@code append} method ({@link #append(double)}, - * {@link #append(RealVector)}) to gather data into this vector. - */ - public OpenMapRealVector() { - this(0, DEFAULT_ZERO_TOLERANCE); - } - - /** - * Construct a vector of zeroes. - * - * @param dimension Size of the vector. - */ - public OpenMapRealVector(int dimension) { - this(dimension, DEFAULT_ZERO_TOLERANCE); - } - - /** - * Construct a vector of zeroes, specifying zero tolerance. - * - * @param dimension Size of the vector. - * @param epsilon Tolerance below which a value considered zero. - */ - public OpenMapRealVector(int dimension, double epsilon) { - virtualSize = dimension; - entries = new OpenIntToDoubleHashMap(0.0); - this.epsilon = epsilon; - } - - /** - * Build a resized vector, for use with append. - * - * @param v Original vector. - * @param resize Amount to add. - */ - protected OpenMapRealVector(OpenMapRealVector v, int resize) { - virtualSize = v.getDimension() + resize; - entries = new OpenIntToDoubleHashMap(v.entries); - epsilon = v.epsilon; - } - - /** - * Build a vector with known the sparseness (for advanced use only). - * - * @param dimension Size of the vector. - * @param expectedSize The expected number of non-zero entries. - */ - public OpenMapRealVector(int dimension, int expectedSize) { - this(dimension, expectedSize, DEFAULT_ZERO_TOLERANCE); - } - - /** - * Build a vector with known the sparseness and zero tolerance - * setting (for advanced use only). - * - * @param dimension Size of the vector. - * @param expectedSize Expected number of non-zero entries. - * @param epsilon Tolerance below which a value is considered zero. - */ - public OpenMapRealVector(int dimension, int expectedSize, double epsilon) { - virtualSize = dimension; - entries = new OpenIntToDoubleHashMap(expectedSize, 0.0); - this.epsilon = epsilon; - } - - /** - * Create from an array. - * Only non-zero entries will be stored. - * - * @param values Set of values to create from. - */ - public OpenMapRealVector(double[] values) { - this(values, DEFAULT_ZERO_TOLERANCE); - } - - /** - * Create from an array, specifying zero tolerance. - * Only non-zero entries will be stored. - * - * @param values Set of values to create from. - * @param epsilon Tolerance below which a value is considered zero. - */ - public OpenMapRealVector(double[] values, double epsilon) { - virtualSize = values.length; - entries = new OpenIntToDoubleHashMap(0.0); - this.epsilon = epsilon; - for (int key = 0; key < values.length; key++) { - double value = values[key]; - if (!isDefaultValue(value)) { - entries.put(key, value); - } - } - } - - /** - * Create from an array. - * Only non-zero entries will be stored. - * - * @param values The set of values to create from - */ - public OpenMapRealVector(Double[] values) { - this(values, DEFAULT_ZERO_TOLERANCE); - } - - /** - * Create from an array. - * Only non-zero entries will be stored. - * - * @param values Set of values to create from. - * @param epsilon Tolerance below which a value is considered zero. - */ - public OpenMapRealVector(Double[] values, double epsilon) { - virtualSize = values.length; - entries = new OpenIntToDoubleHashMap(0.0); - this.epsilon = epsilon; - for (int key = 0; key < values.length; key++) { - double value = values[key].doubleValue(); - if (!isDefaultValue(value)) { - entries.put(key, value); - } - } - } - - /** - * Copy constructor. - * - * @param v Instance to copy from. - */ - public OpenMapRealVector(OpenMapRealVector v) { - virtualSize = v.getDimension(); - entries = new OpenIntToDoubleHashMap(v.getEntries()); - epsilon = v.epsilon; - } - - /** - * Generic copy constructor. - * - * @param v Instance to copy from. - */ - public OpenMapRealVector(RealVector v) { - virtualSize = v.getDimension(); - entries = new OpenIntToDoubleHashMap(0.0); - epsilon = DEFAULT_ZERO_TOLERANCE; - for (int key = 0; key < virtualSize; key++) { - double value = v.getEntry(key); - if (!isDefaultValue(value)) { - entries.put(key, value); - } - } - } - - /** - * Get the entries of this instance. - * - * @return the entries of this instance. - */ - private OpenIntToDoubleHashMap getEntries() { - return entries; - } - - /** - * Determine if this value is within epsilon of zero. - * - * @param value Value to test - * @return {@code true} if this value is within epsilon to zero, - * {@code false} otherwise. - * @since 2.1 - */ - protected boolean isDefaultValue(double value) { - return FastMath.abs(value) < epsilon; - } - - /** {@inheritDoc} */ - @Override - public RealVector add(RealVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - if (v instanceof OpenMapRealVector) { - return add((OpenMapRealVector) v); - } else { - return super.add(v); - } - } - - /** - * Optimized method to add two OpenMapRealVectors. - * It copies the larger vector, then iterates over the smaller. - * - * @param v Vector to add. - * @return the sum of {@code this} and {@code v}. - * @throws DimensionMismatchException if the dimensions do not match. - */ - public OpenMapRealVector add(OpenMapRealVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - boolean copyThis = entries.size() > v.entries.size(); - OpenMapRealVector res = copyThis ? this.copy() : v.copy(); - Iterator iter = copyThis ? v.entries.iterator() : entries.iterator(); - OpenIntToDoubleHashMap randomAccess = copyThis ? entries : v.entries; - while (iter.hasNext()) { - iter.advance(); - int key = iter.key(); - if (randomAccess.containsKey(key)) { - res.setEntry(key, randomAccess.get(key) + iter.value()); - } else { - res.setEntry(key, iter.value()); - } - } - return res; - } - - /** - * Optimized method to append a OpenMapRealVector. - * @param v vector to append - * @return The result of appending {@code v} to self - */ - public OpenMapRealVector append(OpenMapRealVector v) { - OpenMapRealVector res = new OpenMapRealVector(this, v.getDimension()); - Iterator iter = v.entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - res.setEntry(iter.key() + virtualSize, iter.value()); - } - return res; - } - - /** {@inheritDoc} */ - @Override - public OpenMapRealVector append(RealVector v) { - if (v instanceof OpenMapRealVector) { - return append((OpenMapRealVector) v); - } else { - final OpenMapRealVector res = new OpenMapRealVector(this, v.getDimension()); - for (int i = 0; i < v.getDimension(); i++) { - res.setEntry(i + virtualSize, v.getEntry(i)); - } - return res; - } - } - - /** {@inheritDoc} */ - @Override - public OpenMapRealVector append(double d) { - OpenMapRealVector res = new OpenMapRealVector(this, 1); - res.setEntry(virtualSize, d); - return res; - } - - /** - * {@inheritDoc} - * @since 2.1 - */ - @Override - public OpenMapRealVector copy() { - return new OpenMapRealVector(this); - } - - /** {@inheritDoc} */ - @Override - public OpenMapRealVector ebeDivide(RealVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - OpenMapRealVector res = new OpenMapRealVector(this); - /* - * MATH-803: it is not sufficient to loop through non zero entries of - * this only. Indeed, if this[i] = 0d and v[i] = 0d, then - * this[i] / v[i] = NaN, and not 0d. - */ - final int n = getDimension(); - for (int i = 0; i < n; i++) { - res.setEntry(i, this.getEntry(i) / v.getEntry(i)); - } - return res; - } - - /** {@inheritDoc} */ - @Override - public OpenMapRealVector ebeMultiply(RealVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - OpenMapRealVector res = new OpenMapRealVector(this); - Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - res.setEntry(iter.key(), iter.value() * v.getEntry(iter.key())); - } - return res; - } - - /** {@inheritDoc} */ - @Override - public OpenMapRealVector getSubVector(int index, int n) - throws NotPositiveException, OutOfRangeException { - checkIndex(index); - if (n < 0) { - throw new NotPositiveException(LocalizedFormats.NUMBER_OF_ELEMENTS_SHOULD_BE_POSITIVE, n); - } - checkIndex(index + n - 1); - OpenMapRealVector res = new OpenMapRealVector(n); - int end = index + n; - Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - int key = iter.key(); - if (key >= index && key < end) { - res.setEntry(key - index, iter.value()); - } - } - return res; - } - - /** {@inheritDoc} */ - @Override - public int getDimension() { - return virtualSize; - } - - /** - * Optimized method to compute distance. - * - * @param v Vector to compute distance to. - * @return the distance from {@code this} and {@code v}. - * @throws DimensionMismatchException if the dimensions do not match. - */ - public double getDistance(OpenMapRealVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - Iterator iter = entries.iterator(); - double res = 0; - while (iter.hasNext()) { - iter.advance(); - int key = iter.key(); - double delta; - delta = iter.value() - v.getEntry(key); - res += delta * delta; - } - iter = v.getEntries().iterator(); - while (iter.hasNext()) { - iter.advance(); - int key = iter.key(); - if (!entries.containsKey(key)) { - final double value = iter.value(); - res += value * value; - } - } - return FastMath.sqrt(res); - } - - /** {@inheritDoc} */ - @Override - public double getDistance(RealVector v) throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - if (v instanceof OpenMapRealVector) { - return getDistance((OpenMapRealVector) v); - } else { - return super.getDistance(v); - } - } - - /** {@inheritDoc} */ - @Override - public double getEntry(int index) throws OutOfRangeException { - checkIndex(index); - return entries.get(index); - } - - /** - * Distance between two vectors. - * This method computes the distance consistent with - * L1 norm, i.e. the sum of the absolute values of - * elements differences. - * - * @param v Vector to which distance is requested. - * @return distance between this vector and {@code v}. - * @throws DimensionMismatchException if the dimensions do not match. - */ - public double getL1Distance(OpenMapRealVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - double max = 0; - Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - double delta = FastMath.abs(iter.value() - v.getEntry(iter.key())); - max += delta; - } - iter = v.getEntries().iterator(); - while (iter.hasNext()) { - iter.advance(); - int key = iter.key(); - if (!entries.containsKey(key)) { - double delta = FastMath.abs(iter.value()); - max += FastMath.abs(delta); - } - } - return max; - } - - /** {@inheritDoc} */ - @Override - public double getL1Distance(RealVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - if (v instanceof OpenMapRealVector) { - return getL1Distance((OpenMapRealVector) v); - } else { - return super.getL1Distance(v); - } - } - - /** - * Optimized method to compute LInfDistance. - * - * @param v Vector to compute distance from. - * @return the LInfDistance. - * @throws DimensionMismatchException if the dimensions do not match. - */ - private double getLInfDistance(OpenMapRealVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - double max = 0; - Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - double delta = FastMath.abs(iter.value() - v.getEntry(iter.key())); - if (delta > max) { - max = delta; - } - } - iter = v.getEntries().iterator(); - while (iter.hasNext()) { - iter.advance(); - int key = iter.key(); - if (!entries.containsKey(key) && iter.value() > max) { - max = iter.value(); - } - } - return max; - } - - /** {@inheritDoc} */ - @Override - public double getLInfDistance(RealVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - if (v instanceof OpenMapRealVector) { - return getLInfDistance((OpenMapRealVector) v); - } else { - return super.getLInfDistance(v); - } - } - - /** {@inheritDoc} */ - @Override - public boolean isInfinite() { - boolean infiniteFound = false; - Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - final double value = iter.value(); - if (Double.isNaN(value)) { - return false; - } - if (Double.isInfinite(value)) { - infiniteFound = true; - } - } - return infiniteFound; - } - - /** {@inheritDoc} */ - @Override - public boolean isNaN() { - Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - if (Double.isNaN(iter.value())) { - return true; - } - } - return false; - } - - /** {@inheritDoc} */ - @Override - public OpenMapRealVector mapAdd(double d) { - return copy().mapAddToSelf(d); - } - - /** {@inheritDoc} */ - @Override - public OpenMapRealVector mapAddToSelf(double d) { - for (int i = 0; i < virtualSize; i++) { - setEntry(i, getEntry(i) + d); - } - return this; - } - - /** {@inheritDoc} */ - @Override - public void setEntry(int index, double value) - throws OutOfRangeException { - checkIndex(index); - if (!isDefaultValue(value)) { - entries.put(index, value); - } else if (entries.containsKey(index)) { - entries.remove(index); - } - } - - /** {@inheritDoc} */ - @Override - public void setSubVector(int index, RealVector v) - throws OutOfRangeException { - checkIndex(index); - checkIndex(index + v.getDimension() - 1); - for (int i = 0; i < v.getDimension(); i++) { - setEntry(i + index, v.getEntry(i)); - } - } - - /** {@inheritDoc} */ - @Override - public void set(double value) { - for (int i = 0; i < virtualSize; i++) { - setEntry(i, value); - } - } - - /** - * Optimized method to subtract OpenMapRealVectors. - * - * @param v Vector to subtract from {@code this}. - * @return the difference of {@code this} and {@code v}. - * @throws DimensionMismatchException if the dimensions do not match. - */ - public OpenMapRealVector subtract(OpenMapRealVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - OpenMapRealVector res = copy(); - Iterator iter = v.getEntries().iterator(); - while (iter.hasNext()) { - iter.advance(); - int key = iter.key(); - if (entries.containsKey(key)) { - res.setEntry(key, entries.get(key) - iter.value()); - } else { - res.setEntry(key, -iter.value()); - } - } - return res; - } - - /** {@inheritDoc} */ - @Override - public RealVector subtract(RealVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - if (v instanceof OpenMapRealVector) { - return subtract((OpenMapRealVector) v); - } else { - return super.subtract(v); - } - } - - /** {@inheritDoc} */ - @Override - public OpenMapRealVector unitVector() throws MathArithmeticException { - OpenMapRealVector res = copy(); - res.unitize(); - return res; - } - - /** {@inheritDoc} */ - @Override - public void unitize() throws MathArithmeticException { - double norm = getNorm(); - if (isDefaultValue(norm)) { - throw new MathArithmeticException(LocalizedFormats.ZERO_NORM); - } - Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - entries.put(iter.key(), iter.value() / norm); - } - } - - /** {@inheritDoc} */ - @Override - public double[] toArray() { - double[] res = new double[virtualSize]; - Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - res[iter.key()] = iter.value(); - } - return res; - } - - /** - * {@inheritDoc} - * Implementation Note: This works on exact values, and as a result - * it is possible for {@code a.subtract(b)} to be the zero vector, while - * {@code a.hashCode() != b.hashCode()}. - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - long temp; - temp = Double.doubleToLongBits(epsilon); - result = prime * result + (int) (temp ^ (temp >>> 32)); - result = prime * result + virtualSize; - Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - temp = Double.doubleToLongBits(iter.value()); - result = prime * result + (int) (temp ^ (temp >>32)); - } - return result; - } - - /** - * {@inheritDoc} - * Implementation Note: This performs an exact comparison, and as a result - * it is possible for {@code a.subtract(b}} to be the zero vector, while - * {@code a.equals(b) == false}. - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof OpenMapRealVector)) { - return false; - } - OpenMapRealVector other = (OpenMapRealVector) obj; - if (virtualSize != other.virtualSize) { - return false; - } - if (Double.doubleToLongBits(epsilon) != - Double.doubleToLongBits(other.epsilon)) { - return false; - } - Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - double test = other.getEntry(iter.key()); - if (Double.doubleToLongBits(test) != Double.doubleToLongBits(iter.value())) { - return false; - } - } - iter = other.getEntries().iterator(); - while (iter.hasNext()) { - iter.advance(); - double test = iter.value(); - if (Double.doubleToLongBits(test) != Double.doubleToLongBits(getEntry(iter.key()))) { - return false; - } - } - return true; - } - - /** - * - * @return the percentage of none zero elements as a decimal percent. - * @since 2.2 - */ - public double getSparsity() { - return (double)entries.size()/(double)getDimension(); - } - - /** {@inheritDoc} */ - @Override - public java.util.Iterator sparseIterator() { - return new OpenMapSparseIterator(); - } - - /** - * Implementation of {@code Entry} optimized for OpenMap. - * This implementation does not allow arbitrary calls to {@code setIndex} - * since the order in which entries are returned is undefined. - */ - protected class OpenMapEntry extends Entry { - /** Iterator pointing to the entry. */ - private final Iterator iter; - - /** - * Build an entry from an iterator point to an element. - * - * @param iter Iterator pointing to the entry. - */ - protected OpenMapEntry(Iterator iter) { - this.iter = iter; - } - - /** {@inheritDoc} */ - @Override - public double getValue() { - return iter.value(); - } - - /** {@inheritDoc} */ - @Override - public void setValue(double value) { - entries.put(iter.key(), value); - } - - /** {@inheritDoc} */ - @Override - public int getIndex() { - return iter.key(); - } - - } - - /** - * Iterator class to do iteration over just the non-zero elements. - * This implementation is fail-fast, so cannot be used to modify - * any zero element. - */ - protected class OpenMapSparseIterator implements java.util.Iterator { - /** Underlying iterator. */ - private final Iterator iter; - /** Current entry. */ - private final Entry current; - - /** Simple constructor. */ - protected OpenMapSparseIterator() { - iter = entries.iterator(); - current = new OpenMapEntry(iter); - } - - /** {@inheritDoc} */ - @Override - public boolean hasNext() { - return iter.hasNext(); - } - - /** {@inheritDoc} */ - @Override - public Entry next() { - iter.advance(); - return current; - } - - /** {@inheritDoc} */ - @Override - public void remove() { - throw new UnsupportedOperationException("Not supported"); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/PreconditionedIterativeLinearSolver.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/PreconditionedIterativeLinearSolver.java deleted file mode 100644 index e7f40ed65..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/PreconditionedIterativeLinearSolver.java +++ /dev/null @@ -1,210 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.util.IterationManager; -import org.apache.commons.math4.util.MathUtils; - -/** - *

- * This abstract class defines preconditioned iterative solvers. When A is - * ill-conditioned, instead of solving system A · x = b directly, it is - * preferable to solve either - * (M · A) · x = M · b - * (left preconditioning), or - * (A · M) · y = b,     followed by - * M · y = x - * (right preconditioning), where M approximates in some way A-1, - * while matrix-vector products of the type M · y remain comparatively - * easy to compute. In this library, M (not M-1!) is called the - * preconditionner. - * - *

- * Concrete implementations of this abstract class must be provided with the - * preconditioner M, as a {@link RealLinearOperator}. - *

- * - * @since 3.0 - */ -public abstract class PreconditionedIterativeLinearSolver - extends IterativeLinearSolver { - - /** - * Creates a new instance of this class, with default iteration manager. - * - * @param maxIterations the maximum number of iterations - */ - public PreconditionedIterativeLinearSolver(final int maxIterations) { - super(maxIterations); - } - - /** - * Creates a new instance of this class, with custom iteration manager. - * - * @param manager the custom iteration manager - * @throws NullArgumentException if {@code manager} is {@code null} - */ - public PreconditionedIterativeLinearSolver(final IterationManager manager) - throws NullArgumentException { - super(manager); - } - - /** - * Returns an estimate of the solution to the linear system A · x = - * b. - * - * @param a the linear operator A of the system - * @param m the preconditioner, M (can be {@code null}) - * @param b the right-hand side vector - * @param x0 the initial guess of the solution - * @return a new vector containing the solution - * @throws NullArgumentException if one of the parameters is {@code null} - * @throws NonSquareOperatorException if {@code a} or {@code m} is not - * square - * @throws DimensionMismatchException if {@code m}, {@code b} or - * {@code x0} have dimensions inconsistent with {@code a} - * @throws MaxCountExceededException at exhaustion of the iteration count, - * unless a custom - * {@link org.apache.commons.math4.util.Incrementor.MaxCountExceededCallback callback} - * has been set at construction of the {@link IterationManager} - */ - public RealVector solve(final RealLinearOperator a, - final RealLinearOperator m, final RealVector b, final RealVector x0) - throws NullArgumentException, NonSquareOperatorException, - DimensionMismatchException, MaxCountExceededException { - MathUtils.checkNotNull(x0); - return solveInPlace(a, m, b, x0.copy()); - } - - /** {@inheritDoc} */ - @Override - public RealVector solve(final RealLinearOperator a, final RealVector b) - throws NullArgumentException, NonSquareOperatorException, - DimensionMismatchException, MaxCountExceededException { - MathUtils.checkNotNull(a); - final RealVector x = new ArrayRealVector(a.getColumnDimension()); - x.set(0.); - return solveInPlace(a, null, b, x); - } - - /** {@inheritDoc} */ - @Override - public RealVector solve(final RealLinearOperator a, final RealVector b, - final RealVector x0) - throws NullArgumentException, NonSquareOperatorException, - DimensionMismatchException, MaxCountExceededException { - MathUtils.checkNotNull(x0); - return solveInPlace(a, null, b, x0.copy()); - } - - /** - * Performs all dimension checks on the parameters of - * {@link #solve(RealLinearOperator, RealLinearOperator, RealVector, RealVector) solve} - * and - * {@link #solveInPlace(RealLinearOperator, RealLinearOperator, RealVector, RealVector) solveInPlace}, - * and throws an exception if one of the checks fails. - * - * @param a the linear operator A of the system - * @param m the preconditioner, M (can be {@code null}) - * @param b the right-hand side vector - * @param x0 the initial guess of the solution - * @throws NullArgumentException if one of the parameters is {@code null} - * @throws NonSquareOperatorException if {@code a} or {@code m} is not - * square - * @throws DimensionMismatchException if {@code m}, {@code b} or - * {@code x0} have dimensions inconsistent with {@code a} - */ - protected static void checkParameters(final RealLinearOperator a, - final RealLinearOperator m, final RealVector b, final RealVector x0) - throws NullArgumentException, NonSquareOperatorException, - DimensionMismatchException { - checkParameters(a, b, x0); - if (m != null) { - if (m.getColumnDimension() != m.getRowDimension()) { - throw new NonSquareOperatorException(m.getColumnDimension(), - m.getRowDimension()); - } - if (m.getRowDimension() != a.getRowDimension()) { - throw new DimensionMismatchException(m.getRowDimension(), - a.getRowDimension()); - } - } - } - - /** - * Returns an estimate of the solution to the linear system A · x = - * b. - * - * @param a the linear operator A of the system - * @param m the preconditioner, M (can be {@code null}) - * @param b the right-hand side vector - * @return a new vector containing the solution - * @throws NullArgumentException if one of the parameters is {@code null} - * @throws NonSquareOperatorException if {@code a} or {@code m} is not - * square - * @throws DimensionMismatchException if {@code m} or {@code b} have - * dimensions inconsistent with {@code a} - * @throws MaxCountExceededException at exhaustion of the iteration count, - * unless a custom - * {@link org.apache.commons.math4.util.Incrementor.MaxCountExceededCallback callback} - * has been set at construction of the {@link IterationManager} - */ - public RealVector solve(RealLinearOperator a, RealLinearOperator m, - RealVector b) throws NullArgumentException, NonSquareOperatorException, - DimensionMismatchException, MaxCountExceededException { - MathUtils.checkNotNull(a); - final RealVector x = new ArrayRealVector(a.getColumnDimension()); - return solveInPlace(a, m, b, x); - } - - /** - * Returns an estimate of the solution to the linear system A · x = - * b. The solution is computed in-place (initial guess is modified). - * - * @param a the linear operator A of the system - * @param m the preconditioner, M (can be {@code null}) - * @param b the right-hand side vector - * @param x0 the initial guess of the solution - * @return a reference to {@code x0} (shallow copy) updated with the - * solution - * @throws NullArgumentException if one of the parameters is {@code null} - * @throws NonSquareOperatorException if {@code a} or {@code m} is not - * square - * @throws DimensionMismatchException if {@code m}, {@code b} or - * {@code x0} have dimensions inconsistent with {@code a} - * @throws MaxCountExceededException at exhaustion of the iteration count, - * unless a custom - * {@link org.apache.commons.math4.util.Incrementor.MaxCountExceededCallback callback} - * has been set at construction of the {@link IterationManager} - */ - public abstract RealVector solveInPlace(RealLinearOperator a, - RealLinearOperator m, RealVector b, RealVector x0) throws - NullArgumentException, NonSquareOperatorException, - DimensionMismatchException, MaxCountExceededException; - - /** {@inheritDoc} */ - @Override - public RealVector solveInPlace(final RealLinearOperator a, - final RealVector b, final RealVector x0) throws - NullArgumentException, NonSquareOperatorException, - DimensionMismatchException, MaxCountExceededException { - return solveInPlace(a, null, b, x0); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/QRDecomposition.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/QRDecomposition.java deleted file mode 100644 index 27569b492..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/QRDecomposition.java +++ /dev/null @@ -1,507 +0,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. - */ - -package org.apache.commons.math4.linear; - -import java.util.Arrays; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.exception.util.LocalizedFormats; - - -/** - * Calculates the QR-decomposition of a matrix. - *

The QR-decomposition of a matrix A consists of two matrices Q and R - * that satisfy: A = QR, Q is orthogonal (QTQ = I), and R is - * upper triangular. If A is m×n, Q is m×m and R m×n.

- *

This class compute the decomposition using Householder reflectors.

- *

For efficiency purposes, the decomposition in packed form is transposed. - * This allows inner loop to iterate inside rows, which is much more cache-efficient - * in Java.

- *

This class is based on the class with similar name from the - * JAMA library, with the - * following changes:

- *
    - *
  • a {@link #getQT() getQT} method has been added,
  • - *
  • the {@code solve} and {@code isFullRank} methods have been replaced - * by a {@link #getSolver() getSolver} method and the equivalent methods - * provided by the returned {@link DecompositionSolver}.
  • - *
- * - * @see MathWorld - * @see Wikipedia - * - * @since 1.2 (changed to concrete class in 3.0) - */ -public class QRDecomposition { - /** - * A packed TRANSPOSED representation of the QR decomposition. - *

The elements BELOW the diagonal are the elements of the UPPER triangular - * matrix R, and the rows ABOVE the diagonal are the Householder reflector vectors - * from which an explicit form of Q can be recomputed if desired.

- */ - private double[][] qrt; - /** The diagonal elements of R. */ - private double[] rDiag; - /** Cached value of Q. */ - private RealMatrix cachedQ; - /** Cached value of QT. */ - private RealMatrix cachedQT; - /** Cached value of R. */ - private RealMatrix cachedR; - /** Cached value of H. */ - private RealMatrix cachedH; - /** Singularity threshold. */ - private final double threshold; - - /** - * Calculates the QR-decomposition of the given matrix. - * The singularity threshold defaults to zero. - * - * @param matrix The matrix to decompose. - * - * @see #QRDecomposition(RealMatrix,double) - */ - public QRDecomposition(RealMatrix matrix) { - this(matrix, 0d); - } - - /** - * Calculates the QR-decomposition of the given matrix. - * - * @param matrix The matrix to decompose. - * @param threshold Singularity threshold. - * The matrix will be considered singular if the absolute value of - * any of the diagonal elements of the "R" matrix is smaller than - * the threshold. - */ - public QRDecomposition(RealMatrix matrix, - double threshold) { - this.threshold = threshold; - - final int m = matrix.getRowDimension(); - final int n = matrix.getColumnDimension(); - qrt = matrix.transpose().getData(); - rDiag = new double[FastMath.min(m, n)]; - cachedQ = null; - cachedQT = null; - cachedR = null; - cachedH = null; - - decompose(qrt); - - } - - /** Decompose matrix. - * @param matrix transposed matrix - * @since 3.2 - */ - protected void decompose(double[][] matrix) { - for (int minor = 0; minor < FastMath.min(matrix.length, matrix[0].length); minor++) { - performHouseholderReflection(minor, matrix); - } - } - - /** Perform Householder reflection for a minor A(minor, minor) of A. - * @param minor minor index - * @param matrix transposed matrix - * @since 3.2 - */ - protected void performHouseholderReflection(int minor, double[][] matrix) { - - final double[] qrtMinor = matrix[minor]; - - /* - * Let x be the first column of the minor, and a^2 = |x|^2. - * x will be in the positions qr[minor][minor] through qr[m][minor]. - * The first column of the transformed minor will be (a,0,0,..)' - * The sign of a is chosen to be opposite to the sign of the first - * component of x. Let's find a: - */ - double xNormSqr = 0; - for (int row = minor; row < qrtMinor.length; row++) { - final double c = qrtMinor[row]; - xNormSqr += c * c; - } - final double a = (qrtMinor[minor] > 0) ? -FastMath.sqrt(xNormSqr) : FastMath.sqrt(xNormSqr); - rDiag[minor] = a; - - if (a != 0.0) { - - /* - * Calculate the normalized reflection vector v and transform - * the first column. We know the norm of v beforehand: v = x-ae - * so |v|^2 = = -2a+a^2 = - * a^2+a^2-2a = 2a*(a - ). - * Here is now qr[minor][minor]. - * v = x-ae is stored in the column at qr: - */ - qrtMinor[minor] -= a; // now |v|^2 = -2a*(qr[minor][minor]) - - /* - * Transform the rest of the columns of the minor: - * They will be transformed by the matrix H = I-2vv'/|v|^2. - * If x is a column vector of the minor, then - * Hx = (I-2vv'/|v|^2)x = x-2vv'x/|v|^2 = x - 2/|v|^2 v. - * Therefore the transformation is easily calculated by - * subtracting the column vector (2/|v|^2)v from x. - * - * Let 2/|v|^2 = alpha. From above we have - * |v|^2 = -2a*(qr[minor][minor]), so - * alpha = -/(a*qr[minor][minor]) - */ - for (int col = minor+1; col < matrix.length; col++) { - final double[] qrtCol = matrix[col]; - double alpha = 0; - for (int row = minor; row < qrtCol.length; row++) { - alpha -= qrtCol[row] * qrtMinor[row]; - } - alpha /= a * qrtMinor[minor]; - - // Subtract the column vector alpha*v from x. - for (int row = minor; row < qrtCol.length; row++) { - qrtCol[row] -= alpha * qrtMinor[row]; - } - } - } - } - - - /** - * Returns the matrix R of the decomposition. - *

R is an upper-triangular matrix

- * @return the R matrix - */ - public RealMatrix getR() { - - if (cachedR == null) { - - // R is supposed to be m x n - final int n = qrt.length; - final int m = qrt[0].length; - double[][] ra = new double[m][n]; - // copy the diagonal from rDiag and the upper triangle of qr - for (int row = FastMath.min(m, n) - 1; row >= 0; row--) { - ra[row][row] = rDiag[row]; - for (int col = row + 1; col < n; col++) { - ra[row][col] = qrt[col][row]; - } - } - cachedR = MatrixUtils.createRealMatrix(ra); - } - - // return the cached matrix - return cachedR; - } - - /** - * Returns the matrix Q of the decomposition. - *

Q is an orthogonal matrix

- * @return the Q matrix - */ - public RealMatrix getQ() { - if (cachedQ == null) { - cachedQ = getQT().transpose(); - } - return cachedQ; - } - - /** - * Returns the transpose of the matrix Q of the decomposition. - *

Q is an orthogonal matrix

- * @return the transpose of the Q matrix, QT - */ - public RealMatrix getQT() { - if (cachedQT == null) { - - // QT is supposed to be m x m - final int n = qrt.length; - final int m = qrt[0].length; - double[][] qta = new double[m][m]; - - /* - * Q = Q1 Q2 ... Q_m, so Q is formed by first constructing Q_m and then - * applying the Householder transformations Q_(m-1),Q_(m-2),...,Q1 in - * succession to the result - */ - for (int minor = m - 1; minor >= FastMath.min(m, n); minor--) { - qta[minor][minor] = 1.0d; - } - - for (int minor = FastMath.min(m, n)-1; minor >= 0; minor--){ - final double[] qrtMinor = qrt[minor]; - qta[minor][minor] = 1.0d; - if (qrtMinor[minor] != 0.0) { - for (int col = minor; col < m; col++) { - double alpha = 0; - for (int row = minor; row < m; row++) { - alpha -= qta[col][row] * qrtMinor[row]; - } - alpha /= rDiag[minor] * qrtMinor[minor]; - - for (int row = minor; row < m; row++) { - qta[col][row] += -alpha * qrtMinor[row]; - } - } - } - } - cachedQT = MatrixUtils.createRealMatrix(qta); - } - - // return the cached matrix - return cachedQT; - } - - /** - * Returns the Householder reflector vectors. - *

H is a lower trapezoidal matrix whose columns represent - * each successive Householder reflector vector. This matrix is used - * to compute Q.

- * @return a matrix containing the Householder reflector vectors - */ - public RealMatrix getH() { - if (cachedH == null) { - - final int n = qrt.length; - final int m = qrt[0].length; - double[][] ha = new double[m][n]; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < FastMath.min(i + 1, n); ++j) { - ha[i][j] = qrt[j][i] / -rDiag[j]; - } - } - cachedH = MatrixUtils.createRealMatrix(ha); - } - - // return the cached matrix - return cachedH; - } - - /** - * Get a solver for finding the A × X = B solution in least square sense. - *

- * Least Square sense means a solver can be computed for an overdetermined system, - * (i.e. a system with more equations than unknowns, which corresponds to a tall A - * matrix with more rows than columns). In any case, if the matrix is singular - * within the tolerance set at {@link QRDecomposition#QRDecomposition(RealMatrix, - * double) construction}, an error will be triggered when - * the {@link DecompositionSolver#solve(RealVector) solve} method will be called. - *

- * @return a solver - */ - public DecompositionSolver getSolver() { - return new Solver(qrt, rDiag, threshold); - } - - /** Specialized solver. */ - private static class Solver implements DecompositionSolver { - /** - * A packed TRANSPOSED representation of the QR decomposition. - *

The elements BELOW the diagonal are the elements of the UPPER triangular - * matrix R, and the rows ABOVE the diagonal are the Householder reflector vectors - * from which an explicit form of Q can be recomputed if desired.

- */ - private final double[][] qrt; - /** The diagonal elements of R. */ - private final double[] rDiag; - /** Singularity threshold. */ - private final double threshold; - - /** - * Build a solver from decomposed matrix. - * - * @param qrt Packed TRANSPOSED representation of the QR decomposition. - * @param rDiag Diagonal elements of R. - * @param threshold Singularity threshold. - */ - private Solver(final double[][] qrt, - final double[] rDiag, - final double threshold) { - this.qrt = qrt; - this.rDiag = rDiag; - this.threshold = threshold; - } - - /** {@inheritDoc} */ - @Override - public boolean isNonSingular() { - return !checkSingular(rDiag, threshold, false); - } - - /** {@inheritDoc} */ - @Override - public RealVector solve(RealVector b) { - final int n = qrt.length; - final int m = qrt[0].length; - if (b.getDimension() != m) { - throw new DimensionMismatchException(b.getDimension(), m); - } - checkSingular(rDiag, threshold, true); - - final double[] x = new double[n]; - final double[] y = b.toArray(); - - // apply Householder transforms to solve Q.y = b - for (int minor = 0; minor < FastMath.min(m, n); minor++) { - - final double[] qrtMinor = qrt[minor]; - double dotProduct = 0; - for (int row = minor; row < m; row++) { - dotProduct += y[row] * qrtMinor[row]; - } - dotProduct /= rDiag[minor] * qrtMinor[minor]; - - for (int row = minor; row < m; row++) { - y[row] += dotProduct * qrtMinor[row]; - } - } - - // solve triangular system R.x = y - for (int row = rDiag.length - 1; row >= 0; --row) { - y[row] /= rDiag[row]; - final double yRow = y[row]; - final double[] qrtRow = qrt[row]; - x[row] = yRow; - for (int i = 0; i < row; i++) { - y[i] -= yRow * qrtRow[i]; - } - } - - return new ArrayRealVector(x, false); - } - - /** {@inheritDoc} */ - @Override - public RealMatrix solve(RealMatrix b) { - final int n = qrt.length; - final int m = qrt[0].length; - if (b.getRowDimension() != m) { - throw new DimensionMismatchException(b.getRowDimension(), m); - } - checkSingular(rDiag, threshold, true); - - final int columns = b.getColumnDimension(); - final int blockSize = BlockRealMatrix.BLOCK_SIZE; - final int cBlocks = (columns + blockSize - 1) / blockSize; - final double[][] xBlocks = BlockRealMatrix.createBlocksLayout(n, columns); - final double[][] y = new double[b.getRowDimension()][blockSize]; - final double[] alpha = new double[blockSize]; - - for (int kBlock = 0; kBlock < cBlocks; ++kBlock) { - final int kStart = kBlock * blockSize; - final int kEnd = FastMath.min(kStart + blockSize, columns); - final int kWidth = kEnd - kStart; - - // get the right hand side vector - b.copySubMatrix(0, m - 1, kStart, kEnd - 1, y); - - // apply Householder transforms to solve Q.y = b - for (int minor = 0; minor < FastMath.min(m, n); minor++) { - final double[] qrtMinor = qrt[minor]; - final double factor = 1.0 / (rDiag[minor] * qrtMinor[minor]); - - Arrays.fill(alpha, 0, kWidth, 0.0); - for (int row = minor; row < m; ++row) { - final double d = qrtMinor[row]; - final double[] yRow = y[row]; - for (int k = 0; k < kWidth; ++k) { - alpha[k] += d * yRow[k]; - } - } - for (int k = 0; k < kWidth; ++k) { - alpha[k] *= factor; - } - - for (int row = minor; row < m; ++row) { - final double d = qrtMinor[row]; - final double[] yRow = y[row]; - for (int k = 0; k < kWidth; ++k) { - yRow[k] += alpha[k] * d; - } - } - } - - // solve triangular system R.x = y - for (int j = rDiag.length - 1; j >= 0; --j) { - final int jBlock = j / blockSize; - final int jStart = jBlock * blockSize; - final double factor = 1.0 / rDiag[j]; - final double[] yJ = y[j]; - final double[] xBlock = xBlocks[jBlock * cBlocks + kBlock]; - int index = (j - jStart) * kWidth; - for (int k = 0; k < kWidth; ++k) { - yJ[k] *= factor; - xBlock[index++] = yJ[k]; - } - - final double[] qrtJ = qrt[j]; - for (int i = 0; i < j; ++i) { - final double rIJ = qrtJ[i]; - final double[] yI = y[i]; - for (int k = 0; k < kWidth; ++k) { - yI[k] -= yJ[k] * rIJ; - } - } - } - } - - return new BlockRealMatrix(n, columns, xBlocks, false); - } - - /** - * {@inheritDoc} - * @throws SingularMatrixException if the decomposed matrix is singular. - */ - @Override - public RealMatrix getInverse() { - return solve(MatrixUtils.createRealIdentityMatrix(qrt[0].length)); - } - - /** - * Check singularity. - * - * @param diag Diagonal elements of the R matrix. - * @param min Singularity threshold. - * @param raise Whether to raise a {@link SingularMatrixException} - * if any element of the diagonal fails the check. - * @return {@code true} if any element of the diagonal is smaller - * or equal to {@code min}. - * @throws SingularMatrixException if the matrix is singular and - * {@code raise} is {@code true}. - */ - private static boolean checkSingular(double[] diag, - double min, - boolean raise) { - final int len = diag.length; - for (int i = 0; i < len; i++) { - final double d = diag[i]; - if (FastMath.abs(d) <= min) { - if (raise) { - final SingularMatrixException e = new SingularMatrixException(); - e.getContext().addMessage(LocalizedFormats.NUMBER_TOO_SMALL, d, min); - e.getContext().addMessage(LocalizedFormats.INDEX, i); - throw e; - } else { - return true; - } - } - } - return false; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RRQRDecomposition.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RRQRDecomposition.java deleted file mode 100644 index 261ba09bd..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RRQRDecomposition.java +++ /dev/null @@ -1,247 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.util.FastMath; - - -/** - * Calculates the rank-revealing QR-decomposition of a matrix, with column pivoting. - *

The rank-revealing QR-decomposition of a matrix A consists of three matrices Q, - * R and P such that AP=QR. Q is orthogonal (QTQ = I), and R is upper triangular. - * If A is m×n, Q is m×m and R is m×n and P is n×n.

- *

QR decomposition with column pivoting produces a rank-revealing QR - * decomposition and the {@link #getRank(double)} method may be used to return the rank of the - * input matrix A.

- *

This class compute the decomposition using Householder reflectors.

- *

For efficiency purposes, the decomposition in packed form is transposed. - * This allows inner loop to iterate inside rows, which is much more cache-efficient - * in Java.

- *

This class is based on the class with similar name from the - * JAMA library, with the - * following changes:

- *
    - *
  • a {@link #getQT() getQT} method has been added,
  • - *
  • the {@code solve} and {@code isFullRank} methods have been replaced - * by a {@link #getSolver() getSolver} method and the equivalent methods - * provided by the returned {@link DecompositionSolver}.
  • - *
- * - * @see MathWorld - * @see Wikipedia - * - * @since 3.2 - */ -public class RRQRDecomposition extends QRDecomposition { - - /** An array to record the column pivoting for later creation of P. */ - private int[] p; - - /** Cached value of P. */ - private RealMatrix cachedP; - - - /** - * Calculates the QR-decomposition of the given matrix. - * The singularity threshold defaults to zero. - * - * @param matrix The matrix to decompose. - * - * @see #RRQRDecomposition(RealMatrix, double) - */ - public RRQRDecomposition(RealMatrix matrix) { - this(matrix, 0d); - } - - /** - * Calculates the QR-decomposition of the given matrix. - * - * @param matrix The matrix to decompose. - * @param threshold Singularity threshold. - * @see #RRQRDecomposition(RealMatrix) - */ - public RRQRDecomposition(RealMatrix matrix, double threshold) { - super(matrix, threshold); - } - - /** Decompose matrix. - * @param qrt transposed matrix - */ - @Override - protected void decompose(double[][] qrt) { - p = new int[qrt.length]; - for (int i = 0; i < p.length; i++) { - p[i] = i; - } - super.decompose(qrt); - } - - /** Perform Householder reflection for a minor A(minor, minor) of A. - * - * @param minor minor index - * @param qrt transposed matrix - */ - @Override - protected void performHouseholderReflection(int minor, double[][] qrt) { - double l2NormSquaredMax = 0; - // Find the unreduced column with the greatest L2-Norm - int l2NormSquaredMaxIndex = minor; - for (int i = minor; i < qrt.length; i++) { - double l2NormSquared = 0; - for (int j = minor; j < qrt[i].length; j++) { - l2NormSquared += qrt[i][j] * qrt[i][j]; - } - if (l2NormSquared > l2NormSquaredMax) { - l2NormSquaredMax = l2NormSquared; - l2NormSquaredMaxIndex = i; - } - } - // swap the current column with that with the greated L2-Norm and record in p - if (l2NormSquaredMaxIndex != minor) { - double[] tmp1 = qrt[minor]; - qrt[minor] = qrt[l2NormSquaredMaxIndex]; - qrt[l2NormSquaredMaxIndex] = tmp1; - int tmp2 = p[minor]; - p[minor] = p[l2NormSquaredMaxIndex]; - p[l2NormSquaredMaxIndex] = tmp2; - } - - super.performHouseholderReflection(minor, qrt); - } - - - /** - * Returns the pivot matrix, P, used in the QR Decomposition of matrix A such that AP = QR. - * - * If no pivoting is used in this decomposition then P is equal to the identity matrix. - * - * @return a permutation matrix. - */ - public RealMatrix getP() { - if (cachedP == null) { - int n = p.length; - cachedP = MatrixUtils.createRealMatrix(n,n); - for (int i = 0; i < n; i++) { - cachedP.setEntry(p[i], i, 1); - } - } - return cachedP ; - } - - /** - * Return the effective numerical matrix rank. - *

The effective numerical rank is the number of non-negligible - * singular values.

- *

This implementation looks at Frobenius norms of the sequence of - * bottom right submatrices. When a large fall in norm is seen, - * the rank is returned. The drop is computed as:

- *
-     *   (thisNorm/lastNorm) * rNorm < dropThreshold
-     * 
- *

- * where thisNorm is the Frobenius norm of the current submatrix, - * lastNorm is the Frobenius norm of the previous submatrix, - * rNorm is is the Frobenius norm of the complete matrix - *

- * - * @param dropThreshold threshold triggering rank computation - * @return effective numerical matrix rank - */ - public int getRank(final double dropThreshold) { - RealMatrix r = getR(); - int rows = r.getRowDimension(); - int columns = r.getColumnDimension(); - int rank = 1; - double lastNorm = r.getFrobeniusNorm(); - double rNorm = lastNorm; - while (rank < FastMath.min(rows, columns)) { - double thisNorm = r.getSubMatrix(rank, rows - 1, rank, columns - 1).getFrobeniusNorm(); - if (thisNorm == 0 || (thisNorm / lastNorm) * rNorm < dropThreshold) { - break; - } - lastNorm = thisNorm; - rank++; - } - return rank; - } - - /** - * Get a solver for finding the A × X = B solution in least square sense. - *

- * Least Square sense means a solver can be computed for an overdetermined system, - * (i.e. a system with more equations than unknowns, which corresponds to a tall A - * matrix with more rows than columns). In any case, if the matrix is singular - * within the tolerance set at {@link RRQRDecomposition#RRQRDecomposition(RealMatrix, - * double) construction}, an error will be triggered when - * the {@link DecompositionSolver#solve(RealVector) solve} method will be called. - *

- * @return a solver - */ - @Override - public DecompositionSolver getSolver() { - return new Solver(super.getSolver(), this.getP()); - } - - /** Specialized solver. */ - private static class Solver implements DecompositionSolver { - - /** Upper level solver. */ - private final DecompositionSolver upper; - - /** A permutation matrix for the pivots used in the QR decomposition */ - private RealMatrix p; - - /** - * Build a solver from decomposed matrix. - * - * @param upper upper level solver. - * @param p permutation matrix - */ - private Solver(final DecompositionSolver upper, final RealMatrix p) { - this.upper = upper; - this.p = p; - } - - /** {@inheritDoc} */ - @Override - public boolean isNonSingular() { - return upper.isNonSingular(); - } - - /** {@inheritDoc} */ - @Override - public RealVector solve(RealVector b) { - return p.operate(upper.solve(b)); - } - - /** {@inheritDoc} */ - @Override - public RealMatrix solve(RealMatrix b) { - return p.multiply(upper.solve(b)); - } - - /** - * {@inheritDoc} - * @throws SingularMatrixException if the decomposed matrix is singular. - */ - @Override - public RealMatrix getInverse() { - return solve(MatrixUtils.createRealIdentityMatrix(p.getRowDimension())); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealLinearOperator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealLinearOperator.java deleted file mode 100644 index 7ad7e3ab2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealLinearOperator.java +++ /dev/null @@ -1,109 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.DimensionMismatchException; - -/** - * This class defines a linear operator operating on real ({@code double}) - * vector spaces. No direct access to the coefficients of the underlying matrix - * is provided. - * - * The motivation for such an interface is well stated by - * Barrett et al. (1994): - *
- * We restrict ourselves to iterative methods, which work by repeatedly - * improving an approximate solution until it is accurate enough. These - * methods access the coefficient matrix A of the linear system only via the - * matrix-vector product y = A · x - * (and perhaps z = AT · x). Thus the user need only - * supply a subroutine for computing y (and perhaps z) given x, which permits - * full exploitation of the sparsity or other special structure of A. - *
- *
- * - *
- *
Barret et al. (1994)
- *
- * R. Barrett, M. Berry, T. F. Chan, J. Demmel, J. M. Donato, J. Dongarra, - * V. Eijkhout, R. Pozo, C. Romine and H. Van der Vorst, - * Templates for the Solution of Linear Systems: Building Blocks for - * Iterative Methods, SIAM - *
- *
- * - * @since 3.0 - */ -public abstract class RealLinearOperator { - /** - * Returns the dimension of the codomain of this operator. - * - * @return the number of rows of the underlying matrix - */ - public abstract int getRowDimension(); - - /** - * Returns the dimension of the domain of this operator. - * - * @return the number of columns of the underlying matrix - */ - public abstract int getColumnDimension(); - - /** - * Returns the result of multiplying {@code this} by the vector {@code x}. - * - * @param x the vector to operate on - * @return the product of {@code this} instance with {@code x} - * @throws DimensionMismatchException if the column dimension does not match - * the size of {@code x} - */ - public abstract RealVector operate(final RealVector x) - throws DimensionMismatchException; - - /** - * Returns the result of multiplying the transpose of {@code this} operator - * by the vector {@code x} (optional operation). The default implementation - * throws an {@link UnsupportedOperationException}. Users overriding this - * method must also override {@link #isTransposable()}. - * - * @param x the vector to operate on - * @return the product of the transpose of {@code this} instance with - * {@code x} - * @throws DimensionMismatchException - * if the row dimension does not match the size of {@code x} - * @throws UnsupportedOperationException if this operation is not supported - * by {@code this} operator - */ - public RealVector operateTranspose(final RealVector x) - throws DimensionMismatchException, UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - /** - * Returns {@code true} if this operator supports - * {@link #operateTranspose(RealVector)}. If {@code true} is returned, - * {@link #operateTranspose(RealVector)} should not throw - * {@code UnsupportedOperationException}. The default implementation returns - * {@code false}. - * - * @return {@code false} - */ - public boolean isTransposable() { - return false; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealMatrix.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealMatrix.java deleted file mode 100644 index fb313499f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealMatrix.java +++ /dev/null @@ -1,828 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.OutOfRangeException; - -/** - * Interface defining a real-valued matrix with basic algebraic operations. - *

- * Matrix element indexing is 0-based -- e.g., getEntry(0, 0) - * returns the element in the first row, first column of the matrix.

- * - */ -public interface RealMatrix extends AnyMatrix { - - /** - * Create a new RealMatrix of the same type as the instance with the - * supplied - * row and column dimensions. - * - * @param rowDimension the number of rows in the new matrix - * @param columnDimension the number of columns in the new matrix - * @return a new matrix of the same type as the instance - * @throws NotStrictlyPositiveException if row or column dimension is not - * positive. - * @since 2.0 - */ - RealMatrix createMatrix(int rowDimension, int columnDimension) - throws NotStrictlyPositiveException; - - /** - * Returns a (deep) copy of this. - * - * @return matrix copy - */ - RealMatrix copy(); - - /** - * Returns the sum of {@code this} and {@code m}. - * - * @param m matrix to be added - * @return {@code this + m} - * @throws MatrixDimensionMismatchException if {@code m} is not the same - * size as {@code this}. - */ - RealMatrix add(RealMatrix m) - throws MatrixDimensionMismatchException; - - /** - * Returns {@code this} minus {@code m}. - * - * @param m matrix to be subtracted - * @return {@code this - m} - * @throws MatrixDimensionMismatchException if {@code m} is not the same - * size as {@code this}. - */ - RealMatrix subtract(RealMatrix m) - throws MatrixDimensionMismatchException; - - /** - * Returns the result of adding {@code d} to each entry of {@code this}. - * - * @param d value to be added to each entry - * @return {@code d + this} - */ - RealMatrix scalarAdd(double d); - - /** - * Returns the result of multiplying each entry of {@code this} by - * {@code d}. - * - * @param d value to multiply all entries by - * @return {@code d * this} - */ - RealMatrix scalarMultiply(double d); - - /** - * Returns the result of postmultiplying {@code this} by {@code m}. - * - * @param m matrix to postmultiply by - * @return {@code this * m} - * @throws DimensionMismatchException if - * {@code columnDimension(this) != rowDimension(m)} - */ - RealMatrix multiply(RealMatrix m) - throws DimensionMismatchException; - - /** - * Returns the result of premultiplying {@code this} by {@code m}. - * - * @param m matrix to premultiply by - * @return {@code m * this} - * @throws DimensionMismatchException if - * {@code rowDimension(this) != columnDimension(m)} - */ - RealMatrix preMultiply(RealMatrix m) - throws DimensionMismatchException; - - /** - * Returns the result of multiplying {@code this} with itself {@code p} - * times. Depending on the underlying storage, instability for high powers - * might occur. - * - * @param p raise {@code this} to power {@code p} - * @return {@code this^p} - * @throws NotPositiveException if {@code p < 0} - * @throws NonSquareMatrixException if the matrix is not square - */ - RealMatrix power(final int p) - throws NotPositiveException, NonSquareMatrixException; - - /** - * Returns matrix entries as a two-dimensional array. - * - * @return 2-dimensional array of entries - */ - double[][] getData(); - - /** - * Returns the - * maximum absolute row sum norm of the matrix. - * - * @return norm - */ - double getNorm(); - - /** - * Returns the - * Frobenius norm of the matrix. - * - * @return norm - */ - double getFrobeniusNorm(); - - /** - * Gets a submatrix. Rows and columns are indicated - * counting from 0 to n-1. - * - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index (inclusive) - * @return The subMatrix containing the data of the - * specified rows and columns. - * @throws OutOfRangeException if the indices are not valid. - * @throws NumberIsTooSmallException if {@code endRow < startRow} or - * {@code endColumn < startColumn}. - */ - RealMatrix getSubMatrix(int startRow, int endRow, int startColumn, - int endColumn) - throws OutOfRangeException, NumberIsTooSmallException; - - /** - * Gets a submatrix. Rows and columns are indicated counting from 0 to n-1. - * - * @param selectedRows Array of row indices. - * @param selectedColumns Array of column indices. - * @return The subMatrix containing the data in the specified rows and - * columns - * @throws NullArgumentException if the row or column selections are - * {@code null} - * @throws NoDataException if the row or column selections are empty (zero - * length). - * @throws OutOfRangeException if the indices are not valid. - */ - RealMatrix getSubMatrix(int[] selectedRows, int[] selectedColumns) - throws NullArgumentException, NoDataException, OutOfRangeException; - - /** - * Copy a submatrix. Rows and columns are indicated counting from 0 to n-1. - * - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index (inclusive) - * @param destination The arrays where the submatrix data should be copied - * (if larger than rows/columns counts, only the upper-left part will be - * used) - * @throws OutOfRangeException if the indices are not valid. - * @throws NumberIsTooSmallException if {@code endRow < startRow} or - * {@code endColumn < startColumn}. - * @throws MatrixDimensionMismatchException if the destination array is too - * small. - */ - void copySubMatrix(int startRow, int endRow, int startColumn, - int endColumn, double[][] destination) - throws OutOfRangeException, NumberIsTooSmallException, - MatrixDimensionMismatchException; - - /** - * Copy a submatrix. Rows and columns are indicated counting from 0 to n-1. - * - * @param selectedRows Array of row indices. - * @param selectedColumns Array of column indices. - * @param destination The arrays where the submatrix data should be copied - * (if larger than rows/columns counts, only the upper-left part will be - * used) - * @throws NullArgumentException if the row or column selections are - * {@code null} - * @throws NoDataException if the row or column selections are empty (zero - * length). - * @throws OutOfRangeException if the indices are not valid. - * @throws MatrixDimensionMismatchException if the destination array is too - * small. - */ - void copySubMatrix(int[] selectedRows, int[] selectedColumns, - double[][] destination) - throws OutOfRangeException, NullArgumentException, NoDataException, - MatrixDimensionMismatchException; - - /** - * Replace the submatrix starting at {@code row, column} using data in the - * input {@code subMatrix} array. Indexes are 0-based. - *

- * Example:
- * Starting with

-    * 1  2  3  4
-    * 5  6  7  8
-    * 9  0  1  2
-    * 
- * and subMatrix = {{3, 4} {5,6}}, invoking - * {@code setSubMatrix(subMatrix,1,1))} will result in
-    * 1  2  3  4
-    * 5  3  4  8
-    * 9  5  6  2
-    * 
- * - * @param subMatrix array containing the submatrix replacement data - * @param row row coordinate of the top, left element to be replaced - * @param column column coordinate of the top, left element to be replaced - * @throws NoDataException if {@code subMatrix} is empty. - * @throws OutOfRangeException if {@code subMatrix} does not fit into - * this matrix from element in {@code (row, column)}. - * @throws DimensionMismatchException if {@code subMatrix} is not rectangular - * (not all rows have the same length) or empty. - * @throws NullArgumentException if {@code subMatrix} is {@code null}. - * @since 2.0 - */ - void setSubMatrix(double[][] subMatrix, int row, int column) - throws NoDataException, OutOfRangeException, - DimensionMismatchException, NullArgumentException; - - /** - * Get the entries at the given row index as a row matrix. Row indices start - * at 0. - * - * @param row Row to be fetched. - * @return row Matrix. - * @throws OutOfRangeException if the specified row index is invalid. - */ - RealMatrix getRowMatrix(int row) throws OutOfRangeException; - - /** - * Sets the specified {@code row} of {@code this} matrix to the entries of - * the specified row {@code matrix}. Row indices start at 0. - * - * @param row Row to be set. - * @param matrix Row matrix to be copied (must have one row and the same - * number of columns as the instance). - * @throws OutOfRangeException if the specified row index is invalid. - * @throws MatrixDimensionMismatchException if the row dimension of the - * {@code matrix} is not {@code 1}, or the column dimensions of {@code this} - * and {@code matrix} do not match. - */ - void setRowMatrix(int row, RealMatrix matrix) - throws OutOfRangeException, MatrixDimensionMismatchException; - - /** - * Get the entries at the given column index as a column matrix. Column - * indices start at 0. - * - * @param column Column to be fetched. - * @return column Matrix. - * @throws OutOfRangeException if the specified column index is invalid. - */ - RealMatrix getColumnMatrix(int column) - throws OutOfRangeException; - - /** - * Sets the specified {@code column} of {@code this} matrix to the entries - * of the specified column {@code matrix}. Column indices start at 0. - * - * @param column Column to be set. - * @param matrix Column matrix to be copied (must have one column and the - * same number of rows as the instance). - * @throws OutOfRangeException if the specified column index is invalid. - * @throws MatrixDimensionMismatchException if the column dimension of the - * {@code matrix} is not {@code 1}, or the row dimensions of {@code this} - * and {@code matrix} do not match. - */ - void setColumnMatrix(int column, RealMatrix matrix) - throws OutOfRangeException, MatrixDimensionMismatchException; - - /** - * Returns the entries in row number {@code row} as a vector. Row indices - * start at 0. - * - * @param row Row to be fetched. - * @return a row vector. - * @throws OutOfRangeException if the specified row index is invalid. - */ - RealVector getRowVector(int row) - throws OutOfRangeException; - - /** - * Sets the specified {@code row} of {@code this} matrix to the entries of - * the specified {@code vector}. Row indices start at 0. - * - * @param row Row to be set. - * @param vector row vector to be copied (must have the same number of - * column as the instance). - * @throws OutOfRangeException if the specified row index is invalid. - * @throws MatrixDimensionMismatchException if the {@code vector} dimension - * does not match the column dimension of {@code this} matrix. - */ - void setRowVector(int row, RealVector vector) - throws OutOfRangeException, MatrixDimensionMismatchException; - - /** - * Get the entries at the given column index as a vector. Column indices - * start at 0. - * - * @param column Column to be fetched. - * @return a column vector. - * @throws OutOfRangeException if the specified column index is invalid - */ - RealVector getColumnVector(int column) - throws OutOfRangeException; - - /** - * Sets the specified {@code column} of {@code this} matrix to the entries - * of the specified {@code vector}. Column indices start at 0. - * - * @param column Column to be set. - * @param vector column vector to be copied (must have the same number of - * rows as the instance). - * @throws OutOfRangeException if the specified column index is invalid. - * @throws MatrixDimensionMismatchException if the {@code vector} dimension - * does not match the row dimension of {@code this} matrix. - */ - void setColumnVector(int column, RealVector vector) - throws OutOfRangeException, MatrixDimensionMismatchException; - - /** - * Get the entries at the given row index. Row indices start at 0. - * - * @param row Row to be fetched. - * @return the array of entries in the row. - * @throws OutOfRangeException if the specified row index is not valid. - */ - double[] getRow(int row) throws OutOfRangeException; - - /** - * Sets the specified {@code row} of {@code this} matrix to the entries - * of the specified {@code array}. Row indices start at 0. - * - * @param row Row to be set. - * @param array Row matrix to be copied (must have the same number of - * columns as the instance) - * @throws OutOfRangeException if the specified row index is invalid. - * @throws MatrixDimensionMismatchException if the {@code array} length does - * not match the column dimension of {@code this} matrix. - */ - void setRow(int row, double[] array) - throws OutOfRangeException, MatrixDimensionMismatchException; - - /** - * Get the entries at the given column index as an array. Column indices - * start at 0. - * - * @param column Column to be fetched. - * @return the array of entries in the column. - * @throws OutOfRangeException if the specified column index is not valid. - */ - double[] getColumn(int column) throws OutOfRangeException; - - /** - * Sets the specified {@code column} of {@code this} matrix to the entries - * of the specified {@code array}. Column indices start at 0. - * - * @param column Column to be set. - * @param array Column array to be copied (must have the same number of - * rows as the instance). - * @throws OutOfRangeException if the specified column index is invalid. - * @throws MatrixDimensionMismatchException if the {@code array} length does - * not match the row dimension of {@code this} matrix. - */ - void setColumn(int column, double[] array) - throws OutOfRangeException, MatrixDimensionMismatchException; - - /** - * Get the entry in the specified row and column. Row and column indices - * start at 0. - * - * @param row Row index of entry to be fetched. - * @param column Column index of entry to be fetched. - * @return the matrix entry at {@code (row, column)}. - * @throws OutOfRangeException if the row or column index is not valid. - */ - double getEntry(int row, int column) throws OutOfRangeException; - - /** - * Set the entry in the specified row and column. Row and column indices - * start at 0. - * - * @param row Row index of entry to be set. - * @param column Column index of entry to be set. - * @param value the new value of the entry. - * @throws OutOfRangeException if the row or column index is not valid - * @since 2.0 - */ - void setEntry(int row, int column, double value) throws OutOfRangeException; - - /** - * Adds (in place) the specified value to the specified entry of - * {@code this} matrix. Row and column indices start at 0. - * - * @param row Row index of the entry to be modified. - * @param column Column index of the entry to be modified. - * @param increment value to add to the matrix entry. - * @throws OutOfRangeException if the row or column index is not valid. - * @since 2.0 - */ - void addToEntry(int row, int column, double increment) throws OutOfRangeException; - - /** - * Multiplies (in place) the specified entry of {@code this} matrix by the - * specified value. Row and column indices start at 0. - * - * @param row Row index of the entry to be modified. - * @param column Column index of the entry to be modified. - * @param factor Multiplication factor for the matrix entry. - * @throws OutOfRangeException if the row or column index is not valid. - * @since 2.0 - */ - void multiplyEntry(int row, int column, double factor) throws OutOfRangeException; - - /** - * Returns the transpose of this matrix. - * - * @return transpose matrix - */ - RealMatrix transpose(); - - /** - * Returns the - * trace of the matrix (the sum of the elements on the main diagonal). - * - * @return the trace. - * @throws NonSquareMatrixException if the matrix is not square. - */ - double getTrace() throws NonSquareMatrixException; - - /** - * Returns the result of multiplying this by the vector {@code v}. - * - * @param v the vector to operate on - * @return {@code this * v} - * @throws DimensionMismatchException if the length of {@code v} does not - * match the column dimension of {@code this}. - */ - double[] operate(double[] v) throws DimensionMismatchException; - - /** - * Returns the result of multiplying this by the vector {@code v}. - * - * @param v the vector to operate on - * @return {@code this * v} - * @throws DimensionMismatchException if the dimension of {@code v} does not - * match the column dimension of {@code this}. - */ - RealVector operate(RealVector v) throws DimensionMismatchException; - - /** - * Returns the (row) vector result of premultiplying this by the vector {@code v}. - * - * @param v the row vector to premultiply by - * @return {@code v * this} - * @throws DimensionMismatchException if the length of {@code v} does not - * match the row dimension of {@code this}. - */ - double[] preMultiply(double[] v) throws DimensionMismatchException; - - /** - * Returns the (row) vector result of premultiplying this by the vector {@code v}. - * - * @param v the row vector to premultiply by - * @return {@code v * this} - * @throws DimensionMismatchException if the dimension of {@code v} does not - * match the row dimension of {@code this}. - */ - RealVector preMultiply(RealVector v) throws DimensionMismatchException; - - /** - * Visit (and possibly change) all matrix entries in row order. - *

Row order starts at upper left and iterating through all elements - * of a row from left to right before going to the leftmost element - * of the next row.

- * @param visitor visitor used to process all matrix entries - * @see #walkInRowOrder(RealMatrixPreservingVisitor) - * @see #walkInRowOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixChangingVisitor) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor) - * @see #walkInColumnOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link RealMatrixChangingVisitor#end()} at the end - * of the walk - */ - double walkInRowOrder(RealMatrixChangingVisitor visitor); - - /** - * Visit (but don't change) all matrix entries in row order. - *

Row order starts at upper left and iterating through all elements - * of a row from left to right before going to the leftmost element - * of the next row.

- * @param visitor visitor used to process all matrix entries - * @see #walkInRowOrder(RealMatrixChangingVisitor) - * @see #walkInRowOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixChangingVisitor) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor) - * @see #walkInColumnOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link RealMatrixPreservingVisitor#end()} at the end - * of the walk - */ - double walkInRowOrder(RealMatrixPreservingVisitor visitor); - - /** - * Visit (and possibly change) some matrix entries in row order. - *

Row order starts at upper left and iterating through all elements - * of a row from left to right before going to the leftmost element - * of the next row.

- * @param visitor visitor used to process all matrix entries - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index - * @throws OutOfRangeException if the indices are not valid. - * @throws NumberIsTooSmallException if {@code endRow < startRow} or - * {@code endColumn < startColumn}. - * @see #walkInRowOrder(RealMatrixChangingVisitor) - * @see #walkInRowOrder(RealMatrixPreservingVisitor) - * @see #walkInRowOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixChangingVisitor) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor) - * @see #walkInColumnOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link RealMatrixChangingVisitor#end()} at the end - * of the walk - */ - double walkInRowOrder(RealMatrixChangingVisitor visitor, int startRow, - int endRow, int startColumn, int endColumn) - throws OutOfRangeException, NumberIsTooSmallException; - - /** - * Visit (but don't change) some matrix entries in row order. - *

Row order starts at upper left and iterating through all elements - * of a row from left to right before going to the leftmost element - * of the next row.

- * @param visitor visitor used to process all matrix entries - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index - * @throws OutOfRangeException if the indices are not valid. - * @throws NumberIsTooSmallException if {@code endRow < startRow} or - * {@code endColumn < startColumn}. - * @see #walkInRowOrder(RealMatrixChangingVisitor) - * @see #walkInRowOrder(RealMatrixPreservingVisitor) - * @see #walkInRowOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixChangingVisitor) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor) - * @see #walkInColumnOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link RealMatrixPreservingVisitor#end()} at the end - * of the walk - */ - double walkInRowOrder(RealMatrixPreservingVisitor visitor, int startRow, - int endRow, int startColumn, int endColumn) - throws OutOfRangeException, NumberIsTooSmallException; - - /** - * Visit (and possibly change) all matrix entries in column order. - *

Column order starts at upper left and iterating through all elements - * of a column from top to bottom before going to the topmost element - * of the next column.

- * @param visitor visitor used to process all matrix entries - * @see #walkInRowOrder(RealMatrixChangingVisitor) - * @see #walkInRowOrder(RealMatrixPreservingVisitor) - * @see #walkInRowOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor) - * @see #walkInColumnOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link RealMatrixChangingVisitor#end()} at the end - * of the walk - */ - double walkInColumnOrder(RealMatrixChangingVisitor visitor); - - /** - * Visit (but don't change) all matrix entries in column order. - *

Column order starts at upper left and iterating through all elements - * of a column from top to bottom before going to the topmost element - * of the next column.

- * @param visitor visitor used to process all matrix entries - * @see #walkInRowOrder(RealMatrixChangingVisitor) - * @see #walkInRowOrder(RealMatrixPreservingVisitor) - * @see #walkInRowOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixChangingVisitor) - * @see #walkInColumnOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link RealMatrixPreservingVisitor#end()} at the end - * of the walk - */ - double walkInColumnOrder(RealMatrixPreservingVisitor visitor); - - /** - * Visit (and possibly change) some matrix entries in column order. - *

Column order starts at upper left and iterating through all elements - * of a column from top to bottom before going to the topmost element - * of the next column.

- * @param visitor visitor used to process all matrix entries - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index - * @throws OutOfRangeException if the indices are not valid. - * @throws NumberIsTooSmallException if {@code endRow < startRow} or - * {@code endColumn < startColumn}. - * @see #walkInRowOrder(RealMatrixChangingVisitor) - * @see #walkInRowOrder(RealMatrixPreservingVisitor) - * @see #walkInRowOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixChangingVisitor) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link RealMatrixChangingVisitor#end()} at the end - * of the walk - */ - double walkInColumnOrder(RealMatrixChangingVisitor visitor, int startRow, - int endRow, int startColumn, int endColumn) - throws OutOfRangeException, NumberIsTooSmallException; - - /** - * Visit (but don't change) some matrix entries in column order. - *

Column order starts at upper left and iterating through all elements - * of a column from top to bottom before going to the topmost element - * of the next column.

- * @param visitor visitor used to process all matrix entries - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index - * @throws OutOfRangeException if the indices are not valid. - * @throws NumberIsTooSmallException if {@code endRow < startRow} or - * {@code endColumn < startColumn}. - * @see #walkInRowOrder(RealMatrixChangingVisitor) - * @see #walkInRowOrder(RealMatrixPreservingVisitor) - * @see #walkInRowOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixChangingVisitor) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor) - * @see #walkInColumnOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link RealMatrixPreservingVisitor#end()} at the end - * of the walk - */ - double walkInColumnOrder(RealMatrixPreservingVisitor visitor, int startRow, - int endRow, int startColumn, int endColumn) - throws OutOfRangeException, NumberIsTooSmallException; - - /** - * Visit (and possibly change) all matrix entries using the fastest possible order. - *

The fastest walking order depends on the exact matrix class. It may be - * different from traditional row or column orders.

- * @param visitor visitor used to process all matrix entries - * @see #walkInRowOrder(RealMatrixChangingVisitor) - * @see #walkInRowOrder(RealMatrixPreservingVisitor) - * @see #walkInRowOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixChangingVisitor) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor) - * @see #walkInColumnOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link RealMatrixChangingVisitor#end()} at the end - * of the walk - */ - double walkInOptimizedOrder(RealMatrixChangingVisitor visitor); - - /** - * Visit (but don't change) all matrix entries using the fastest possible order. - *

The fastest walking order depends on the exact matrix class. It may be - * different from traditional row or column orders.

- * @param visitor visitor used to process all matrix entries - * @see #walkInRowOrder(RealMatrixChangingVisitor) - * @see #walkInRowOrder(RealMatrixPreservingVisitor) - * @see #walkInRowOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixChangingVisitor) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor) - * @see #walkInColumnOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link RealMatrixPreservingVisitor#end()} at the end - * of the walk - */ - double walkInOptimizedOrder(RealMatrixPreservingVisitor visitor); - - /** - * Visit (and possibly change) some matrix entries using the fastest possible order. - *

The fastest walking order depends on the exact matrix class. It may be - * different from traditional row or column orders.

- * @param visitor visitor used to process all matrix entries - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index (inclusive) - * @throws OutOfRangeException if the indices are not valid. - * @throws NumberIsTooSmallException if {@code endRow < startRow} or - * {@code endColumn < startColumn}. - * @see #walkInRowOrder(RealMatrixChangingVisitor) - * @see #walkInRowOrder(RealMatrixPreservingVisitor) - * @see #walkInRowOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixChangingVisitor) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor) - * @see #walkInColumnOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @return the value returned by {@link RealMatrixChangingVisitor#end()} at the end - * of the walk - */ - double walkInOptimizedOrder(RealMatrixChangingVisitor visitor, - int startRow, int endRow, int startColumn, int endColumn) - throws OutOfRangeException, NumberIsTooSmallException; - - /** - * Visit (but don't change) some matrix entries using the fastest possible order. - *

The fastest walking order depends on the exact matrix class. It may be - * different from traditional row or column orders.

- * @param visitor visitor used to process all matrix entries - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index (inclusive) - * @throws OutOfRangeException if the indices are not valid. - * @throws NumberIsTooSmallException if {@code endRow < startRow} or - * {@code endColumn < startColumn}. - * @see #walkInRowOrder(RealMatrixChangingVisitor) - * @see #walkInRowOrder(RealMatrixPreservingVisitor) - * @see #walkInRowOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInRowOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixChangingVisitor) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor) - * @see #walkInColumnOrder(RealMatrixChangingVisitor, int, int, int, int) - * @see #walkInColumnOrder(RealMatrixPreservingVisitor, int, int, int, int) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor) - * @see #walkInOptimizedOrder(RealMatrixPreservingVisitor) - * @see #walkInOptimizedOrder(RealMatrixChangingVisitor, int, int, int, int) - * @return the value returned by {@link RealMatrixPreservingVisitor#end()} at the end - * of the walk - */ - double walkInOptimizedOrder(RealMatrixPreservingVisitor visitor, - int startRow, int endRow, int startColumn, int endColumn) - throws OutOfRangeException, NumberIsTooSmallException; -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealMatrixChangingVisitor.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealMatrixChangingVisitor.java deleted file mode 100644 index 7a672efa8..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealMatrixChangingVisitor.java +++ /dev/null @@ -1,55 +0,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. - */ - -package org.apache.commons.math4.linear; - -/** - * Interface defining a visitor for matrix entries. - * - * @see DefaultRealMatrixChangingVisitor - * @since 2.0 - */ -public interface RealMatrixChangingVisitor { - /** - * Start visiting a matrix. - *

This method is called once before any entry of the matrix is visited.

- * @param rows number of rows of the matrix - * @param columns number of columns of the matrix - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index (inclusive) - */ - void start(int rows, int columns, - int startRow, int endRow, int startColumn, int endColumn); - - /** - * Visit one matrix entry. - * @param row row index of the entry - * @param column column index of the entry - * @param value current value of the entry - * @return the new value to be set for the entry - */ - double visit(int row, int column, double value); - - /** - * End visiting a matrix. - *

This method is called once after all entries of the matrix have been visited.

- * @return the value that the walkInXxxOrder must return - */ - double end(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealMatrixFormat.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealMatrixFormat.java deleted file mode 100644 index 34c0b0e9c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealMatrixFormat.java +++ /dev/null @@ -1,394 +0,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. - */ - -package org.apache.commons.math4.linear; - -import java.text.FieldPosition; -import java.text.NumberFormat; -import java.text.ParsePosition; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import org.apache.commons.math4.exception.MathParseException; -import org.apache.commons.math4.util.CompositeFormat; - -/** - * Formats a {@code nxm} matrix in components list format - * "{{a00,a01, ..., - * a0m-1},{a10, - * a11, ..., a1m-1},{...},{ - * an-10, an-11, ..., - * an-1m-1}}". - *

The prefix and suffix "{" and "}", the row prefix and suffix "{" and "}", - * the row separator "," and the column separator "," can be replaced by any - * user-defined strings. The number format for components can be configured.

- * - *

White space is ignored at parse time, even if it is in the prefix, suffix - * or separator specifications. So even if the default separator does include a space - * character that is used at format time, both input string "{{1,1,1}}" and - * " { { 1 , 1 , 1 } } " will be parsed without error and the same matrix will be - * returned. In the second case, however, the parse position after parsing will be - * just after the closing curly brace, i.e. just before the trailing space.

- * - *

Note: the grouping functionality of the used {@link NumberFormat} is - * disabled to prevent problems when parsing (e.g. 1,345.34 would be a valid number - * but conflicts with the default column separator).

- * - * @since 3.1 - */ -public class RealMatrixFormat { - - /** The default prefix: "{". */ - private static final String DEFAULT_PREFIX = "{"; - /** The default suffix: "}". */ - private static final String DEFAULT_SUFFIX = "}"; - /** The default row prefix: "{". */ - private static final String DEFAULT_ROW_PREFIX = "{"; - /** The default row suffix: "}". */ - private static final String DEFAULT_ROW_SUFFIX = "}"; - /** The default row separator: ",". */ - private static final String DEFAULT_ROW_SEPARATOR = ","; - /** The default column separator: ",". */ - private static final String DEFAULT_COLUMN_SEPARATOR = ","; - /** Prefix. */ - private final String prefix; - /** Suffix. */ - private final String suffix; - /** Row prefix. */ - private final String rowPrefix; - /** Row suffix. */ - private final String rowSuffix; - /** Row separator. */ - private final String rowSeparator; - /** Column separator. */ - private final String columnSeparator; - /** The format used for components. */ - private final NumberFormat format; - - /** - * Create an instance with default settings. - *

The instance uses the default prefix, suffix and row/column separator: - * "[", "]", ";" and ", " and the default number format for components.

- */ - public RealMatrixFormat() { - this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ROW_PREFIX, DEFAULT_ROW_SUFFIX, - DEFAULT_ROW_SEPARATOR, DEFAULT_COLUMN_SEPARATOR, CompositeFormat.getDefaultNumberFormat()); - } - - /** - * Create an instance with a custom number format for components. - * @param format the custom format for components. - */ - public RealMatrixFormat(final NumberFormat format) { - this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ROW_PREFIX, DEFAULT_ROW_SUFFIX, - DEFAULT_ROW_SEPARATOR, DEFAULT_COLUMN_SEPARATOR, format); - } - - /** - * Create an instance with custom prefix, suffix and separator. - * @param prefix prefix to use instead of the default "{" - * @param suffix suffix to use instead of the default "}" - * @param rowPrefix row prefix to use instead of the default "{" - * @param rowSuffix row suffix to use instead of the default "}" - * @param rowSeparator tow separator to use instead of the default ";" - * @param columnSeparator column separator to use instead of the default ", " - */ - public RealMatrixFormat(final String prefix, final String suffix, - final String rowPrefix, final String rowSuffix, - final String rowSeparator, final String columnSeparator) { - this(prefix, suffix, rowPrefix, rowSuffix, rowSeparator, columnSeparator, - CompositeFormat.getDefaultNumberFormat()); - } - - /** - * Create an instance with custom prefix, suffix, separator and format - * for components. - * @param prefix prefix to use instead of the default "{" - * @param suffix suffix to use instead of the default "}" - * @param rowPrefix row prefix to use instead of the default "{" - * @param rowSuffix row suffix to use instead of the default "}" - * @param rowSeparator tow separator to use instead of the default ";" - * @param columnSeparator column separator to use instead of the default ", " - * @param format the custom format for components. - */ - public RealMatrixFormat(final String prefix, final String suffix, - final String rowPrefix, final String rowSuffix, - final String rowSeparator, final String columnSeparator, - final NumberFormat format) { - this.prefix = prefix; - this.suffix = suffix; - this.rowPrefix = rowPrefix; - this.rowSuffix = rowSuffix; - this.rowSeparator = rowSeparator; - this.columnSeparator = columnSeparator; - this.format = format; - // disable grouping to prevent parsing problems - this.format.setGroupingUsed(false); - } - - /** - * Get the set of locales for which real vectors formats are available. - *

This is the same set as the {@link NumberFormat} set.

- * @return available real vector format locales. - */ - public static Locale[] getAvailableLocales() { - return NumberFormat.getAvailableLocales(); - } - - /** - * Get the format prefix. - * @return format prefix. - */ - public String getPrefix() { - return prefix; - } - - /** - * Get the format suffix. - * @return format suffix. - */ - public String getSuffix() { - return suffix; - } - - /** - * Get the format prefix. - * @return format prefix. - */ - public String getRowPrefix() { - return rowPrefix; - } - - /** - * Get the format suffix. - * @return format suffix. - */ - public String getRowSuffix() { - return rowSuffix; - } - - /** - * Get the format separator between rows of the matrix. - * @return format separator for rows. - */ - public String getRowSeparator() { - return rowSeparator; - } - - /** - * Get the format separator between components. - * @return format separator between components. - */ - public String getColumnSeparator() { - return columnSeparator; - } - - /** - * Get the components format. - * @return components format. - */ - public NumberFormat getFormat() { - return format; - } - - /** - * Returns the default real vector format for the current locale. - * @return the default real vector format. - */ - public static RealMatrixFormat getInstance() { - return getInstance(Locale.getDefault()); - } - - /** - * Returns the default real vector format for the given locale. - * @param locale the specific locale used by the format. - * @return the real vector format specific to the given locale. - */ - public static RealMatrixFormat getInstance(final Locale locale) { - return new RealMatrixFormat(CompositeFormat.getDefaultNumberFormat(locale)); - } - - /** - * This method calls {@link #format(RealMatrix,StringBuffer,FieldPosition)}. - * - * @param m RealMatrix object to format. - * @return a formatted matrix. - */ - public String format(RealMatrix m) { - return format(m, new StringBuffer(), new FieldPosition(0)).toString(); - } - - /** - * Formats a {@link RealMatrix} object to produce a string. - * @param matrix the object to format. - * @param toAppendTo where the text is to be appended - * @param pos On input: an alignment field, if desired. On output: the - * offsets of the alignment field - * @return the value passed in as toAppendTo. - */ - public StringBuffer format(RealMatrix matrix, StringBuffer toAppendTo, - FieldPosition pos) { - - pos.setBeginIndex(0); - pos.setEndIndex(0); - - // format prefix - toAppendTo.append(prefix); - - // format rows - final int rows = matrix.getRowDimension(); - for (int i = 0; i < rows; ++i) { - toAppendTo.append(rowPrefix); - for (int j = 0; j < matrix.getColumnDimension(); ++j) { - if (j > 0) { - toAppendTo.append(columnSeparator); - } - CompositeFormat.formatDouble(matrix.getEntry(i, j), format, toAppendTo, pos); - } - toAppendTo.append(rowSuffix); - if (i < rows - 1) { - toAppendTo.append(rowSeparator); - } - } - - // format suffix - toAppendTo.append(suffix); - - return toAppendTo; - } - - /** - * Parse a string to produce a {@link RealMatrix} object. - * - * @param source String to parse. - * @return the parsed {@link RealMatrix} object. - * @throws MathParseException if the beginning of the specified string - * cannot be parsed. - */ - public RealMatrix parse(String source) { - final ParsePosition parsePosition = new ParsePosition(0); - final RealMatrix result = parse(source, parsePosition); - if (parsePosition.getIndex() == 0) { - throw new MathParseException(source, - parsePosition.getErrorIndex(), - Array2DRowRealMatrix.class); - } - return result; - } - - /** - * Parse a string to produce a {@link RealMatrix} object. - * - * @param source String to parse. - * @param pos input/ouput parsing parameter. - * @return the parsed {@link RealMatrix} object. - */ - public RealMatrix parse(String source, ParsePosition pos) { - int initialIndex = pos.getIndex(); - - final String trimmedPrefix = prefix.trim(); - final String trimmedSuffix = suffix.trim(); - final String trimmedRowPrefix = rowPrefix.trim(); - final String trimmedRowSuffix = rowSuffix.trim(); - final String trimmedColumnSeparator = columnSeparator.trim(); - final String trimmedRowSeparator = rowSeparator.trim(); - - // parse prefix - CompositeFormat.parseAndIgnoreWhitespace(source, pos); - if (!CompositeFormat.parseFixedstring(source, trimmedPrefix, pos)) { - return null; - } - - // parse components - List> matrix = new ArrayList<>(); - List rowComponents = new ArrayList<>(); - for (boolean loop = true; loop;){ - - if (!rowComponents.isEmpty()) { - CompositeFormat.parseAndIgnoreWhitespace(source, pos); - if (!CompositeFormat.parseFixedstring(source, trimmedColumnSeparator, pos)) { - if (trimmedRowSuffix.length() != 0 && - !CompositeFormat.parseFixedstring(source, trimmedRowSuffix, pos)) { - return null; - } else { - CompositeFormat.parseAndIgnoreWhitespace(source, pos); - if (CompositeFormat.parseFixedstring(source, trimmedRowSeparator, pos)) { - matrix.add(rowComponents); - rowComponents = new ArrayList<>(); - continue; - } else { - loop = false; - } - } - } - } else { - CompositeFormat.parseAndIgnoreWhitespace(source, pos); - if (trimmedRowPrefix.length() != 0 && - !CompositeFormat.parseFixedstring(source, trimmedRowPrefix, pos)) { - return null; - } - } - - if (loop) { - CompositeFormat.parseAndIgnoreWhitespace(source, pos); - Number component = CompositeFormat.parseNumber(source, format, pos); - if (component != null) { - rowComponents.add(component); - } else { - if (rowComponents.isEmpty()) { - loop = false; - } else { - // invalid component - // set index back to initial, error index should already be set - pos.setIndex(initialIndex); - return null; - } - } - } - - } - - if (!rowComponents.isEmpty()) { - matrix.add(rowComponents); - } - - // parse suffix - CompositeFormat.parseAndIgnoreWhitespace(source, pos); - if (!CompositeFormat.parseFixedstring(source, trimmedSuffix, pos)) { - return null; - } - - // do not allow an empty matrix - if (matrix.isEmpty()) { - pos.setIndex(initialIndex); - return null; - } - - // build vector - double[][] data = new double[matrix.size()][]; - int row = 0; - for (List rowList : matrix) { - data[row] = new double[rowList.size()]; - for (int i = 0; i < rowList.size(); i++) { - data[row][i] = rowList.get(i).doubleValue(); - } - row++; - } - return MatrixUtils.createRealMatrix(data); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealMatrixPreservingVisitor.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealMatrixPreservingVisitor.java deleted file mode 100644 index 17195d1ee..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealMatrixPreservingVisitor.java +++ /dev/null @@ -1,54 +0,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. - */ - -package org.apache.commons.math4.linear; - -/** - * Interface defining a visitor for matrix entries. - * - * @see DefaultRealMatrixPreservingVisitor - * @since 2.0 - */ -public interface RealMatrixPreservingVisitor { - /** - * Start visiting a matrix. - *

This method is called once before any entry of the matrix is visited.

- * @param rows number of rows of the matrix - * @param columns number of columns of the matrix - * @param startRow Initial row index - * @param endRow Final row index (inclusive) - * @param startColumn Initial column index - * @param endColumn Final column index (inclusive) - */ - void start(int rows, int columns, - int startRow, int endRow, int startColumn, int endColumn); - - /** - * Visit one matrix entry. - * @param row row index of the entry - * @param column column index of the entry - * @param value current value of the entry - */ - void visit(int row, int column, double value); - - /** - * End visiting a matrix. - *

This method is called once after all entries of the matrix have been visited.

- * @return the value that the walkInXxxOrder must return - */ - double end(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealVector.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealVector.java deleted file mode 100644 index f4fa84396..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealVector.java +++ /dev/null @@ -1,1629 +0,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. - */ - -package org.apache.commons.math4.linear; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -import org.apache.commons.math4.analysis.FunctionUtils; -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.analysis.function.Add; -import org.apache.commons.math4.analysis.function.Divide; -import org.apache.commons.math4.analysis.function.Multiply; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.MathUnsupportedOperationException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; - -/** - * Class defining a real-valued vector with basic algebraic operations. - *

- * vector element indexing is 0-based -- e.g., {@code getEntry(0)} - * returns the first element of the vector. - *

- *

- * The {@code code map} and {@code mapToSelf} methods operate - * on vectors element-wise, i.e. they perform the same operation (adding a scalar, - * applying a function ...) on each element in turn. The {@code map} - * versions create a new vector to hold the result and do not change the instance. - * The {@code mapToSelf} version uses the instance itself to store the - * results, so the instance is changed by this method. In all cases, the result - * vector is returned by the methods, allowing the fluent API - * style, like this: - *

- *
- *   RealVector result = v.mapAddToSelf(3.4).mapToSelf(new Tan()).mapToSelf(new Power(2.3));
- * 
- * - * @since 2.1 - */ -public abstract class RealVector { - /** - * Returns the size of the vector. - * - * @return the size of this vector. - */ - public abstract int getDimension(); - - /** - * Return the entry at the specified index. - * - * @param index Index location of entry to be fetched. - * @return the vector entry at {@code index}. - * @throws OutOfRangeException if the index is not valid. - * @see #setEntry(int, double) - */ - public abstract double getEntry(int index) throws OutOfRangeException; - - /** - * Set a single element. - * - * @param index element index. - * @param value new value for the element. - * @throws OutOfRangeException if the index is not valid. - * @see #getEntry(int) - */ - public abstract void setEntry(int index, double value) - throws OutOfRangeException; - - /** - * Change an entry at the specified index. - * - * @param index Index location of entry to be set. - * @param increment Value to add to the vector entry. - * @throws OutOfRangeException if the index is not valid. - * @since 3.0 - */ - public void addToEntry(int index, double increment) - throws OutOfRangeException { - setEntry(index, getEntry(index) + increment); - } - - /** - * Construct a new vector by appending a vector to this vector. - * - * @param v vector to append to this one. - * @return a new vector. - */ - public abstract RealVector append(RealVector v); - - /** - * Construct a new vector by appending a double to this vector. - * - * @param d double to append. - * @return a new vector. - */ - public abstract RealVector append(double d); - - /** - * Get a subvector from consecutive elements. - * - * @param index index of first element. - * @param n number of elements to be retrieved. - * @return a vector containing n elements. - * @throws OutOfRangeException if the index is not valid. - * @throws NotPositiveException if the number of elements is not positive. - */ - public abstract RealVector getSubVector(int index, int n) - throws NotPositiveException, OutOfRangeException; - - /** - * Set a sequence of consecutive elements. - * - * @param index index of first element to be set. - * @param v vector containing the values to set. - * @throws OutOfRangeException if the index is not valid. - */ - public abstract void setSubVector(int index, RealVector v) - throws OutOfRangeException; - - /** - * Check whether any coordinate of this vector is {@code NaN}. - * - * @return {@code true} if any coordinate of this vector is {@code NaN}, - * {@code false} otherwise. - */ - public abstract boolean isNaN(); - - /** - * Check whether any coordinate of this vector is infinite and none are {@code NaN}. - * - * @return {@code true} if any coordinate of this vector is infinite and - * none are {@code NaN}, {@code false} otherwise. - */ - public abstract boolean isInfinite(); - - /** - * Check if instance and specified vectors have the same dimension. - * - * @param v Vector to compare instance with. - * @throws DimensionMismatchException if the vectors do not - * have the same dimension. - */ - protected void checkVectorDimensions(RealVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - } - - /** - * Check if instance dimension is equal to some expected value. - * - * @param n Expected dimension. - * @throws DimensionMismatchException if the dimension is - * inconsistent with the vector size. - */ - protected void checkVectorDimensions(int n) - throws DimensionMismatchException { - int d = getDimension(); - if (d != n) { - throw new DimensionMismatchException(d, n); - } - } - - /** - * Check if an index is valid. - * - * @param index Index to check. - * @exception OutOfRangeException if {@code index} is not valid. - */ - protected void checkIndex(final int index) throws OutOfRangeException { - if (index < 0 || - index >= getDimension()) { - throw new OutOfRangeException(LocalizedFormats.INDEX, - index, 0, getDimension() - 1); - } - } - - /** - * Checks that the indices of a subvector are valid. - * - * @param start the index of the first entry of the subvector - * @param end the index of the last entry of the subvector (inclusive) - * @throws OutOfRangeException if {@code start} of {@code end} are not valid - * @throws NumberIsTooSmallException if {@code end < start} - * @since 3.1 - */ - protected void checkIndices(final int start, final int end) - throws NumberIsTooSmallException, OutOfRangeException { - final int dim = getDimension(); - if ((start < 0) || (start >= dim)) { - throw new OutOfRangeException(LocalizedFormats.INDEX, start, 0, - dim - 1); - } - if ((end < 0) || (end >= dim)) { - throw new OutOfRangeException(LocalizedFormats.INDEX, end, 0, - dim - 1); - } - if (end < start) { - // TODO Use more specific error message - throw new NumberIsTooSmallException(LocalizedFormats.INITIAL_ROW_AFTER_FINAL_ROW, - end, start, false); - } - } - - /** - * Compute the sum of this vector and {@code v}. - * Returns a new vector. Does not change instance data. - * - * @param v Vector to be added. - * @return {@code this} + {@code v}. - * @throws DimensionMismatchException if {@code v} is not the same size as - * {@code this} vector. - */ - public RealVector add(RealVector v) throws DimensionMismatchException { - checkVectorDimensions(v); - RealVector result = v.copy(); - Iterator it = iterator(); - while (it.hasNext()) { - final Entry e = it.next(); - final int index = e.getIndex(); - result.setEntry(index, e.getValue() + result.getEntry(index)); - } - return result; - } - - /** - * Subtract {@code v} from this vector. - * Returns a new vector. Does not change instance data. - * - * @param v Vector to be subtracted. - * @return {@code this} - {@code v}. - * @throws DimensionMismatchException if {@code v} is not the same size as - * {@code this} vector. - */ - public RealVector subtract(RealVector v) throws DimensionMismatchException { - checkVectorDimensions(v); - RealVector result = v.mapMultiply(-1d); - Iterator it = iterator(); - while (it.hasNext()) { - final Entry e = it.next(); - final int index = e.getIndex(); - result.setEntry(index, e.getValue() + result.getEntry(index)); - } - return result; - } - - /** - * Add a value to each entry. - * Returns a new vector. Does not change instance data. - * - * @param d Value to be added to each entry. - * @return {@code this} + {@code d}. - */ - public RealVector mapAdd(double d) { - return copy().mapAddToSelf(d); - } - - /** - * Add a value to each entry. - * The instance is changed in-place. - * - * @param d Value to be added to each entry. - * @return {@code this}. - */ - public RealVector mapAddToSelf(double d) { - if (d != 0) { - return mapToSelf(FunctionUtils.fix2ndArgument(new Add(), d)); - } - return this; - } - - /** - * Returns a (deep) copy of this vector. - * - * @return a vector copy. - */ - public abstract RealVector copy(); - - /** - * Compute the dot product of this vector with {@code v}. - * - * @param v Vector with which dot product should be computed - * @return the scalar dot product between this instance and {@code v}. - * @throws DimensionMismatchException if {@code v} is not the same size as - * {@code this} vector. - */ - public double dotProduct(RealVector v) throws DimensionMismatchException { - checkVectorDimensions(v); - double d = 0; - final int n = getDimension(); - for (int i = 0; i < n; i++) { - d += getEntry(i) * v.getEntry(i); - } - return d; - } - - /** - * Computes the cosine of the angle between this vector and the - * argument. - * - * @param v Vector. - * @return the cosine of the angle between this vector and {@code v}. - * @throws MathArithmeticException if {@code this} or {@code v} is the null - * vector - * @throws DimensionMismatchException if the dimensions of {@code this} and - * {@code v} do not match - */ - public double cosine(RealVector v) throws DimensionMismatchException, - MathArithmeticException { - final double norm = getNorm(); - final double vNorm = v.getNorm(); - - if (norm == 0 || - vNorm == 0) { - throw new MathArithmeticException(LocalizedFormats.ZERO_NORM); - } - return dotProduct(v) / (norm * vNorm); - } - - /** - * Element-by-element division. - * - * @param v Vector by which instance elements must be divided. - * @return a vector containing this[i] / v[i] for all i. - * @throws DimensionMismatchException if {@code v} is not the same size as - * {@code this} vector. - */ - public abstract RealVector ebeDivide(RealVector v) - throws DimensionMismatchException; - - /** - * Element-by-element multiplication. - * - * @param v Vector by which instance elements must be multiplied - * @return a vector containing this[i] * v[i] for all i. - * @throws DimensionMismatchException if {@code v} is not the same size as - * {@code this} vector. - */ - public abstract RealVector ebeMultiply(RealVector v) - throws DimensionMismatchException; - - /** - * Distance between two vectors. - *

This method computes the distance consistent with the - * L2 norm, i.e. the square root of the sum of - * element differences, or Euclidean distance.

- * - * @param v Vector to which distance is requested. - * @return the distance between two vectors. - * @throws DimensionMismatchException if {@code v} is not the same size as - * {@code this} vector. - * @see #getL1Distance(RealVector) - * @see #getLInfDistance(RealVector) - * @see #getNorm() - */ - public double getDistance(RealVector v) throws DimensionMismatchException { - checkVectorDimensions(v); - double d = 0; - Iterator it = iterator(); - while (it.hasNext()) { - final Entry e = it.next(); - final double diff = e.getValue() - v.getEntry(e.getIndex()); - d += diff * diff; - } - return FastMath.sqrt(d); - } - - /** - * Returns the L2 norm of the vector. - *

The L2 norm is the root of the sum of - * the squared elements.

- * - * @return the norm. - * @see #getL1Norm() - * @see #getLInfNorm() - * @see #getDistance(RealVector) - */ - public double getNorm() { - double sum = 0; - Iterator it = iterator(); - while (it.hasNext()) { - final Entry e = it.next(); - final double value = e.getValue(); - sum += value * value; - } - return FastMath.sqrt(sum); - } - - /** - * Returns the L1 norm of the vector. - *

The L1 norm is the sum of the absolute - * values of the elements.

- * - * @return the norm. - * @see #getNorm() - * @see #getLInfNorm() - * @see #getL1Distance(RealVector) - */ - public double getL1Norm() { - double norm = 0; - Iterator it = iterator(); - while (it.hasNext()) { - final Entry e = it.next(); - norm += FastMath.abs(e.getValue()); - } - return norm; - } - - /** - * Returns the L norm of the vector. - *

The L norm is the max of the absolute - * values of the elements.

- * - * @return the norm. - * @see #getNorm() - * @see #getL1Norm() - * @see #getLInfDistance(RealVector) - */ - public double getLInfNorm() { - double norm = 0; - Iterator it = iterator(); - while (it.hasNext()) { - final Entry e = it.next(); - norm = FastMath.max(norm, FastMath.abs(e.getValue())); - } - return norm; - } - - /** - * Distance between two vectors. - *

This method computes the distance consistent with - * L1 norm, i.e. the sum of the absolute values of - * the elements differences.

- * - * @param v Vector to which distance is requested. - * @return the distance between two vectors. - * @throws DimensionMismatchException if {@code v} is not the same size as - * {@code this} vector. - */ - public double getL1Distance(RealVector v) - throws DimensionMismatchException { - checkVectorDimensions(v); - double d = 0; - Iterator it = iterator(); - while (it.hasNext()) { - final Entry e = it.next(); - d += FastMath.abs(e.getValue() - v.getEntry(e.getIndex())); - } - return d; - } - - /** - * Distance between two vectors. - *

This method computes the distance consistent with - * L norm, i.e. the max of the absolute values of - * element differences.

- * - * @param v Vector to which distance is requested. - * @return the distance between two vectors. - * @throws DimensionMismatchException if {@code v} is not the same size as - * {@code this} vector. - * @see #getDistance(RealVector) - * @see #getL1Distance(RealVector) - * @see #getLInfNorm() - */ - public double getLInfDistance(RealVector v) - throws DimensionMismatchException { - checkVectorDimensions(v); - double d = 0; - Iterator it = iterator(); - while (it.hasNext()) { - final Entry e = it.next(); - d = FastMath.max(FastMath.abs(e.getValue() - v.getEntry(e.getIndex())), d); - } - return d; - } - - /** - * Get the index of the minimum entry. - * - * @return the index of the minimum entry or -1 if vector length is 0 - * or all entries are {@code NaN}. - */ - public int getMinIndex() { - int minIndex = -1; - double minValue = Double.POSITIVE_INFINITY; - Iterator iterator = iterator(); - while (iterator.hasNext()) { - final Entry entry = iterator.next(); - if (entry.getValue() <= minValue) { - minIndex = entry.getIndex(); - minValue = entry.getValue(); - } - } - return minIndex; - } - - /** - * Get the value of the minimum entry. - * - * @return the value of the minimum entry or {@code NaN} if all - * entries are {@code NaN}. - */ - public double getMinValue() { - final int minIndex = getMinIndex(); - return minIndex < 0 ? Double.NaN : getEntry(minIndex); - } - - /** - * Get the index of the maximum entry. - * - * @return the index of the maximum entry or -1 if vector length is 0 - * or all entries are {@code NaN} - */ - public int getMaxIndex() { - int maxIndex = -1; - double maxValue = Double.NEGATIVE_INFINITY; - Iterator iterator = iterator(); - while (iterator.hasNext()) { - final Entry entry = iterator.next(); - if (entry.getValue() >= maxValue) { - maxIndex = entry.getIndex(); - maxValue = entry.getValue(); - } - } - return maxIndex; - } - - /** - * Get the value of the maximum entry. - * - * @return the value of the maximum entry or {@code NaN} if all - * entries are {@code NaN}. - */ - public double getMaxValue() { - final int maxIndex = getMaxIndex(); - return maxIndex < 0 ? Double.NaN : getEntry(maxIndex); - } - - - /** - * Multiply each entry by the argument. Returns a new vector. - * Does not change instance data. - * - * @param d Multiplication factor. - * @return {@code this} * {@code d}. - */ - public RealVector mapMultiply(double d) { - return copy().mapMultiplyToSelf(d); - } - - /** - * Multiply each entry. - * The instance is changed in-place. - * - * @param d Multiplication factor. - * @return {@code this}. - */ - public RealVector mapMultiplyToSelf(double d){ - return mapToSelf(FunctionUtils.fix2ndArgument(new Multiply(), d)); - } - - /** - * Subtract a value from each entry. Returns a new vector. - * Does not change instance data. - * - * @param d Value to be subtracted. - * @return {@code this} - {@code d}. - */ - public RealVector mapSubtract(double d) { - return copy().mapSubtractToSelf(d); - } - - /** - * Subtract a value from each entry. - * The instance is changed in-place. - * - * @param d Value to be subtracted. - * @return {@code this}. - */ - public RealVector mapSubtractToSelf(double d){ - return mapAddToSelf(-d); - } - - /** - * Divide each entry by the argument. Returns a new vector. - * Does not change instance data. - * - * @param d Value to divide by. - * @return {@code this} / {@code d}. - */ - public RealVector mapDivide(double d) { - return copy().mapDivideToSelf(d); - } - - /** - * Divide each entry by the argument. - * The instance is changed in-place. - * - * @param d Value to divide by. - * @return {@code this}. - */ - public RealVector mapDivideToSelf(double d){ - return mapToSelf(FunctionUtils.fix2ndArgument(new Divide(), d)); - } - - /** - * Compute the outer product. - * - * @param v Vector with which outer product should be computed. - * @return the matrix outer product between this instance and {@code v}. - */ - public RealMatrix outerProduct(RealVector v) { - final int m = this.getDimension(); - final int n = v.getDimension(); - final RealMatrix product; - if (v instanceof SparseRealVector || this instanceof SparseRealVector) { - product = new OpenMapRealMatrix(m, n); - } else { - product = new Array2DRowRealMatrix(m, n); - } - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - product.setEntry(i, j, this.getEntry(i) * v.getEntry(j)); - } - } - return product; - } - - /** - * Find the orthogonal projection of this vector onto another vector. - * - * @param v vector onto which instance must be projected. - * @return projection of the instance onto {@code v}. - * @throws DimensionMismatchException if {@code v} is not the same size as - * {@code this} vector. - * @throws MathArithmeticException if {@code this} or {@code v} is the null - * vector - */ - public RealVector projection(final RealVector v) - throws DimensionMismatchException, MathArithmeticException { - final double norm2 = v.dotProduct(v); - if (norm2 == 0.0) { - throw new MathArithmeticException(LocalizedFormats.ZERO_NORM); - } - return v.mapMultiply(dotProduct(v) / v.dotProduct(v)); - } - - /** - * Set all elements to a single value. - * - * @param value Single value to set for all elements. - */ - public void set(double value) { - Iterator it = iterator(); - while (it.hasNext()) { - final Entry e = it.next(); - e.setValue(value); - } - } - - /** - * Convert the vector to an array of {@code double}s. - * The array is independent from this vector data: the elements - * are copied. - * - * @return an array containing a copy of the vector elements. - */ - public double[] toArray() { - int dim = getDimension(); - double[] values = new double[dim]; - for (int i = 0; i < dim; i++) { - values[i] = getEntry(i); - } - return values; - } - - /** - * Creates a unit vector pointing in the direction of this vector. - * The instance is not changed by this method. - * - * @return a unit vector pointing in direction of this vector. - * @throws MathArithmeticException if the norm is zero. - */ - public RealVector unitVector() throws MathArithmeticException { - final double norm = getNorm(); - if (norm == 0) { - throw new MathArithmeticException(LocalizedFormats.ZERO_NORM); - } - return mapDivide(norm); - } - - /** - * Converts this vector into a unit vector. - * The instance itself is changed by this method. - * - * @throws MathArithmeticException if the norm is zero. - */ - public void unitize() throws MathArithmeticException { - final double norm = getNorm(); - if (norm == 0) { - throw new MathArithmeticException(LocalizedFormats.ZERO_NORM); - } - mapDivideToSelf(getNorm()); - } - - /** - * Create a sparse iterator over the vector, which may omit some entries. - * The ommitted entries are either exact zeroes (for dense implementations) - * or are the entries which are not stored (for real sparse vectors). - * No guarantees are made about order of iteration. - * - *

Note: derived classes are required to return an {@link Iterator} that - * returns non-null {@link Entry} objects as long as {@link Iterator#hasNext()} - * returns {@code true}.

- * - * @return a sparse iterator. - */ - public Iterator sparseIterator() { - return new SparseEntryIterator(); - } - - /** - * Generic dense iterator. Iteration is in increasing order - * of the vector index. - * - *

Note: derived classes are required to return an {@link Iterator} that - * returns non-null {@link Entry} objects as long as {@link Iterator#hasNext()} - * returns {@code true}.

- * - * @return a dense iterator. - */ - public Iterator iterator() { - final int dim = getDimension(); - return new Iterator() { - - /** Current index. */ - private int i = 0; - - /** Current entry. */ - private Entry e = new Entry(); - - /** {@inheritDoc} */ - @Override - public boolean hasNext() { - return i < dim; - } - - /** {@inheritDoc} */ - @Override - public Entry next() { - if (i < dim) { - e.setIndex(i++); - return e; - } else { - throw new NoSuchElementException(); - } - } - - /** - * {@inheritDoc} - * - * @throws MathUnsupportedOperationException in all circumstances. - */ - @Override - public void remove() throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - }; - } - - /** - * Acts as if implemented as: - *
-     *  return copy().mapToSelf(function);
-     * 
- * Returns a new vector. Does not change instance data. - * - * @param function Function to apply to each entry. - * @return a new vector. - */ - public RealVector map(UnivariateFunction function) { - return copy().mapToSelf(function); - } - - /** - * Acts as if it is implemented as: - * {@code - * Entry e = null; - * for(Iterator it = iterator(); it.hasNext(); e = it.next()) { - * e.setValue(function.value(e.getValue())); - * } - * } - * Entries of this vector are modified in-place by this method. - * - * @param function Function to apply to each entry. - * @return a reference to this vector. - */ - public RealVector mapToSelf(UnivariateFunction function) { - Iterator it = iterator(); - while (it.hasNext()) { - final Entry e = it.next(); - e.setValue(function.value(e.getValue())); - } - return this; - } - - /** - * Returns a new vector representing {@code a * this + b * y}, the linear - * combination of {@code this} and {@code y}. - * Returns a new vector. Does not change instance data. - * - * @param a Coefficient of {@code this}. - * @param b Coefficient of {@code y}. - * @param y Vector with which {@code this} is linearly combined. - * @return a vector containing {@code a * this[i] + b * y[i]} for all - * {@code i}. - * @throws DimensionMismatchException if {@code y} is not the same size as - * {@code this} vector. - */ - public RealVector combine(double a, double b, RealVector y) - throws DimensionMismatchException { - return copy().combineToSelf(a, b, y); - } - - /** - * Updates {@code this} with the linear combination of {@code this} and - * {@code y}. - * - * @param a Weight of {@code this}. - * @param b Weight of {@code y}. - * @param y Vector with which {@code this} is linearly combined. - * @return {@code this}, with components equal to - * {@code a * this[i] + b * y[i]} for all {@code i}. - * @throws DimensionMismatchException if {@code y} is not the same size as - * {@code this} vector. - */ - public RealVector combineToSelf(double a, double b, RealVector y) - throws DimensionMismatchException { - checkVectorDimensions(y); - for (int i = 0; i < getDimension(); i++) { - final double xi = getEntry(i); - final double yi = y.getEntry(i); - setEntry(i, a * xi + b * yi); - } - return this; - } - - /** - * Visits (but does not alter) all entries of this vector in default order - * (increasing index). - * - * @param visitor the visitor to be used to process the entries of this - * vector - * @return the value returned by {@link RealVectorPreservingVisitor#end()} - * at the end of the walk - * @since 3.1 - */ - public double walkInDefaultOrder(final RealVectorPreservingVisitor visitor) { - final int dim = getDimension(); - visitor.start(dim, 0, dim - 1); - for (int i = 0; i < dim; i++) { - visitor.visit(i, getEntry(i)); - } - return visitor.end(); - } - - /** - * Visits (but does not alter) some entries of this vector in default order - * (increasing index). - * - * @param visitor visitor to be used to process the entries of this vector - * @param start the index of the first entry to be visited - * @param end the index of the last entry to be visited (inclusive) - * @return the value returned by {@link RealVectorPreservingVisitor#end()} - * at the end of the walk - * @throws NumberIsTooSmallException if {@code end < start}. - * @throws OutOfRangeException if the indices are not valid. - * @since 3.1 - */ - public double walkInDefaultOrder(final RealVectorPreservingVisitor visitor, - final int start, final int end) - throws NumberIsTooSmallException, OutOfRangeException { - checkIndices(start, end); - visitor.start(getDimension(), start, end); - for (int i = start; i <= end; i++) { - visitor.visit(i, getEntry(i)); - } - return visitor.end(); - } - - /** - * Visits (but does not alter) all entries of this vector in optimized - * order. The order in which the entries are visited is selected so as to - * lead to the most efficient implementation; it might depend on the - * concrete implementation of this abstract class. - * - * @param visitor the visitor to be used to process the entries of this - * vector - * @return the value returned by {@link RealVectorPreservingVisitor#end()} - * at the end of the walk - * @since 3.1 - */ - public double walkInOptimizedOrder(final RealVectorPreservingVisitor visitor) { - return walkInDefaultOrder(visitor); - } - - /** - * Visits (but does not alter) some entries of this vector in optimized - * order. The order in which the entries are visited is selected so as to - * lead to the most efficient implementation; it might depend on the - * concrete implementation of this abstract class. - * - * @param visitor visitor to be used to process the entries of this vector - * @param start the index of the first entry to be visited - * @param end the index of the last entry to be visited (inclusive) - * @return the value returned by {@link RealVectorPreservingVisitor#end()} - * at the end of the walk - * @throws NumberIsTooSmallException if {@code end < start}. - * @throws OutOfRangeException if the indices are not valid. - * @since 3.1 - */ - public double walkInOptimizedOrder(final RealVectorPreservingVisitor visitor, - final int start, final int end) - throws NumberIsTooSmallException, OutOfRangeException { - return walkInDefaultOrder(visitor, start, end); - } - - /** - * Visits (and possibly alters) all entries of this vector in default order - * (increasing index). - * - * @param visitor the visitor to be used to process and modify the entries - * of this vector - * @return the value returned by {@link RealVectorChangingVisitor#end()} - * at the end of the walk - * @since 3.1 - */ - public double walkInDefaultOrder(final RealVectorChangingVisitor visitor) { - final int dim = getDimension(); - visitor.start(dim, 0, dim - 1); - for (int i = 0; i < dim; i++) { - setEntry(i, visitor.visit(i, getEntry(i))); - } - return visitor.end(); - } - - /** - * Visits (and possibly alters) some entries of this vector in default order - * (increasing index). - * - * @param visitor visitor to be used to process the entries of this vector - * @param start the index of the first entry to be visited - * @param end the index of the last entry to be visited (inclusive) - * @return the value returned by {@link RealVectorChangingVisitor#end()} - * at the end of the walk - * @throws NumberIsTooSmallException if {@code end < start}. - * @throws OutOfRangeException if the indices are not valid. - * @since 3.1 - */ - public double walkInDefaultOrder(final RealVectorChangingVisitor visitor, - final int start, final int end) - throws NumberIsTooSmallException, OutOfRangeException { - checkIndices(start, end); - visitor.start(getDimension(), start, end); - for (int i = start; i <= end; i++) { - setEntry(i, visitor.visit(i, getEntry(i))); - } - return visitor.end(); - } - - /** - * Visits (and possibly alters) all entries of this vector in optimized - * order. The order in which the entries are visited is selected so as to - * lead to the most efficient implementation; it might depend on the - * concrete implementation of this abstract class. - * - * @param visitor the visitor to be used to process the entries of this - * vector - * @return the value returned by {@link RealVectorChangingVisitor#end()} - * at the end of the walk - * @since 3.1 - */ - public double walkInOptimizedOrder(final RealVectorChangingVisitor visitor) { - return walkInDefaultOrder(visitor); - } - - /** - * Visits (and possibly change) some entries of this vector in optimized - * order. The order in which the entries are visited is selected so as to - * lead to the most efficient implementation; it might depend on the - * concrete implementation of this abstract class. - * - * @param visitor visitor to be used to process the entries of this vector - * @param start the index of the first entry to be visited - * @param end the index of the last entry to be visited (inclusive) - * @return the value returned by {@link RealVectorChangingVisitor#end()} - * at the end of the walk - * @throws NumberIsTooSmallException if {@code end < start}. - * @throws OutOfRangeException if the indices are not valid. - * @since 3.1 - */ - public double walkInOptimizedOrder(final RealVectorChangingVisitor visitor, - final int start, final int end) - throws NumberIsTooSmallException, OutOfRangeException { - return walkInDefaultOrder(visitor, start, end); - } - - /** An entry in the vector. */ - protected class Entry { - /** Index of this entry. */ - private int index; - - /** Simple constructor. */ - public Entry() { - setIndex(0); - } - - /** - * Get the value of the entry. - * - * @return the value of the entry. - */ - public double getValue() { - return getEntry(getIndex()); - } - - /** - * Set the value of the entry. - * - * @param value New value for the entry. - */ - public void setValue(double value) { - setEntry(getIndex(), value); - } - - /** - * Get the index of the entry. - * - * @return the index of the entry. - */ - public int getIndex() { - return index; - } - - /** - * Set the index of the entry. - * - * @param index New index for the entry. - */ - public void setIndex(int index) { - this.index = index; - } - } - - /** - *

- * Test for the equality of two real vectors. If all coordinates of two real - * vectors are exactly the same, and none are {@code NaN}, the two real - * vectors are considered to be equal. {@code NaN} coordinates are - * considered to affect globally the vector and be equals to each other - - * i.e, if either (or all) coordinates of the real vector are equal to - * {@code NaN}, the real vector is equal to a vector with all {@code NaN} - * coordinates. - *

- *

- * This method must be overriden by concrete subclasses of - * {@link RealVector} (the current implementation throws an exception). - *

- * - * @param other Object to test for equality. - * @return {@code true} if two vector objects are equal, {@code false} if - * {@code other} is null, not an instance of {@code RealVector}, or - * not equal to this {@code RealVector} instance. - * @throws MathUnsupportedOperationException if this method is not - * overridden. - */ - @Override - public boolean equals(Object other) - throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - - /** - * {@inheritDoc}. This method must be overriden by concrete - * subclasses of {@link RealVector} (current implementation throws an - * exception). - * - * @throws MathUnsupportedOperationException if this method is not - * overridden. - */ - @Override - public int hashCode() throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - - /** - * This class should rarely be used, but is here to provide - * a default implementation of sparseIterator(), which is implemented - * by walking over the entries, skipping those that are zero. - * - * Concrete subclasses which are SparseVector implementations should - * make their own sparse iterator, rather than using this one. - * - * This implementation might be useful for ArrayRealVector, when expensive - * operations which preserve the default value are to be done on the entries, - * and the fraction of non-default values is small (i.e. someone took a - * SparseVector, and passed it into the copy-constructor of ArrayRealVector) - - */ - protected class SparseEntryIterator implements Iterator { - /** Dimension of the vector. */ - private final int dim; - /** Last entry returned by {@link #next()}. */ - private Entry current; - /** Next entry for {@link #next()} to return. */ - private Entry next; - - /** Simple constructor. */ - protected SparseEntryIterator() { - dim = getDimension(); - current = new Entry(); - next = new Entry(); - if (next.getValue() == 0) { - advance(next); - } - } - - /** - * Advance an entry up to the next nonzero one. - * - * @param e entry to advance. - */ - protected void advance(Entry e) { - if (e == null) { - return; - } - do { - e.setIndex(e.getIndex() + 1); - } while (e.getIndex() < dim && e.getValue() == 0); - if (e.getIndex() >= dim) { - e.setIndex(-1); - } - } - - /** {@inheritDoc} */ - @Override - public boolean hasNext() { - return next.getIndex() >= 0; - } - - /** {@inheritDoc} */ - @Override - public Entry next() { - int index = next.getIndex(); - if (index < 0) { - throw new NoSuchElementException(); - } - current.setIndex(index); - advance(next); - return current; - } - - /** - * {@inheritDoc} - * - * @throws MathUnsupportedOperationException in all circumstances. - */ - @Override - public void remove() throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - } - - /** - * Returns an unmodifiable view of the specified vector. - * The returned vector has read-only access. An attempt to modify it will - * result in a {@link MathUnsupportedOperationException}. However, the - * returned vector is not immutable, since any modification of - * {@code v} will also change the returned view. - * For example, in the following piece of code - *
-     *     RealVector v = new ArrayRealVector(2);
-     *     RealVector w = RealVector.unmodifiableRealVector(v);
-     *     v.setEntry(0, 1.2);
-     *     v.setEntry(1, -3.4);
-     * 
- * the changes will be seen in the {@code w} view of {@code v}. - * - * @param v Vector for which an unmodifiable view is to be returned. - * @return an unmodifiable view of {@code v}. - */ - public static RealVector unmodifiableRealVector(final RealVector v) { - /** - * This anonymous class is an implementation of {@link RealVector} - * with read-only access. - * It wraps any {@link RealVector}, and exposes all methods which - * do not modify it. Invoking methods which should normally result - * in the modification of the calling {@link RealVector} results in - * a {@link MathUnsupportedOperationException}. It should be noted - * that {@link UnmodifiableVector} is not immutable. - */ - return new RealVector() { - /** - * {@inheritDoc} - * - * @throws MathUnsupportedOperationException in all circumstances. - */ - @Override - public RealVector mapToSelf(UnivariateFunction function) - throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - - /** {@inheritDoc} */ - @Override - public RealVector map(UnivariateFunction function) { - return v.map(function); - } - - /** {@inheritDoc} */ - @Override - public Iterator iterator() { - final Iterator i = v.iterator(); - return new Iterator() { - /** The current entry. */ - private final UnmodifiableEntry e = new UnmodifiableEntry(); - - /** {@inheritDoc} */ - @Override - public boolean hasNext() { - return i.hasNext(); - } - - /** {@inheritDoc} */ - @Override - public Entry next() { - e.setIndex(i.next().getIndex()); - return e; - } - - /** - * {@inheritDoc} - * - * @throws MathUnsupportedOperationException in all - * circumstances. - */ - @Override - public void remove() throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - }; - } - - /** {@inheritDoc} */ - @Override - public Iterator sparseIterator() { - final Iterator i = v.sparseIterator(); - - return new Iterator() { - /** The current entry. */ - private final UnmodifiableEntry e = new UnmodifiableEntry(); - - /** {@inheritDoc} */ - @Override - public boolean hasNext() { - return i.hasNext(); - } - - /** {@inheritDoc} */ - @Override - public Entry next() { - e.setIndex(i.next().getIndex()); - return e; - } - - /** - * {@inheritDoc} - * - * @throws MathUnsupportedOperationException in all - * circumstances. - */ - @Override - public void remove() - throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - }; - } - - /** {@inheritDoc} */ - @Override - public RealVector copy() { - return v.copy(); - } - - /** {@inheritDoc} */ - @Override - public RealVector add(RealVector w) - throws DimensionMismatchException { - return v.add(w); - } - - /** {@inheritDoc} */ - @Override - public RealVector subtract(RealVector w) - throws DimensionMismatchException { - return v.subtract(w); - } - - /** {@inheritDoc} */ - @Override - public RealVector mapAdd(double d) { - return v.mapAdd(d); - } - - /** - * {@inheritDoc} - * - * @throws MathUnsupportedOperationException in all - * circumstances. - */ - @Override - public RealVector mapAddToSelf(double d) - throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - - /** {@inheritDoc} */ - @Override - public RealVector mapSubtract(double d) { - return v.mapSubtract(d); - } - - /** - * {@inheritDoc} - * - * @throws MathUnsupportedOperationException in all - * circumstances. - */ - @Override - public RealVector mapSubtractToSelf(double d) - throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - - /** {@inheritDoc} */ - @Override - public RealVector mapMultiply(double d) { - return v.mapMultiply(d); - } - - /** - * {@inheritDoc} - * - * @throws MathUnsupportedOperationException in all - * circumstances. - */ - @Override - public RealVector mapMultiplyToSelf(double d) - throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - - /** {@inheritDoc} */ - @Override - public RealVector mapDivide(double d) { - return v.mapDivide(d); - } - - /** - * {@inheritDoc} - * - * @throws MathUnsupportedOperationException in all - * circumstances. - */ - @Override - public RealVector mapDivideToSelf(double d) - throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - - /** {@inheritDoc} */ - @Override - public RealVector ebeMultiply(RealVector w) - throws DimensionMismatchException { - return v.ebeMultiply(w); - } - - /** {@inheritDoc} */ - @Override - public RealVector ebeDivide(RealVector w) - throws DimensionMismatchException { - return v.ebeDivide(w); - } - - /** {@inheritDoc} */ - @Override - public double dotProduct(RealVector w) - throws DimensionMismatchException { - return v.dotProduct(w); - } - - /** {@inheritDoc} */ - @Override - public double cosine(RealVector w) - throws DimensionMismatchException, MathArithmeticException { - return v.cosine(w); - } - - /** {@inheritDoc} */ - @Override - public double getNorm() { - return v.getNorm(); - } - - /** {@inheritDoc} */ - @Override - public double getL1Norm() { - return v.getL1Norm(); - } - - /** {@inheritDoc} */ - @Override - public double getLInfNorm() { - return v.getLInfNorm(); - } - - /** {@inheritDoc} */ - @Override - public double getDistance(RealVector w) - throws DimensionMismatchException { - return v.getDistance(w); - } - - /** {@inheritDoc} */ - @Override - public double getL1Distance(RealVector w) - throws DimensionMismatchException { - return v.getL1Distance(w); - } - - /** {@inheritDoc} */ - @Override - public double getLInfDistance(RealVector w) - throws DimensionMismatchException { - return v.getLInfDistance(w); - } - - /** {@inheritDoc} */ - @Override - public RealVector unitVector() throws MathArithmeticException { - return v.unitVector(); - } - - /** - * {@inheritDoc} - * - * @throws MathUnsupportedOperationException in all - * circumstances. - */ - @Override - public void unitize() throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - - /** {@inheritDoc} */ - @Override - public RealMatrix outerProduct(RealVector w) { - return v.outerProduct(w); - } - - /** {@inheritDoc} */ - @Override - public double getEntry(int index) throws OutOfRangeException { - return v.getEntry(index); - } - - /** - * {@inheritDoc} - * - * @throws MathUnsupportedOperationException in all - * circumstances. - */ - @Override - public void setEntry(int index, double value) - throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - - /** - * {@inheritDoc} - * - * @throws MathUnsupportedOperationException in all - * circumstances. - */ - @Override - public void addToEntry(int index, double value) - throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - - /** {@inheritDoc} */ - @Override - public int getDimension() { - return v.getDimension(); - } - - /** {@inheritDoc} */ - @Override - public RealVector append(RealVector w) { - return v.append(w); - } - - /** {@inheritDoc} */ - @Override - public RealVector append(double d) { - return v.append(d); - } - - /** {@inheritDoc} */ - @Override - public RealVector getSubVector(int index, int n) - throws OutOfRangeException, NotPositiveException { - return v.getSubVector(index, n); - } - - /** - * {@inheritDoc} - * - * @throws MathUnsupportedOperationException in all - * circumstances. - */ - @Override - public void setSubVector(int index, RealVector w) - throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - - /** - * {@inheritDoc} - * - * @throws MathUnsupportedOperationException in all - * circumstances. - */ - @Override - public void set(double value) - throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - - /** {@inheritDoc} */ - @Override - public double[] toArray() { - return v.toArray(); - } - - /** {@inheritDoc} */ - @Override - public boolean isNaN() { - return v.isNaN(); - } - - /** {@inheritDoc} */ - @Override - public boolean isInfinite() { - return v.isInfinite(); - } - - /** {@inheritDoc} */ - @Override - public RealVector combine(double a, double b, RealVector y) - throws DimensionMismatchException { - return v.combine(a, b, y); - } - - /** - * {@inheritDoc} - * - * @throws MathUnsupportedOperationException in all - * circumstances. - */ - @Override - public RealVector combineToSelf(double a, double b, RealVector y) - throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - - /** An entry in the vector. */ - class UnmodifiableEntry extends Entry { - /** {@inheritDoc} */ - @Override - public double getValue() { - return v.getEntry(getIndex()); - } - - /** - * {@inheritDoc} - * - * @throws MathUnsupportedOperationException in all - * circumstances. - */ - @Override - public void setValue(double value) - throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealVectorChangingVisitor.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealVectorChangingVisitor.java deleted file mode 100644 index 2aa9d0b93..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealVectorChangingVisitor.java +++ /dev/null @@ -1,58 +0,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. - */ -package org.apache.commons.math4.linear; - -/** - * This interface defines a visitor for the entries of a vector. Visitors - * implementing this interface may alter the entries of the vector being - * visited. - * - * @since 3.1 - */ -public interface RealVectorChangingVisitor { - /** - * Start visiting a vector. This method is called once, before any entry - * of the vector is visited. - * - * @param dimension the size of the vector - * @param start the index of the first entry to be visited - * @param end the index of the last entry to be visited (inclusive) - */ - void start(int dimension, int start, int end); - - /** - * Visit one entry of the vector. - * - * @param index the index of the entry being visited - * @param value the value of the entry being visited - * @return the new value of the entry being visited - */ - double visit(int index, double value); - - /** - * End visiting a vector. This method is called once, after all entries of - * the vector have been visited. - * - * @return the value returned by - * {@link RealVector#walkInDefaultOrder(RealVectorChangingVisitor)}, - * {@link RealVector#walkInDefaultOrder(RealVectorChangingVisitor, int, int)}, - * {@link RealVector#walkInOptimizedOrder(RealVectorChangingVisitor)} - * or - * {@link RealVector#walkInOptimizedOrder(RealVectorChangingVisitor, int, int)} - */ - double end(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealVectorFormat.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealVectorFormat.java deleted file mode 100644 index 2ffb37865..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealVectorFormat.java +++ /dev/null @@ -1,288 +0,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. - */ - -package org.apache.commons.math4.linear; - -import java.text.FieldPosition; -import java.text.NumberFormat; -import java.text.ParsePosition; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import org.apache.commons.math4.exception.MathParseException; -import org.apache.commons.math4.util.CompositeFormat; - -/** - * Formats a vector in components list format "{v0; v1; ...; vk-1}". - *

The prefix and suffix "{" and "}" and the separator "; " can be replaced by - * any user-defined strings. The number format for components can be configured.

- *

White space is ignored at parse time, even if it is in the prefix, suffix - * or separator specifications. So even if the default separator does include a space - * character that is used at format time, both input string "{1;1;1}" and - * " { 1 ; 1 ; 1 } " will be parsed without error and the same vector will be - * returned. In the second case, however, the parse position after parsing will be - * just after the closing curly brace, i.e. just before the trailing space.

- * - * @since 2.0 - */ -public class RealVectorFormat { - - /** The default prefix: "{". */ - private static final String DEFAULT_PREFIX = "{"; - /** The default suffix: "}". */ - private static final String DEFAULT_SUFFIX = "}"; - /** The default separator: ", ". */ - private static final String DEFAULT_SEPARATOR = "; "; - /** Prefix. */ - private final String prefix; - /** Suffix. */ - private final String suffix; - /** Separator. */ - private final String separator; - /** Trimmed prefix. */ - private final String trimmedPrefix; - /** Trimmed suffix. */ - private final String trimmedSuffix; - /** Trimmed separator. */ - private final String trimmedSeparator; - /** The format used for components. */ - private final NumberFormat format; - - /** - * Create an instance with default settings. - *

The instance uses the default prefix, suffix and separator: - * "{", "}", and "; " and the default number format for components.

- */ - public RealVectorFormat() { - this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR, - CompositeFormat.getDefaultNumberFormat()); - } - - /** - * Create an instance with a custom number format for components. - * @param format the custom format for components. - */ - public RealVectorFormat(final NumberFormat format) { - this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR, format); - } - - /** - * Create an instance with custom prefix, suffix and separator. - * @param prefix prefix to use instead of the default "{" - * @param suffix suffix to use instead of the default "}" - * @param separator separator to use instead of the default "; " - */ - public RealVectorFormat(final String prefix, final String suffix, - final String separator) { - this(prefix, suffix, separator, - CompositeFormat.getDefaultNumberFormat()); - } - - /** - * Create an instance with custom prefix, suffix, separator and format - * for components. - * @param prefix prefix to use instead of the default "{" - * @param suffix suffix to use instead of the default "}" - * @param separator separator to use instead of the default "; " - * @param format the custom format for components. - */ - public RealVectorFormat(final String prefix, final String suffix, - final String separator, final NumberFormat format) { - this.prefix = prefix; - this.suffix = suffix; - this.separator = separator; - trimmedPrefix = prefix.trim(); - trimmedSuffix = suffix.trim(); - trimmedSeparator = separator.trim(); - this.format = format; - } - - /** - * Get the set of locales for which real vectors formats are available. - *

This is the same set as the {@link NumberFormat} set.

- * @return available real vector format locales. - */ - public static Locale[] getAvailableLocales() { - return NumberFormat.getAvailableLocales(); - } - - /** - * Get the format prefix. - * @return format prefix. - */ - public String getPrefix() { - return prefix; - } - - /** - * Get the format suffix. - * @return format suffix. - */ - public String getSuffix() { - return suffix; - } - - /** - * Get the format separator between components. - * @return format separator. - */ - public String getSeparator() { - return separator; - } - - /** - * Get the components format. - * @return components format. - */ - public NumberFormat getFormat() { - return format; - } - - /** - * Returns the default real vector format for the current locale. - * @return the default real vector format. - */ - public static RealVectorFormat getInstance() { - return getInstance(Locale.getDefault()); - } - - /** - * Returns the default real vector format for the given locale. - * @param locale the specific locale used by the format. - * @return the real vector format specific to the given locale. - */ - public static RealVectorFormat getInstance(final Locale locale) { - return new RealVectorFormat(CompositeFormat.getDefaultNumberFormat(locale)); - } - - /** - * This method calls {@link #format(RealVector,StringBuffer,FieldPosition)}. - * - * @param v RealVector object to format. - * @return a formatted vector. - */ - public String format(RealVector v) { - return format(v, new StringBuffer(), new FieldPosition(0)).toString(); - } - - /** - * Formats a {@link RealVector} object to produce a string. - * @param vector the object to format. - * @param toAppendTo where the text is to be appended - * @param pos On input: an alignment field, if desired. On output: the - * offsets of the alignment field - * @return the value passed in as toAppendTo. - */ - public StringBuffer format(RealVector vector, StringBuffer toAppendTo, - FieldPosition pos) { - - pos.setBeginIndex(0); - pos.setEndIndex(0); - - // format prefix - toAppendTo.append(prefix); - - // format components - for (int i = 0; i < vector.getDimension(); ++i) { - if (i > 0) { - toAppendTo.append(separator); - } - CompositeFormat.formatDouble(vector.getEntry(i), format, toAppendTo, pos); - } - - // format suffix - toAppendTo.append(suffix); - - return toAppendTo; - } - - /** - * Parse a string to produce a {@link RealVector} object. - * - * @param source String to parse. - * @return the parsed {@link RealVector} object. - * @throws MathParseException if the beginning of the specified string - * cannot be parsed. - */ - public ArrayRealVector parse(String source) { - final ParsePosition parsePosition = new ParsePosition(0); - final ArrayRealVector result = parse(source, parsePosition); - if (parsePosition.getIndex() == 0) { - throw new MathParseException(source, - parsePosition.getErrorIndex(), - ArrayRealVector.class); - } - return result; - } - - /** - * Parse a string to produce a {@link RealVector} object. - * - * @param source String to parse. - * @param pos input/ouput parsing parameter. - * @return the parsed {@link RealVector} object. - */ - public ArrayRealVector parse(String source, ParsePosition pos) { - int initialIndex = pos.getIndex(); - - // parse prefix - CompositeFormat.parseAndIgnoreWhitespace(source, pos); - if (!CompositeFormat.parseFixedstring(source, trimmedPrefix, pos)) { - return null; - } - - // parse components - List components = new ArrayList<>(); - for (boolean loop = true; loop;){ - - if (!components.isEmpty()) { - CompositeFormat.parseAndIgnoreWhitespace(source, pos); - if (!CompositeFormat.parseFixedstring(source, trimmedSeparator, pos)) { - loop = false; - } - } - - if (loop) { - CompositeFormat.parseAndIgnoreWhitespace(source, pos); - Number component = CompositeFormat.parseNumber(source, format, pos); - if (component != null) { - components.add(component); - } else { - // invalid component - // set index back to initial, error index should already be set - pos.setIndex(initialIndex); - return null; - } - } - - } - - // parse suffix - CompositeFormat.parseAndIgnoreWhitespace(source, pos); - if (!CompositeFormat.parseFixedstring(source, trimmedSuffix, pos)) { - return null; - } - - // build vector - double[] data = new double[components.size()]; - for (int i = 0; i < data.length; ++i) { - data[i] = components.get(i).doubleValue(); - } - return new ArrayRealVector(data, false); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealVectorPreservingVisitor.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealVectorPreservingVisitor.java deleted file mode 100644 index 60d5f9dc1..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RealVectorPreservingVisitor.java +++ /dev/null @@ -1,57 +0,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. - */ -package org.apache.commons.math4.linear; - -/** - * This interface defines a visitor for the entries of a vector. Visitors - * implementing this interface do not alter the entries of the vector being - * visited. - * - * @since 3.1 - */ -public interface RealVectorPreservingVisitor { - /** - * Start visiting a vector. This method is called once, before any entry - * of the vector is visited. - * - * @param dimension the size of the vector - * @param start the index of the first entry to be visited - * @param end the index of the last entry to be visited (inclusive) - */ - void start(int dimension, int start, int end); - - /** - * Visit one entry of the vector. - * - * @param index the index of the entry being visited - * @param value the value of the entry being visited - */ - void visit(int index, double value); - - /** - * End visiting a vector. This method is called once, after all entries of - * the vector have been visited. - * - * @return the value returned by - * {@link RealVector#walkInDefaultOrder(RealVectorPreservingVisitor)}, - * {@link RealVector#walkInDefaultOrder(RealVectorPreservingVisitor, int, int)}, - * {@link RealVector#walkInOptimizedOrder(RealVectorPreservingVisitor)} - * or - * {@link RealVector#walkInOptimizedOrder(RealVectorPreservingVisitor, int, int)} - */ - double end(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RectangularCholeskyDecomposition.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RectangularCholeskyDecomposition.java deleted file mode 100644 index 16e446f87..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/RectangularCholeskyDecomposition.java +++ /dev/null @@ -1,195 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.util.FastMath; - -/** - * Calculates the rectangular Cholesky decomposition of a matrix. - *

The rectangular Cholesky decomposition of a real symmetric positive - * semidefinite matrix A consists of a rectangular matrix B with the same - * number of rows such that: A is almost equal to BBT, depending - * on a user-defined tolerance. In a sense, this is the square root of A.

- *

The difference with respect to the regular {@link CholeskyDecomposition} - * is that rows/columns may be permuted (hence the rectangular shape instead - * of the traditional triangular shape) and there is a threshold to ignore - * small diagonal elements. This is used for example to generate {@link - * org.apache.commons.math4.random.CorrelatedRandomVectorGenerator correlated - * random n-dimensions vectors} in a p-dimension subspace (p < n). - * In other words, it allows generating random vectors from a covariance - * matrix that is only positive semidefinite, and not positive definite.

- *

Rectangular Cholesky decomposition is not suited for solving - * linear systems, so it does not provide any {@link DecompositionSolver - * decomposition solver}.

- * - * @see MathWorld - * @see Wikipedia - * @since 2.0 (changed to concrete class in 3.0) - */ -public class RectangularCholeskyDecomposition { - - /** Permutated Cholesky root of the symmetric positive semidefinite matrix. */ - private final RealMatrix root; - - /** Rank of the symmetric positive semidefinite matrix. */ - private int rank; - - /** - * Decompose a symmetric positive semidefinite matrix. - *

- * Note: this constructor follows the linpack method to detect dependent - * columns by proceeding with the Cholesky algorithm until a nonpositive diagonal - * element is encountered. - * - * @see - * Analysis of the Cholesky Decomposition of a Semi-definite Matrix - * - * @param matrix Symmetric positive semidefinite matrix. - * @exception NonPositiveDefiniteMatrixException if the matrix is not - * positive semidefinite. - * @since 3.1 - */ - public RectangularCholeskyDecomposition(RealMatrix matrix) - throws NonPositiveDefiniteMatrixException { - this(matrix, 0); - } - - /** - * Decompose a symmetric positive semidefinite matrix. - * - * @param matrix Symmetric positive semidefinite matrix. - * @param small Diagonal elements threshold under which columns are - * considered to be dependent on previous ones and are discarded. - * @exception NonPositiveDefiniteMatrixException if the matrix is not - * positive semidefinite. - */ - public RectangularCholeskyDecomposition(RealMatrix matrix, double small) - throws NonPositiveDefiniteMatrixException { - - final int order = matrix.getRowDimension(); - final double[][] c = matrix.getData(); - final double[][] b = new double[order][order]; - - int[] index = new int[order]; - for (int i = 0; i < order; ++i) { - index[i] = i; - } - - int r = 0; - for (boolean loop = true; loop;) { - - // find maximal diagonal element - int swapR = r; - for (int i = r + 1; i < order; ++i) { - int ii = index[i]; - int isr = index[swapR]; - if (c[ii][ii] > c[isr][isr]) { - swapR = i; - } - } - - - // swap elements - if (swapR != r) { - final int tmpIndex = index[r]; - index[r] = index[swapR]; - index[swapR] = tmpIndex; - final double[] tmpRow = b[r]; - b[r] = b[swapR]; - b[swapR] = tmpRow; - } - - // check diagonal element - int ir = index[r]; - if (c[ir][ir] <= small) { - - if (r == 0) { - throw new NonPositiveDefiniteMatrixException(c[ir][ir], ir, small); - } - - // check remaining diagonal elements - for (int i = r; i < order; ++i) { - if (c[index[i]][index[i]] < -small) { - // there is at least one sufficiently negative diagonal element, - // the symmetric positive semidefinite matrix is wrong - throw new NonPositiveDefiniteMatrixException(c[index[i]][index[i]], i, small); - } - } - - // all remaining diagonal elements are close to zero, we consider we have - // found the rank of the symmetric positive semidefinite matrix - loop = false; - - } else { - - // transform the matrix - final double sqrt = FastMath.sqrt(c[ir][ir]); - b[r][r] = sqrt; - final double inverse = 1 / sqrt; - final double inverse2 = 1 / c[ir][ir]; - for (int i = r + 1; i < order; ++i) { - final int ii = index[i]; - final double e = inverse * c[ii][ir]; - b[i][r] = e; - c[ii][ii] -= c[ii][ir] * c[ii][ir] * inverse2; - for (int j = r + 1; j < i; ++j) { - final int ij = index[j]; - final double f = c[ii][ij] - e * b[j][r]; - c[ii][ij] = f; - c[ij][ii] = f; - } - } - - // prepare next iteration - loop = ++r < order; - } - } - - // build the root matrix - rank = r; - root = MatrixUtils.createRealMatrix(order, r); - for (int i = 0; i < order; ++i) { - for (int j = 0; j < r; ++j) { - root.setEntry(index[i], j, b[i][j]); - } - } - - } - - /** Get the root of the covariance matrix. - * The root is the rectangular matrix B such that - * the covariance matrix is equal to B.BT - * @return root of the square matrix - * @see #getRank() - */ - public RealMatrix getRootMatrix() { - return root; - } - - /** Get the rank of the symmetric positive semidefinite matrix. - * The r is the number of independent rows in the symmetric positive semidefinite - * matrix, it is also the number of columns of the rectangular - * matrix of the decomposition. - * @return r of the square matrix. - * @see #getRootMatrix() - */ - public int getRank() { - return rank; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SchurTransformer.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SchurTransformer.java deleted file mode 100644 index b836efe18..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SchurTransformer.java +++ /dev/null @@ -1,453 +0,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. - */ - -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.numbers.core.Precision; - -/** - * Class transforming a general real matrix to Schur form. - *

A m × m matrix A can be written as the product of three matrices: A = P - * × T × PT with P an orthogonal matrix and T an quasi-triangular - * matrix. Both P and T are m × m matrices.

- *

Transformation to Schur form is often not a goal by itself, but it is an - * intermediate step in more general decomposition algorithms like - * {@link EigenDecomposition eigen decomposition}. This class is therefore - * intended for internal use by the library and is not public. As a consequence - * of this explicitly limited scope, many methods directly returns references to - * internal arrays, not copies.

- *

This class is based on the method hqr2 in class EigenvalueDecomposition - * from the JAMA library.

- * - * @see Schur Decomposition - MathWorld - * @see Schur Decomposition - Wikipedia - * @see Householder Transformations - * @since 3.1 - */ -class SchurTransformer { - /** Maximum allowed iterations for convergence of the transformation. */ - private static final int MAX_ITERATIONS = 100; - - /** P matrix. */ - private final double matrixP[][]; - /** T matrix. */ - private final double matrixT[][]; - /** Cached value of P. */ - private RealMatrix cachedP; - /** Cached value of T. */ - private RealMatrix cachedT; - /** Cached value of PT. */ - private RealMatrix cachedPt; - - /** Epsilon criteria taken from JAMA code (originally was 2^-52). */ - private final double epsilon = Precision.EPSILON; - - /** - * Build the transformation to Schur form of a general real matrix. - * - * @param matrix matrix to transform - * @throws NonSquareMatrixException if the matrix is not square - */ - SchurTransformer(final RealMatrix matrix) { - if (!matrix.isSquare()) { - throw new NonSquareMatrixException(matrix.getRowDimension(), - matrix.getColumnDimension()); - } - - HessenbergTransformer transformer = new HessenbergTransformer(matrix); - matrixT = transformer.getH().getData(); - matrixP = transformer.getP().getData(); - cachedT = null; - cachedP = null; - cachedPt = null; - - // transform matrix - transform(); - } - - /** - * Returns the matrix P of the transform. - *

P is an orthogonal matrix, i.e. its inverse is also its transpose.

- * - * @return the P matrix - */ - public RealMatrix getP() { - if (cachedP == null) { - cachedP = MatrixUtils.createRealMatrix(matrixP); - } - return cachedP; - } - - /** - * Returns the transpose of the matrix P of the transform. - *

P is an orthogonal matrix, i.e. its inverse is also its transpose.

- * - * @return the transpose of the P matrix - */ - public RealMatrix getPT() { - if (cachedPt == null) { - cachedPt = getP().transpose(); - } - - // return the cached matrix - return cachedPt; - } - - /** - * Returns the quasi-triangular Schur matrix T of the transform. - * - * @return the T matrix - */ - public RealMatrix getT() { - if (cachedT == null) { - cachedT = MatrixUtils.createRealMatrix(matrixT); - } - - // return the cached matrix - return cachedT; - } - - /** - * Transform original matrix to Schur form. - * @throws MaxCountExceededException if the transformation does not converge - */ - private void transform() { - final int n = matrixT.length; - - // compute matrix norm - final double norm = getNorm(); - - // shift information - final ShiftInfo shift = new ShiftInfo(); - - // Outer loop over eigenvalue index - int iteration = 0; - int iu = n - 1; - while (iu >= 0) { - - // Look for single small sub-diagonal element - final int il = findSmallSubDiagonalElement(iu, norm); - - // Check for convergence - if (il == iu) { - // One root found - matrixT[iu][iu] += shift.exShift; - iu--; - iteration = 0; - } else if (il == iu - 1) { - // Two roots found - double p = (matrixT[iu - 1][iu - 1] - matrixT[iu][iu]) / 2.0; - double q = p * p + matrixT[iu][iu - 1] * matrixT[iu - 1][iu]; - matrixT[iu][iu] += shift.exShift; - matrixT[iu - 1][iu - 1] += shift.exShift; - - if (q >= 0) { - double z = FastMath.sqrt(FastMath.abs(q)); - if (p >= 0) { - z = p + z; - } else { - z = p - z; - } - final double x = matrixT[iu][iu - 1]; - final double s = FastMath.abs(x) + FastMath.abs(z); - p = x / s; - q = z / s; - final double r = FastMath.sqrt(p * p + q * q); - p /= r; - q /= r; - - // Row modification - for (int j = iu - 1; j < n; j++) { - z = matrixT[iu - 1][j]; - matrixT[iu - 1][j] = q * z + p * matrixT[iu][j]; - matrixT[iu][j] = q * matrixT[iu][j] - p * z; - } - - // Column modification - for (int i = 0; i <= iu; i++) { - z = matrixT[i][iu - 1]; - matrixT[i][iu - 1] = q * z + p * matrixT[i][iu]; - matrixT[i][iu] = q * matrixT[i][iu] - p * z; - } - - // Accumulate transformations - for (int i = 0; i <= n - 1; i++) { - z = matrixP[i][iu - 1]; - matrixP[i][iu - 1] = q * z + p * matrixP[i][iu]; - matrixP[i][iu] = q * matrixP[i][iu] - p * z; - } - } - iu -= 2; - iteration = 0; - } else { - // No convergence yet - computeShift(il, iu, iteration, shift); - - // stop transformation after too many iterations - if (++iteration > MAX_ITERATIONS) { - throw new MaxCountExceededException(LocalizedFormats.CONVERGENCE_FAILED, - MAX_ITERATIONS); - } - - // the initial houseHolder vector for the QR step - final double[] hVec = new double[3]; - - final int im = initQRStep(il, iu, shift, hVec); - performDoubleQRStep(il, im, iu, shift, hVec); - } - } - } - - /** - * Computes the L1 norm of the (quasi-)triangular matrix T. - * - * @return the L1 norm of matrix T - */ - private double getNorm() { - double norm = 0.0; - for (int i = 0; i < matrixT.length; i++) { - // as matrix T is (quasi-)triangular, also take the sub-diagonal element into account - for (int j = FastMath.max(i - 1, 0); j < matrixT.length; j++) { - norm += FastMath.abs(matrixT[i][j]); - } - } - return norm; - } - - /** - * Find the first small sub-diagonal element and returns its index. - * - * @param startIdx the starting index for the search - * @param norm the L1 norm of the matrix - * @return the index of the first small sub-diagonal element - */ - private int findSmallSubDiagonalElement(final int startIdx, final double norm) { - int l = startIdx; - while (l > 0) { - double s = FastMath.abs(matrixT[l - 1][l - 1]) + FastMath.abs(matrixT[l][l]); - if (s == 0.0) { - s = norm; - } - if (FastMath.abs(matrixT[l][l - 1]) < epsilon * s) { - break; - } - l--; - } - return l; - } - - /** - * Compute the shift for the current iteration. - * - * @param l the index of the small sub-diagonal element - * @param idx the current eigenvalue index - * @param iteration the current iteration - * @param shift holder for shift information - */ - private void computeShift(final int l, final int idx, final int iteration, final ShiftInfo shift) { - // Form shift - shift.x = matrixT[idx][idx]; - shift.y = shift.w = 0.0; - if (l < idx) { - shift.y = matrixT[idx - 1][idx - 1]; - shift.w = matrixT[idx][idx - 1] * matrixT[idx - 1][idx]; - } - - // Wilkinson's original ad hoc shift - if (iteration == 10) { - shift.exShift += shift.x; - for (int i = 0; i <= idx; i++) { - matrixT[i][i] -= shift.x; - } - final double s = FastMath.abs(matrixT[idx][idx - 1]) + FastMath.abs(matrixT[idx - 1][idx - 2]); - shift.x = 0.75 * s; - shift.y = 0.75 * s; - shift.w = -0.4375 * s * s; - } - - // MATLAB's new ad hoc shift - if (iteration == 30) { - double s = (shift.y - shift.x) / 2.0; - s = s * s + shift.w; - if (s > 0.0) { - s = FastMath.sqrt(s); - if (shift.y < shift.x) { - s = -s; - } - s = shift.x - shift.w / ((shift.y - shift.x) / 2.0 + s); - for (int i = 0; i <= idx; i++) { - matrixT[i][i] -= s; - } - shift.exShift += s; - shift.x = shift.y = shift.w = 0.964; - } - } - } - - /** - * Initialize the householder vectors for the QR step. - * - * @param il the index of the small sub-diagonal element - * @param iu the current eigenvalue index - * @param shift shift information holder - * @param hVec the initial houseHolder vector - * @return the start index for the QR step - */ - private int initQRStep(int il, final int iu, final ShiftInfo shift, double[] hVec) { - // Look for two consecutive small sub-diagonal elements - int im = iu - 2; - while (im >= il) { - final double z = matrixT[im][im]; - final double r = shift.x - z; - double s = shift.y - z; - hVec[0] = (r * s - shift.w) / matrixT[im + 1][im] + matrixT[im][im + 1]; - hVec[1] = matrixT[im + 1][im + 1] - z - r - s; - hVec[2] = matrixT[im + 2][im + 1]; - - if (im == il) { - break; - } - - final double lhs = FastMath.abs(matrixT[im][im - 1]) * (FastMath.abs(hVec[1]) + FastMath.abs(hVec[2])); - final double rhs = FastMath.abs(hVec[0]) * (FastMath.abs(matrixT[im - 1][im - 1]) + - FastMath.abs(z) + - FastMath.abs(matrixT[im + 1][im + 1])); - - if (lhs < epsilon * rhs) { - break; - } - im--; - } - - return im; - } - - /** - * Perform a double QR step involving rows l:idx and columns m:n - * - * @param il the index of the small sub-diagonal element - * @param im the start index for the QR step - * @param iu the current eigenvalue index - * @param shift shift information holder - * @param hVec the initial houseHolder vector - */ - private void performDoubleQRStep(final int il, final int im, final int iu, - final ShiftInfo shift, final double[] hVec) { - - final int n = matrixT.length; - double p = hVec[0]; - double q = hVec[1]; - double r = hVec[2]; - - for (int k = im; k <= iu - 1; k++) { - boolean notlast = k != (iu - 1); - if (k != im) { - p = matrixT[k][k - 1]; - q = matrixT[k + 1][k - 1]; - r = notlast ? matrixT[k + 2][k - 1] : 0.0; - shift.x = FastMath.abs(p) + FastMath.abs(q) + FastMath.abs(r); - if (Precision.equals(shift.x, 0.0, epsilon)) { - continue; - } - p /= shift.x; - q /= shift.x; - r /= shift.x; - } - double s = FastMath.sqrt(p * p + q * q + r * r); - if (p < 0.0) { - s = -s; - } - if (s != 0.0) { - if (k != im) { - matrixT[k][k - 1] = -s * shift.x; - } else if (il != im) { - matrixT[k][k - 1] = -matrixT[k][k - 1]; - } - p += s; - shift.x = p / s; - shift.y = q / s; - double z = r / s; - q /= p; - r /= p; - - // Row modification - for (int j = k; j < n; j++) { - p = matrixT[k][j] + q * matrixT[k + 1][j]; - if (notlast) { - p += r * matrixT[k + 2][j]; - matrixT[k + 2][j] -= p * z; - } - matrixT[k][j] -= p * shift.x; - matrixT[k + 1][j] -= p * shift.y; - } - - // Column modification - for (int i = 0; i <= FastMath.min(iu, k + 3); i++) { - p = shift.x * matrixT[i][k] + shift.y * matrixT[i][k + 1]; - if (notlast) { - p += z * matrixT[i][k + 2]; - matrixT[i][k + 2] -= p * r; - } - matrixT[i][k] -= p; - matrixT[i][k + 1] -= p * q; - } - - // Accumulate transformations - final int high = matrixT.length - 1; - for (int i = 0; i <= high; i++) { - p = shift.x * matrixP[i][k] + shift.y * matrixP[i][k + 1]; - if (notlast) { - p += z * matrixP[i][k + 2]; - matrixP[i][k + 2] -= p * r; - } - matrixP[i][k] -= p; - matrixP[i][k + 1] -= p * q; - } - } // (s != 0) - } // k loop - - // clean up pollution due to round-off errors - for (int i = im + 2; i <= iu; i++) { - matrixT[i][i-2] = 0.0; - if (i > im + 2) { - matrixT[i][i-3] = 0.0; - } - } - } - - /** - * Internal data structure holding the current shift information. - * Contains variable names as present in the original JAMA code. - */ - private static class ShiftInfo { - // CHECKSTYLE: stop all - - /** x shift info */ - double x; - /** y shift info */ - double y; - /** w shift info */ - double w; - /** Indicates an exceptional shift. */ - double exShift; - - // CHECKSTYLE: resume all - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SingularMatrixException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SingularMatrixException.java deleted file mode 100644 index f1548adbd..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SingularMatrixException.java +++ /dev/null @@ -1,37 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when a non-singular matrix is expected. - * - * @since 3.0 - */ -public class SingularMatrixException extends MathIllegalArgumentException { - /** Serializable version Id. */ - private static final long serialVersionUID = -4206514844735401070L; - - /** - * Construct an exception. - */ - public SingularMatrixException() { - super(LocalizedFormats.SINGULAR_MATRIX); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SingularOperatorException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SingularOperatorException.java deleted file mode 100644 index 6352d7f64..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SingularOperatorException.java +++ /dev/null @@ -1,38 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Exception to be thrown when trying to invert a singular operator. - * - * @since 3.0 - */ -public class SingularOperatorException - extends MathIllegalArgumentException { - /** Serializable version Id. */ - private static final long serialVersionUID = -476049978595245033L; - - /** - * Creates a new instance of this class. - */ - public SingularOperatorException() { - super(LocalizedFormats.SINGULAR_OPERATOR); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SingularValueDecomposition.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SingularValueDecomposition.java deleted file mode 100644 index 4d4116e58..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SingularValueDecomposition.java +++ /dev/null @@ -1,744 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.numbers.core.Precision; - -/** - * Calculates the compact Singular Value Decomposition of a matrix. - *

- * The Singular Value Decomposition of matrix A is a set of three matrices: U, - * Σ and V such that A = U × Σ × VT. Let A be - * a m × n matrix, then U is a m × p orthogonal matrix, Σ is a - * p × p diagonal matrix with positive or null elements, V is a p × - * n orthogonal matrix (hence VT is also orthogonal) where - * p=min(m,n). - *

- *

This class is similar to the class with similar name from the - * JAMA library, with the - * following changes:

- *
    - *
  • the {@code norm2} method which has been renamed as {@link #getNorm() - * getNorm},
  • - *
  • the {@code cond} method which has been renamed as {@link - * #getConditionNumber() getConditionNumber},
  • - *
  • the {@code rank} method which has been renamed as {@link #getRank() - * getRank},
  • - *
  • a {@link #getUT() getUT} method has been added,
  • - *
  • a {@link #getVT() getVT} method has been added,
  • - *
  • a {@link #getSolver() getSolver} method has been added,
  • - *
  • a {@link #getCovariance(double) getCovariance} method has been added.
  • - *
- * @see MathWorld - * @see Wikipedia - * @since 2.0 (changed to concrete class in 3.0) - */ -public class SingularValueDecomposition { - /** Relative threshold for small singular values. */ - private static final double EPS = 0x1.0p-52; - /** Absolute threshold for small singular values. */ - private static final double TINY = 0x1.0p-966; - /** Computed singular values. */ - private final double[] singularValues; - /** max(row dimension, column dimension). */ - private final int m; - /** min(row dimension, column dimension). */ - private final int n; - /** Indicator for transposed matrix. */ - private final boolean transposed; - /** Cached value of U matrix. */ - private final RealMatrix cachedU; - /** Cached value of transposed U matrix. */ - private RealMatrix cachedUt; - /** Cached value of S (diagonal) matrix. */ - private RealMatrix cachedS; - /** Cached value of V matrix. */ - private final RealMatrix cachedV; - /** Cached value of transposed V matrix. */ - private RealMatrix cachedVt; - /** - * Tolerance value for small singular values, calculated once we have - * populated "singularValues". - **/ - private final double tol; - - /** - * Calculates the compact Singular Value Decomposition of the given matrix. - * - * @param matrix Matrix to decompose. - */ - public SingularValueDecomposition(final RealMatrix matrix) { - final double[][] A; - - // "m" is always the largest dimension. - if (matrix.getRowDimension() < matrix.getColumnDimension()) { - transposed = true; - A = matrix.transpose().getData(); - m = matrix.getColumnDimension(); - n = matrix.getRowDimension(); - } else { - transposed = false; - A = matrix.getData(); - m = matrix.getRowDimension(); - n = matrix.getColumnDimension(); - } - - singularValues = new double[n]; - final double[][] U = new double[m][n]; - final double[][] V = new double[n][n]; - final double[] e = new double[n]; - final double[] work = new double[m]; - // Reduce A to bidiagonal form, storing the diagonal elements - // in s and the super-diagonal elements in e. - final int nct = FastMath.min(m - 1, n); - final int nrt = FastMath.max(0, n - 2); - for (int k = 0; k < FastMath.max(nct, nrt); k++) { - if (k < nct) { - // Compute the transformation for the k-th column and - // place the k-th diagonal in s[k]. - // Compute 2-norm of k-th column without under/overflow. - singularValues[k] = 0; - for (int i = k; i < m; i++) { - singularValues[k] = FastMath.hypot(singularValues[k], A[i][k]); - } - if (singularValues[k] != 0) { - if (A[k][k] < 0) { - singularValues[k] = -singularValues[k]; - } - for (int i = k; i < m; i++) { - A[i][k] /= singularValues[k]; - } - A[k][k] += 1; - } - singularValues[k] = -singularValues[k]; - } - for (int j = k + 1; j < n; j++) { - if (k < nct && - singularValues[k] != 0) { - // Apply the transformation. - double t = 0; - for (int i = k; i < m; i++) { - t += A[i][k] * A[i][j]; - } - t = -t / A[k][k]; - for (int i = k; i < m; i++) { - A[i][j] += t * A[i][k]; - } - } - // Place the k-th row of A into e for the - // subsequent calculation of the row transformation. - e[j] = A[k][j]; - } - if (k < nct) { - // Place the transformation in U for subsequent back - // multiplication. - for (int i = k; i < m; i++) { - U[i][k] = A[i][k]; - } - } - if (k < nrt) { - // Compute the k-th row transformation and place the - // k-th super-diagonal in e[k]. - // Compute 2-norm without under/overflow. - e[k] = 0; - for (int i = k + 1; i < n; i++) { - e[k] = FastMath.hypot(e[k], e[i]); - } - if (e[k] != 0) { - if (e[k + 1] < 0) { - e[k] = -e[k]; - } - for (int i = k + 1; i < n; i++) { - e[i] /= e[k]; - } - e[k + 1] += 1; - } - e[k] = -e[k]; - if (k + 1 < m && - e[k] != 0) { - // Apply the transformation. - for (int i = k + 1; i < m; i++) { - work[i] = 0; - } - for (int j = k + 1; j < n; j++) { - for (int i = k + 1; i < m; i++) { - work[i] += e[j] * A[i][j]; - } - } - for (int j = k + 1; j < n; j++) { - final double t = -e[j] / e[k + 1]; - for (int i = k + 1; i < m; i++) { - A[i][j] += t * work[i]; - } - } - } - - // Place the transformation in V for subsequent - // back multiplication. - for (int i = k + 1; i < n; i++) { - V[i][k] = e[i]; - } - } - } - // Set up the final bidiagonal matrix or order p. - int p = n; - if (nct < n) { - singularValues[nct] = A[nct][nct]; - } - if (m < p) { - singularValues[p - 1] = 0; - } - if (nrt + 1 < p) { - e[nrt] = A[nrt][p - 1]; - } - e[p - 1] = 0; - - // Generate U. - for (int j = nct; j < n; j++) { - for (int i = 0; i < m; i++) { - U[i][j] = 0; - } - U[j][j] = 1; - } - for (int k = nct - 1; k >= 0; k--) { - if (singularValues[k] != 0) { - for (int j = k + 1; j < n; j++) { - double t = 0; - for (int i = k; i < m; i++) { - t += U[i][k] * U[i][j]; - } - t = -t / U[k][k]; - for (int i = k; i < m; i++) { - U[i][j] += t * U[i][k]; - } - } - for (int i = k; i < m; i++) { - U[i][k] = -U[i][k]; - } - U[k][k] = 1 + U[k][k]; - for (int i = 0; i < k - 1; i++) { - U[i][k] = 0; - } - } else { - for (int i = 0; i < m; i++) { - U[i][k] = 0; - } - U[k][k] = 1; - } - } - - // Generate V. - for (int k = n - 1; k >= 0; k--) { - if (k < nrt && - e[k] != 0) { - for (int j = k + 1; j < n; j++) { - double t = 0; - for (int i = k + 1; i < n; i++) { - t += V[i][k] * V[i][j]; - } - t = -t / V[k + 1][k]; - for (int i = k + 1; i < n; i++) { - V[i][j] += t * V[i][k]; - } - } - } - for (int i = 0; i < n; i++) { - V[i][k] = 0; - } - V[k][k] = 1; - } - - // Main iteration loop for the singular values. - final int pp = p - 1; - while (p > 0) { - int k; - int kase; - // Here is where a test for too many iterations would go. - // This section of the program inspects for - // negligible elements in the s and e arrays. On - // completion the variables kase and k are set as follows. - // kase = 1 if s(p) and e[k-1] are negligible and k

= 0; k--) { - final double threshold - = TINY + EPS * (FastMath.abs(singularValues[k]) + - FastMath.abs(singularValues[k + 1])); - - // the following condition is written this way in order - // to break out of the loop when NaN occurs, writing it - // as "if (FastMath.abs(e[k]) <= threshold)" would loop - // indefinitely in case of NaNs because comparison on NaNs - // always return false, regardless of what is checked - // see issue MATH-947 - if (!(FastMath.abs(e[k]) > threshold)) { - e[k] = 0; - break; - } - - } - - if (k == p - 2) { - kase = 4; - } else { - int ks; - for (ks = p - 1; ks >= k; ks--) { - if (ks == k) { - break; - } - final double t = (ks != p ? FastMath.abs(e[ks]) : 0) + - (ks != k + 1 ? FastMath.abs(e[ks - 1]) : 0); - if (FastMath.abs(singularValues[ks]) <= TINY + EPS * t) { - singularValues[ks] = 0; - break; - } - } - if (ks == k) { - kase = 3; - } else if (ks == p - 1) { - kase = 1; - } else { - kase = 2; - k = ks; - } - } - k++; - // Perform the task indicated by kase. - switch (kase) { - // Deflate negligible s(p). - case 1: { - double f = e[p - 2]; - e[p - 2] = 0; - for (int j = p - 2; j >= k; j--) { - double t = FastMath.hypot(singularValues[j], f); - final double cs = singularValues[j] / t; - final double sn = f / t; - singularValues[j] = t; - if (j != k) { - f = -sn * e[j - 1]; - e[j - 1] = cs * e[j - 1]; - } - - for (int i = 0; i < n; i++) { - t = cs * V[i][j] + sn * V[i][p - 1]; - V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1]; - V[i][j] = t; - } - } - } - break; - // Split at negligible s(k). - case 2: { - double f = e[k - 1]; - e[k - 1] = 0; - for (int j = k; j < p; j++) { - double t = FastMath.hypot(singularValues[j], f); - final double cs = singularValues[j] / t; - final double sn = f / t; - singularValues[j] = t; - f = -sn * e[j]; - e[j] = cs * e[j]; - - for (int i = 0; i < m; i++) { - t = cs * U[i][j] + sn * U[i][k - 1]; - U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1]; - U[i][j] = t; - } - } - } - break; - // Perform one qr step. - case 3: { - // Calculate the shift. - final double maxPm1Pm2 = FastMath.max(FastMath.abs(singularValues[p - 1]), - FastMath.abs(singularValues[p - 2])); - final double scale = FastMath.max(FastMath.max(FastMath.max(maxPm1Pm2, - FastMath.abs(e[p - 2])), - FastMath.abs(singularValues[k])), - FastMath.abs(e[k])); - final double sp = singularValues[p - 1] / scale; - final double spm1 = singularValues[p - 2] / scale; - final double epm1 = e[p - 2] / scale; - final double sk = singularValues[k] / scale; - final double ek = e[k] / scale; - final double b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2.0; - final double c = (sp * epm1) * (sp * epm1); - double shift = 0; - if (b != 0 || - c != 0) { - shift = FastMath.sqrt(b * b + c); - if (b < 0) { - shift = -shift; - } - shift = c / (b + shift); - } - double f = (sk + sp) * (sk - sp) + shift; - double g = sk * ek; - // Chase zeros. - for (int j = k; j < p - 1; j++) { - double t = FastMath.hypot(f, g); - double cs = f / t; - double sn = g / t; - if (j != k) { - e[j - 1] = t; - } - f = cs * singularValues[j] + sn * e[j]; - e[j] = cs * e[j] - sn * singularValues[j]; - g = sn * singularValues[j + 1]; - singularValues[j + 1] = cs * singularValues[j + 1]; - - for (int i = 0; i < n; i++) { - t = cs * V[i][j] + sn * V[i][j + 1]; - V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1]; - V[i][j] = t; - } - t = FastMath.hypot(f, g); - cs = f / t; - sn = g / t; - singularValues[j] = t; - f = cs * e[j] + sn * singularValues[j + 1]; - singularValues[j + 1] = -sn * e[j] + cs * singularValues[j + 1]; - g = sn * e[j + 1]; - e[j + 1] = cs * e[j + 1]; - if (j < m - 1) { - for (int i = 0; i < m; i++) { - t = cs * U[i][j] + sn * U[i][j + 1]; - U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1]; - U[i][j] = t; - } - } - } - e[p - 2] = f; - } - break; - // Convergence. - default: { - // Make the singular values positive. - if (singularValues[k] <= 0) { - singularValues[k] = singularValues[k] < 0 ? -singularValues[k] : 0; - - for (int i = 0; i <= pp; i++) { - V[i][k] = -V[i][k]; - } - } - // Order the singular values. - while (k < pp) { - if (singularValues[k] >= singularValues[k + 1]) { - break; - } - double t = singularValues[k]; - singularValues[k] = singularValues[k + 1]; - singularValues[k + 1] = t; - if (k < n - 1) { - for (int i = 0; i < n; i++) { - t = V[i][k + 1]; - V[i][k + 1] = V[i][k]; - V[i][k] = t; - } - } - if (k < m - 1) { - for (int i = 0; i < m; i++) { - t = U[i][k + 1]; - U[i][k + 1] = U[i][k]; - U[i][k] = t; - } - } - k++; - } - p--; - } - break; - } - } - - // Set the small value tolerance used to calculate rank and pseudo-inverse - tol = FastMath.max(m * singularValues[0] * EPS, - FastMath.sqrt(Precision.SAFE_MIN)); - - if (!transposed) { - cachedU = MatrixUtils.createRealMatrix(U); - cachedV = MatrixUtils.createRealMatrix(V); - } else { - cachedU = MatrixUtils.createRealMatrix(V); - cachedV = MatrixUtils.createRealMatrix(U); - } - } - - /** - * Returns the matrix U of the decomposition. - *

U is an orthogonal matrix, i.e. its transpose is also its inverse.

- * @return the U matrix - * @see #getUT() - */ - public RealMatrix getU() { - // return the cached matrix - return cachedU; - - } - - /** - * Returns the transpose of the matrix U of the decomposition. - *

U is an orthogonal matrix, i.e. its transpose is also its inverse.

- * @return the U matrix (or null if decomposed matrix is singular) - * @see #getU() - */ - public RealMatrix getUT() { - if (cachedUt == null) { - cachedUt = getU().transpose(); - } - // return the cached matrix - return cachedUt; - } - - /** - * Returns the diagonal matrix Σ of the decomposition. - *

Σ is a diagonal matrix. The singular values are provided in - * non-increasing order, for compatibility with Jama.

- * @return the Σ matrix - */ - public RealMatrix getS() { - if (cachedS == null) { - // cache the matrix for subsequent calls - cachedS = MatrixUtils.createRealDiagonalMatrix(singularValues); - } - return cachedS; - } - - /** - * Returns the diagonal elements of the matrix Σ of the decomposition. - *

The singular values are provided in non-increasing order, for - * compatibility with Jama.

- * @return the diagonal elements of the Σ matrix - */ - public double[] getSingularValues() { - return singularValues.clone(); - } - - /** - * Returns the matrix V of the decomposition. - *

V is an orthogonal matrix, i.e. its transpose is also its inverse.

- * @return the V matrix (or null if decomposed matrix is singular) - * @see #getVT() - */ - public RealMatrix getV() { - // return the cached matrix - return cachedV; - } - - /** - * Returns the transpose of the matrix V of the decomposition. - *

V is an orthogonal matrix, i.e. its transpose is also its inverse.

- * @return the V matrix (or null if decomposed matrix is singular) - * @see #getV() - */ - public RealMatrix getVT() { - if (cachedVt == null) { - cachedVt = getV().transpose(); - } - // return the cached matrix - return cachedVt; - } - - /** - * Returns the n × n covariance matrix. - *

The covariance matrix is V × J × VT - * where J is the diagonal matrix of the inverse of the squares of - * the singular values.

- * @param minSingularValue value below which singular values are ignored - * (a 0 or negative value implies all singular value will be used) - * @return covariance matrix - * @exception IllegalArgumentException if minSingularValue is larger than - * the largest singular value, meaning all singular values are ignored - */ - public RealMatrix getCovariance(final double minSingularValue) { - // get the number of singular values to consider - final int p = singularValues.length; - int dimension = 0; - while (dimension < p && - singularValues[dimension] >= minSingularValue) { - ++dimension; - } - - if (dimension == 0) { - throw new NumberIsTooLargeException(LocalizedFormats.TOO_LARGE_CUTOFF_SINGULAR_VALUE, - minSingularValue, singularValues[0], true); - } - - final double[][] data = new double[dimension][p]; - getVT().walkInOptimizedOrder(new DefaultRealMatrixPreservingVisitor() { - /** {@inheritDoc} */ - @Override - public void visit(final int row, final int column, - final double value) { - data[row][column] = value / singularValues[row]; - } - }, 0, dimension - 1, 0, p - 1); - - RealMatrix jv = new Array2DRowRealMatrix(data, false); - return jv.transpose().multiply(jv); - } - - /** - * Returns the L2 norm of the matrix. - *

The L2 norm is max(|A × u|2 / - * |u|2), where |.|2 denotes the vectorial 2-norm - * (i.e. the traditional euclidian norm).

- * @return norm - */ - public double getNorm() { - return singularValues[0]; - } - - /** - * Return the condition number of the matrix. - * @return condition number of the matrix - */ - public double getConditionNumber() { - return singularValues[0] / singularValues[n - 1]; - } - - /** - * Computes the inverse of the condition number. - * In cases of rank deficiency, the {@link #getConditionNumber() condition - * number} will become undefined. - * - * @return the inverse of the condition number. - */ - public double getInverseConditionNumber() { - return singularValues[n - 1] / singularValues[0]; - } - - /** - * Return the effective numerical matrix rank. - *

The effective numerical rank is the number of non-negligible - * singular values. The threshold used to identify non-negligible - * terms is max(m,n) × ulp(s1) where ulp(s1) - * is the least significant bit of the largest singular value.

- * @return effective numerical matrix rank - */ - public int getRank() { - int r = 0; - for (int i = 0; i < singularValues.length; i++) { - if (singularValues[i] > tol) { - r++; - } - } - return r; - } - - /** - * Get a solver for finding the A × X = B solution in least square sense. - * @return a solver - */ - public DecompositionSolver getSolver() { - return new Solver(singularValues, getUT(), getV(), getRank() == m, tol); - } - - /** Specialized solver. */ - private static class Solver implements DecompositionSolver { - /** Pseudo-inverse of the initial matrix. */ - private final RealMatrix pseudoInverse; - /** Singularity indicator. */ - private final boolean nonSingular; - - /** - * Build a solver from decomposed matrix. - * - * @param singularValues Singular values. - * @param uT UT matrix of the decomposition. - * @param v V matrix of the decomposition. - * @param nonSingular Singularity indicator. - * @param tol tolerance for singular values - */ - private Solver(final double[] singularValues, final RealMatrix uT, - final RealMatrix v, final boolean nonSingular, final double tol) { - final double[][] suT = uT.getData(); - for (int i = 0; i < singularValues.length; ++i) { - final double a; - if (singularValues[i] > tol) { - a = 1 / singularValues[i]; - } else { - a = 0; - } - final double[] suTi = suT[i]; - for (int j = 0; j < suTi.length; ++j) { - suTi[j] *= a; - } - } - pseudoInverse = v.multiply(new Array2DRowRealMatrix(suT, false)); - this.nonSingular = nonSingular; - } - - /** - * Solve the linear equation A × X = B in least square sense. - *

- * The m×n matrix A may not be square, the solution X is such that - * ||A × X - B|| is minimal. - *

- * @param b Right-hand side of the equation A × X = B - * @return a vector X that minimizes the two norm of A × X - B - * @throws org.apache.commons.math4.exception.DimensionMismatchException - * if the matrices dimensions do not match. - */ - @Override - public RealVector solve(final RealVector b) { - return pseudoInverse.operate(b); - } - - /** - * Solve the linear equation A × X = B in least square sense. - *

- * The m×n matrix A may not be square, the solution X is such that - * ||A × X - B|| is minimal. - *

- * - * @param b Right-hand side of the equation A × X = B - * @return a matrix X that minimizes the two norm of A × X - B - * @throws org.apache.commons.math4.exception.DimensionMismatchException - * if the matrices dimensions do not match. - */ - @Override - public RealMatrix solve(final RealMatrix b) { - return pseudoInverse.multiply(b); - } - - /** - * Check if the decomposed matrix is non-singular. - * - * @return {@code true} if the decomposed matrix is non-singular. - */ - @Override - public boolean isNonSingular() { - return nonSingular; - } - - /** - * Get the pseudo-inverse of the decomposed matrix. - * - * @return the inverse matrix. - */ - @Override - public RealMatrix getInverse() { - return pseudoInverse; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SparseFieldMatrix.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SparseFieldMatrix.java deleted file mode 100644 index a3ae81d5c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SparseFieldMatrix.java +++ /dev/null @@ -1,187 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; -import org.apache.commons.math4.util.OpenIntToFieldHashMap; - -/** - * Sparse matrix implementation based on an open addressed map. - * - *

- * Caveat: This implementation assumes that, for any {@code x}, - * the equality {@code x * 0d == 0d} holds. But it is is not true for - * {@code NaN}. Moreover, zero entries will lose their sign. - * Some operations (that involve {@code NaN} and/or infinities) may - * thus give incorrect results. - *

- * @param the type of the field elements - * @since 2.0 - */ -public class SparseFieldMatrix> extends AbstractFieldMatrix { - - /** Storage for (sparse) matrix elements. */ - private final OpenIntToFieldHashMap entries; - /** Row dimension. */ - private final int rows; - /** Column dimension. */ - private final int columns; - - /** - * Create a matrix with no data. - * - * @param field Field to which the elements belong. - */ - public SparseFieldMatrix(final Field field) { - super(field); - rows = 0; - columns= 0; - entries = new OpenIntToFieldHashMap<>(field); - } - - /** - * Create a new {@code SparseFieldMatrix} with the supplied row and column - * dimensions. - * - * @param field Field to which the elements belong. - * @param rowDimension Number of rows in the new matrix. - * @param columnDimension Number of columns in the new matrix. - * @throws org.apache.commons.math4.exception.NotStrictlyPositiveException - * if row or column dimension is not positive. - */ - public SparseFieldMatrix(final Field field, - final int rowDimension, final int columnDimension) { - super(field, rowDimension, columnDimension); - this.rows = rowDimension; - this.columns = columnDimension; - entries = new OpenIntToFieldHashMap<>(field); - } - - /** - * Copy constructor. - * - * @param other Instance to copy. - */ - public SparseFieldMatrix(SparseFieldMatrix other) { - super(other.getField(), other.getRowDimension(), other.getColumnDimension()); - rows = other.getRowDimension(); - columns = other.getColumnDimension(); - entries = new OpenIntToFieldHashMap<>(other.entries); - } - - /** - * Generic copy constructor. - * - * @param other Instance to copy. - */ - public SparseFieldMatrix(FieldMatrix other){ - super(other.getField(), other.getRowDimension(), other.getColumnDimension()); - rows = other.getRowDimension(); - columns = other.getColumnDimension(); - entries = new OpenIntToFieldHashMap<>(getField()); - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - setEntry(i, j, other.getEntry(i, j)); - } - } - } - - /** {@inheritDoc} */ - @Override - public void addToEntry(int row, int column, T increment) { - checkRowIndex(row); - checkColumnIndex(column); - final int key = computeKey(row, column); - final T value = entries.get(key).add(increment); - if (getField().getZero().equals(value)) { - entries.remove(key); - } else { - entries.put(key, value); - } - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix copy() { - return new SparseFieldMatrix<>(this); - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix createMatrix(int rowDimension, int columnDimension) { - return new SparseFieldMatrix<>(getField(), rowDimension, columnDimension); - } - - /** {@inheritDoc} */ - @Override - public int getColumnDimension() { - return columns; - } - - /** {@inheritDoc} */ - @Override - public T getEntry(int row, int column) { - checkRowIndex(row); - checkColumnIndex(column); - return entries.get(computeKey(row, column)); - } - - /** {@inheritDoc} */ - @Override - public int getRowDimension() { - return rows; - } - - /** {@inheritDoc} */ - @Override - public void multiplyEntry(int row, int column, T factor) { - checkRowIndex(row); - checkColumnIndex(column); - final int key = computeKey(row, column); - final T value = entries.get(key).multiply(factor); - if (getField().getZero().equals(value)) { - entries.remove(key); - } else { - entries.put(key, value); - } - - } - - /** {@inheritDoc} */ - @Override - public void setEntry(int row, int column, T value) { - checkRowIndex(row); - checkColumnIndex(column); - if (getField().getZero().equals(value)) { - entries.remove(computeKey(row, column)); - } else { - entries.put(computeKey(row, column), value); - } - } - - /** - * Compute the key to access a matrix element. - * - * @param row Row index of the matrix element. - * @param column Column index of the matrix element. - * @return the key within the map to access the matrix element. - */ - private int computeKey(int row, int column) { - return row * columns + column; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SparseFieldVector.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SparseFieldVector.java deleted file mode 100644 index 1bf041dc6..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SparseFieldVector.java +++ /dev/null @@ -1,811 +0,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. - */ -package org.apache.commons.math4.linear; - -import java.io.Serializable; - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; -import org.apache.commons.math4.util.OpenIntToFieldHashMap; - -/** - * This class implements the {@link FieldVector} interface with a {@link OpenIntToFieldHashMap} backing store. - *

- * Caveat: This implementation assumes that, for any {@code x}, - * the equality {@code x * 0d == 0d} holds. But it is is not true for - * {@code NaN}. Moreover, zero entries will lose their sign. - * Some operations (that involve {@code NaN} and/or infinities) may - * thus give incorrect results. - *

- * @param the type of the field elements - * @since 2.0 - */ -public class SparseFieldVector> implements FieldVector, Serializable { - /** Serialization identifier. */ - private static final long serialVersionUID = 7841233292190413362L; - /** Field to which the elements belong. */ - private final Field field; - /** Entries of the vector. */ - private final OpenIntToFieldHashMap entries; - /** Dimension of the vector. */ - private final int virtualSize; - - /** - * Build a 0-length vector. - * Zero-length vectors may be used to initialize construction of vectors - * by data gathering. We start with zero-length and use either the {@link - * #SparseFieldVector(SparseFieldVector, int)} constructor - * or one of the {@code append} method ({@link #append(FieldVector)} or - * {@link #append(SparseFieldVector)}) to gather data into this vector. - * - * @param field Field to which the elements belong. - */ - public SparseFieldVector(Field field) { - this(field, 0); - } - - - /** - * Construct a vector of zeroes. - * - * @param field Field to which the elements belong. - * @param dimension Size of the vector. - */ - public SparseFieldVector(Field field, int dimension) { - this.field = field; - virtualSize = dimension; - entries = new OpenIntToFieldHashMap<>(field); - } - - /** - * Build a resized vector, for use with append. - * - * @param v Original vector - * @param resize Amount to add. - */ - protected SparseFieldVector(SparseFieldVector v, int resize) { - field = v.field; - virtualSize = v.getDimension() + resize; - entries = new OpenIntToFieldHashMap<>(v.entries); - } - - - /** - * Build a vector with known the sparseness (for advanced use only). - * - * @param field Field to which the elements belong. - * @param dimension Size of the vector. - * @param expectedSize Expected number of non-zero entries. - */ - public SparseFieldVector(Field field, int dimension, int expectedSize) { - this.field = field; - virtualSize = dimension; - entries = new OpenIntToFieldHashMap<>(field,expectedSize); - } - - /** - * Create from a Field array. - * Only non-zero entries will be stored. - * - * @param field Field to which the elements belong. - * @param values Set of values to create from. - * @exception NullArgumentException if values is null - */ - public SparseFieldVector(Field field, T[] values) throws NullArgumentException { - MathUtils.checkNotNull(values); - this.field = field; - virtualSize = values.length; - entries = new OpenIntToFieldHashMap<>(field); - for (int key = 0; key < values.length; key++) { - T value = values[key]; - entries.put(key, value); - } - } - - /** - * Copy constructor. - * - * @param v Instance to copy. - */ - public SparseFieldVector(SparseFieldVector v) { - field = v.field; - virtualSize = v.getDimension(); - entries = new OpenIntToFieldHashMap<>(v.getEntries()); - } - - /** - * Get the entries of this instance. - * - * @return the entries of this instance - */ - private OpenIntToFieldHashMap getEntries() { - return entries; - } - - /** - * Optimized method to add sparse vectors. - * - * @param v Vector to add. - * @return {@code this + v}. - * @throws DimensionMismatchException if {@code v} is not the same size as - * {@code this}. - */ - public FieldVector add(SparseFieldVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - SparseFieldVector res = (SparseFieldVector)copy(); - OpenIntToFieldHashMap.Iterator iter = v.getEntries().iterator(); - while (iter.hasNext()) { - iter.advance(); - int key = iter.key(); - T value = iter.value(); - if (entries.containsKey(key)) { - res.setEntry(key, entries.get(key).add(value)); - } else { - res.setEntry(key, value); - } - } - return res; - - } - - /** - * Construct a vector by appending a vector to this vector. - * - * @param v Vector to append to this one. - * @return a new vector. - */ - public FieldVector append(SparseFieldVector v) { - SparseFieldVector res = new SparseFieldVector<>(this, v.getDimension()); - OpenIntToFieldHashMap.Iterator iter = v.entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - res.setEntry(iter.key() + virtualSize, iter.value()); - } - return res; - } - - /** {@inheritDoc} */ - @Override - public FieldVector append(FieldVector v) { - if (v instanceof SparseFieldVector) { - return append((SparseFieldVector) v); - } else { - final int n = v.getDimension(); - FieldVector res = new SparseFieldVector<>(this, n); - for (int i = 0; i < n; i++) { - res.setEntry(i + virtualSize, v.getEntry(i)); - } - return res; - } - } - - /** {@inheritDoc} - * @exception NullArgumentException if d is null - */ - @Override - public FieldVector append(T d) throws NullArgumentException { - MathUtils.checkNotNull(d); - FieldVector res = new SparseFieldVector<>(this, 1); - res.setEntry(virtualSize, d); - return res; - } - - /** {@inheritDoc} */ - @Override - public FieldVector copy() { - return new SparseFieldVector<>(this); - } - - /** {@inheritDoc} */ - @Override - public T dotProduct(FieldVector v) throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - T res = field.getZero(); - OpenIntToFieldHashMap.Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - res = res.add(v.getEntry(iter.key()).multiply(iter.value())); - } - return res; - } - - /** {@inheritDoc} */ - @Override - public FieldVector ebeDivide(FieldVector v) - throws DimensionMismatchException, MathArithmeticException { - checkVectorDimensions(v.getDimension()); - SparseFieldVector res = new SparseFieldVector<>(this); - OpenIntToFieldHashMap.Iterator iter = res.entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - res.setEntry(iter.key(), iter.value().divide(v.getEntry(iter.key()))); - } - return res; - } - - /** {@inheritDoc} */ - @Override - public FieldVector ebeMultiply(FieldVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - SparseFieldVector res = new SparseFieldVector<>(this); - OpenIntToFieldHashMap.Iterator iter = res.entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - res.setEntry(iter.key(), iter.value().multiply(v.getEntry(iter.key()))); - } - return res; - } - - /** {@inheritDoc} */ - @Override - public int getDimension() { - return virtualSize; - } - - /** {@inheritDoc} */ - @Override - public T getEntry(int index) throws OutOfRangeException { - checkIndex(index); - return entries.get(index); - } - - /** {@inheritDoc} */ - @Override - public Field getField() { - return field; - } - - /** {@inheritDoc} */ - @Override - public FieldVector getSubVector(int index, int n) - throws OutOfRangeException, NotPositiveException { - if (n < 0) { - throw new NotPositiveException(LocalizedFormats.NUMBER_OF_ELEMENTS_SHOULD_BE_POSITIVE, n); - } - checkIndex(index); - checkIndex(index + n - 1); - SparseFieldVector res = new SparseFieldVector<>(field,n); - int end = index + n; - OpenIntToFieldHashMap.Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - int key = iter.key(); - if (key >= index && key < end) { - res.setEntry(key - index, iter.value()); - } - } - return res; - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapAdd(T d) throws NullArgumentException { - return copy().mapAddToSelf(d); - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapAddToSelf(T d) throws NullArgumentException { - for (int i = 0; i < virtualSize; i++) { - setEntry(i, getEntry(i).add(d)); - } - return this; - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapDivide(T d) - throws NullArgumentException, MathArithmeticException { - return copy().mapDivideToSelf(d); - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapDivideToSelf(T d) - throws NullArgumentException, MathArithmeticException { - OpenIntToFieldHashMap.Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - entries.put(iter.key(), iter.value().divide(d)); - } - return this; - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapInv() throws MathArithmeticException { - return copy().mapInvToSelf(); - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapInvToSelf() throws MathArithmeticException { - for (int i = 0; i < virtualSize; i++) { - setEntry(i, field.getOne().divide(getEntry(i))); - } - return this; - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapMultiply(T d) throws NullArgumentException { - return copy().mapMultiplyToSelf(d); - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapMultiplyToSelf(T d) throws NullArgumentException { - OpenIntToFieldHashMap.Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - entries.put(iter.key(), iter.value().multiply(d)); - } - return this; - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapSubtract(T d) throws NullArgumentException { - return copy().mapSubtractToSelf(d); - } - - /** {@inheritDoc} */ - @Override - public FieldVector mapSubtractToSelf(T d) throws NullArgumentException { - return mapAddToSelf(field.getZero().subtract(d)); - } - - /** - * Optimized method to compute outer product when both vectors are sparse. - * @param v vector with which outer product should be computed - * @return the matrix outer product between instance and v - */ - public FieldMatrix outerProduct(SparseFieldVector v) { - final int n = v.getDimension(); - SparseFieldMatrix res = new SparseFieldMatrix<>(field, virtualSize, n); - OpenIntToFieldHashMap.Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - OpenIntToFieldHashMap.Iterator iter2 = v.entries.iterator(); - while (iter2.hasNext()) { - iter2.advance(); - res.setEntry(iter.key(), iter2.key(), iter.value().multiply(iter2.value())); - } - } - return res; - } - - /** {@inheritDoc} */ - @Override - public FieldMatrix outerProduct(FieldVector v) { - if (v instanceof SparseFieldVector) { - return outerProduct((SparseFieldVector)v); - } else { - final int n = v.getDimension(); - FieldMatrix res = new SparseFieldMatrix<>(field, virtualSize, n); - OpenIntToFieldHashMap.Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - int row = iter.key(); - FieldElementvalue = iter.value(); - for (int col = 0; col < n; col++) { - res.setEntry(row, col, value.multiply(v.getEntry(col))); - } - } - return res; - } - } - - /** {@inheritDoc} */ - @Override - public FieldVector projection(FieldVector v) - throws DimensionMismatchException, MathArithmeticException { - checkVectorDimensions(v.getDimension()); - return v.mapMultiply(dotProduct(v).divide(v.dotProduct(v))); - } - - /** {@inheritDoc} - * @exception NullArgumentException if value is null - */ - @Override - public void set(T value) { - MathUtils.checkNotNull(value); - for (int i = 0; i < virtualSize; i++) { - setEntry(i, value); - } - } - - /** {@inheritDoc} - * @exception NullArgumentException if value is null - */ - @Override - public void setEntry(int index, T value) throws NullArgumentException, OutOfRangeException { - MathUtils.checkNotNull(value); - checkIndex(index); - entries.put(index, value); - } - - /** {@inheritDoc} */ - @Override - public void setSubVector(int index, FieldVector v) - throws OutOfRangeException { - checkIndex(index); - checkIndex(index + v.getDimension() - 1); - final int n = v.getDimension(); - for (int i = 0; i < n; i++) { - setEntry(i + index, v.getEntry(i)); - } - } - - /** - * Optimized method to compute {@code this} minus {@code v}. - * @param v vector to be subtracted - * @return {@code this - v} - * @throws DimensionMismatchException if {@code v} is not the same size as - * {@code this}. - */ - public SparseFieldVector subtract(SparseFieldVector v) - throws DimensionMismatchException { - checkVectorDimensions(v.getDimension()); - SparseFieldVector res = (SparseFieldVector)copy(); - OpenIntToFieldHashMap.Iterator iter = v.getEntries().iterator(); - while (iter.hasNext()) { - iter.advance(); - int key = iter.key(); - if (entries.containsKey(key)) { - res.setEntry(key, entries.get(key).subtract(iter.value())); - } else { - res.setEntry(key, field.getZero().subtract(iter.value())); - } - } - return res; - } - - /** {@inheritDoc} */ - @Override - public FieldVector subtract(FieldVector v) - throws DimensionMismatchException { - if (v instanceof SparseFieldVector) { - return subtract((SparseFieldVector)v); - } else { - final int n = v.getDimension(); - checkVectorDimensions(n); - SparseFieldVector res = new SparseFieldVector<>(this); - for (int i = 0; i < n; i++) { - if (entries.containsKey(i)) { - res.setEntry(i, entries.get(i).subtract(v.getEntry(i))); - } else { - res.setEntry(i, field.getZero().subtract(v.getEntry(i))); - } - } - return res; - } - } - - /** {@inheritDoc} */ - @Override - public T[] toArray() { - T[] res = MathArrays.buildArray(field, virtualSize); - OpenIntToFieldHashMap.Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - res[iter.key()] = iter.value(); - } - return res; - } - - /** - * Check whether an index is valid. - * - * @param index Index to check. - * @throws OutOfRangeException if the index is not valid. - */ - private void checkIndex(final int index) throws OutOfRangeException { - if (index < 0 || index >= getDimension()) { - throw new OutOfRangeException(index, 0, getDimension() - 1); - } - } - - /** - * Checks that the indices of a subvector are valid. - * - * @param start the index of the first entry of the subvector - * @param end the index of the last entry of the subvector (inclusive) - * @throws OutOfRangeException if {@code start} of {@code end} are not valid - * @throws NumberIsTooSmallException if {@code end < start} - * @since 3.3 - */ - private void checkIndices(final int start, final int end) - throws NumberIsTooSmallException, OutOfRangeException { - final int dim = getDimension(); - if ((start < 0) || (start >= dim)) { - throw new OutOfRangeException(LocalizedFormats.INDEX, start, 0, - dim - 1); - } - if ((end < 0) || (end >= dim)) { - throw new OutOfRangeException(LocalizedFormats.INDEX, end, 0, - dim - 1); - } - if (end < start) { - throw new NumberIsTooSmallException(LocalizedFormats.INITIAL_ROW_AFTER_FINAL_ROW, - end, start, false); - } - } - - /** - * Check if instance dimension is equal to some expected value. - * - * @param n Expected dimension. - * @throws DimensionMismatchException if the dimensions do not match. - */ - protected void checkVectorDimensions(int n) - throws DimensionMismatchException { - if (getDimension() != n) { - throw new DimensionMismatchException(getDimension(), n); - } - } - - /** {@inheritDoc} */ - @Override - public FieldVector add(FieldVector v) throws DimensionMismatchException { - if (v instanceof SparseFieldVector) { - return add((SparseFieldVector) v); - } else { - final int n = v.getDimension(); - checkVectorDimensions(n); - SparseFieldVector res = new SparseFieldVector<>(field, - getDimension()); - for (int i = 0; i < n; i++) { - res.setEntry(i, v.getEntry(i).add(getEntry(i))); - } - return res; - } - } - - /** - * Visits (but does not alter) all entries of this vector in default order - * (increasing index). - * - * @param visitor the visitor to be used to process the entries of this - * vector - * @return the value returned by {@link FieldVectorPreservingVisitor#end()} - * at the end of the walk - * @since 3.3 - */ - public T walkInDefaultOrder(final FieldVectorPreservingVisitor visitor) { - final int dim = getDimension(); - visitor.start(dim, 0, dim - 1); - for (int i = 0; i < dim; i++) { - visitor.visit(i, getEntry(i)); - } - return visitor.end(); - } - - /** - * Visits (but does not alter) some entries of this vector in default order - * (increasing index). - * - * @param visitor visitor to be used to process the entries of this vector - * @param start the index of the first entry to be visited - * @param end the index of the last entry to be visited (inclusive) - * @return the value returned by {@link FieldVectorPreservingVisitor#end()} - * at the end of the walk - * @throws NumberIsTooSmallException if {@code end < start}. - * @throws OutOfRangeException if the indices are not valid. - * @since 3.3 - */ - public T walkInDefaultOrder(final FieldVectorPreservingVisitor visitor, - final int start, final int end) - throws NumberIsTooSmallException, OutOfRangeException { - checkIndices(start, end); - visitor.start(getDimension(), start, end); - for (int i = start; i <= end; i++) { - visitor.visit(i, getEntry(i)); - } - return visitor.end(); - } - - /** - * Visits (but does not alter) all entries of this vector in optimized - * order. The order in which the entries are visited is selected so as to - * lead to the most efficient implementation; it might depend on the - * concrete implementation of this abstract class. - * - * @param visitor the visitor to be used to process the entries of this - * vector - * @return the value returned by {@link FieldVectorPreservingVisitor#end()} - * at the end of the walk - * @since 3.3 - */ - public T walkInOptimizedOrder(final FieldVectorPreservingVisitor visitor) { - return walkInDefaultOrder(visitor); - } - - /** - * Visits (but does not alter) some entries of this vector in optimized - * order. The order in which the entries are visited is selected so as to - * lead to the most efficient implementation; it might depend on the - * concrete implementation of this abstract class. - * - * @param visitor visitor to be used to process the entries of this vector - * @param start the index of the first entry to be visited - * @param end the index of the last entry to be visited (inclusive) - * @return the value returned by {@link FieldVectorPreservingVisitor#end()} - * at the end of the walk - * @throws NumberIsTooSmallException if {@code end < start}. - * @throws OutOfRangeException if the indices are not valid. - * @since 3.3 - */ - public T walkInOptimizedOrder(final FieldVectorPreservingVisitor visitor, - final int start, final int end) - throws NumberIsTooSmallException, OutOfRangeException { - return walkInDefaultOrder(visitor, start, end); - } - - /** - * Visits (and possibly alters) all entries of this vector in default order - * (increasing index). - * - * @param visitor the visitor to be used to process and modify the entries - * of this vector - * @return the value returned by {@link FieldVectorChangingVisitor#end()} - * at the end of the walk - * @since 3.3 - */ - public T walkInDefaultOrder(final FieldVectorChangingVisitor visitor) { - final int dim = getDimension(); - visitor.start(dim, 0, dim - 1); - for (int i = 0; i < dim; i++) { - setEntry(i, visitor.visit(i, getEntry(i))); - } - return visitor.end(); - } - - /** - * Visits (and possibly alters) some entries of this vector in default order - * (increasing index). - * - * @param visitor visitor to be used to process the entries of this vector - * @param start the index of the first entry to be visited - * @param end the index of the last entry to be visited (inclusive) - * @return the value returned by {@link FieldVectorChangingVisitor#end()} - * at the end of the walk - * @throws NumberIsTooSmallException if {@code end < start}. - * @throws OutOfRangeException if the indices are not valid. - * @since 3.3 - */ - public T walkInDefaultOrder(final FieldVectorChangingVisitor visitor, - final int start, final int end) - throws NumberIsTooSmallException, OutOfRangeException { - checkIndices(start, end); - visitor.start(getDimension(), start, end); - for (int i = start; i <= end; i++) { - setEntry(i, visitor.visit(i, getEntry(i))); - } - return visitor.end(); - } - - /** - * Visits (and possibly alters) all entries of this vector in optimized - * order. The order in which the entries are visited is selected so as to - * lead to the most efficient implementation; it might depend on the - * concrete implementation of this abstract class. - * - * @param visitor the visitor to be used to process the entries of this - * vector - * @return the value returned by {@link FieldVectorChangingVisitor#end()} - * at the end of the walk - * @since 3.3 - */ - public T walkInOptimizedOrder(final FieldVectorChangingVisitor visitor) { - return walkInDefaultOrder(visitor); - } - - /** - * Visits (and possibly change) some entries of this vector in optimized - * order. The order in which the entries are visited is selected so as to - * lead to the most efficient implementation; it might depend on the - * concrete implementation of this abstract class. - * - * @param visitor visitor to be used to process the entries of this vector - * @param start the index of the first entry to be visited - * @param end the index of the last entry to be visited (inclusive) - * @return the value returned by {@link FieldVectorChangingVisitor#end()} - * at the end of the walk - * @throws NumberIsTooSmallException if {@code end < start}. - * @throws OutOfRangeException if the indices are not valid. - * @since 3.3 - */ - public T walkInOptimizedOrder(final FieldVectorChangingVisitor visitor, - final int start, final int end) - throws NumberIsTooSmallException, OutOfRangeException { - return walkInDefaultOrder(visitor, start, end); - } - - /** {@inheritDoc} */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((field == null) ? 0 : field.hashCode()); - result = prime * result + virtualSize; - OpenIntToFieldHashMap.Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - int temp = iter.value().hashCode(); - result = prime * result + temp; - } - return result; - } - - - /** {@inheritDoc} */ - @Override - public boolean equals(Object obj) { - - if (this == obj) { - return true; - } - - if (!(obj instanceof SparseFieldVector)) { - return false; - } - - @SuppressWarnings("unchecked") // OK, because "else if" check below ensures that - // other must be the same type as this - SparseFieldVector other = (SparseFieldVector) obj; - if (field == null) { - if (other.field != null) { - return false; - } - } else if (!field.equals(other.field)) { - return false; - } - if (virtualSize != other.virtualSize) { - return false; - } - - OpenIntToFieldHashMap.Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - T test = other.getEntry(iter.key()); - if (!test.equals(iter.value())) { - return false; - } - } - iter = other.getEntries().iterator(); - while (iter.hasNext()) { - iter.advance(); - T test = iter.value(); - if (!test.equals(getEntry(iter.key()))) { - return false; - } - } - return true; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SparseRealMatrix.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SparseRealMatrix.java deleted file mode 100644 index 75a2ecbc3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SparseRealMatrix.java +++ /dev/null @@ -1,34 +0,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. - */ - -package org.apache.commons.math4.linear; - -/** - * Marker interface for {@link RealMatrix} implementations that require sparse backing storage - * - *

- * Caveat: Implementation are allowed to assume that, for any {@code x}, - * the equality {@code x * 0d == 0d} holds. But it is is not true for - * {@code NaN}. Moreover, zero entries will lose their sign. - * Some operations (that involve {@code NaN} and/or infinities) may - * thus give incorrect results. - *

- * @since 2.0 - */ -public interface SparseRealMatrix extends RealMatrix { - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SparseRealVector.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SparseRealVector.java deleted file mode 100644 index 05ed3effc..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SparseRealVector.java +++ /dev/null @@ -1,31 +0,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. - */ -package org.apache.commons.math4.linear; - -/** - * Marker class for RealVectors that require sparse backing storage - *

- * Caveat: Implementation are allowed to assume that, for any {@code x}, - * the equality {@code x * 0d == 0d} holds. But it is is not true for - * {@code NaN}. Moreover, zero entries will lose their sign. - * Some operations (that involve {@code NaN} and/or infinities) may - * thus give incorrect results, like multiplications, divisions or - * functions mapping. - *

- * @since 2.0 - */ -public abstract class SparseRealVector extends RealVector {} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SymmLQ.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SymmLQ.java deleted file mode 100644 index 7411427d6..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SymmLQ.java +++ /dev/null @@ -1,1221 +0,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. - */ -package org.apache.commons.math4.linear; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.util.ExceptionContext; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.IterationManager; -import org.apache.commons.math4.util.MathUtils; - -/** - *

- * Implementation of the SYMMLQ iterative linear solver proposed by Paige and Saunders (1975). This implementation is - * largely based on the FORTRAN code by Pr. Michael A. Saunders, available here. - *

- *

- * SYMMLQ is designed to solve the system of linear equations A · x = b - * where A is an n × n self-adjoint linear operator (defined as a - * {@link RealLinearOperator}), and b is a given vector. The operator A is not - * required to be positive definite. If A is known to be definite, the method of - * conjugate gradients might be preferred, since it will require about the same - * number of iterations as SYMMLQ but slightly less work per iteration. - *

- *

- * SYMMLQ is designed to solve the system (A - shift · I) · x = b, - * where shift is a specified scalar value. If shift and b are suitably chosen, - * the computed vector x may approximate an (unnormalized) eigenvector of A, as - * in the methods of inverse iteration and/or Rayleigh-quotient iteration. - * Again, the linear operator (A - shift · I) need not be positive - * definite (but must be self-adjoint). The work per iteration is very - * slightly less if shift = 0. - *

- *

Preconditioning

- *

- * Preconditioning may reduce the number of iterations required. The solver may - * be provided with a positive definite preconditioner - * M = PT · P - * that is known to approximate - * (A - shift · I)-1 in some sense, where matrix-vector - * products of the form M · y = x can be computed efficiently. Then - * SYMMLQ will implicitly solve the system of equations - * P · (A - shift · I) · PT · - * xhat = P · b, i.e. - * Ahat · xhat = bhat, - * where - * Ahat = P · (A - shift · I) · PT, - * bhat = P · b, - * and return the solution - * x = PT · xhat. - * The associated residual is - * rhat = bhat - Ahat · xhat - * = P · [b - (A - shift · I) · x] - * = P · r. - *

- *

- * In the case of preconditioning, the {@link IterativeLinearSolverEvent}s that - * this solver fires are such that - * {@link IterativeLinearSolverEvent#getNormOfResidual()} returns the norm of - * the preconditioned, updated residual, ||P · r||, not the norm - * of the true residual ||r||. - *

- *

Default stopping criterion

- *

- * A default stopping criterion is implemented. The iterations stop when || rhat - * || ≤ δ || Ahat || || xhat ||, where xhat is the current estimate of - * the solution of the transformed system, rhat the current estimate of the - * corresponding residual, and δ a user-specified tolerance. - *

- *

Iteration count

- *

- * In the present context, an iteration should be understood as one evaluation - * of the matrix-vector product A · x. The initialization phase therefore - * counts as one iteration. If the user requires checks on the symmetry of A, - * this entails one further matrix-vector product in the initial phase. This - * further product is not accounted for in the iteration count. In - * other words, the number of iterations required to reach convergence will be - * identical, whether checks have been required or not. - *

- *

- * The present definition of the iteration count differs from that adopted in - * the original FOTRAN code, where the initialization phase was not - * taken into account. - *

- *

Initial guess of the solution

- *

- * The {@code x} parameter in - *

    - *
  • {@link #solve(RealLinearOperator, RealVector, RealVector)},
  • - *
  • {@link #solve(RealLinearOperator, RealLinearOperator, RealVector, RealVector)}},
  • - *
  • {@link #solveInPlace(RealLinearOperator, RealVector, RealVector)},
  • - *
  • {@link #solveInPlace(RealLinearOperator, RealLinearOperator, RealVector, RealVector)},
  • - *
  • {@link #solveInPlace(RealLinearOperator, RealLinearOperator, RealVector, RealVector, boolean, double)},
  • - *
- * should not be considered as an initial guess, as it is set to zero in the - * initial phase. If x0 is known to be a good approximation to x, one - * should compute r0 = b - A · x, solve A · dx = r0, - * and set x = x0 + dx. - * - *

Exception context

- *

- * Besides standard {@link DimensionMismatchException}, this class might throw - * {@link NonSelfAdjointOperatorException} if the linear operator or the - * preconditioner are not symmetric. In this case, the {@link ExceptionContext} - * provides more information - *

    - *
  • key {@code "operator"} points to the offending linear operator, say L,
  • - *
  • key {@code "vector1"} points to the first offending vector, say x, - *
  • key {@code "vector2"} points to the second offending vector, say y, such - * that xT · L · y ≠ yT · L - * · x (within a certain accuracy).
  • - *
- * - *

- * {@link NonPositiveDefiniteOperatorException} might also be thrown in case the - * preconditioner is not positive definite. The relevant keys to the - * {@link ExceptionContext} are - *

    - *
  • key {@code "operator"}, which points to the offending linear operator, - * say L,
  • - *
  • key {@code "vector"}, which points to the offending vector, say x, such - * that xT · L · x < 0.
  • - *
- * - *

References

- *
- *
Paige and Saunders (1975)
- *
C. C. Paige and M. A. Saunders, - * Solution of Sparse Indefinite Systems of Linear Equations, SIAM - * Journal on Numerical Analysis 12(4): 617-629, 1975
- *
- * - * @since 3.0 - */ -public class SymmLQ - extends PreconditionedIterativeLinearSolver { - - /* - * IMPLEMENTATION NOTES - * -------------------- - * The implementation follows as closely as possible the notations of Paige - * and Saunders (1975). Attention must be paid to the fact that some - * quantities which are relevant to iteration k can only be computed in - * iteration (k+1). Therefore, minute attention must be paid to the index of - * each state variable of this algorithm. - * - * 1. Preconditioning - * --------------- - * The Lanczos iterations associated with Ahat and bhat read - * beta[1] = ||P * b|| - * v[1] = P * b / beta[1] - * beta[k+1] * v[k+1] = Ahat * v[k] - alpha[k] * v[k] - beta[k] * v[k-1] - * = P * (A - shift * I) * P' * v[k] - alpha[k] * v[k] - * - beta[k] * v[k-1] - * Multiplying both sides by P', we get - * beta[k+1] * (P' * v)[k+1] = M * (A - shift * I) * (P' * v)[k] - * - alpha[k] * (P' * v)[k] - * - beta[k] * (P' * v[k-1]), - * and - * alpha[k+1] = v[k+1]' * Ahat * v[k+1] - * = v[k+1]' * P * (A - shift * I) * P' * v[k+1] - * = (P' * v)[k+1]' * (A - shift * I) * (P' * v)[k+1]. - * - * In other words, the Lanczos iterations are unchanged, except for the fact - * that we really compute (P' * v) instead of v. It can easily be checked - * that all other formulas are unchanged. It must be noted that P is never - * explicitly used, only matrix-vector products involving are invoked. - * - * 2. Accounting for the shift parameter - * ---------------------------------- - * Is trivial: each time A.operate(x) is invoked, one must subtract shift * x - * to the result. - * - * 3. Accounting for the goodb flag - * ----------------------------- - * When goodb is set to true, the component of xL along b is computed - * separately. From Paige and Saunders (1975), equation (5.9), we have - * wbar[k+1] = s[k] * wbar[k] - c[k] * v[k+1], - * wbar[1] = v[1]. - * Introducing wbar2[k] = wbar[k] - s[1] * ... * s[k-1] * v[1], it can - * easily be verified by induction that wbar2 follows the same recursive - * relation - * wbar2[k+1] = s[k] * wbar2[k] - c[k] * v[k+1], - * wbar2[1] = 0, - * and we then have - * w[k] = c[k] * wbar2[k] + s[k] * v[k+1] - * + s[1] * ... * s[k-1] * c[k] * v[1]. - * Introducing w2[k] = w[k] - s[1] * ... * s[k-1] * c[k] * v[1], we find, - * from (5.10) - * xL[k] = zeta[1] * w[1] + ... + zeta[k] * w[k] - * = zeta[1] * w2[1] + ... + zeta[k] * w2[k] - * + (s[1] * c[2] * zeta[2] + ... - * + s[1] * ... * s[k-1] * c[k] * zeta[k]) * v[1] - * = xL2[k] + bstep[k] * v[1], - * where xL2[k] is defined by - * xL2[0] = 0, - * xL2[k+1] = xL2[k] + zeta[k+1] * w2[k+1], - * and bstep is defined by - * bstep[1] = 0, - * bstep[k] = bstep[k-1] + s[1] * ... * s[k-1] * c[k] * zeta[k]. - * We also have, from (5.11) - * xC[k] = xL[k-1] + zbar[k] * wbar[k] - * = xL2[k-1] + zbar[k] * wbar2[k] - * + (bstep[k-1] + s[1] * ... * s[k-1] * zbar[k]) * v[1]. - */ - - /** - *

- * A simple container holding the non-final variables used in the - * iterations. Making the current state of the solver visible from the - * outside is necessary, because during the iterations, {@code x} does not - * exactly hold the current estimate of the solution. Indeed, - * {@code x} needs in general to be moved from the LQ point to the CG point. - * Besides, additional upudates must be carried out in case {@code goodb} is - * set to {@code true}. - *

- *

- * In all subsequent comments, the description of the state variables refer - * to their value after a call to {@link #update()}. In these comments, k is - * the current number of evaluations of matrix-vector products. - *

- */ - private static class State { - /** The cubic root of {@link #MACH_PREC}. */ - static final double CBRT_MACH_PREC; - - /** The machine precision. */ - static final double MACH_PREC; - - /** Reference to the linear operator. */ - private final RealLinearOperator a; - - /** Reference to the right-hand side vector. */ - private final RealVector b; - - /** {@code true} if symmetry of matrix and conditioner must be checked. */ - private final boolean check; - - /** - * The value of the custom tolerance δ for the default stopping - * criterion. - */ - private final double delta; - - /** The value of beta[k+1]. */ - private double beta; - - /** The value of beta[1]. */ - private double beta1; - - /** The value of bstep[k-1]. */ - private double bstep; - - /** The estimate of the norm of P * rC[k]. */ - private double cgnorm; - - /** The value of dbar[k+1] = -beta[k+1] * c[k-1]. */ - private double dbar; - - /** - * The value of gamma[k] * zeta[k]. Was called {@code rhs1} in the - * initial code. - */ - private double gammaZeta; - - /** The value of gbar[k]. */ - private double gbar; - - /** The value of max(|alpha[1]|, gamma[1], ..., gamma[k-1]). */ - private double gmax; - - /** The value of min(|alpha[1]|, gamma[1], ..., gamma[k-1]). */ - private double gmin; - - /** Copy of the {@code goodb} parameter. */ - private final boolean goodb; - - /** {@code true} if the default convergence criterion is verified. */ - private boolean hasConverged; - - /** The estimate of the norm of P * rL[k-1]. */ - private double lqnorm; - - /** Reference to the preconditioner, M. */ - private final RealLinearOperator m; - - /** - * The value of (-eps[k+1] * zeta[k-1]). Was called {@code rhs2} in the - * initial code. - */ - private double minusEpsZeta; - - /** The value of M * b. */ - private final RealVector mb; - - /** The value of beta[k]. */ - private double oldb; - - /** The value of beta[k] * M^(-1) * P' * v[k]. */ - private RealVector r1; - - /** The value of beta[k+1] * M^(-1) * P' * v[k+1]. */ - private RealVector r2; - - /** - * The value of the updated, preconditioned residual P * r. This value is - * given by {@code min(}{@link #cgnorm}{@code , }{@link #lqnorm}{@code )}. - */ - private double rnorm; - - /** Copy of the {@code shift} parameter. */ - private final double shift; - - /** The value of s[1] * ... * s[k-1]. */ - private double snprod; - - /** - * An estimate of the square of the norm of A * V[k], based on Paige and - * Saunders (1975), equation (3.3). - */ - private double tnorm; - - /** - * The value of P' * wbar[k] or P' * (wbar[k] - s[1] * ... * s[k-1] * - * v[1]) if {@code goodb} is {@code true}. Was called {@code w} in the - * initial code. - */ - private RealVector wbar; - - /** - * A reference to the vector to be updated with the solution. Contains - * the value of xL[k-1] if {@code goodb} is {@code false}, (xL[k-1] - - * bstep[k-1] * v[1]) otherwise. - */ - private final RealVector xL; - - /** The value of beta[k+1] * P' * v[k+1]. */ - private RealVector y; - - /** The value of zeta[1]^2 + ... + zeta[k-1]^2. */ - private double ynorm2; - - /** The value of {@code b == 0} (exact floating-point equality). */ - private boolean bIsNull; - - static { - MACH_PREC = FastMath.ulp(1.); - CBRT_MACH_PREC = FastMath.cbrt(MACH_PREC); - } - - /** - * Creates and inits to k = 1 a new instance of this class. - * - * @param a the linear operator A of the system - * @param m the preconditioner, M (can be {@code null}) - * @param b the right-hand side vector - * @param goodb usually {@code false}, except if {@code x} is expected - * to contain a large multiple of {@code b} - * @param shift the amount to be subtracted to all diagonal elements of - * A - * @param delta the δ parameter for the default stopping criterion - * @param check {@code true} if self-adjointedness of both matrix and - * preconditioner should be checked - */ - State(final RealLinearOperator a, - final RealLinearOperator m, - final RealVector b, - final boolean goodb, - final double shift, - final double delta, - final boolean check) { - this.a = a; - this.m = m; - this.b = b; - this.xL = new ArrayRealVector(b.getDimension()); - this.goodb = goodb; - this.shift = shift; - this.mb = m == null ? b : m.operate(b); - this.hasConverged = false; - this.check = check; - this.delta = delta; - } - - /** - * Performs a symmetry check on the specified linear operator, and throws an - * exception in case this check fails. Given a linear operator L, and a - * vector x, this method checks that - * x' · L · y = y' · L · x - * (within a given accuracy), where y = L · x. - * - * @param l the linear operator L - * @param x the candidate vector x - * @param y the candidate vector y = L · x - * @param z the vector z = L · y - * @throws NonSelfAdjointOperatorException when the test fails - */ - private static void checkSymmetry(final RealLinearOperator l, - final RealVector x, final RealVector y, final RealVector z) - throws NonSelfAdjointOperatorException { - final double s = y.dotProduct(y); - final double t = x.dotProduct(z); - final double epsa = (s + MACH_PREC) * CBRT_MACH_PREC; - if (FastMath.abs(s - t) > epsa) { - final NonSelfAdjointOperatorException e; - e = new NonSelfAdjointOperatorException(); - final ExceptionContext context = e.getContext(); - context.setValue(SymmLQ.OPERATOR, l); - context.setValue(SymmLQ.VECTOR1, x); - context.setValue(SymmLQ.VECTOR2, y); - context.setValue(SymmLQ.THRESHOLD, Double.valueOf(epsa)); - throw e; - } - } - - /** - * Throws a new {@link NonPositiveDefiniteOperatorException} with - * appropriate context. - * - * @param l the offending linear operator - * @param v the offending vector - * @throws NonPositiveDefiniteOperatorException in any circumstances - */ - private static void throwNPDLOException(final RealLinearOperator l, - final RealVector v) throws NonPositiveDefiniteOperatorException { - final NonPositiveDefiniteOperatorException e; - e = new NonPositiveDefiniteOperatorException(); - final ExceptionContext context = e.getContext(); - context.setValue(OPERATOR, l); - context.setValue(VECTOR, v); - throw e; - } - - /** - * A clone of the BLAS {@code DAXPY} function, which carries out the - * operation y ← a · x + y. This is for internal use only: no - * dimension checks are provided. - * - * @param a the scalar by which {@code x} is to be multiplied - * @param x the vector to be added to {@code y} - * @param y the vector to be incremented - */ - private static void daxpy(final double a, final RealVector x, - final RealVector y) { - final int n = x.getDimension(); - for (int i = 0; i < n; i++) { - y.setEntry(i, a * x.getEntry(i) + y.getEntry(i)); - } - } - - /** - * A BLAS-like function, for the operation z ← a · x + b - * · y + z. This is for internal use only: no dimension checks are - * provided. - * - * @param a the scalar by which {@code x} is to be multiplied - * @param x the first vector to be added to {@code z} - * @param b the scalar by which {@code y} is to be multiplied - * @param y the second vector to be added to {@code z} - * @param z the vector to be incremented - */ - private static void daxpbypz(final double a, final RealVector x, - final double b, final RealVector y, final RealVector z) { - final int n = z.getDimension(); - for (int i = 0; i < n; i++) { - final double zi; - zi = a * x.getEntry(i) + b * y.getEntry(i) + z.getEntry(i); - z.setEntry(i, zi); - } - } - - /** - *

- * Move to the CG point if it seems better. In this version of SYMMLQ, - * the convergence tests involve only cgnorm, so we're unlikely to stop - * at an LQ point, except if the iteration limit interferes. - *

- *

- * Additional upudates are also carried out in case {@code goodb} is set - * to {@code true}. - *

- * - * @param x the vector to be updated with the refined value of xL - */ - void refineSolution(final RealVector x) { - final int n = this.xL.getDimension(); - if (lqnorm < cgnorm) { - if (!goodb) { - x.setSubVector(0, this.xL); - } else { - final double step = bstep / beta1; - for (int i = 0; i < n; i++) { - final double bi = mb.getEntry(i); - final double xi = this.xL.getEntry(i); - x.setEntry(i, xi + step * bi); - } - } - } else { - final double anorm = FastMath.sqrt(tnorm); - final double diag = gbar == 0. ? anorm * MACH_PREC : gbar; - final double zbar = gammaZeta / diag; - final double step = (bstep + snprod * zbar) / beta1; - // ynorm = FastMath.sqrt(ynorm2 + zbar * zbar); - if (!goodb) { - for (int i = 0; i < n; i++) { - final double xi = this.xL.getEntry(i); - final double wi = wbar.getEntry(i); - x.setEntry(i, xi + zbar * wi); - } - } else { - for (int i = 0; i < n; i++) { - final double xi = this.xL.getEntry(i); - final double wi = wbar.getEntry(i); - final double bi = mb.getEntry(i); - x.setEntry(i, xi + zbar * wi + step * bi); - } - } - } - } - - /** - * Performs the initial phase of the SYMMLQ algorithm. On return, the - * value of the state variables of {@code this} object correspond to k = - * 1. - */ - void init() { - this.xL.set(0.); - /* - * Set up y for the first Lanczos vector. y and beta1 will be zero - * if b = 0. - */ - this.r1 = this.b.copy(); - this.y = this.m == null ? this.b.copy() : this.m.operate(this.r1); - if ((this.m != null) && this.check) { - checkSymmetry(this.m, this.r1, this.y, this.m.operate(this.y)); - } - - this.beta1 = this.r1.dotProduct(this.y); - if (this.beta1 < 0.) { - throwNPDLOException(this.m, this.y); - } - if (this.beta1 == 0.) { - /* If b = 0 exactly, stop with x = 0. */ - this.bIsNull = true; - return; - } - this.bIsNull = false; - this.beta1 = FastMath.sqrt(this.beta1); - /* At this point - * r1 = b, - * y = M * b, - * beta1 = beta[1]. - */ - final RealVector v = this.y.mapMultiply(1. / this.beta1); - this.y = this.a.operate(v); - if (this.check) { - checkSymmetry(this.a, v, this.y, this.a.operate(this.y)); - } - /* - * Set up y for the second Lanczos vector. y and beta will be zero - * or very small if b is an eigenvector. - */ - daxpy(-this.shift, v, this.y); - final double alpha = v.dotProduct(this.y); - daxpy(-alpha / this.beta1, this.r1, this.y); - /* - * At this point - * alpha = alpha[1] - * y = beta[2] * M^(-1) * P' * v[2] - */ - /* Make sure r2 will be orthogonal to the first v. */ - final double vty = v.dotProduct(this.y); - final double vtv = v.dotProduct(v); - daxpy(-vty / vtv, v, this.y); - this.r2 = this.y.copy(); - if (this.m != null) { - this.y = this.m.operate(this.r2); - } - this.oldb = this.beta1; - this.beta = this.r2.dotProduct(this.y); - if (this.beta < 0.) { - throwNPDLOException(this.m, this.y); - } - this.beta = FastMath.sqrt(this.beta); - /* - * At this point - * oldb = beta[1] - * beta = beta[2] - * y = beta[2] * P' * v[2] - * r2 = beta[2] * M^(-1) * P' * v[2] - */ - this.cgnorm = this.beta1; - this.gbar = alpha; - this.dbar = this.beta; - this.gammaZeta = this.beta1; - this.minusEpsZeta = 0.; - this.bstep = 0.; - this.snprod = 1.; - this.tnorm = alpha * alpha + this.beta * this.beta; - this.ynorm2 = 0.; - this.gmax = FastMath.abs(alpha) + MACH_PREC; - this.gmin = this.gmax; - - if (this.goodb) { - this.wbar = new ArrayRealVector(this.a.getRowDimension()); - this.wbar.set(0.); - } else { - this.wbar = v; - } - updateNorms(); - } - - /** - * Performs the next iteration of the algorithm. The iteration count - * should be incremented prior to calling this method. On return, the - * value of the state variables of {@code this} object correspond to the - * current iteration count {@code k}. - */ - void update() { - final RealVector v = y.mapMultiply(1. / beta); - y = a.operate(v); - daxpbypz(-shift, v, -beta / oldb, r1, y); - final double alpha = v.dotProduct(y); - /* - * At this point - * v = P' * v[k], - * y = (A - shift * I) * P' * v[k] - beta[k] * M^(-1) * P' * v[k-1], - * alpha = v'[k] * P * (A - shift * I) * P' * v[k] - * - beta[k] * v[k]' * P * M^(-1) * P' * v[k-1] - * = v'[k] * P * (A - shift * I) * P' * v[k] - * - beta[k] * v[k]' * v[k-1] - * = alpha[k]. - */ - daxpy(-alpha / beta, r2, y); - /* - * At this point - * y = (A - shift * I) * P' * v[k] - alpha[k] * M^(-1) * P' * v[k] - * - beta[k] * M^(-1) * P' * v[k-1] - * = M^(-1) * P' * (P * (A - shift * I) * P' * v[k] -alpha[k] * v[k] - * - beta[k] * v[k-1]) - * = beta[k+1] * M^(-1) * P' * v[k+1], - * from Paige and Saunders (1975), equation (3.2). - * - * WATCH-IT: the two following lines work only because y is no longer - * updated up to the end of the present iteration, and is - * reinitialized at the beginning of the next iteration. - */ - r1 = r2; - r2 = y; - if (m != null) { - y = m.operate(r2); - } - oldb = beta; - beta = r2.dotProduct(y); - if (beta < 0.) { - throwNPDLOException(m, y); - } - beta = FastMath.sqrt(beta); - /* - * At this point - * r1 = beta[k] * M^(-1) * P' * v[k], - * r2 = beta[k+1] * M^(-1) * P' * v[k+1], - * y = beta[k+1] * P' * v[k+1], - * oldb = beta[k], - * beta = beta[k+1]. - */ - tnorm += alpha * alpha + oldb * oldb + beta * beta; - /* - * Compute the next plane rotation for Q. See Paige and Saunders - * (1975), equation (5.6), with - * gamma = gamma[k-1], - * c = c[k-1], - * s = s[k-1]. - */ - final double gamma = FastMath.sqrt(gbar * gbar + oldb * oldb); - final double c = gbar / gamma; - final double s = oldb / gamma; - /* - * The relations - * gbar[k] = s[k-1] * (-c[k-2] * beta[k]) - c[k-1] * alpha[k] - * = s[k-1] * dbar[k] - c[k-1] * alpha[k], - * delta[k] = c[k-1] * dbar[k] + s[k-1] * alpha[k], - * are not stated in Paige and Saunders (1975), but can be retrieved - * by expanding the (k, k-1) and (k, k) coefficients of the matrix in - * equation (5.5). - */ - final double deltak = c * dbar + s * alpha; - gbar = s * dbar - c * alpha; - final double eps = s * beta; - dbar = -c * beta; - final double zeta = gammaZeta / gamma; - /* - * At this point - * gbar = gbar[k] - * deltak = delta[k] - * eps = eps[k+1] - * dbar = dbar[k+1] - * zeta = zeta[k-1] - */ - final double zetaC = zeta * c; - final double zetaS = zeta * s; - final int n = xL.getDimension(); - for (int i = 0; i < n; i++) { - final double xi = xL.getEntry(i); - final double vi = v.getEntry(i); - final double wi = wbar.getEntry(i); - xL.setEntry(i, xi + wi * zetaC + vi * zetaS); - wbar.setEntry(i, wi * s - vi * c); - } - /* - * At this point - * x = xL[k-1], - * ptwbar = P' wbar[k], - * see Paige and Saunders (1975), equations (5.9) and (5.10). - */ - bstep += snprod * c * zeta; - snprod *= s; - gmax = FastMath.max(gmax, gamma); - gmin = FastMath.min(gmin, gamma); - ynorm2 += zeta * zeta; - gammaZeta = minusEpsZeta - deltak * zeta; - minusEpsZeta = -eps * zeta; - /* - * At this point - * snprod = s[1] * ... * s[k-1], - * gmax = max(|alpha[1]|, gamma[1], ..., gamma[k-1]), - * gmin = min(|alpha[1]|, gamma[1], ..., gamma[k-1]), - * ynorm2 = zeta[1]^2 + ... + zeta[k-1]^2, - * gammaZeta = gamma[k] * zeta[k], - * minusEpsZeta = -eps[k+1] * zeta[k-1]. - * The relation for gammaZeta can be retrieved from Paige and - * Saunders (1975), equation (5.4a), last line of the vector - * gbar[k] * zbar[k] = -eps[k] * zeta[k-2] - delta[k] * zeta[k-1]. - */ - updateNorms(); - } - - /** - * Computes the norms of the residuals, and checks for convergence. - * Updates {@link #lqnorm} and {@link #cgnorm}. - */ - private void updateNorms() { - final double anorm = FastMath.sqrt(tnorm); - final double ynorm = FastMath.sqrt(ynorm2); - final double epsa = anorm * MACH_PREC; - final double epsx = anorm * ynorm * MACH_PREC; - final double epsr = anorm * ynorm * delta; - final double diag = gbar == 0. ? epsa : gbar; - lqnorm = FastMath.sqrt(gammaZeta * gammaZeta + - minusEpsZeta * minusEpsZeta); - final double qrnorm = snprod * beta1; - cgnorm = qrnorm * beta / FastMath.abs(diag); - - /* - * Estimate cond(A). In this version we look at the diagonals of L - * in the factorization of the tridiagonal matrix, T = L * Q. - * Sometimes, T[k] can be misleadingly ill-conditioned when T[k+1] - * is not, so we must be careful not to overestimate acond. - */ - final double acond; - if (lqnorm <= cgnorm) { - acond = gmax / gmin; - } else { - acond = gmax / FastMath.min(gmin, FastMath.abs(diag)); - } - if (acond * MACH_PREC >= 0.1) { - throw new IllConditionedOperatorException(acond); - } - if (beta1 <= epsx) { - /* - * x has converged to an eigenvector of A corresponding to the - * eigenvalue shift. - */ - throw new SingularOperatorException(); - } - rnorm = FastMath.min(cgnorm, lqnorm); - hasConverged = (cgnorm <= epsx) || (cgnorm <= epsr); - } - - /** - * Returns {@code true} if the default stopping criterion is fulfilled. - * - * @return {@code true} if convergence of the iterations has occurred - */ - boolean hasConverged() { - return hasConverged; - } - - /** - * Returns {@code true} if the right-hand side vector is zero exactly. - * - * @return the boolean value of {@code b == 0} - */ - boolean bEqualsNullVector() { - return bIsNull; - } - - /** - * Returns {@code true} if {@code beta} is essentially zero. This method - * is used to check for early stop of the iterations. - * - * @return {@code true} if {@code beta < }{@link #MACH_PREC} - */ - boolean betaEqualsZero() { - return beta < MACH_PREC; - } - - /** - * Returns the norm of the updated, preconditioned residual. - * - * @return the norm of the residual, ||P * r|| - */ - double getNormOfResidual() { - return rnorm; - } - } - - /** Key for the exception context. */ - private static final String OPERATOR = "operator"; - - /** Key for the exception context. */ - private static final String THRESHOLD = "threshold"; - - /** Key for the exception context. */ - private static final String VECTOR = "vector"; - - /** Key for the exception context. */ - private static final String VECTOR1 = "vector1"; - - /** Key for the exception context. */ - private static final String VECTOR2 = "vector2"; - - /** {@code true} if symmetry of matrix and conditioner must be checked. */ - private final boolean check; - - /** - * The value of the custom tolerance δ for the default stopping - * criterion. - */ - private final double delta; - - /** - * Creates a new instance of this class, with default - * stopping criterion. Note that setting {@code check} to {@code true} - * entails an extra matrix-vector product in the initial phase. - * - * @param maxIterations the maximum number of iterations - * @param delta the δ parameter for the default stopping criterion - * @param check {@code true} if self-adjointedness of both matrix and - * preconditioner should be checked - */ - public SymmLQ(final int maxIterations, final double delta, - final boolean check) { - super(maxIterations); - this.delta = delta; - this.check = check; - } - - /** - * Creates a new instance of this class, with default - * stopping criterion and custom iteration manager. Note that setting - * {@code check} to {@code true} entails an extra matrix-vector product in - * the initial phase. - * - * @param manager the custom iteration manager - * @param delta the δ parameter for the default stopping criterion - * @param check {@code true} if self-adjointedness of both matrix and - * preconditioner should be checked - */ - public SymmLQ(final IterationManager manager, final double delta, - final boolean check) { - super(manager); - this.delta = delta; - this.check = check; - } - - /** - * Returns {@code true} if symmetry of the matrix, and symmetry as well as - * positive definiteness of the preconditioner should be checked. - * - * @return {@code true} if the tests are to be performed - */ - public final boolean getCheck() { - return check; - } - - /** - * {@inheritDoc} - * - * @throws NonSelfAdjointOperatorException if {@link #getCheck()} is - * {@code true}, and {@code a} or {@code m} is not self-adjoint - * @throws NonPositiveDefiniteOperatorException if {@code m} is not - * positive definite - * @throws IllConditionedOperatorException if {@code a} is ill-conditioned - */ - @Override - public RealVector solve(final RealLinearOperator a, - final RealLinearOperator m, final RealVector b) throws - NullArgumentException, NonSquareOperatorException, - DimensionMismatchException, MaxCountExceededException, - NonSelfAdjointOperatorException, NonPositiveDefiniteOperatorException, - IllConditionedOperatorException { - MathUtils.checkNotNull(a); - final RealVector x = new ArrayRealVector(a.getColumnDimension()); - return solveInPlace(a, m, b, x, false, 0.); - } - - /** - * Returns an estimate of the solution to the linear system (A - shift - * · I) · x = b. - *

- * If the solution x is expected to contain a large multiple of {@code b} - * (as in Rayleigh-quotient iteration), then better precision may be - * achieved with {@code goodb} set to {@code true}; this however requires an - * extra call to the preconditioner. - *

- *

- * {@code shift} should be zero if the system A · x = b is to be - * solved. Otherwise, it could be an approximation to an eigenvalue of A, - * such as the Rayleigh quotient bT · A · b / - * (bT · b) corresponding to the vector b. If b is - * sufficiently like an eigenvector corresponding to an eigenvalue near - * shift, then the computed x may have very large components. When - * normalized, x may be closer to an eigenvector than b. - *

- * - * @param a the linear operator A of the system - * @param m the preconditioner, M (can be {@code null}) - * @param b the right-hand side vector - * @param goodb usually {@code false}, except if {@code x} is expected to - * contain a large multiple of {@code b} - * @param shift the amount to be subtracted to all diagonal elements of A - * @return a reference to {@code x} (shallow copy) - * @throws NullArgumentException if one of the parameters is {@code null} - * @throws NonSquareOperatorException if {@code a} or {@code m} is not square - * @throws DimensionMismatchException if {@code m} or {@code b} have dimensions - * inconsistent with {@code a} - * @throws MaxCountExceededException at exhaustion of the iteration count, - * unless a custom - * {@link org.apache.commons.math4.util.Incrementor.MaxCountExceededCallback callback} - * has been set at construction of the {@link IterationManager} - * @throws NonSelfAdjointOperatorException if {@link #getCheck()} is - * {@code true}, and {@code a} or {@code m} is not self-adjoint - * @throws NonPositiveDefiniteOperatorException if {@code m} is not - * positive definite - * @throws IllConditionedOperatorException if {@code a} is ill-conditioned - */ - public RealVector solve(final RealLinearOperator a, - final RealLinearOperator m, final RealVector b, final boolean goodb, - final double shift) throws NullArgumentException, - NonSquareOperatorException, DimensionMismatchException, - MaxCountExceededException, NonSelfAdjointOperatorException, - NonPositiveDefiniteOperatorException, IllConditionedOperatorException { - MathUtils.checkNotNull(a); - final RealVector x = new ArrayRealVector(a.getColumnDimension()); - return solveInPlace(a, m, b, x, goodb, shift); - } - - /** - * {@inheritDoc} - * - * @param x not meaningful in this implementation; should not be considered - * as an initial guess (more) - * @throws NonSelfAdjointOperatorException if {@link #getCheck()} is - * {@code true}, and {@code a} or {@code m} is not self-adjoint - * @throws NonPositiveDefiniteOperatorException if {@code m} is not positive - * definite - * @throws IllConditionedOperatorException if {@code a} is ill-conditioned - */ - @Override - public RealVector solve(final RealLinearOperator a, - final RealLinearOperator m, final RealVector b, final RealVector x) - throws NullArgumentException, NonSquareOperatorException, - DimensionMismatchException, NonSelfAdjointOperatorException, - NonPositiveDefiniteOperatorException, IllConditionedOperatorException, - MaxCountExceededException { - MathUtils.checkNotNull(x); - return solveInPlace(a, m, b, x.copy(), false, 0.); - } - - /** - * {@inheritDoc} - * - * @throws NonSelfAdjointOperatorException if {@link #getCheck()} is - * {@code true}, and {@code a} is not self-adjoint - * @throws IllConditionedOperatorException if {@code a} is ill-conditioned - */ - @Override - public RealVector solve(final RealLinearOperator a, final RealVector b) - throws NullArgumentException, NonSquareOperatorException, - DimensionMismatchException, NonSelfAdjointOperatorException, - IllConditionedOperatorException, MaxCountExceededException { - MathUtils.checkNotNull(a); - final RealVector x = new ArrayRealVector(a.getColumnDimension()); - x.set(0.); - return solveInPlace(a, null, b, x, false, 0.); - } - - /** - * Returns the solution to the system (A - shift · I) · x = b. - *

- * If the solution x is expected to contain a large multiple of {@code b} - * (as in Rayleigh-quotient iteration), then better precision may be - * achieved with {@code goodb} set to {@code true}. - *

- *

- * {@code shift} should be zero if the system A · x = b is to be - * solved. Otherwise, it could be an approximation to an eigenvalue of A, - * such as the Rayleigh quotient bT · A · b / - * (bT · b) corresponding to the vector b. If b is - * sufficiently like an eigenvector corresponding to an eigenvalue near - * shift, then the computed x may have very large components. When - * normalized, x may be closer to an eigenvector than b. - *

- * - * @param a the linear operator A of the system - * @param b the right-hand side vector - * @param goodb usually {@code false}, except if {@code x} is expected to - * contain a large multiple of {@code b} - * @param shift the amount to be subtracted to all diagonal elements of A - * @return a reference to {@code x} - * @throws NullArgumentException if one of the parameters is {@code null} - * @throws NonSquareOperatorException if {@code a} is not square - * @throws DimensionMismatchException if {@code b} has dimensions - * inconsistent with {@code a} - * @throws MaxCountExceededException at exhaustion of the iteration count, - * unless a custom - * {@link org.apache.commons.math4.util.Incrementor.MaxCountExceededCallback callback} - * has been set at construction of the {@link IterationManager} - * @throws NonSelfAdjointOperatorException if {@link #getCheck()} is - * {@code true}, and {@code a} is not self-adjoint - * @throws IllConditionedOperatorException if {@code a} is ill-conditioned - */ - public RealVector solve(final RealLinearOperator a, final RealVector b, - final boolean goodb, final double shift) throws NullArgumentException, - NonSquareOperatorException, DimensionMismatchException, - NonSelfAdjointOperatorException, IllConditionedOperatorException, - MaxCountExceededException { - MathUtils.checkNotNull(a); - final RealVector x = new ArrayRealVector(a.getColumnDimension()); - return solveInPlace(a, null, b, x, goodb, shift); - } - - /** - * {@inheritDoc} - * - * @param x not meaningful in this implementation; should not be considered - * as an initial guess (more) - * @throws NonSelfAdjointOperatorException if {@link #getCheck()} is - * {@code true}, and {@code a} is not self-adjoint - * @throws IllConditionedOperatorException if {@code a} is ill-conditioned - */ - @Override - public RealVector solve(final RealLinearOperator a, final RealVector b, - final RealVector x) throws NullArgumentException, - NonSquareOperatorException, DimensionMismatchException, - NonSelfAdjointOperatorException, IllConditionedOperatorException, - MaxCountExceededException { - MathUtils.checkNotNull(x); - return solveInPlace(a, null, b, x.copy(), false, 0.); - } - - /** - * {@inheritDoc} - * - * @param x the vector to be updated with the solution; {@code x} should - * not be considered as an initial guess (more) - * @throws NonSelfAdjointOperatorException if {@link #getCheck()} is - * {@code true}, and {@code a} or {@code m} is not self-adjoint - * @throws NonPositiveDefiniteOperatorException if {@code m} is not - * positive definite - * @throws IllConditionedOperatorException if {@code a} is ill-conditioned - */ - @Override - public RealVector solveInPlace(final RealLinearOperator a, - final RealLinearOperator m, final RealVector b, final RealVector x) - throws NullArgumentException, NonSquareOperatorException, - DimensionMismatchException, NonSelfAdjointOperatorException, - NonPositiveDefiniteOperatorException, IllConditionedOperatorException, - MaxCountExceededException { - return solveInPlace(a, m, b, x, false, 0.); - } - - /** - * Returns an estimate of the solution to the linear system (A - shift - * · I) · x = b. The solution is computed in-place. - *

- * If the solution x is expected to contain a large multiple of {@code b} - * (as in Rayleigh-quotient iteration), then better precision may be - * achieved with {@code goodb} set to {@code true}; this however requires an - * extra call to the preconditioner. - *

- *

- * {@code shift} should be zero if the system A · x = b is to be - * solved. Otherwise, it could be an approximation to an eigenvalue of A, - * such as the Rayleigh quotient bT · A · b / - * (bT · b) corresponding to the vector b. If b is - * sufficiently like an eigenvector corresponding to an eigenvalue near - * shift, then the computed x may have very large components. When - * normalized, x may be closer to an eigenvector than b. - *

- * - * @param a the linear operator A of the system - * @param m the preconditioner, M (can be {@code null}) - * @param b the right-hand side vector - * @param x the vector to be updated with the solution; {@code x} should - * not be considered as an initial guess (more) - * @param goodb usually {@code false}, except if {@code x} is expected to - * contain a large multiple of {@code b} - * @param shift the amount to be subtracted to all diagonal elements of A - * @return a reference to {@code x} (shallow copy). - * @throws NullArgumentException if one of the parameters is {@code null} - * @throws NonSquareOperatorException if {@code a} or {@code m} is not square - * @throws DimensionMismatchException if {@code m}, {@code b} or {@code x} - * have dimensions inconsistent with {@code a}. - * @throws MaxCountExceededException at exhaustion of the iteration count, - * unless a custom - * {@link org.apache.commons.math4.util.Incrementor.MaxCountExceededCallback callback} - * has been set at construction of the {@link IterationManager} - * @throws NonSelfAdjointOperatorException if {@link #getCheck()} is - * {@code true}, and {@code a} or {@code m} is not self-adjoint - * @throws NonPositiveDefiniteOperatorException if {@code m} is not positive - * definite - * @throws IllConditionedOperatorException if {@code a} is ill-conditioned - */ - public RealVector solveInPlace(final RealLinearOperator a, - final RealLinearOperator m, final RealVector b, - final RealVector x, final boolean goodb, final double shift) - throws NullArgumentException, NonSquareOperatorException, - DimensionMismatchException, NonSelfAdjointOperatorException, - NonPositiveDefiniteOperatorException, IllConditionedOperatorException, - MaxCountExceededException { - checkParameters(a, m, b, x); - - final IterationManager manager = getIterationManager(); - /* Initialization counts as an iteration. */ - manager.resetIterationCount(); - manager.incrementIterationCount(); - - final State state; - state = new State(a, m, b, goodb, shift, delta, check); - state.init(); - state.refineSolution(x); - IterativeLinearSolverEvent event; - event = new DefaultIterativeLinearSolverEvent(this, - manager.getIterations(), - x, - b, - state.getNormOfResidual()); - if (state.bEqualsNullVector()) { - /* If b = 0 exactly, stop with x = 0. */ - manager.fireTerminationEvent(event); - return x; - } - /* Cause termination if beta is essentially zero. */ - final boolean earlyStop; - earlyStop = state.betaEqualsZero() || state.hasConverged(); - manager.fireInitializationEvent(event); - if (!earlyStop) { - do { - manager.incrementIterationCount(); - event = new DefaultIterativeLinearSolverEvent(this, - manager.getIterations(), - x, - b, - state.getNormOfResidual()); - manager.fireIterationStartedEvent(event); - state.update(); - state.refineSolution(x); - event = new DefaultIterativeLinearSolverEvent(this, - manager.getIterations(), - x, - b, - state.getNormOfResidual()); - manager.fireIterationPerformedEvent(event); - } while (!state.hasConverged()); - } - event = new DefaultIterativeLinearSolverEvent(this, - manager.getIterations(), - x, - b, - state.getNormOfResidual()); - manager.fireTerminationEvent(event); - return x; - } - - /** - * {@inheritDoc} - * - * @param x the vector to be updated with the solution; {@code x} should - * not be considered as an initial guess (more) - * @throws NonSelfAdjointOperatorException if {@link #getCheck()} is - * {@code true}, and {@code a} is not self-adjoint - * @throws IllConditionedOperatorException if {@code a} is ill-conditioned - */ - @Override - public RealVector solveInPlace(final RealLinearOperator a, - final RealVector b, final RealVector x) throws NullArgumentException, - NonSquareOperatorException, DimensionMismatchException, - NonSelfAdjointOperatorException, IllConditionedOperatorException, - MaxCountExceededException { - return solveInPlace(a, null, b, x, false, 0.); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/TriDiagonalTransformer.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/TriDiagonalTransformer.java deleted file mode 100644 index dea5da11e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/TriDiagonalTransformer.java +++ /dev/null @@ -1,253 +0,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. - */ - -package org.apache.commons.math4.linear; - -import java.util.Arrays; - -import org.apache.commons.math4.util.FastMath; - - -/** - * Class transforming a symmetrical matrix to tridiagonal shape. - *

A symmetrical m × m matrix A can be written as the product of three matrices: - * A = Q × T × QT with Q an orthogonal matrix and T a symmetrical - * tridiagonal matrix. Both Q and T are m × m matrices.

- *

This implementation only uses the upper part of the matrix, the part below the - * diagonal is not accessed at all.

- *

Transformation to tridiagonal shape is often not a goal by itself, but it is - * an intermediate step in more general decomposition algorithms like {@link - * EigenDecomposition eigen decomposition}. This class is therefore intended for internal - * use by the library and is not public. As a consequence of this explicitly limited scope, - * many methods directly returns references to internal arrays, not copies.

- * @since 2.0 - */ -class TriDiagonalTransformer { - /** Householder vectors. */ - private final double householderVectors[][]; - /** Main diagonal. */ - private final double[] main; - /** Secondary diagonal. */ - private final double[] secondary; - /** Cached value of Q. */ - private RealMatrix cachedQ; - /** Cached value of Qt. */ - private RealMatrix cachedQt; - /** Cached value of T. */ - private RealMatrix cachedT; - - /** - * Build the transformation to tridiagonal shape of a symmetrical matrix. - *

The specified matrix is assumed to be symmetrical without any check. - * Only the upper triangular part of the matrix is used.

- * - * @param matrix Symmetrical matrix to transform. - * @throws NonSquareMatrixException if the matrix is not square. - */ - TriDiagonalTransformer(RealMatrix matrix) { - if (!matrix.isSquare()) { - throw new NonSquareMatrixException(matrix.getRowDimension(), - matrix.getColumnDimension()); - } - - final int m = matrix.getRowDimension(); - householderVectors = matrix.getData(); - main = new double[m]; - secondary = new double[m - 1]; - cachedQ = null; - cachedQt = null; - cachedT = null; - - // transform matrix - transform(); - } - - /** - * Returns the matrix Q of the transform. - *

Q is an orthogonal matrix, i.e. its transpose is also its inverse.

- * @return the Q matrix - */ - public RealMatrix getQ() { - if (cachedQ == null) { - cachedQ = getQT().transpose(); - } - return cachedQ; - } - - /** - * Returns the transpose of the matrix Q of the transform. - *

Q is an orthogonal matrix, i.e. its transpose is also its inverse.

- * @return the Q matrix - */ - public RealMatrix getQT() { - if (cachedQt == null) { - final int m = householderVectors.length; - double[][] qta = new double[m][m]; - - // build up first part of the matrix by applying Householder transforms - for (int k = m - 1; k >= 1; --k) { - final double[] hK = householderVectors[k - 1]; - qta[k][k] = 1; - if (hK[k] != 0.0) { - final double inv = 1.0 / (secondary[k - 1] * hK[k]); - double beta = 1.0 / secondary[k - 1]; - qta[k][k] = 1 + beta * hK[k]; - for (int i = k + 1; i < m; ++i) { - qta[k][i] = beta * hK[i]; - } - for (int j = k + 1; j < m; ++j) { - beta = 0; - for (int i = k + 1; i < m; ++i) { - beta += qta[j][i] * hK[i]; - } - beta *= inv; - qta[j][k] = beta * hK[k]; - for (int i = k + 1; i < m; ++i) { - qta[j][i] += beta * hK[i]; - } - } - } - } - qta[0][0] = 1; - cachedQt = MatrixUtils.createRealMatrix(qta); - } - - // return the cached matrix - return cachedQt; - } - - /** - * Returns the tridiagonal matrix T of the transform. - * @return the T matrix - */ - public RealMatrix getT() { - if (cachedT == null) { - final int m = main.length; - double[][] ta = new double[m][m]; - for (int i = 0; i < m; ++i) { - ta[i][i] = main[i]; - if (i > 0) { - ta[i][i - 1] = secondary[i - 1]; - } - if (i < main.length - 1) { - ta[i][i + 1] = secondary[i]; - } - } - cachedT = MatrixUtils.createRealMatrix(ta); - } - - // return the cached matrix - return cachedT; - } - - /** - * Get the Householder vectors of the transform. - *

Note that since this class is only intended for internal use, - * it returns directly a reference to its internal arrays, not a copy.

- * @return the main diagonal elements of the B matrix - */ - double[][] getHouseholderVectorsRef() { - return householderVectors; - } - - /** - * Get the main diagonal elements of the matrix T of the transform. - *

Note that since this class is only intended for internal use, - * it returns directly a reference to its internal arrays, not a copy.

- * @return the main diagonal elements of the T matrix - */ - double[] getMainDiagonalRef() { - return main; - } - - /** - * Get the secondary diagonal elements of the matrix T of the transform. - *

Note that since this class is only intended for internal use, - * it returns directly a reference to its internal arrays, not a copy.

- * @return the secondary diagonal elements of the T matrix - */ - double[] getSecondaryDiagonalRef() { - return secondary; - } - - /** - * Transform original matrix to tridiagonal form. - *

Transformation is done using Householder transforms.

- */ - private void transform() { - final int m = householderVectors.length; - final double[] z = new double[m]; - for (int k = 0; k < m - 1; k++) { - - //zero-out a row and a column simultaneously - final double[] hK = householderVectors[k]; - main[k] = hK[k]; - double xNormSqr = 0; - for (int j = k + 1; j < m; ++j) { - final double c = hK[j]; - xNormSqr += c * c; - } - final double a = (hK[k + 1] > 0) ? -FastMath.sqrt(xNormSqr) : FastMath.sqrt(xNormSqr); - secondary[k] = a; - if (a != 0.0) { - // apply Householder transform from left and right simultaneously - - hK[k + 1] -= a; - final double beta = -1 / (a * hK[k + 1]); - - // compute a = beta A v, where v is the Householder vector - // this loop is written in such a way - // 1) only the upper triangular part of the matrix is accessed - // 2) access is cache-friendly for a matrix stored in rows - Arrays.fill(z, k + 1, m, 0); - for (int i = k + 1; i < m; ++i) { - final double[] hI = householderVectors[i]; - final double hKI = hK[i]; - double zI = hI[i] * hKI; - for (int j = i + 1; j < m; ++j) { - final double hIJ = hI[j]; - zI += hIJ * hK[j]; - z[j] += hIJ * hKI; - } - z[i] = beta * (z[i] + zI); - } - - // compute gamma = beta vT z / 2 - double gamma = 0; - for (int i = k + 1; i < m; ++i) { - gamma += z[i] * hK[i]; - } - gamma *= beta / 2; - - // compute z = z - gamma v - for (int i = k + 1; i < m; ++i) { - z[i] -= gamma * hK[i]; - } - - // update matrix: A = A - v zT - z vT - // only the upper triangular part of the matrix is updated - for (int i = k + 1; i < m; ++i) { - final double[] hI = householderVectors[i]; - for (int j = i; j < m; ++j) { - hI[j] -= hK[i] * z[j] + z[i] * hK[j]; - } - } - } - } - main[m - 1] = householderVectors[m - 1][m - 1]; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/package-info.java deleted file mode 100644 index a1a091eca..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/package-info.java +++ /dev/null @@ -1,20 +0,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. - */ -/** - * Linear algebra support. - */ -package org.apache.commons.math4.linear; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/package-info.java deleted file mode 100644 index 86871c6d1..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/package-info.java +++ /dev/null @@ -1,20 +0,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. - */ -/** - * Common classes used throughout the commons-math library. - */ -package org.apache.commons.math4; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/CorrelatedRandomVectorGenerator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/CorrelatedRandomVectorGenerator.java deleted file mode 100644 index a16768626..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/CorrelatedRandomVectorGenerator.java +++ /dev/null @@ -1,185 +0,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. - */ - -package org.apache.commons.math4.random; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.linear.RealMatrix; -import org.apache.commons.math4.linear.RectangularCholeskyDecomposition; - -/** - * A {@link RandomVectorGenerator} that generates vectors with with - * correlated components. - *

Random vectors with correlated components are built by combining - * the uncorrelated components of another random vector in such a way that - * the resulting correlations are the ones specified by a positive - * definite covariance matrix.

- *

The main use for correlated random vector generation is for Monte-Carlo - * simulation of physical problems with several variables, for example to - * generate error vectors to be added to a nominal vector. A particularly - * interesting case is when the generated vector should be drawn from a - * Multivariate Normal Distribution. The approach using a Cholesky - * decomposition is quite usual in this case. However, it can be extended - * to other cases as long as the underlying random generator provides - * {@link NormalizedRandomGenerator normalized values} like {@link - * GaussianRandomGenerator} or {@link UniformRandomGenerator}.

- *

Sometimes, the covariance matrix for a given simulation is not - * strictly positive definite. This means that the correlations are - * not all independent from each other. In this case, however, the non - * strictly positive elements found during the Cholesky decomposition - * of the covariance matrix should not be negative either, they - * should be null. Another non-conventional extension handling this case - * is used here. Rather than computing C = UT.U - * where C is the covariance matrix and U - * is an upper-triangular matrix, we compute C = B.BT - * where B is a rectangular matrix having - * more rows than columns. The number of columns of B is - * the rank of the covariance matrix, and it is the dimension of the - * uncorrelated random vector that is needed to compute the component - * of the correlated vector. This class handles this situation - * automatically.

- * - * @since 1.2 - */ - -public class CorrelatedRandomVectorGenerator - implements RandomVectorGenerator { - /** Mean vector. */ - private final double[] mean; - /** Underlying generator. */ - private final NormalizedRandomGenerator generator; - /** Storage for the normalized vector. */ - private final double[] normalized; - /** Root of the covariance matrix. */ - private final RealMatrix root; - - /** - * Builds a correlated random vector generator from its mean - * vector and covariance matrix. - * - * @param mean Expected mean values for all components. - * @param covariance Covariance matrix. - * @param small Diagonal elements threshold under which column are - * considered to be dependent on previous ones and are discarded - * @param generator underlying generator for uncorrelated normalized - * components. - * @throws org.apache.commons.math4.linear.NonPositiveDefiniteMatrixException - * if the covariance matrix is not strictly positive definite. - * @throws DimensionMismatchException if the mean and covariance - * arrays dimensions do not match. - */ - public CorrelatedRandomVectorGenerator(double[] mean, - RealMatrix covariance, double small, - NormalizedRandomGenerator generator) { - int order = covariance.getRowDimension(); - if (mean.length != order) { - throw new DimensionMismatchException(mean.length, order); - } - this.mean = mean.clone(); - - final RectangularCholeskyDecomposition decomposition = - new RectangularCholeskyDecomposition(covariance, small); - root = decomposition.getRootMatrix(); - - this.generator = generator; - normalized = new double[decomposition.getRank()]; - - } - - /** - * Builds a null mean random correlated vector generator from its - * covariance matrix. - * - * @param covariance Covariance matrix. - * @param small Diagonal elements threshold under which column are - * considered to be dependent on previous ones and are discarded. - * @param generator Underlying generator for uncorrelated normalized - * components. - * @throws org.apache.commons.math4.linear.NonPositiveDefiniteMatrixException - * if the covariance matrix is not strictly positive definite. - */ - public CorrelatedRandomVectorGenerator(RealMatrix covariance, double small, - NormalizedRandomGenerator generator) { - int order = covariance.getRowDimension(); - mean = new double[order]; - for (int i = 0; i < order; ++i) { - mean[i] = 0; - } - - final RectangularCholeskyDecomposition decomposition = - new RectangularCholeskyDecomposition(covariance, small); - root = decomposition.getRootMatrix(); - - this.generator = generator; - normalized = new double[decomposition.getRank()]; - - } - - /** Get the underlying normalized components generator. - * @return underlying uncorrelated components generator - */ - public NormalizedRandomGenerator getGenerator() { - return generator; - } - - /** Get the rank of the covariance matrix. - * The rank is the number of independent rows in the covariance - * matrix, it is also the number of columns of the root matrix. - * @return rank of the square matrix. - * @see #getRootMatrix() - */ - public int getRank() { - return normalized.length; - } - - /** Get the root of the covariance matrix. - * The root is the rectangular matrix B such that - * the covariance matrix is equal to B.BT - * @return root of the square matrix - * @see #getRank() - */ - public RealMatrix getRootMatrix() { - return root; - } - - /** Generate a correlated random vector. - * @return a random vector as an array of double. The returned array - * is created at each call, the caller can do what it wants with it. - */ - @Override - public double[] nextVector() { - - // generate uncorrelated vector - for (int i = 0; i < normalized.length; ++i) { - normalized[i] = generator.nextNormalizedDouble(); - } - - // compute correlated vector - double[] correlated = new double[mean.length]; - for (int i = 0; i < correlated.length; ++i) { - correlated[i] = mean[i]; - for (int j = 0; j < root.getColumnDimension(); ++j) { - correlated[i] += root.getEntry(i, j) * normalized[j]; - } - } - - return correlated; - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/GaussianRandomGenerator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/GaussianRandomGenerator.java deleted file mode 100644 index 5c108c0f5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/GaussianRandomGenerator.java +++ /dev/null @@ -1,51 +0,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. - */ - -package org.apache.commons.math4.random; - -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.NormalizedGaussianSampler; -import org.apache.commons.rng.sampling.distribution.MarsagliaNormalizedGaussianSampler; - -/** - * Random generator that generates normally distributed samples. - * - * @since 1.2 - */ -public class GaussianRandomGenerator implements NormalizedRandomGenerator { - /** Gaussian distribution sampler. */ - private final NormalizedGaussianSampler sampler; - - /** - * Creates a new generator. - * - * @param generator Underlying random generator. - */ - public GaussianRandomGenerator(final UniformRandomProvider generator) { - sampler = new MarsagliaNormalizedGaussianSampler(generator); - } - - /** - * Generates a random scalar with zero mean and unit standard deviation. - * - * @return a random value sampled from a normal distribution. - */ - @Override - public double nextNormalizedDouble() { - return sampler.sample(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/HaltonSequenceGenerator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/HaltonSequenceGenerator.java deleted file mode 100644 index efbe21d7b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/HaltonSequenceGenerator.java +++ /dev/null @@ -1,184 +0,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. - */ -package org.apache.commons.math4.random; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.util.MathUtils; - -/** - * Implementation of a Halton sequence. - *

- * A Halton sequence is a low-discrepancy sequence generating points in the interval [0, 1] according to - *

- *   H(n) = d_0 / b + d_1 / b^2 .... d_j / b^j+1
- *
- *   with
- *
- *   n = d_j * b^j-1 + ... d_1 * b + d_0 * b^0
- * 
- * For higher dimensions, subsequent prime numbers are used as base, e.g. { 2, 3, 5 } for a Halton sequence in R^3. - *

- * Halton sequences are known to suffer from linear correlation for larger prime numbers, thus the individual digits - * are usually scrambled. This implementation already comes with support for up to 40 dimensions with optimal weight - * numbers from - * H. Chi: Scrambled quasirandom sequences and their applications. - *

- * The generator supports two modes: - *

    - *
  • sequential generation of points: {@link #nextVector()}
  • - *
  • random access to the i-th point in the sequence: {@link #skipTo(int)}
  • - *
- * - * @see Halton sequence (Wikipedia) - * @see - * On the Halton sequence and its scramblings - * @since 3.3 - */ -public class HaltonSequenceGenerator implements RandomVectorGenerator { - - /** The first 40 primes. */ - private static final int[] PRIMES = new int[] { - 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, - 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, - 149, 151, 157, 163, 167, 173 - }; - - /** The optimal weights used for scrambling of the first 40 dimension. */ - private static final int[] WEIGHTS = new int[] { - 1, 2, 3, 3, 8, 11, 12, 14, 7, 18, 12, 13, 17, 18, 29, 14, 18, 43, 41, - 44, 40, 30, 47, 65, 71, 28, 40, 60, 79, 89, 56, 50, 52, 61, 108, 56, - 66, 63, 60, 66 - }; - - /** Space dimension. */ - private final int dimension; - - /** The current index in the sequence. */ - private int count = 0; - - /** The base numbers for each component. */ - private final int[] base; - - /** The scrambling weights for each component. */ - private final int[] weight; - - /** - * Construct a new Halton sequence generator for the given space dimension. - * - * @param dimension the space dimension - * @throws OutOfRangeException if the space dimension is outside the allowed range of [1, 40] - */ - public HaltonSequenceGenerator(final int dimension) throws OutOfRangeException { - this(dimension, PRIMES, WEIGHTS); - } - - /** - * Construct a new Halton sequence generator with the given base numbers and weights for each dimension. - * The length of the bases array defines the space dimension and is required to be > 0. - * - * @param dimension the space dimension - * @param bases the base number for each dimension, entries should be (pairwise) prime, may not be null - * @param weights the weights used during scrambling, may be null in which case no scrambling will be performed - * @throws NullArgumentException if base is null - * @throws OutOfRangeException if the space dimension is outside the range [1, len], where - * len refers to the length of the bases array - * @throws DimensionMismatchException if weights is non-null and the length of the input arrays differ - */ - public HaltonSequenceGenerator(final int dimension, final int[] bases, final int[] weights) - throws NullArgumentException, OutOfRangeException, DimensionMismatchException { - - MathUtils.checkNotNull(bases); - - if (dimension < 1 || dimension > bases.length) { - throw new OutOfRangeException(dimension, 1, PRIMES.length); - } - - if (weights != null && weights.length != bases.length) { - throw new DimensionMismatchException(weights.length, bases.length); - } - - this.dimension = dimension; - this.base = bases.clone(); - this.weight = weights == null ? null : weights.clone(); - count = 0; - } - - /** {@inheritDoc} */ - @Override - public double[] nextVector() { - final double[] v = new double[dimension]; - for (int i = 0; i < dimension; i++) { - int index = count; - double f = 1.0 / base[i]; - - int j = 0; - while (index > 0) { - final int digit = scramble(i, j, base[i], index % base[i]); - v[i] += f * digit; - index /= base[i]; // floor( index / base ) - f /= base[i]; - } - } - count++; - return v; - } - - /** - * Performs scrambling of digit {@code d_j} according to the formula: - *
-     *   ( weight_i * d_j ) mod base
-     * 
- * Implementations can override this method to do a different scrambling. - * - * @param i the dimension index - * @param j the digit index - * @param b the base for this dimension - * @param digit the j-th digit - * @return the scrambled digit - */ - protected int scramble(final int i, final int j, final int b, final int digit) { - return weight != null ? (weight[i] * digit) % b : digit; - } - - /** - * Skip to the i-th point in the Halton sequence. - *

- * This operation can be performed in O(1). - * - * @param index the index in the sequence to skip to - * @return the i-th point in the Halton sequence - * @throws NotPositiveException if index < 0 - */ - public double[] skipTo(final int index) throws NotPositiveException { - count = index; - return nextVector(); - } - - /** - * Returns the index i of the next point in the Halton sequence that will be returned - * by calling {@link #nextVector()}. - * - * @return the index of the next point - */ - public int getNextIndex() { - return count; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/NormalizedRandomGenerator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/NormalizedRandomGenerator.java deleted file mode 100644 index 0574cc726..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/NormalizedRandomGenerator.java +++ /dev/null @@ -1,37 +0,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. - */ - -package org.apache.commons.math4.random; - -/** - * This interface represent a normalized random generator for - * scalars. - * Normalized generator provide null mean and unit standard deviation scalars. - * @since 1.2 - */ -public interface NormalizedRandomGenerator { - - /** Generate a random scalar with null mean and unit standard deviation. - *

This method does not specify the shape of the - * distribution, it is the implementing class that provides it. The - * only contract here is to generate numbers with null mean and unit - * standard deviation.

- * @return a random scalar with null mean and unit standard deviation - */ - double nextNormalizedDouble(); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/RandomGenerator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/RandomGenerator.java deleted file mode 100644 index 72dfbd6be..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/RandomGenerator.java +++ /dev/null @@ -1,148 +0,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. - */ -package org.apache.commons.math4.random; - - -/** - * Interface extracted from java.util.Random. - * - * @since 1.1 - * @deprecated As of 4.0. Please use {@link org.apache.commons.rng.UniformRandomProvider} instead. - */ -@Deprecated -public interface RandomGenerator { - - /** - * Sets the seed of the underlying random number generator using an - * int seed. - *

Sequences of values generated starting with the same seeds - * should be identical. - *

- * @param seed the seed value - */ - void setSeed(int seed); - - /** - * Sets the seed of the underlying random number generator using an - * int array seed. - *

Sequences of values generated starting with the same seeds - * should be identical. - *

- * @param seed the seed value - */ - void setSeed(int[] seed); - - /** - * Sets the seed of the underlying random number generator using a - * long seed. - *

Sequences of values generated starting with the same seeds - * should be identical. - *

- * @param seed the seed value - */ - void setSeed(long seed); - - /** - * Generates random bytes and places them into a user-supplied - * byte array. The number of random bytes produced is equal to - * the length of the byte array. - * - * @param bytes the non-null byte array in which to put the - * random bytes - */ - void nextBytes(byte[] bytes); - - /** - * Returns the next pseudorandom, uniformly distributed int - * value from this random number generator's sequence. - * All 232 possible {@code int} values - * should be produced with (approximately) equal probability. - * - * @return the next pseudorandom, uniformly distributed int - * value from this random number generator's sequence - */ - int nextInt(); - - /** - * Returns a pseudorandom, uniformly distributed {@code int} value - * between 0 (inclusive) and the specified value (exclusive), drawn from - * this random number generator's sequence. - * - * @param n the bound on the random number to be returned. Must be - * positive. - * @return a pseudorandom, uniformly distributed {@code int} - * value between 0 (inclusive) and n (exclusive). - * @throws IllegalArgumentException if n is not positive. - */ - int nextInt(int n); - - /** - * Returns the next pseudorandom, uniformly distributed long - * value from this random number generator's sequence. All - * 264 possible {@code long} values - * should be produced with (approximately) equal probability. - * - * @return the next pseudorandom, uniformly distributed long - *value from this random number generator's sequence - */ - long nextLong(); - - /** - * Returns the next pseudorandom, uniformly distributed - * boolean value from this random number generator's - * sequence. - * - * @return the next pseudorandom, uniformly distributed - * boolean value from this random number generator's - * sequence - */ - boolean nextBoolean(); - - /** - * Returns the next pseudorandom, uniformly distributed float - * value between 0.0 and 1.0 from this random - * number generator's sequence. - * - * @return the next pseudorandom, uniformly distributed float - * value between 0.0 and 1.0 from this - * random number generator's sequence - */ - float nextFloat(); - - /** - * Returns the next pseudorandom, uniformly distributed - * double value between 0.0 and - * 1.0 from this random number generator's sequence. - * - * @return the next pseudorandom, uniformly distributed - * double value between 0.0 and - * 1.0 from this random number generator's sequence - */ - double nextDouble(); - - /** - * Returns the next pseudorandom, Gaussian ("normally") distributed - * double value with mean 0.0 and standard - * deviation 1.0 from this random number generator's sequence. - * - * @return the next pseudorandom, Gaussian ("normally") distributed - * double value with mean 0.0 and - * standard deviation 1.0 from this random number - * generator's sequence - */ - double nextGaussian(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/RandomUtils.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/RandomUtils.java deleted file mode 100644 index 4e9476ac2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/RandomUtils.java +++ /dev/null @@ -1,403 +0,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. - */ - -package org.apache.commons.math4.random; - -import java.util.Random; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import org.apache.commons.math4.exception.MathInternalError; -import org.apache.commons.math4.exception.NotANumberException; -import org.apache.commons.math4.exception.NotFiniteNumberException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Factory for creating generators of miscellaneous data. - * - * @since 4.0 - */ -public class RandomUtils { - /** - * Class contains only static methods. - */ - private RandomUtils() {} - - /** - * @param rng Underlying generator. Reference is copied so the RNG - * is shared with the caller. - * @return a {@link DataGenerator data generator}. - */ - public static DataGenerator createDataGenerator(final UniformRandomProvider rng) { - return new DataGenerator(rng); - } - - /** - * Wraps an instance of the JDK's {@link Random} class. - * The actual generation of random numbers will be delegated to that - * instance. - *

- * If cryptographically secure data is required, one can use this - * factory method, with an instance of the {@link java.security.SecureRandom} - * class as the argument. - * Note that data generation will be much slower in this case. - *

- * - * @param rng Underlying generator. Reference is copied so the RNG - * is shared with the caller. - * @return a {@link DataGenerator data generator}. - */ - public static DataGenerator createDataGenerator(final Random rng) { - return createDataGenerator(asUniformRandomProvider(rng)); - } - - /** - * Wraps a {@link Random} instance. - * - * @param rng JDK {@link Random} instance to which the random number - * generation is delegated. Reference is copied so the RNG is shared - * with the caller. - * @return a {@link UniformRandomProvider} instance. - */ - public static UniformRandomProvider asUniformRandomProvider(final Random rng) { - return new UniformRandomProvider() { - /** {@inheritDoc} */ - @Override - public void nextBytes(byte[] bytes) { - rng.nextBytes(bytes); - } - - /** {@inheritDoc} */ - @Override - public void nextBytes(byte[] bytes, - int start, - int len) { - final byte[] reduced = new byte[len]; - rng.nextBytes(reduced); - System.arraycopy(reduced, 0, bytes, start, len); - } - - /** {@inheritDoc} */ - @Override - public int nextInt() { - return rng.nextInt(); - } - - /** {@inheritDoc} */ - @Override - public int nextInt(int n) { - if (n <= 0) { - throw new NotStrictlyPositiveException(n); - } - return rng.nextInt(n); - } - - /** {@inheritDoc} */ - @Override - public long nextLong() { - return rng.nextLong(); - } - - /** {@inheritDoc} */ - @Override - public long nextLong(long n) { - // Code copied from "o.a.c.m.rng.internal.BaseProvider". - - if (n > 0) { - long bits; - long val; - do { - bits = rng.nextLong() >>> 1; - val = bits % n; - } while (bits - val + (n - 1) < 0); - return val; - } - - throw new NotStrictlyPositiveException(n); - } - - /** {@inheritDoc} */ - @Override - public boolean nextBoolean() { - return rng.nextBoolean(); - } - - /** {@inheritDoc} */ - @Override - public float nextFloat() { - return rng.nextFloat(); - } - - /** {@inheritDoc} */ - @Override - public double nextDouble() { - return rng.nextDouble(); - } - }; - } - - /** - * Various random data generation routines. - */ - public static class DataGenerator { - /** Underlying RNG. */ - private final UniformRandomProvider rng; - - /** - * @param rng Underlying generator. - */ - DataGenerator(UniformRandomProvider rng) { - this.rng = rng; - } - - /** - * Generates a random string of hex characters of length {@code len}. - * - * Algorithm Description: how hexadecimal strings are - * generated depends on the value of the {@code useSha1} argument. - * - *
    - *
  • If {@code useSha1 == false}, a 2-step process is used: - *
      - *
    1. - * {@code len / 2 + 1} binary bytes are generated using the underlying - * generator. - *
    2. - *
    3. - * Each binary byte is translated into 2 hex digits. - *
    4. - *
    - *
  • - *
  • - * If {@code useSha1 == true}, hex strings are generated in 40-byte - * segments using a 3-step process: - *
      - *
    1. - * 20 random bytes are generated using the underlying generator. - *
    2. - *
    3. - * SHA-1 hash is applied to yield a 20-byte binary digest. - *
    4. - *
    5. - * Each byte of the binary digest is converted to 2 hex digits. - *
    6. - *
    - *
  • - *
- * - * @param len Length of the generated string. - * @param useSha1 Whether to use a digest. - * If {@code true} (resp. {@code false}), the 3-step (resp. 2-step) - * process will be used. - * @return the random string. - * @throws NotStrictlyPositiveException if {@code len <= 0}. - */ - public String nextHexString(int len, - boolean useSha1) { - if (len <= 0) { - throw new NotStrictlyPositiveException(LocalizedFormats.LENGTH, len); - } - - // Initialize output buffer. - final StringBuilder outBuffer = new StringBuilder(); - - if (!useSha1) { - // Generate int(len/2)+1 random bytes. - final byte[] randomBytes = new byte[(len / 2) + 1]; - rng.nextBytes(randomBytes); - - // Convert each byte to 2 hex digits. - for (int i = 0; i < randomBytes.length; i++) { - final Integer c = Integer.valueOf(randomBytes[i]); - - // Add 128 to byte value to make interval 0-255 before - // conversion to hex. - // This guarantees <= 2 hex digits from "toHexString". - // "toHexString" would otherwise add 2^32 to negative arguments. - String hex = Integer.toHexString(c.intValue() + 128); - - // Make sure we add 2 hex digits for each byte. - if (hex.length() == 1) { - hex = "0" + hex; - } - outBuffer.append(hex); - } - } else { - MessageDigest alg = null; - try { - alg = MessageDigest.getInstance("SHA-1"); - } catch (NoSuchAlgorithmException ex) { - // Should never happen. - throw new MathInternalError(ex); - } - alg.reset(); - - // Compute number of iterations required (40 bytes each). - final int numIter = (len / 40) + 1; - - for (int iter = 1; iter < numIter + 1; iter++) { - final byte[] randomBytes = new byte[40]; - rng.nextBytes(randomBytes); - alg.update(randomBytes); - - // Create 20-byte binary hash. - final byte[] hash = alg.digest(); - - // Loop over the hash, converting each byte to 2 hex digits - for (int i = 0; i < hash.length; i++) { - final Integer c = Integer.valueOf(hash[i]); - - // Add 128 to byte value to make interval 0-255. - // This guarantees <= 2 hex digits from "toHexString". - // "toHexString" would otherwise add 2^32 to negative arguments. - String hex = Integer.toHexString(c.intValue() + 128); - - // Keep strings uniform length: guarantees 40 bytes. - if (hex.length() == 1) { - hex = "0" + hex; - } - outBuffer.append(hex); - } - } - } - - return outBuffer.toString().substring(0, len); - } - - /** - * Generates a uniformly distributed random long integer between {@code lower} - * and {@code upper} (endpoints included). - * - * @param lower Lower bound for generated long integer. - * @param upper Upper bound for generated long integer. - * @return a random long integer greater than or equal to {@code lower} - * and less than or equal to {@code upper} - * @throws NumberIsTooLargeException if {@code lower >= upper} - */ - public long nextLong(final long lower, - final long upper) { - if (lower >= upper) { - throw new NumberIsTooLargeException(LocalizedFormats.LOWER_BOUND_NOT_BELOW_UPPER_BOUND, - lower, upper, false); - } - final long max = (upper - lower) + 1; - if (max <= 0) { - // Range is too wide to fit in a positive long (larger than 2^63); - // as it covers more than half the long range, we use directly a - // simple rejection method. - while (true) { - final long r = rng.nextLong(); - if (r >= lower && r <= upper) { - return r; - } - } - } else if (max < Integer.MAX_VALUE){ - // We can shift the range and generate directly a positive int. - return lower + rng.nextInt((int) max); - } else { - // We can shift the range and generate directly a positive long. - return lower + rng.nextLong(max); - } - } - - /** - * Generates a uniformly distributed random value from the open interval - * {@code (lower, upper)} (i.e., endpoints excluded). - *

- * Definition: - * - * Uniform Distribution {@code lower} and {@code upper - lower} are the - * - * location and scale parameters, respectively.

- *

- * Algorithm Description: scales the output of - * Random.nextDouble(), but rejects 0 values (i.e., will generate another - * random double if Random.nextDouble() returns 0). This is necessary to - * provide a symmetric output interval (both endpoints excluded). - *

- * - * @param lower Lower bound of the support (excluded). - * @param upper Upper bound of the support (excluded). - * @return a uniformly distributed random value between lower and upper - * (both excluded). - * @throws NumberIsTooLargeException if {@code lower >= upper}. - * @throws NotFiniteNumberException if one of the bounds is infinite. - * @throws NotANumberException if one of the bounds is NaN. - */ - public double nextUniform(double lower, double upper) { - return nextUniform(lower, upper, false); - } - - /** - * Generates a uniformly distributed random value from the interval - * {@code (lower, upper)} or the interval {@code [lower, upper)}. The lower - * bound is thus optionally included, while the upper bound is always - * excluded. - *

- * Definition: - * - * Uniform Distribution {@code lower} and {@code upper - lower} are the - * - * location and scale parameters, respectively.

- *

- * Algorithm Description: if the lower bound is excluded, - * scales the output of "nextDouble()", but rejects 0 values (i.e. it - * will generate another random double if "nextDouble()" returns 0). - * This is necessary to provide a symmetric output interval (both - * endpoints excluded). - *

- * - * @param lower Lower bound of the support. - * @param upper Exclusive upper bound of the support. - * @param lowerInclusive {@code true} if the lower bound is inclusive. - * @return a uniformly distributed random value in the {@code (lower, upper)} - * interval, if {@code lowerInclusive} is {@code false}, or in the - * {@code [lower, upper)} interval, if {@code lowerInclusive} is - * {@code true}. - * @throws NumberIsTooLargeException if {@code lower >= upper}. - * @throws NotFiniteNumberException if one of the bounds is infinite. - * @throws NotANumberException if one of the bounds is NaN. - */ - public double nextUniform(double lower, - double upper, - boolean lowerInclusive) { - if (lower >= upper) { - throw new NumberIsTooLargeException(LocalizedFormats.LOWER_BOUND_NOT_BELOW_UPPER_BOUND, - lower, upper, false); - } - if (Double.isInfinite(lower)) { - throw new NotFiniteNumberException(LocalizedFormats.INFINITE_BOUND, lower); - } - if (Double.isInfinite(upper)) { - throw new NotFiniteNumberException(LocalizedFormats.INFINITE_BOUND, upper); - } - if (Double.isNaN(lower) || Double.isNaN(upper)) { - throw new NotANumberException(); - } - - // Ensure nextDouble() isn't 0.0 - double u = rng.nextDouble(); - while (!lowerInclusive && u <= 0.0) { - u = rng.nextDouble(); - } - - return u * upper + (1.0 - u) * lower; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/RandomVectorGenerator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/RandomVectorGenerator.java deleted file mode 100644 index 2a6250cd2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/RandomVectorGenerator.java +++ /dev/null @@ -1,32 +0,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. - */ - -package org.apache.commons.math4.random; - - -/** This interface represents a random generator for whole vectors. - * - * @since 1.2 - */ -public interface RandomVectorGenerator { - - /** Generate a random vector. - * @return a random vector as an array of double. - */ - double[] nextVector(); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/RngAdaptor.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/RngAdaptor.java deleted file mode 100644 index 6109cd1b4..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/RngAdaptor.java +++ /dev/null @@ -1,232 +0,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. - */ -package org.apache.commons.math4.random; - -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.rng.RestorableUniformRandomProvider; -import org.apache.commons.rng.core.RandomProviderDefaultState; -import org.apache.commons.rng.simple.RandomSource; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; - -/** - * Adaptor that delegates to a - * {@link org.apache.commons.rng.UniformRandomProvider} instance. - *

- * It is provided for users who wish to test the new RNG implementations - * the current generators (up to version 3.6 of Commons Math) in - * codes that require the {@code RandomGenerator} interface. - *

- *

- * Applications should upgrade to use the new generators ASAP. - * If problems are found that jeopardize the upgrade, please report them - * on the project's - * - * issue tracking system. - *

- * - *

- * Notes: - *

    - *
  • - * The - * {@link RandomGenerator#setSeed(int) setSeed(int)}, - * {@link RandomGenerator#setSeed(int[]) setSeed(int[])} and - * {@link RandomGenerator#setSeed(long) setSeed(long)} - * methods of the {@link RandomGenerator} are not part of the - * {@link org.apache.commons.rng.UniformRandomProvider new API}. - *
  • - *
  • - * The new RNG implementations are not {@code Serializable}. - * Use {@link RestorableUniformRandomProvider#saveState()} - * instead. - *
  • - *
  • - * {@link RandomGenerator#nextGaussian() nextGaussian()} is not - * part of the {@link org.apache.commons.rng.UniformRandomProvider - * new API} as it defines a "post-processing" of the output of a - * uniform RNG in order to follow a different distribution. - *
  • - *
- * - * @since 4.0 - * - * @deprecated As of 4.0. This class is made available for testing - * the {@link RandomSource new RNG implementations} in existing - * applications. - * It will be removed in the next major release. - */ -@Deprecated -public final class RngAdaptor - implements RandomGenerator, - Serializable { - /** Serializable version identifier. */ - private static final long serialVersionUID = 12345L; - /** Source. */ - private final RandomSource source; - /** Delegate. */ - private transient RestorableUniformRandomProvider delegate; - /** Next gaussian. */ - private double nextGaussian = Double.NaN; - - /** - * Creates a new instance. - * - * @param source Source of randomness. - */ - public RngAdaptor(RandomSource source) { - this(source, null); - } - - /** - * Creates a new instance. - * - * @param source Source of randomness. - * @param seed Seed. Can be {@code null}. - */ - public RngAdaptor(RandomSource source, - Object seed) { - this.source = source; - delegate = RandomSource.create(source, seed); - } - - /** {@inheritDoc} */ - @Override - public void setSeed(int seed) { - delegate = RandomSource.create(source, seed); - clear(); - } - - /** {@inheritDoc} */ - @Override - public void setSeed(int[] seed) { - delegate = RandomSource.create(source, seed); - clear(); - } - - /** {@inheritDoc} */ - @Override - public void setSeed(long seed) { - delegate = RandomSource.create(source, seed); - clear(); - } - - /** {@inheritDoc} */ - @Override - public boolean nextBoolean() { - return delegate.nextBoolean(); - } - - /** {@inheritDoc} */ - @Override - public void nextBytes(byte[] bytes) { - delegate.nextBytes(bytes); - } - - /** {@inheritDoc} */ - @Override - public double nextDouble() { - return delegate.nextDouble(); - } - - /** {@inheritDoc} */ - @Override - public float nextFloat() { - return delegate.nextFloat(); - } - - /** {@inheritDoc} */ - @Override - public double nextGaussian() { - final double random; - if (Double.isNaN(nextGaussian)) { - // generate a new pair of gaussian numbers - final double x = nextDouble(); - final double y = nextDouble(); - final double alpha = 2 * FastMath.PI * x; - final double r = FastMath.sqrt(-2 * FastMath.log(y)); - random = r * FastMath.cos(alpha); - nextGaussian = r * FastMath.sin(alpha); - } else { - // use the second element of the pair already generated - random = nextGaussian; - nextGaussian = Double.NaN; - } - - return random; - } - - /** {@inheritDoc} */ - @Override - public int nextInt() { - return delegate.nextInt(); - } - - /** {@inheritDoc} */ - @Override - public int nextInt(int n) { - return delegate.nextInt(n); - } - - /** {@inheritDoc} */ - @Override - public long nextLong() { - return delegate.nextLong(); - } - - /** - * Clears the cache used by the default implementation of - * {@link #nextGaussian}. - */ - private void clear() { - nextGaussian = Double.NaN; - } - - /** - * @param out Output stream. - * @throws IOException if an error occurs. - */ - private void writeObject(ObjectOutputStream out) - throws IOException { - // Write non-transient fields. - out.defaultWriteObject(); - - // Save current state. - out.writeObject(((RandomProviderDefaultState) delegate.saveState()).getState()); - } - - /** - * @param in Input stream. - * @throws IOException if an error occurs. - * @throws ClassNotFoundException if an error occurs. - */ - private void readObject(ObjectInputStream in) - throws IOException, - ClassNotFoundException { - // Read non-transient fields. - in.defaultReadObject(); - - // Recreate the "delegate" from serialized info. - delegate = RandomSource.create(source); - // And restore its state. - final RandomProviderDefaultState state = new RandomProviderDefaultState((byte[]) in.readObject()); - delegate.restoreState(state); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/SobolSequenceGenerator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/SobolSequenceGenerator.java deleted file mode 100644 index af3cf2251..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/SobolSequenceGenerator.java +++ /dev/null @@ -1,326 +0,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. - */ -package org.apache.commons.math4.random; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.NoSuchElementException; -import java.util.StringTokenizer; - -import org.apache.commons.math4.exception.MathInternalError; -import org.apache.commons.math4.exception.MathParseException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.util.FastMath; - -/** - * Implementation of a Sobol sequence. - *

- * A Sobol sequence is a low-discrepancy sequence with the property that for all values of N, - * its subsequence (x1, ... xN) has a low discrepancy. It can be used to generate pseudo-random - * points in a space S, which are equi-distributed. - *

- * The implementation already comes with support for up to 1000 dimensions with direction numbers - * calculated from Stephen Joe and Frances Kuo. - *

- * The generator supports two modes: - *

    - *
  • sequential generation of points: {@link #nextVector()}
  • - *
  • random access to the i-th point in the sequence: {@link #skipTo(int)}
  • - *
- * - * @see Sobol sequence (Wikipedia) - * @see Sobol sequence direction numbers - * - * @since 3.3 - */ -public class SobolSequenceGenerator implements RandomVectorGenerator { - - /** The number of bits to use. */ - private static final int BITS = 52; - - /** The scaling factor. */ - private static final double SCALE = FastMath.pow(2, BITS); - - /** The maximum supported space dimension. */ - private static final int MAX_DIMENSION = 1000; - - /** The resource containing the direction numbers. */ - private static final String RESOURCE_NAME = "/assets/org/apache/commons/math4/random/new-joe-kuo-6.1000"; - - /** Character set for file input. */ - private static final String FILE_CHARSET = "US-ASCII"; - - /** Space dimension. */ - private final int dimension; - - /** The current index in the sequence. */ - private int count = 0; - - /** The direction vector for each component. */ - private final long[][] direction; - - /** The current state. */ - private final long[] x; - - /** - * Construct a new Sobol sequence generator for the given space dimension. - * - * @param dimension the space dimension - * @throws OutOfRangeException if the space dimension is outside the allowed range of [1, 1000] - */ - public SobolSequenceGenerator(final int dimension) throws OutOfRangeException { - if (dimension < 1 || dimension > MAX_DIMENSION) { - throw new OutOfRangeException(dimension, 1, MAX_DIMENSION); - } - - // initialize the other dimensions with direction numbers from a resource - final InputStream is = getClass().getResourceAsStream(RESOURCE_NAME); - if (is == null) { - throw new MathInternalError(); - } - - this.dimension = dimension; - - // init data structures - direction = new long[dimension][BITS + 1]; - x = new long[dimension]; - - try { - initFromStream(is); - } catch (IOException e) { - // the internal resource file could not be read -> should not happen - throw new MathInternalError(); - } catch (MathParseException e) { - // the internal resource file could not be parsed -> should not happen - throw new MathInternalError(); - } finally { - try { - is.close(); - } catch (IOException e) { // NOPMD - // ignore - } - } - } - - /** - * Construct a new Sobol sequence generator for the given space dimension with - * direction vectors loaded from the given stream. - *

- * The expected format is identical to the files available from - * Stephen Joe and Frances Kuo. - * The first line will be ignored as it is assumed to contain only the column headers. - * The columns are: - *

    - *
  • d: the dimension
  • - *
  • s: the degree of the primitive polynomial
  • - *
  • a: the number representing the coefficients
  • - *
  • m: the list of initial direction numbers
  • - *
- * Example: - *
-     * d       s       a       m_i
-     * 2       1       0       1
-     * 3       2       1       1 3
-     * 
- *

- * The input stream must be an ASCII text containing one valid direction vector per line. - * - * @param dimension the space dimension - * @param is the stream to read the direction vectors from - * @throws NotStrictlyPositiveException if the space dimension is < 1 - * @throws OutOfRangeException if the space dimension is outside the range [1, max], where - * max refers to the maximum dimension found in the input stream - * @throws MathParseException if the content in the stream could not be parsed successfully - * @throws IOException if an error occurs while reading from the input stream - */ - public SobolSequenceGenerator(final int dimension, final InputStream is) - throws NotStrictlyPositiveException, MathParseException, IOException { - - if (dimension < 1) { - throw new NotStrictlyPositiveException(dimension); - } - - this.dimension = dimension; - - // init data structures - direction = new long[dimension][BITS + 1]; - x = new long[dimension]; - - // initialize the other dimensions with direction numbers from the stream - int lastDimension = initFromStream(is); - if (lastDimension < dimension) { - throw new OutOfRangeException(dimension, 1, lastDimension); - } - } - - /** - * Load the direction vector for each dimension from the given stream. - *

- * The input stream must be an ASCII text containing one - * valid direction vector per line. - * - * @param is the input stream to read the direction vector from - * @return the last dimension that has been read from the input stream - * @throws IOException if the stream could not be read - * @throws MathParseException if the content could not be parsed successfully - */ - private int initFromStream(final InputStream is) throws MathParseException, IOException { - - // special case: dimension 1 -> use unit initialization - for (int i = 1; i <= BITS; i++) { - direction[0][i] = 1l << (BITS - i); - } - - final Charset charset = Charset.forName(FILE_CHARSET); - final BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset)); - int dim = -1; - - try { - // ignore first line - reader.readLine(); - - int lineNumber = 2; - int index = 1; - String line = null; - while ( (line = reader.readLine()) != null) { - StringTokenizer st = new StringTokenizer(line, " "); - try { - dim = Integer.parseInt(st.nextToken()); - if (dim >= 2 && dim <= dimension) { // we have found the right dimension - final int s = Integer.parseInt(st.nextToken()); - final int a = Integer.parseInt(st.nextToken()); - final int[] m = new int[s + 1]; - for (int i = 1; i <= s; i++) { - m[i] = Integer.parseInt(st.nextToken()); - } - initDirectionVector(index++, a, m); - } - - if (dim > dimension) { - return dim; - } - } catch (NoSuchElementException e) { - throw new MathParseException(line, lineNumber); - } catch (NumberFormatException e) { - throw new MathParseException(line, lineNumber); - } - lineNumber++; - } - } finally { - reader.close(); - } - - return dim; - } - - /** - * Calculate the direction numbers from the given polynomial. - * - * @param d the dimension, zero-based - * @param a the coefficients of the primitive polynomial - * @param m the initial direction numbers - */ - private void initDirectionVector(final int d, final int a, final int[] m) { - final int s = m.length - 1; - for (int i = 1; i <= s; i++) { - direction[d][i] = ((long) m[i]) << (BITS - i); - } - for (int i = s + 1; i <= BITS; i++) { - direction[d][i] = direction[d][i - s] ^ (direction[d][i - s] >> s); - for (int k = 1; k <= s - 1; k++) { - direction[d][i] ^= ((a >> (s - 1 - k)) & 1) * direction[d][i - k]; - } - } - } - - /** {@inheritDoc} */ - @Override - public double[] nextVector() { - final double[] v = new double[dimension]; - if (count == 0) { - count++; - return v; - } - - // find the index c of the rightmost 0 - int c = 1; - int value = count - 1; - while ((value & 1) == 1) { - value >>= 1; - c++; - } - - for (int i = 0; i < dimension; i++) { - x[i] ^= direction[i][c]; - v[i] = (double) x[i] / SCALE; - } - count++; - return v; - } - - /** - * Skip to the i-th point in the Sobol sequence. - *

- * This operation can be performed in O(1). - * - * @param index the index in the sequence to skip to - * @return the i-th point in the Sobol sequence - * @throws NotPositiveException if index < 0 - */ - public double[] skipTo(final int index) throws NotPositiveException { - if (index == 0) { - // reset x vector - Arrays.fill(x, 0); - } else { - final int i = index - 1; - final long grayCode = i ^ (i >> 1); // compute the gray code of i = i XOR floor(i / 2) - for (int j = 0; j < dimension; j++) { - long result = 0; - for (int k = 1; k <= BITS; k++) { - final long shift = grayCode >> (k - 1); - if (shift == 0) { - // stop, as all remaining bits will be zero - break; - } - // the k-th bit of i - final long ik = shift & 1; - result ^= ik * direction[j][k]; - } - x[j] = result; - } - } - count = index; - return nextVector(); - } - - /** - * Returns the index i of the next point in the Sobol sequence that will be returned - * by calling {@link #nextVector()}. - * - * @return the index of the next point - */ - public int getNextIndex() { - return count; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/StableRandomGenerator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/StableRandomGenerator.java deleted file mode 100644 index f3a851b9b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/StableRandomGenerator.java +++ /dev/null @@ -1,133 +0,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. - */ -package org.apache.commons.math4.random; - -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; - -/** - *

This class provides a stable normalized random generator. It samples from a stable - * distribution with location parameter 0 and scale 1.

- * - *

The implementation uses the Chambers-Mallows-Stuck method as described in - * Handbook of computational statistics: concepts and methods by - * James E. Gentle, Wolfgang Härdle, Yuichi Mori.

- * - * @since 3.0 - */ -public class StableRandomGenerator implements NormalizedRandomGenerator { - /** Underlying generator. */ - private final UniformRandomProvider generator; - /** stability parameter */ - private final double alpha; - /** skewness parameter */ - private final double beta; - /** cache of expression value used in generation */ - private final double zeta; - - /** - * Create a new generator. - * - * @param generator Underlying random generator - * @param alpha Stability parameter. Must be in range (0, 2] - * @param beta Skewness parameter. Must be in range [-1, 1] - * @throws NullArgumentException if generator is null - * @throws OutOfRangeException if {@code alpha <= 0} or {@code alpha > 2} - * or {@code beta < -1} or {@code beta > 1} - */ - public StableRandomGenerator(final UniformRandomProvider generator, - final double alpha, final double beta) - throws NullArgumentException, OutOfRangeException { - if (generator == null) { - throw new NullArgumentException(); - } - - if (!(alpha > 0d && alpha <= 2d)) { - throw new OutOfRangeException(LocalizedFormats.OUT_OF_RANGE_LEFT, - alpha, 0, 2); - } - - if (!(beta >= -1d && beta <= 1d)) { - throw new OutOfRangeException(LocalizedFormats.OUT_OF_RANGE_SIMPLE, - beta, -1, 1); - } - - this.generator = generator; - this.alpha = alpha; - this.beta = beta; - if (alpha < 2d && beta != 0d) { - zeta = beta * FastMath.tan(FastMath.PI * alpha / 2); - } else { - zeta = 0d; - } - } - - /** - * Generate a random scalar with zero location and unit scale. - * - * @return a random scalar with zero location and unit scale - */ - @Override - public double nextNormalizedDouble() { - // we need 2 uniform random numbers to calculate omega and phi - double omega = -FastMath.log(generator.nextDouble()); - double phi = FastMath.PI * (generator.nextDouble() - 0.5); - - // Normal distribution case (Box-Muller algorithm) - if (alpha == 2d) { - return FastMath.sqrt(2d * omega) * FastMath.sin(phi); - } - - double x; - // when beta = 0, zeta is zero as well - // Thus we can exclude it from the formula - if (beta == 0d) { - // Cauchy distribution case - if (alpha == 1d) { - x = FastMath.tan(phi); - } else { - x = FastMath.pow(omega * FastMath.cos((1 - alpha) * phi), - 1d / alpha - 1d) * - FastMath.sin(alpha * phi) / - FastMath.pow(FastMath.cos(phi), 1d / alpha); - } - } else { - // Generic stable distribution - double cosPhi = FastMath.cos(phi); - // to avoid rounding errors around alpha = 1 - if (FastMath.abs(alpha - 1d) > 1e-8) { - double alphaPhi = alpha * phi; - double invAlphaPhi = phi - alphaPhi; - x = (FastMath.sin(alphaPhi) + zeta * FastMath.cos(alphaPhi)) / cosPhi * - (FastMath.cos(invAlphaPhi) + zeta * FastMath.sin(invAlphaPhi)) / - FastMath.pow(omega * cosPhi, (1 - alpha) / alpha); - } else { - double betaPhi = FastMath.PI / 2 + beta * phi; - x = 2d / FastMath.PI * (betaPhi * FastMath.tan(phi) - beta * - FastMath.log(FastMath.PI / 2d * omega * cosPhi / betaPhi)); - - if (alpha != 1d) { - x += beta * FastMath.tan(FastMath.PI * alpha / 2); - } - } - } - return x; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/SynchronizedRandomGenerator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/SynchronizedRandomGenerator.java deleted file mode 100644 index 9713eef7a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/SynchronizedRandomGenerator.java +++ /dev/null @@ -1,134 +0,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. - */ -package org.apache.commons.math4.random; - -/** - * Any {@link RandomGenerator} implementation can be thread-safe if it - * is used through an instance of this class. - * This is achieved by enclosing calls to the methods of the actual - * generator inside the overridden {@code synchronized} methods of this - * class. - * - * @since 3.1 - * @deprecated As of 4.0. No replacement. - */ -@Deprecated -public class SynchronizedRandomGenerator implements RandomGenerator { - /** Object to which all calls will be delegated. */ - private final RandomGenerator wrapped; - - /** - * Creates a synchronized wrapper for the given {@code RandomGenerator} - * instance. - * - * @param rng Generator whose methods will be called through - * their corresponding overridden synchronized version. - * To ensure thread-safety, the wrapped generator must - * not be used directly. - */ - public SynchronizedRandomGenerator(RandomGenerator rng) { - wrapped = rng; - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setSeed(int seed) { - wrapped.setSeed(seed); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setSeed(int[] seed) { - wrapped.setSeed(seed); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setSeed(long seed) { - wrapped.setSeed(seed); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void nextBytes(byte[] bytes) { - wrapped.nextBytes(bytes); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized int nextInt() { - return wrapped.nextInt(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized int nextInt(int n) { - return wrapped.nextInt(n); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized long nextLong() { - return wrapped.nextLong(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized boolean nextBoolean() { - return wrapped.nextBoolean(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized float nextFloat() { - return wrapped.nextFloat(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double nextDouble() { - return wrapped.nextDouble(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double nextGaussian() { - return wrapped.nextGaussian(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/UncorrelatedRandomVectorGenerator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/UncorrelatedRandomVectorGenerator.java deleted file mode 100644 index 88360feb5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/UncorrelatedRandomVectorGenerator.java +++ /dev/null @@ -1,92 +0,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. - */ - -package org.apache.commons.math4.random; - -import java.util.Arrays; - -import org.apache.commons.math4.exception.DimensionMismatchException; - -/** - * A {@link RandomVectorGenerator} that generates vectors with uncorrelated - * components. Components of generated vectors follow (independent) Gaussian - * distributions, with parameters supplied in the constructor. - * - * @since 1.2 - */ -public class UncorrelatedRandomVectorGenerator - implements RandomVectorGenerator { - - /** Underlying scalar generator. */ - private final NormalizedRandomGenerator generator; - - /** Mean vector. */ - private final double[] mean; - - /** Standard deviation vector. */ - private final double[] standardDeviation; - - /** Simple constructor. - *

Build an uncorrelated random vector generator from - * its mean and standard deviation vectors.

- * @param mean expected mean values for each component - * @param standardDeviation standard deviation for each component - * @param generator underlying generator for uncorrelated normalized - * components - */ - public UncorrelatedRandomVectorGenerator(double[] mean, - double[] standardDeviation, - NormalizedRandomGenerator generator) { - if (mean.length != standardDeviation.length) { - throw new DimensionMismatchException(mean.length, standardDeviation.length); - } - this.mean = mean.clone(); - this.standardDeviation = standardDeviation.clone(); - this.generator = generator; - } - - /** Simple constructor. - *

Build a null mean random and unit standard deviation - * uncorrelated vector generator

- * @param dimension dimension of the vectors to generate - * @param generator underlying generator for uncorrelated normalized - * components - */ - public UncorrelatedRandomVectorGenerator(int dimension, - NormalizedRandomGenerator generator) { - mean = new double[dimension]; - standardDeviation = new double[dimension]; - Arrays.fill(standardDeviation, 1.0); - this.generator = generator; - } - - /** Generate an uncorrelated random vector. - * @return a random vector as a newly built array of double - */ - @Override -public double[] nextVector() { - - double[] random = new double[mean.length]; - for (int i = 0; i < random.length; ++i) { - random[i] = mean[i] + standardDeviation[i] * generator.nextNormalizedDouble(); - } - - return random; - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/UniformRandomGenerator.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/UniformRandomGenerator.java deleted file mode 100644 index d43c6d9d7..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/UniformRandomGenerator.java +++ /dev/null @@ -1,58 +0,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. - */ - -package org.apache.commons.math4.random; - -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.rng.UniformRandomProvider; - -/** - * This class implements a normalized uniform random generator. - * - *

- * It generates values from a uniform distribution with mean - * equal to 0 and standard deviation equal to 1. - * Generated values fall in the range \( [-\sqrt{3}, +\sqrt{3}] \). - *

- * - * @since 1.2 - */ -public class UniformRandomGenerator implements NormalizedRandomGenerator { - /** Square root of three. */ - private static final double SQRT3 = FastMath.sqrt(3); - /** Underlying generator. */ - private final UniformRandomProvider generator; - - /** - * Creates a new generator. - * - * @param generator Underlying random generator. - */ - public UniformRandomGenerator(UniformRandomProvider generator) { - this.generator = generator; - } - - /** - * Generates a random scalar with zero mean and unit standard deviation. - * - * @return a random scalar in the range \( [-\sqrt{3}, +\sqrt{3}] \). - */ - @Override - public double nextNormalizedDouble() { - return SQRT3 * (2 * generator.nextDouble() - 1); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/package-info.java deleted file mode 100644 index c2e5a1fef..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/random/package-info.java +++ /dev/null @@ -1,33 +0,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. - */ -/** - *

Random Data Generation

- * - *

- * Some of the utilities in this package use the pseudo-random number - * generators defined in the - * Commons RNG library in order to provide - * {@link org.apache.commons.math4.random.RandomUtils.DataGenerator - * higher level functionality} (such as random strings) based on an underlying - * source of randomness that provides sequences of uniformly distributed integers. - *

- *

- * Others are sources of pseudo-randomness that directly produce "compound" types - * such as {@link org.apache.commons.math4.random.RandomVectorGenerator random vectors}. - *

- */ -package org.apache.commons.math4.random; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/Frequency.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/Frequency.java deleted file mode 100644 index 9d8276188..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/Frequency.java +++ /dev/null @@ -1,390 +0,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. - */ -package org.apache.commons.math4.stat; - -import java.io.Serializable; -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.SortedMap; -import java.util.TreeMap; - -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.MathUtils; - -/** - * Maintains a frequency distribution. - * - *

The values are ordered using the default (natural order), unless a - * Comparator is supplied in the constructor.

- * - * @param a comparable type used in the frequency distribution - */ -public class Frequency> implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 605878194679954450L; - /** underlying collection */ - private final SortedMap freqTable; - - /** - * Default constructor. - */ - public Frequency() { - freqTable = new TreeMap<>(); - } - - /** - * Constructor allowing values Comparator to be specified. - * - * @param comparator Comparator used to order values - */ - public Frequency(Comparator comparator) { - freqTable = new TreeMap<>(comparator); - } - - /** - * Return a string representation of this frequency distribution. - * - * @return a string representation. - */ - @Override - public String toString() { - NumberFormat nf = NumberFormat.getPercentInstance(); - StringBuilder outBuffer = new StringBuilder(); - outBuffer.append("Value \t Freq. \t Pct. \t Cum Pct. \n"); - Iterator iter = freqTable.keySet().iterator(); - while (iter.hasNext()) { - T value = iter.next(); - outBuffer.append(value); - outBuffer.append('\t'); - outBuffer.append(getCount(value)); - outBuffer.append('\t'); - outBuffer.append(nf.format(getPct(value))); - outBuffer.append('\t'); - outBuffer.append(nf.format(getCumPct(value))); - outBuffer.append('\n'); - } - return outBuffer.toString(); - } - - /** - * Adds 1 to the frequency count for v. - * - * @param v the value to add. - */ - public void addValue(T v) { - incrementValue(v, 1); - } - - /** - * Increments the frequency count for v. - * - * @param v the value to add. - * @param increment the amount by which the value should be incremented - * @since 3.1 - */ - public void incrementValue(T v, long increment) { - Long count = freqTable.get(v); - if (count == null) { - freqTable.put(v, Long.valueOf(increment)); - } else { - freqTable.put(v, Long.valueOf(count.longValue() + increment)); - } - } - - /** Clears the frequency table */ - public void clear() { - freqTable.clear(); - } - - /** - * Returns an Iterator over the set of values that have been added. - * - * @return values Iterator - */ - public Iterator valuesIterator() { - return freqTable.keySet().iterator(); - } - - /** - * Return an Iterator over the set of keys and values that have been added. - * Using the entry set to iterate is more efficient in the case where you - * need to access respective counts as well as values, since it doesn't - * require a "get" for every key...the value is provided in the Map.Entry. - * - * @return entry set Iterator - * @since 3.1 - */ - public Iterator> entrySetIterator() { - return freqTable.entrySet().iterator(); - } - - //------------------------------------------------------------------------- - - /** - * Returns the sum of all frequencies. - * - * @return the total frequency count. - */ - public long getSumFreq() { - long result = 0; - Iterator iterator = freqTable.values().iterator(); - while (iterator.hasNext()) { - result += iterator.next().longValue(); - } - return result; - } - - /** - * Returns the number of values equal to v. - * - * @param v the value to lookup. - * @return the frequency of v. - */ - public long getCount(T v) { - long result = 0; - Long count = freqTable.get(v); - if (count != null) { - result = count.longValue(); - } - return result; - } - - /** - * Returns the number of values in the frequency table. - * - * @return the number of unique values that have been added to the frequency table. - * @see #valuesIterator() - */ - public int getUniqueCount(){ - return freqTable.keySet().size(); - } - - /** - * Returns the percentage of values that are equal to v - * (as a proportion between 0 and 1). - *

- * Returns Double.NaN if no values have been added. - *

- * - * @param v the value to lookup - * @return the proportion of values equal to v - */ - public double getPct(T v) { - final long sumFreq = getSumFreq(); - if (sumFreq == 0) { - return Double.NaN; - } - return (double) getCount(v) / (double) sumFreq; - } - - //----------------------------------------------------------------------------------------- - - /** - * Returns the cumulative frequency of values less than or equal to v. - * - * @param v the value to lookup. - * @return the proportion of values equal to v - */ - public long getCumFreq(T v) { - if (getSumFreq() == 0) { - return 0; - } - Comparator c = freqTable.comparator(); - if (c == null) { - c = new NaturalComparator(); - } - long result = 0; - - Long value = freqTable.get(v); - if (value != null) { - result = value.longValue(); - } - - if (c.compare(v, freqTable.firstKey()) < 0) { - return 0; // v is comparable, but less than first value - } - - if (c.compare(v, freqTable.lastKey()) >= 0) { - return getSumFreq(); // v is comparable, but greater than the last value - } - - Iterator values = valuesIterator(); - while (values.hasNext()) { - T nextValue = values.next(); - if (c.compare(v, nextValue) > 0) { - result += getCount(nextValue); - } else { - return result; - } - } - return result; - } - - //---------------------------------------------------------------------------------------------- - - /** - * Returns the cumulative percentage of values less than or equal to v - * (as a proportion between 0 and 1). - *

- * Returns Double.NaN if no values have been added. - *

- * - * @param v the value to lookup - * @return the proportion of values less than or equal to v - */ - public double getCumPct(T v) { - final long sumFreq = getSumFreq(); - if (sumFreq == 0) { - return Double.NaN; - } - return (double) getCumFreq(v) / (double) sumFreq; - } - - /** - * Returns the mode value(s) in comparator order. - * - * @return a list containing the value(s) which appear most often. - * @since 3.3 - */ - public List getMode() { - long mostPopular = 0; // frequencies are always positive - - // Get the max count first, so we avoid having to recreate the List each time - for(Long l : freqTable.values()) { - long frequency = l.longValue(); - if (frequency > mostPopular) { - mostPopular = frequency; - } - } - - List modeList = new ArrayList<>(); - for (Entry ent : freqTable.entrySet()) { - long frequency = ent.getValue().longValue(); - if (frequency == mostPopular) { - modeList.add(ent.getKey()); - } - } - return modeList; - } - - //---------------------------------------------------------------------------------------------- - - /** - * Merge another Frequency object's counts into this instance. - * This Frequency's counts will be incremented (or set when not already set) - * by the counts represented by other. - * - * @param other the other {@link Frequency} object to be merged - * @throws NullArgumentException if {@code other} is null - * @since 3.1 - */ - public void merge(final Frequency other) throws NullArgumentException { - MathUtils.checkNotNull(other, LocalizedFormats.NULL_NOT_ALLOWED); - - final Iterator> iter = other.entrySetIterator(); - while (iter.hasNext()) { - final Entry entry = iter.next(); - incrementValue(entry.getKey(), entry.getValue().longValue()); - } - } - - /** - * Merge a {@link Collection} of {@link Frequency} objects into this instance. - * This Frequency's counts will be incremented (or set when not already set) - * by the counts represented by each of the others. - * - * @param others the other {@link Frequency} objects to be merged - * @throws NullArgumentException if the collection is null - * @since 3.1 - */ - public void merge(final Collection> others) throws NullArgumentException { - MathUtils.checkNotNull(others, LocalizedFormats.NULL_NOT_ALLOWED); - - for (final Frequency freq : others) { - merge(freq); - } - } - - //---------------------------------------------------------------------------------------------- - - /** - * A Comparator that compares comparable objects using the - * natural order. Copied from Commons Collections ComparableComparator. - * - * @param the type of the objects compared - */ - private static class NaturalComparator> implements Comparator, Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = -3852193713161395148L; - - /** - * Compare the two {@link Comparable Comparable} arguments. - * This method is equivalent to: - *
(({@link Comparable Comparable})o1).{@link Comparable#compareTo compareTo}(o2)
- * - * @param o1 the first object - * @param o2 the second object - * @return result of comparison - * @throws NullPointerException when o1 is null, - * or when ((Comparable)o1).compareTo(o2) does - */ - @Override - public int compare(U o1, U o2) { - return o1.compareTo(o2); - } - } - - /** {@inheritDoc} */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + - ((freqTable == null) ? 0 : freqTable.hashCode()); - return result; - } - - /** {@inheritDoc} */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof Frequency)) { - return false; - } - Frequency other = (Frequency) obj; - if (freqTable == null) { - if (other.freqTable != null) { - return false; - } - } else if (!freqTable.equals(other.freqTable)) { - return false; - } - return true; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/StatUtils.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/StatUtils.java deleted file mode 100644 index ec246c76e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/StatUtils.java +++ /dev/null @@ -1,861 +0,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. - */ -package org.apache.commons.math4.stat; - -import java.util.List; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.stat.descriptive.DescriptiveStatistics; -import org.apache.commons.math4.stat.descriptive.UnivariateStatistic; -import org.apache.commons.math4.stat.descriptive.moment.GeometricMean; -import org.apache.commons.math4.stat.descriptive.moment.Mean; -import org.apache.commons.math4.stat.descriptive.moment.Variance; -import org.apache.commons.math4.stat.descriptive.rank.Max; -import org.apache.commons.math4.stat.descriptive.rank.Min; -import org.apache.commons.math4.stat.descriptive.rank.Percentile; -import org.apache.commons.math4.stat.descriptive.summary.Product; -import org.apache.commons.math4.stat.descriptive.summary.Sum; -import org.apache.commons.math4.stat.descriptive.summary.SumOfLogs; -import org.apache.commons.math4.stat.descriptive.summary.SumOfSquares; - -/** - * StatUtils provides static methods for computing statistics based on data - * stored in double[] arrays. - */ -public final class StatUtils { - - /** sum */ - private static final UnivariateStatistic SUM = new Sum(); - - /** sumSq */ - private static final UnivariateStatistic SUM_OF_SQUARES = new SumOfSquares(); - - /** prod */ - private static final UnivariateStatistic PRODUCT = new Product(); - - /** sumLog */ - private static final UnivariateStatistic SUM_OF_LOGS = new SumOfLogs(); - - /** min */ - private static final UnivariateStatistic MIN = new Min(); - - /** max */ - private static final UnivariateStatistic MAX = new Max(); - - /** mean */ - private static final UnivariateStatistic MEAN = new Mean(); - - /** variance */ - private static final Variance VARIANCE = new Variance(); - - /** percentile */ - private static final Percentile PERCENTILE = new Percentile(); - - /** geometric mean */ - private static final GeometricMean GEOMETRIC_MEAN = new GeometricMean(); - - /** - * Private Constructor - */ - private StatUtils() { - } - - /** - * Returns the sum of the values in the input array, or - * Double.NaN if the array is empty. - *

- * Throws IllegalArgumentException if the input array is null. - * - * @param values array of values to sum - * @return the sum of the values or Double.NaN if the array is empty - * @throws MathIllegalArgumentException if the array is null - */ - public static double sum(final double[] values) throws MathIllegalArgumentException { - return SUM.evaluate(values); - } - - /** - * Returns the sum of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray is empty. - *

- * Throws IllegalArgumentException if the array is null. - * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the sum of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - public static double sum(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - return SUM.evaluate(values, begin, length); - } - - /** - * Returns the sum of the squares of the entries in the input array, or - * Double.NaN if the array is empty. - *

- * Throws IllegalArgumentException if the array is null. - * - * @param values input array - * @return the sum of the squared values or Double.NaN if the array is empty - * @throws MathIllegalArgumentException if the array is null - */ - public static double sumSq(final double[] values) throws MathIllegalArgumentException { - return SUM_OF_SQUARES.evaluate(values); - } - - /** - * Returns the sum of the squares of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray - * is empty. - *

- * Throws IllegalArgumentException if the array is null. - * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the sum of the squares of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - public static double sumSq(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - return SUM_OF_SQUARES.evaluate(values, begin, length); - } - - /** - * Returns the product of the entries in the input array, or - * Double.NaN if the array is empty. - *

- * Throws IllegalArgumentException if the array is null. - * - * @param values the input array - * @return the product of the values or Double.NaN if the array is empty - * @throws MathIllegalArgumentException if the array is null - */ - public static double product(final double[] values) throws MathIllegalArgumentException { - return PRODUCT.evaluate(values); - } - - /** - * Returns the product of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray - * is empty. - *

- * Throws IllegalArgumentException if the array is null. - * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the product of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - public static double product(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - return PRODUCT.evaluate(values, begin, length); - } - - /** - * Returns the sum of the natural logs of the entries in the input array, or - * Double.NaN if the array is empty. - *

- * Throws IllegalArgumentException if the array is null. - *

- * See {@link SumOfLogs}. - * - * @param values the input array - * @return the sum of the natural logs of the values or Double.NaN if the array is empty - * @throws MathIllegalArgumentException if the array is null - */ - public static double sumLog(final double[] values) throws MathIllegalArgumentException { - return SUM_OF_LOGS.evaluate(values); - } - - /** - * Returns the sum of the natural logs of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray is empty. - *

- * Throws IllegalArgumentException if the array is null. - *

- * See {@link SumOfLogs}. - * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the sum of the natural logs of the values or Double.NaN if - * length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - public static double sumLog(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - return SUM_OF_LOGS.evaluate(values, begin, length); - } - - /** - * Returns the arithmetic mean of the entries in the input array, or - * Double.NaN if the array is empty. - *

- * Throws IllegalArgumentException if the array is null. - *

- * See {@link Mean} for - * details on the computing algorithm. - * - * @param values the input array - * @return the mean of the values or Double.NaN if the array is empty - * @throws MathIllegalArgumentException if the array is null - */ - public static double mean(final double[] values) throws MathIllegalArgumentException { - return MEAN.evaluate(values); - } - - /** - * Returns the arithmetic mean of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray - * is empty. - *

- * Throws IllegalArgumentException if the array is null. - *

- * See {@link Mean Mean} for - * details on the computing algorithm. - * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the mean of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - public static double mean(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - return MEAN.evaluate(values, begin, length); - } - - /** - * Returns the geometric mean of the entries in the input array, or - * Double.NaN if the array is empty. - *

- * Throws IllegalArgumentException if the array is null. - *

- * See {@link GeometricMean GeometricMean} - * for details on the computing algorithm. - * - * @param values the input array - * @return the geometric mean of the values or Double.NaN if the array is empty - * @throws MathIllegalArgumentException if the array is null - */ - public static double geometricMean(final double[] values) throws MathIllegalArgumentException { - return GEOMETRIC_MEAN.evaluate(values); - } - - /** - * Returns the geometric mean of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray - * is empty. - *

- * Throws IllegalArgumentException if the array is null. - *

- * See {@link GeometricMean GeometricMean} - * for details on the computing algorithm. - * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the geometric mean of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - public static double geometricMean(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - return GEOMETRIC_MEAN.evaluate(values, begin, length); - } - - /** - * Returns the variance of the entries in the input array, or - * Double.NaN if the array is empty. - *

- * This method returns the bias-corrected sample variance (using {@code n - 1} in - * the denominator). Use {@link #populationVariance(double[])} for the non-bias-corrected - * population variance. - *

- * See {@link Variance Variance} for - * details on the computing algorithm. - *

- * Returns 0 for a single-value (i.e. length = 1) sample. - *

- * Throws MathIllegalArgumentException if the array is null. - * - * @param values the input array - * @return the variance of the values or Double.NaN if the array is empty - * @throws MathIllegalArgumentException if the array is null - */ - public static double variance(final double[] values) throws MathIllegalArgumentException { - return VARIANCE.evaluate(values); - } - - /** - * Returns the variance of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray - * is empty. - *

- * This method returns the bias-corrected sample variance (using {@code n - 1} in - * the denominator). Use {@link #populationVariance(double[], int, int)} for the non-bias-corrected - * population variance. - *

- * See {@link Variance Variance} for - * details on the computing algorithm. - *

- * Returns 0 for a single-value (i.e. length = 1) sample. - *

- * Throws MathIllegalArgumentException if the array is null or the - * array index parameters are not valid. - * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the variance of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - public static double variance(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - return VARIANCE.evaluate(values, begin, length); - } - - /** - * Returns the variance of the entries in the specified portion of - * the input array, using the precomputed mean value. Returns - * Double.NaN if the designated subarray is empty. - *

- * This method returns the bias-corrected sample variance (using {@code n - 1} in - * the denominator). Use {@link #populationVariance(double[], double, int, int)} for - * the non-bias-corrected population variance. - *

- * See {@link Variance Variance} for - * details on the computing algorithm. - *

- * The formula used assumes that the supplied mean value is the arithmetic - * mean of the sample data, not a known population parameter. This method - * is supplied only to save computation when the mean has already been - * computed. - *

- * Returns 0 for a single-value (i.e. length = 1) sample. - *

- * Throws MathIllegalArgumentException if the array is null or the - * array index parameters are not valid. - * - * @param values the input array - * @param mean the precomputed mean value - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the variance of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - public static double variance(final double[] values, final double mean, final int begin, final int length) - throws MathIllegalArgumentException { - return VARIANCE.evaluate(values, mean, begin, length); - } - - /** - * Returns the variance of the entries in the input array, using the - * precomputed mean value. Returns Double.NaN if the array - * is empty. - *

- * This method returns the bias-corrected sample variance (using {@code n - 1} in - * the denominator). Use {@link #populationVariance(double[], double)} for the - * non-bias-corrected population variance. - *

- * See {@link Variance Variance} for - * details on the computing algorithm. - *

- * The formula used assumes that the supplied mean value is the arithmetic - * mean of the sample data, not a known population parameter. This method - * is supplied only to save computation when the mean has already been - * computed. - *

- * Returns 0 for a single-value (i.e. length = 1) sample. - *

- * Throws MathIllegalArgumentException if the array is null. - * - * @param values the input array - * @param mean the precomputed mean value - * @return the variance of the values or Double.NaN if the array is empty - * @throws MathIllegalArgumentException if the array is null - */ - public static double variance(final double[] values, final double mean) throws MathIllegalArgumentException { - return VARIANCE.evaluate(values, mean); - } - - /** - * Returns the - * population variance of the entries in the input array, or - * Double.NaN if the array is empty. - *

- * See {@link Variance Variance} for - * details on the formula and computing algorithm. - *

- * Returns 0 for a single-value (i.e. length = 1) sample. - *

- * Throws MathIllegalArgumentException if the array is null. - * - * @param values the input array - * @return the population variance of the values or Double.NaN if the array is empty - * @throws MathIllegalArgumentException if the array is null - */ - public static double populationVariance(final double[] values) throws MathIllegalArgumentException { - return new Variance(false).evaluate(values); - } - - /** - * Returns the - * population variance of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray - * is empty. - *

- * See {@link Variance Variance} for - * details on the computing algorithm. - *

- * Returns 0 for a single-value (i.e. length = 1) sample. - *

- * Throws MathIllegalArgumentException if the array is null or the - * array index parameters are not valid. - * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the population variance of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - public static double populationVariance(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - return new Variance(false).evaluate(values, begin, length); - } - - /** - * Returns the - * population variance of the entries in the specified portion of - * the input array, using the precomputed mean value. Returns - * Double.NaN if the designated subarray is empty. - *

- * See {@link Variance Variance} for - * details on the computing algorithm. - *

- * The formula used assumes that the supplied mean value is the arithmetic - * mean of the sample data, not a known population parameter. This method - * is supplied only to save computation when the mean has already been - * computed. - *

- * Returns 0 for a single-value (i.e. length = 1) sample. - *

- * Throws MathIllegalArgumentException if the array is null or the - * array index parameters are not valid. - * - * @param values the input array - * @param mean the precomputed mean value - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the population variance of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - public static double populationVariance(final double[] values, final double mean, - final int begin, final int length) - throws MathIllegalArgumentException { - return new Variance(false).evaluate(values, mean, begin, length); - } - - /** - * Returns the - * population variance of the entries in the input array, using the precomputed - * mean value. Returns Double.NaN if the array is empty. - *

- * See {@link Variance Variance} for - * details on the computing algorithm. - *

- * The formula used assumes that the supplied mean value is the arithmetic - * mean of the sample data, not a known population parameter. This method is - * supplied only to save computation when the mean has already been computed. - *

- * Returns 0 for a single-value (i.e. length = 1) sample. - *

- * Throws MathIllegalArgumentException if the array is null. - * - * @param values the input array - * @param mean the precomputed mean value - * @return the population variance of the values or Double.NaN if the array is empty - * @throws MathIllegalArgumentException if the array is null - */ - public static double populationVariance(final double[] values, final double mean) - throws MathIllegalArgumentException { - return new Variance(false).evaluate(values, mean); - } - - /** - * Returns the maximum of the entries in the input array, or - * Double.NaN if the array is empty. - *

- * Throws MathIllegalArgumentException if the array is null. - *

    - *
  • The result is NaN iff all values are NaN - * (i.e. NaN values have no impact on the value of the statistic).
  • - *
  • If any of the values equals Double.POSITIVE_INFINITY, - * the result is Double.POSITIVE_INFINITY.
  • - *
- * - * @param values the input array - * @return the maximum of the values or Double.NaN if the array is empty - * @throws MathIllegalArgumentException if the array is null - */ - public static double max(final double[] values) throws MathIllegalArgumentException { - return MAX.evaluate(values); - } - - /** - * Returns the maximum of the entries in the specified portion of the input array, - * or Double.NaN if the designated subarray is empty. - *

- * Throws MathIllegalArgumentException if the array is null or - * the array index parameters are not valid. - *

    - *
  • The result is NaN iff all values are NaN - * (i.e. NaN values have no impact on the value of the statistic).
  • - *
  • If any of the values equals Double.POSITIVE_INFINITY, - * the result is Double.POSITIVE_INFINITY.
  • - *
- * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the maximum of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - public static double max(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - return MAX.evaluate(values, begin, length); - } - - /** - * Returns the minimum of the entries in the input array, or - * Double.NaN if the array is empty. - *

- * Throws MathIllegalArgumentException if the array is null. - *

    - *
  • The result is NaN iff all values are NaN - * (i.e. NaN values have no impact on the value of the statistic).
  • - *
  • If any of the values equals Double.NEGATIVE_INFINITY, - * the result is Double.NEGATIVE_INFINITY.
  • - *
- * - * @param values the input array - * @return the minimum of the values or Double.NaN if the array is empty - * @throws MathIllegalArgumentException if the array is null - */ - public static double min(final double[] values) throws MathIllegalArgumentException { - return MIN.evaluate(values); - } - - /** - * Returns the minimum of the entries in the specified portion of the input array, - * or Double.NaN if the designated subarray is empty. - *

- * Throws MathIllegalArgumentException if the array is null or - * the array index parameters are not valid. - *

    - *
  • The result is NaN iff all values are NaN - * (i.e. NaN values have no impact on the value of the statistic).
  • - *
  • If any of the values equals Double.NEGATIVE_INFINITY, - * the result is Double.NEGATIVE_INFINITY.
  • - *
- * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the minimum of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - public static double min(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - return MIN.evaluate(values, begin, length); - } - - /** - * Returns an estimate of the pth percentile of the values - * in the values array. - *
    - *
  • Returns Double.NaN if values has length - * 0
  • - *
  • Returns (for any value of p) values[0] - * if values has length 1
  • - *
  • Throws IllegalArgumentException if values - * is null or p is not a valid quantile value (p must be greater than 0 - * and less than or equal to 100)
  • - *
- *

- * See {@link Percentile Percentile} - * for a description of the percentile estimation algorithm used. - * - * @param values input array of values - * @param p the percentile value to compute - * @return the percentile value or Double.NaN if the array is empty - * @throws MathIllegalArgumentException if values is null or p is invalid - */ - public static double percentile(final double[] values, final double p) throws MathIllegalArgumentException { - return PERCENTILE.evaluate(values,p); - } - - /** - * Returns an estimate of the pth percentile of the values - * in the values array, starting with the element in (0-based) - * position begin in the array and including length - * values. - *

    - *
  • Returns Double.NaN if length = 0
  • - *
  • Returns (for any value of p) values[begin] - * if length = 1
  • - *
  • Throws MathIllegalArgumentException if values - * is null, begin or length is invalid, or - * p is not a valid quantile value (p must be greater than 0 - * and less than or equal to 100)
  • - *
- *

- * See {@link Percentile Percentile} - * for a description of the percentile estimation algorithm used. - * - * @param values array of input values - * @param p the percentile to compute - * @param begin the first (0-based) element to include in the computation - * @param length the number of array elements to include - * @return the percentile value - * @throws MathIllegalArgumentException if the parameters are not valid or the input array is null - */ - public static double percentile(final double[] values, final int begin, final int length, final double p) - throws MathIllegalArgumentException { - return PERCENTILE.evaluate(values, begin, length, p); - } - - /** - * Returns the sum of the (signed) differences between corresponding elements of the - * input arrays -- i.e., sum(sample1[i] - sample2[i]). - * - * @param sample1 the first array - * @param sample2 the second array - * @return sum of paired differences - * @throws DimensionMismatchException if the arrays do not have the same (positive) length. - * @throws NoDataException if the sample arrays are empty. - */ - public static double sumDifference(final double[] sample1, final double[] sample2) - throws DimensionMismatchException, NoDataException { - - int n = sample1.length; - if (n != sample2.length) { - throw new DimensionMismatchException(n, sample2.length); - } - if (n <= 0) { - throw new NoDataException(LocalizedFormats.INSUFFICIENT_DIMENSION); - } - double result = 0; - for (int i = 0; i < n; i++) { - result += sample1[i] - sample2[i]; - } - return result; - } - - /** - * Returns the mean of the (signed) differences between corresponding elements of the - * input arrays -- i.e., sum(sample1[i] - sample2[i]) / sample1.length. - * - * @param sample1 the first array - * @param sample2 the second array - * @return mean of paired differences - * @throws DimensionMismatchException if the arrays do not have the same (positive) length. - * @throws NoDataException if the sample arrays are empty. - */ - public static double meanDifference(final double[] sample1, final double[] sample2) - throws DimensionMismatchException, NoDataException { - return sumDifference(sample1, sample2) / sample1.length; - } - - /** - * Returns the variance of the (signed) differences between corresponding elements of the - * input arrays -- i.e., var(sample1[i] - sample2[i]). - * - * @param sample1 the first array - * @param sample2 the second array - * @param meanDifference the mean difference between corresponding entries - * @return variance of paired differences - * @throws DimensionMismatchException if the arrays do not have the same length. - * @throws NumberIsTooSmallException if the arrays length is less than 2. - * @see #meanDifference(double[],double[]) - */ - public static double varianceDifference(final double[] sample1, final double[] sample2, double meanDifference) - throws DimensionMismatchException, NumberIsTooSmallException { - - double sum1 = 0d; - double sum2 = 0d; - double diff = 0d; - int n = sample1.length; - if (n != sample2.length) { - throw new DimensionMismatchException(n, sample2.length); - } - if (n < 2) { - throw new NumberIsTooSmallException(n, 2, true); - } - for (int i = 0; i < n; i++) { - diff = sample1[i] - sample2[i]; - sum1 += (diff - meanDifference) *(diff - meanDifference); - sum2 += diff - meanDifference; - } - return (sum1 - (sum2 * sum2 / n)) / (n - 1); - } - - /** - * Normalize (standardize) the sample, so it is has a mean of 0 and a standard deviation of 1. - * - * @param sample Sample to normalize. - * @return normalized (standardized) sample. - * @since 2.2 - */ - public static double[] normalize(final double[] sample) { - DescriptiveStatistics stats = new DescriptiveStatistics(); - - // Add the data from the series to stats - for (int i = 0; i < sample.length; i++) { - stats.addValue(sample[i]); - } - - // Compute mean and standard deviation - double mean = stats.getMean(); - double standardDeviation = stats.getStandardDeviation(); - - // initialize the standardizedSample, which has the same length as the sample - double[] standardizedSample = new double[sample.length]; - - for (int i = 0; i < sample.length; i++) { - // z = (x- mean)/standardDeviation - standardizedSample[i] = (sample[i] - mean) / standardDeviation; - } - return standardizedSample; - } - - /** - * Returns the sample mode(s). - *

- * The mode is the most frequently occurring value in the sample. - * If there is a unique value with maximum frequency, this value is returned - * as the only element of the output array. Otherwise, the returned array - * contains the maximum frequency elements in increasing order. - *

- * For example, if {@code sample} is {0, 12, 5, 6, 0, 13, 5, 17}, - * the returned array will have length two, with 0 in the first element and - * 5 in the second. - *

- * NaN values are ignored when computing the mode - i.e., NaNs will never - * appear in the output array. If the sample includes only NaNs or has - * length 0, an empty array is returned. - * - * @param sample input data - * @return array of array of the most frequently occurring element(s) sorted in ascending order. - * @throws MathIllegalArgumentException if the indices are invalid or the array is null - * @since 3.3 - */ - public static double[] mode(double[] sample) throws MathIllegalArgumentException { - if (sample == null) { - throw new NullArgumentException(LocalizedFormats.INPUT_ARRAY); - } - return getMode(sample, 0, sample.length); - } - - /** - * Returns the sample mode(s). - *

- * The mode is the most frequently occurring value in the sample. - * If there is a unique value with maximum frequency, this value is returned - * as the only element of the output array. Otherwise, the returned array - * contains the maximum frequency elements in increasing order. - *

- * For example, if {@code sample} is {0, 12, 5, 6, 0, 13, 5, 17}, - * the returned array will have length two, with 0 in the first element and - * 5 in the second. - *

- * NaN values are ignored when computing the mode - i.e., NaNs will never - * appear in the output array. If the sample includes only NaNs or has - * length 0, an empty array is returned. - * - * @param sample input data - * @param begin index (0-based) of the first array element to include - * @param length the number of elements to include - * @return array of array of the most frequently occurring element(s) sorted in ascending order. - * @throws MathIllegalArgumentException if the indices are invalid or the array is null - * @since 3.3 - */ - public static double[] mode(double[] sample, final int begin, final int length) { - if (sample == null) { - throw new NullArgumentException(LocalizedFormats.INPUT_ARRAY); - } - - if (begin < 0) { - throw new NotPositiveException(LocalizedFormats.START_POSITION, Integer.valueOf(begin)); - } - - if (length < 0) { - throw new NotPositiveException(LocalizedFormats.LENGTH, Integer.valueOf(length)); - } - - return getMode(sample, begin, length); - } - - /** - * Private helper method. - * Assumes parameters have been validated. - * @param values input data - * @param begin index (0-based) of the first array element to include - * @param length the number of elements to include - * @return array of array of the most frequently occurring element(s) sorted in ascending order. - */ - private static double[] getMode(double[] values, final int begin, final int length) { - // Add the values to the frequency table - Frequency freq = new Frequency<>(); - for (int i = begin; i < begin + length; i++) { - final double value = values[i]; - if (!Double.isNaN(value)) { - freq.addValue(Double.valueOf(value)); - } - } - List list = freq.getMode(); - // Convert the list to an array of primitive double - double[] modes = new double[list.size()]; - int i = 0; - for(Double c : list) { - modes[i++] = c.doubleValue(); - } - return modes; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/Covariance.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/Covariance.java deleted file mode 100644 index a42d43548..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/Covariance.java +++ /dev/null @@ -1,295 +0,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. - */ -package org.apache.commons.math4.stat.correlation; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.linear.BlockRealMatrix; -import org.apache.commons.math4.linear.RealMatrix; -import org.apache.commons.math4.stat.descriptive.moment.Mean; -import org.apache.commons.math4.stat.descriptive.moment.Variance; - -/** - * Computes covariances for pairs of arrays or columns of a matrix. - * - *

The constructors that take RealMatrix or - * double[][] arguments generate covariance matrices. The - * columns of the input matrices are assumed to represent variable values.

- * - *

The constructor argument biasCorrected determines whether or - * not computed covariances are bias-corrected.

- * - *

Unbiased covariances are given by the formula

- * cov(X, Y) = Σ[(xi - E(X))(yi - E(Y))] / (n - 1) - * where E(X) is the mean of X and E(Y) - * is the mean of the Y values. - * - *

Non-bias-corrected estimates use n in place of n - 1 - * - * @since 2.0 - */ -public class Covariance { - - /** covariance matrix */ - private final RealMatrix covarianceMatrix; - - /** - * Create an empty covariance matrix. - */ - /** Number of observations (length of covariate vectors) */ - private final int n; - - /** - * Create a Covariance with no data - */ - public Covariance() { - super(); - covarianceMatrix = null; - n = 0; - } - - /** - * Create a Covariance matrix from a rectangular array - * whose columns represent covariates. - * - *

The biasCorrected parameter determines whether or not - * covariance estimates are bias-corrected.

- * - *

The input array must be rectangular with at least one column - * and two rows.

- * - * @param data rectangular array with columns representing covariates - * @param biasCorrected true means covariances are bias-corrected - * @throws MathIllegalArgumentException if the input data array is not - * rectangular with at least two rows and one column. - * @throws NotStrictlyPositiveException if the input data array is not - * rectangular with at least one row and one column. - */ - public Covariance(double[][] data, boolean biasCorrected) - throws MathIllegalArgumentException, NotStrictlyPositiveException { - this(new BlockRealMatrix(data), biasCorrected); - } - - /** - * Create a Covariance matrix from a rectangular array - * whose columns represent covariates. - * - *

The input array must be rectangular with at least one column - * and two rows

- * - * @param data rectangular array with columns representing covariates - * @throws MathIllegalArgumentException if the input data array is not - * rectangular with at least two rows and one column. - * @throws NotStrictlyPositiveException if the input data array is not - * rectangular with at least one row and one column. - */ - public Covariance(double[][] data) - throws MathIllegalArgumentException, NotStrictlyPositiveException { - this(data, true); - } - - /** - * Create a covariance matrix from a matrix whose columns - * represent covariates. - * - *

The biasCorrected parameter determines whether or not - * covariance estimates are bias-corrected.

- * - *

The matrix must have at least one column and two rows

- * - * @param matrix matrix with columns representing covariates - * @param biasCorrected true means covariances are bias-corrected - * @throws MathIllegalArgumentException if the input matrix does not have - * at least two rows and one column - */ - public Covariance(RealMatrix matrix, boolean biasCorrected) - throws MathIllegalArgumentException { - checkSufficientData(matrix); - n = matrix.getRowDimension(); - covarianceMatrix = computeCovarianceMatrix(matrix, biasCorrected); - } - - /** - * Create a covariance matrix from a matrix whose columns - * represent covariates. - * - *

The matrix must have at least one column and two rows

- * - * @param matrix matrix with columns representing covariates - * @throws MathIllegalArgumentException if the input matrix does not have - * at least two rows and one column - */ - public Covariance(RealMatrix matrix) throws MathIllegalArgumentException { - this(matrix, true); - } - - /** - * Returns the covariance matrix - * - * @return covariance matrix - */ - public RealMatrix getCovarianceMatrix() { - return covarianceMatrix; - } - - /** - * Returns the number of observations (length of covariate vectors) - * - * @return number of observations - */ - public int getN() { - return n; - } - - /** - * Compute a covariance matrix from a matrix whose columns represent - * covariates. - * @param matrix input matrix (must have at least one column and two rows) - * @param biasCorrected determines whether or not covariance estimates are bias-corrected - * @return covariance matrix - * @throws MathIllegalArgumentException if the matrix does not contain sufficient data - */ - protected RealMatrix computeCovarianceMatrix(RealMatrix matrix, boolean biasCorrected) - throws MathIllegalArgumentException { - int dimension = matrix.getColumnDimension(); - Variance variance = new Variance(biasCorrected); - RealMatrix outMatrix = new BlockRealMatrix(dimension, dimension); - for (int i = 0; i < dimension; i++) { - for (int j = 0; j < i; j++) { - double cov = covariance(matrix.getColumn(i), matrix.getColumn(j), biasCorrected); - outMatrix.setEntry(i, j, cov); - outMatrix.setEntry(j, i, cov); - } - outMatrix.setEntry(i, i, variance.evaluate(matrix.getColumn(i))); - } - return outMatrix; - } - - /** - * Create a covariance matrix from a matrix whose columns represent - * covariates. Covariances are computed using the bias-corrected formula. - * @param matrix input matrix (must have at least one column and two rows) - * @return covariance matrix - * @throws MathIllegalArgumentException if matrix does not contain sufficient data - * @see #Covariance - */ - protected RealMatrix computeCovarianceMatrix(RealMatrix matrix) - throws MathIllegalArgumentException { - return computeCovarianceMatrix(matrix, true); - } - - /** - * Compute a covariance matrix from a rectangular array whose columns represent - * covariates. - * @param data input array (must have at least one column and two rows) - * @param biasCorrected determines whether or not covariance estimates are bias-corrected - * @return covariance matrix - * @throws MathIllegalArgumentException if the data array does not contain sufficient - * data - * @throws NotStrictlyPositiveException if the input data array is not - * rectangular with at least one row and one column. - */ - protected RealMatrix computeCovarianceMatrix(double[][] data, boolean biasCorrected) - throws MathIllegalArgumentException, NotStrictlyPositiveException { - return computeCovarianceMatrix(new BlockRealMatrix(data), biasCorrected); - } - - /** - * Create a covariance matrix from a rectangular array whose columns represent - * covariates. Covariances are computed using the bias-corrected formula. - * @param data input array (must have at least one column and two rows) - * @return covariance matrix - * @throws MathIllegalArgumentException if the data array does not contain sufficient data - * @throws NotStrictlyPositiveException if the input data array is not - * rectangular with at least one row and one column. - * @see #Covariance - */ - protected RealMatrix computeCovarianceMatrix(double[][] data) - throws MathIllegalArgumentException, NotStrictlyPositiveException { - return computeCovarianceMatrix(data, true); - } - - /** - * Computes the covariance between the two arrays. - * - *

Array lengths must match and the common length must be at least 2.

- * - * @param xArray first data array - * @param yArray second data array - * @param biasCorrected if true, returned value will be bias-corrected - * @return returns the covariance for the two arrays - * @throws MathIllegalArgumentException if the arrays lengths do not match or - * there is insufficient data - */ - public double covariance(final double[] xArray, final double[] yArray, boolean biasCorrected) - throws MathIllegalArgumentException { - Mean mean = new Mean(); - double result = 0d; - int length = xArray.length; - if (length != yArray.length) { - throw new MathIllegalArgumentException( - LocalizedFormats.DIMENSIONS_MISMATCH_SIMPLE, length, yArray.length); - } else if (length < 2) { - throw new MathIllegalArgumentException( - LocalizedFormats.INSUFFICIENT_OBSERVED_POINTS_IN_SAMPLE, length, 2); - } else { - double xMean = mean.evaluate(xArray); - double yMean = mean.evaluate(yArray); - for (int i = 0; i < length; i++) { - double xDev = xArray[i] - xMean; - double yDev = yArray[i] - yMean; - result += (xDev * yDev - result) / (i + 1); - } - } - return biasCorrected ? result * ((double) length / (double)(length - 1)) : result; - } - - /** - * Computes the covariance between the two arrays, using the bias-corrected - * formula. - * - *

Array lengths must match and the common length must be at least 2.

- * - * @param xArray first data array - * @param yArray second data array - * @return returns the covariance for the two arrays - * @throws MathIllegalArgumentException if the arrays lengths do not match or - * there is insufficient data - */ - public double covariance(final double[] xArray, final double[] yArray) - throws MathIllegalArgumentException { - return covariance(xArray, yArray, true); - } - - /** - * Throws MathIllegalArgumentException if the matrix does not have at least - * one column and two rows. - * @param matrix matrix to check - * @throws MathIllegalArgumentException if the matrix does not contain sufficient data - * to compute covariance - */ - private void checkSufficientData(final RealMatrix matrix) throws MathIllegalArgumentException { - int nRows = matrix.getRowDimension(); - int nCols = matrix.getColumnDimension(); - if (nRows < 2 || nCols < 1) { - throw new MathIllegalArgumentException( - LocalizedFormats.INSUFFICIENT_ROWS_AND_COLUMNS, - nRows, nCols); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java deleted file mode 100644 index 1fdb155a3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java +++ /dev/null @@ -1,273 +0,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. - */ -package org.apache.commons.math4.stat.correlation; - -import java.util.Arrays; -import java.util.Comparator; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.linear.BlockRealMatrix; -import org.apache.commons.math4.linear.MatrixUtils; -import org.apache.commons.math4.linear.RealMatrix; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.Pair; - -/** - * Implementation of Kendall's Tau-b rank correlation. - *

- * A pair of observations (x1, y1) and - * (x2, y2) are considered concordant if - * x1 < x2 and y1 < y2 - * or x2 < x1 and y2 < y1. - * The pair is discordant if x1 < x2 and - * y2 < y1 or x2 < x1 and - * y1 < y2. If either x1 = x2 - * or y1 = y2, the pair is neither concordant nor - * discordant. - *

- * Kendall's Tau-b is defined as: - *

- * taub = (nc - nd) / sqrt((n0 - n1) * (n0 - n2)) - *
- *

- * where: - *

    - *
  • n0 = n * (n - 1) / 2
  • - *
  • nc = Number of concordant pairs
  • - *
  • nd = Number of discordant pairs
  • - *
  • n1 = sum of ti * (ti - 1) / 2 for all i
  • - *
  • n2 = sum of uj * (uj - 1) / 2 for all j
  • - *
  • ti = Number of tied values in the ith group of ties in x
  • - *
  • uj = Number of tied values in the jth group of ties in y
  • - *
- *

- * This implementation uses the O(n log n) algorithm described in - * William R. Knight's 1966 paper "A Computer Method for Calculating - * Kendall's Tau with Ungrouped Data" in the Journal of the American - * Statistical Association. - * - * @see - * Kendall tau rank correlation coefficient (Wikipedia) - * @see A Computer - * Method for Calculating Kendall's Tau with Ungrouped Data - * - * @since 3.3 - */ -public class KendallsCorrelation { - - /** correlation matrix */ - private final RealMatrix correlationMatrix; - - /** - * Create a KendallsCorrelation instance without data. - */ - public KendallsCorrelation() { - correlationMatrix = null; - } - - /** - * Create a KendallsCorrelation from a rectangular array - * whose columns represent values of variables to be correlated. - * - * @param data rectangular array with columns representing variables - * @throws IllegalArgumentException if the input data array is not - * rectangular with at least two rows and two columns. - */ - public KendallsCorrelation(double[][] data) { - this(MatrixUtils.createRealMatrix(data)); - } - - /** - * Create a KendallsCorrelation from a RealMatrix whose columns - * represent variables to be correlated. - * - * @param matrix matrix with columns representing variables to correlate - */ - public KendallsCorrelation(RealMatrix matrix) { - correlationMatrix = computeCorrelationMatrix(matrix); - } - - /** - * Returns the correlation matrix. - * - * @return correlation matrix - */ - public RealMatrix getCorrelationMatrix() { - return correlationMatrix; - } - - /** - * Computes the Kendall's Tau rank correlation matrix for the columns of - * the input matrix. - * - * @param matrix matrix with columns representing variables to correlate - * @return correlation matrix - */ - public RealMatrix computeCorrelationMatrix(final RealMatrix matrix) { - int nVars = matrix.getColumnDimension(); - RealMatrix outMatrix = new BlockRealMatrix(nVars, nVars); - for (int i = 0; i < nVars; i++) { - for (int j = 0; j < i; j++) { - double corr = correlation(matrix.getColumn(i), matrix.getColumn(j)); - outMatrix.setEntry(i, j, corr); - outMatrix.setEntry(j, i, corr); - } - outMatrix.setEntry(i, i, 1d); - } - return outMatrix; - } - - /** - * Computes the Kendall's Tau rank correlation matrix for the columns of - * the input rectangular array. The columns of the array represent values - * of variables to be correlated. - * - * @param matrix matrix with columns representing variables to correlate - * @return correlation matrix - */ - public RealMatrix computeCorrelationMatrix(final double[][] matrix) { - return computeCorrelationMatrix(new BlockRealMatrix(matrix)); - } - - /** - * Computes the Kendall's Tau rank correlation coefficient between the two arrays. - * - * @param xArray first data array - * @param yArray second data array - * @return Returns Kendall's Tau rank correlation coefficient for the two arrays - * @throws DimensionMismatchException if the arrays lengths do not match - */ - public double correlation(final double[] xArray, final double[] yArray) - throws DimensionMismatchException { - - if (xArray.length != yArray.length) { - throw new DimensionMismatchException(xArray.length, yArray.length); - } - - final int n = xArray.length; - final long numPairs = sum(n - 1); - - @SuppressWarnings("unchecked") - Pair[] pairs = new Pair[n]; - for (int i = 0; i < n; i++) { - pairs[i] = new Pair<>(xArray[i], yArray[i]); - } - - Arrays.sort(pairs, new Comparator>() { - /** {@inheritDoc} */ - @Override - public int compare(Pair pair1, Pair pair2) { - int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); - return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); - } - }); - - long tiedXPairs = 0; - long tiedXYPairs = 0; - long consecutiveXTies = 1; - long consecutiveXYTies = 1; - Pair prev = pairs[0]; - for (int i = 1; i < n; i++) { - final Pair curr = pairs[i]; - if (curr.getFirst().equals(prev.getFirst())) { - consecutiveXTies++; - if (curr.getSecond().equals(prev.getSecond())) { - consecutiveXYTies++; - } else { - tiedXYPairs += sum(consecutiveXYTies - 1); - consecutiveXYTies = 1; - } - } else { - tiedXPairs += sum(consecutiveXTies - 1); - consecutiveXTies = 1; - tiedXYPairs += sum(consecutiveXYTies - 1); - consecutiveXYTies = 1; - } - prev = curr; - } - tiedXPairs += sum(consecutiveXTies - 1); - tiedXYPairs += sum(consecutiveXYTies - 1); - - long swaps = 0; - @SuppressWarnings("unchecked") - Pair[] pairsDestination = new Pair[n]; - for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { - for (int offset = 0; offset < n; offset += 2 * segmentSize) { - int i = offset; - final int iEnd = FastMath.min(i + segmentSize, n); - int j = iEnd; - final int jEnd = FastMath.min(j + segmentSize, n); - - int copyLocation = offset; - while (i < iEnd || j < jEnd) { - if (i < iEnd) { - if (j < jEnd) { - if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { - pairsDestination[copyLocation] = pairs[i]; - i++; - } else { - pairsDestination[copyLocation] = pairs[j]; - j++; - swaps += iEnd - i; - } - } else { - pairsDestination[copyLocation] = pairs[i]; - i++; - } - } else { - pairsDestination[copyLocation] = pairs[j]; - j++; - } - copyLocation++; - } - } - final Pair[] pairsTemp = pairs; - pairs = pairsDestination; - pairsDestination = pairsTemp; - } - - long tiedYPairs = 0; - long consecutiveYTies = 1; - prev = pairs[0]; - for (int i = 1; i < n; i++) { - final Pair curr = pairs[i]; - if (curr.getSecond().equals(prev.getSecond())) { - consecutiveYTies++; - } else { - tiedYPairs += sum(consecutiveYTies - 1); - consecutiveYTies = 1; - } - prev = curr; - } - tiedYPairs += sum(consecutiveYTies - 1); - - final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; - final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); - return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); - } - - /** - * Returns the sum of the number from 1 .. n according to Gauss' summation formula: - * \[ \sum\limits_{k=1}^n k = \frac{n(n + 1)}{2} \] - * - * @param n the summation end - * @return the sum of the number from 1 to n - */ - private static long sum(long n) { - return n * (n + 1) / 2l; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/PearsonsCorrelation.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/PearsonsCorrelation.java deleted file mode 100644 index c964d586b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/PearsonsCorrelation.java +++ /dev/null @@ -1,330 +0,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. - */ -package org.apache.commons.math4.stat.correlation; - -import org.apache.commons.statistics.distribution.TDistribution; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.linear.BlockRealMatrix; -import org.apache.commons.math4.linear.RealMatrix; -import org.apache.commons.math4.stat.regression.SimpleRegression; -import org.apache.commons.math4.util.FastMath; - -/** - * Computes Pearson's product-moment correlation coefficients for pairs of arrays - * or columns of a matrix. - * - *

The constructors that take RealMatrix or - * double[][] arguments generate correlation matrices. The - * columns of the input matrices are assumed to represent variable values. - * Correlations are given by the formula

- * - *

cor(X, Y) = Σ[(xi - E(X))(yi - E(Y))] / [(n - 1)s(X)s(Y)] - * where E(X) is the mean of X, E(Y) - * is the mean of the Y values and s(X), s(Y) are standard deviations.

- * - *

To compute the correlation coefficient for a single pair of arrays, use {@link #PearsonsCorrelation()} - * to construct an instance with no data and then {@link #correlation(double[], double[])}. - * Correlation matrices can also be computed directly from an instance with no data using - * {@link #computeCorrelationMatrix(double[][])}. In order to use {@link #getCorrelationMatrix()}, - * {@link #getCorrelationPValues()}, or {@link #getCorrelationStandardErrors()}; however, one of the - * constructors supplying data or a covariance matrix must be used to create the instance.

- * - * @since 2.0 - */ -public class PearsonsCorrelation { - - /** correlation matrix */ - private final RealMatrix correlationMatrix; - - /** number of observations */ - private final int nObs; - - /** - * Create a PearsonsCorrelation instance without data. - */ - public PearsonsCorrelation() { - super(); - correlationMatrix = null; - nObs = 0; - } - - /** - * Create a PearsonsCorrelation from a rectangular array - * whose columns represent values of variables to be correlated. - * - * Throws MathIllegalArgumentException if the input array does not have at least - * two columns and two rows. Pairwise correlations are set to NaN if one - * of the correlates has zero variance. - * - * @param data rectangular array with columns representing variables - * @throws MathIllegalArgumentException if the input data array is not - * rectangular with at least two rows and two columns. - * @see #correlation(double[], double[]) - */ - public PearsonsCorrelation(double[][] data) { - this(new BlockRealMatrix(data)); - } - - /** - * Create a PearsonsCorrelation from a RealMatrix whose columns - * represent variables to be correlated. - * - * Throws MathIllegalArgumentException if the matrix does not have at least - * two columns and two rows. Pairwise correlations are set to NaN if one - * of the correlates has zero variance. - * - * @param matrix matrix with columns representing variables to correlate - * @throws MathIllegalArgumentException if the matrix does not contain sufficient data - * @see #correlation(double[], double[]) - */ - public PearsonsCorrelation(RealMatrix matrix) { - nObs = matrix.getRowDimension(); - correlationMatrix = computeCorrelationMatrix(matrix); - } - - /** - * Create a PearsonsCorrelation from a {@link Covariance}. The correlation - * matrix is computed by scaling the Covariance's covariance matrix. - * The Covariance instance must have been created from a data matrix with - * columns representing variable values. - * - * @param covariance Covariance instance - */ - public PearsonsCorrelation(Covariance covariance) { - RealMatrix covarianceMatrix = covariance.getCovarianceMatrix(); - if (covarianceMatrix == null) { - throw new NullArgumentException(LocalizedFormats.COVARIANCE_MATRIX); - } - nObs = covariance.getN(); - correlationMatrix = covarianceToCorrelation(covarianceMatrix); - } - - /** - * Create a PearsonsCorrelation from a covariance matrix. The correlation - * matrix is computed by scaling the covariance matrix. - * - * @param covarianceMatrix covariance matrix - * @param numberOfObservations the number of observations in the dataset used to compute - * the covariance matrix - */ - public PearsonsCorrelation(RealMatrix covarianceMatrix, int numberOfObservations) { - nObs = numberOfObservations; - correlationMatrix = covarianceToCorrelation(covarianceMatrix); - } - - /** - * Returns the correlation matrix. - * - *

This method will return null if the argumentless constructor was used - * to create this instance, even if {@link #computeCorrelationMatrix(double[][])} - * has been called before it is activated.

- * - * @return correlation matrix - */ - public RealMatrix getCorrelationMatrix() { - return correlationMatrix; - } - - /** - * Returns a matrix of standard errors associated with the estimates - * in the correlation matrix.
- * getCorrelationStandardErrors().getEntry(i,j) is the standard - * error associated with getCorrelationMatrix.getEntry(i,j) - * - *

The formula used to compute the standard error is
- * SEr = ((1 - r2) / (n - 2))1/2 - * where r is the estimated correlation coefficient and - * n is the number of observations in the source dataset.

- * - *

To use this method, one of the constructors that supply an input - * matrix must have been used to create this instance.

- * - * @return matrix of correlation standard errors - * @throws NullPointerException if this instance was created with no data - */ - public RealMatrix getCorrelationStandardErrors() { - int nVars = correlationMatrix.getColumnDimension(); - double[][] out = new double[nVars][nVars]; - for (int i = 0; i < nVars; i++) { - for (int j = 0; j < nVars; j++) { - double r = correlationMatrix.getEntry(i, j); - out[i][j] = FastMath.sqrt((1 - r * r) /(nObs - 2)); - } - } - return new BlockRealMatrix(out); - } - - /** - * Returns a matrix of p-values associated with the (two-sided) null - * hypothesis that the corresponding correlation coefficient is zero. - * - *

getCorrelationPValues().getEntry(i,j) is the probability - * that a random variable distributed as tn-2 takes - * a value with absolute value greater than or equal to
- * |r|((n - 2) / (1 - r2))1/2

- * - *

The values in the matrix are sometimes referred to as the - * significance of the corresponding correlation coefficients.

- * - *

To use this method, one of the constructors that supply an input - * matrix must have been used to create this instance.

- * - * @return matrix of p-values - * @throws org.apache.commons.math4.exception.MaxCountExceededException - * if an error occurs estimating probabilities - * @throws NullPointerException if this instance was created with no data - */ - public RealMatrix getCorrelationPValues() { - TDistribution tDistribution = new TDistribution(nObs - 2); - int nVars = correlationMatrix.getColumnDimension(); - double[][] out = new double[nVars][nVars]; - for (int i = 0; i < nVars; i++) { - for (int j = 0; j < nVars; j++) { - if (i == j) { - out[i][j] = 0d; - } else { - double r = correlationMatrix.getEntry(i, j); - double t = FastMath.abs(r * FastMath.sqrt((nObs - 2)/(1 - r * r))); - out[i][j] = 2 * tDistribution.cumulativeProbability(-t); - } - } - } - return new BlockRealMatrix(out); - } - - - /** - * Computes the correlation matrix for the columns of the - * input matrix, using {@link #correlation(double[], double[])}. - * - * Throws MathIllegalArgumentException if the matrix does not have at least - * two columns and two rows. Pairwise correlations are set to NaN if one - * of the correlates has zero variance. - * - * @param matrix matrix with columns representing variables to correlate - * @return correlation matrix - * @throws MathIllegalArgumentException if the matrix does not contain sufficient data - * @see #correlation(double[], double[]) - */ - public RealMatrix computeCorrelationMatrix(RealMatrix matrix) { - checkSufficientData(matrix); - int nVars = matrix.getColumnDimension(); - RealMatrix outMatrix = new BlockRealMatrix(nVars, nVars); - for (int i = 0; i < nVars; i++) { - for (int j = 0; j < i; j++) { - double corr = correlation(matrix.getColumn(i), matrix.getColumn(j)); - outMatrix.setEntry(i, j, corr); - outMatrix.setEntry(j, i, corr); - } - outMatrix.setEntry(i, i, 1d); - } - return outMatrix; - } - - /** - * Computes the correlation matrix for the columns of the - * input rectangular array. The columns of the array represent values - * of variables to be correlated. - * - * Throws MathIllegalArgumentException if the matrix does not have at least - * two columns and two rows or if the array is not rectangular. Pairwise - * correlations are set to NaN if one of the correlates has zero variance. - * - * @param data matrix with columns representing variables to correlate - * @return correlation matrix - * @throws MathIllegalArgumentException if the array does not contain sufficient data - * @see #correlation(double[], double[]) - */ - public RealMatrix computeCorrelationMatrix(double[][] data) { - return computeCorrelationMatrix(new BlockRealMatrix(data)); - } - - /** - * Computes the Pearson's product-moment correlation coefficient between two arrays. - * - *

Throws MathIllegalArgumentException if the arrays do not have the same length - * or their common length is less than 2. Returns {@code NaN} if either of the arrays - * has zero variance (i.e., if one of the arrays does not contain at least two distinct - * values).

- * - * @param xArray first data array - * @param yArray second data array - * @return Returns Pearson's correlation coefficient for the two arrays - * @throws DimensionMismatchException if the arrays lengths do not match - * @throws MathIllegalArgumentException if there is insufficient data - */ - public double correlation(final double[] xArray, final double[] yArray) { - SimpleRegression regression = new SimpleRegression(); - if (xArray.length != yArray.length) { - throw new DimensionMismatchException(xArray.length, yArray.length); - } else if (xArray.length < 2) { - throw new MathIllegalArgumentException(LocalizedFormats.INSUFFICIENT_DIMENSION, - xArray.length, 2); - } else { - for(int i=0; iUses the formula
- * r(X,Y) = cov(X,Y)/s(X)s(Y) where - * r(·,·) is the correlation coefficient and - * s(·) means standard deviation.

- * - * @param covarianceMatrix the covariance matrix - * @return correlation matrix - */ - public RealMatrix covarianceToCorrelation(RealMatrix covarianceMatrix) { - int nVars = covarianceMatrix.getColumnDimension(); - RealMatrix outMatrix = new BlockRealMatrix(nVars, nVars); - for (int i = 0; i < nVars; i++) { - double sigma = FastMath.sqrt(covarianceMatrix.getEntry(i, i)); - outMatrix.setEntry(i, i, 1d); - for (int j = 0; j < i; j++) { - double entry = covarianceMatrix.getEntry(i, j) / - (sigma * FastMath.sqrt(covarianceMatrix.getEntry(j, j))); - outMatrix.setEntry(i, j, entry); - outMatrix.setEntry(j, i, entry); - } - } - return outMatrix; - } - - /** - * Throws MathIllegalArgumentException if the matrix does not have at least - * two columns and two rows. - * - * @param matrix matrix to check for sufficiency - * @throws MathIllegalArgumentException if there is insufficient data - */ - private void checkSufficientData(final RealMatrix matrix) { - int nRows = matrix.getRowDimension(); - int nCols = matrix.getColumnDimension(); - if (nRows < 2 || nCols < 2) { - throw new MathIllegalArgumentException(LocalizedFormats.INSUFFICIENT_ROWS_AND_COLUMNS, - nRows, nCols); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/SpearmansCorrelation.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/SpearmansCorrelation.java deleted file mode 100644 index 2593c125a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/SpearmansCorrelation.java +++ /dev/null @@ -1,203 +0,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. - */ - -package org.apache.commons.math4.stat.correlation; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.linear.BlockRealMatrix; -import org.apache.commons.math4.linear.RealMatrix; -import org.apache.commons.math4.stat.ranking.NaNStrategy; -import org.apache.commons.math4.stat.ranking.NaturalRanking; -import org.apache.commons.math4.stat.ranking.RankingAlgorithm; - -/** - * Spearman's rank correlation. This implementation performs a rank - * transformation on the input data and then computes {@link PearsonsCorrelation} - * on the ranked data. - *

- * By default, ranks are computed using {@link NaturalRanking} with default - * strategies for handling NaNs and ties in the data (NaNs maximal, ties averaged). - * The ranking algorithm can be set using a constructor argument. - * - * @since 2.0 - */ -public class SpearmansCorrelation { - - /** Input data */ - private final RealMatrix data; - - /** Ranking algorithm */ - private final RankingAlgorithm rankingAlgorithm; - - /** Rank correlation */ - private final PearsonsCorrelation rankCorrelation; - - /** - * Create a SpearmansCorrelation without data. - */ - public SpearmansCorrelation() { - this(new NaturalRanking()); - } - - /** - * Create a SpearmansCorrelation with the given ranking algorithm. - * - * @param rankingAlgorithm ranking algorithm - * @throws MathIllegalArgumentException if the provided {@link RankingAlgorithm} is of - * type {@link NaturalRanking} and uses a {@link NaNStrategy#REMOVED} strategy - * @since 3.1 - */ - public SpearmansCorrelation(final RankingAlgorithm rankingAlgorithm) - throws MathIllegalArgumentException { - - if (rankingAlgorithm instanceof NaturalRanking && - NaNStrategy.REMOVED == ((NaturalRanking) rankingAlgorithm).getNanStrategy()) { - throw new MathIllegalArgumentException(LocalizedFormats.NOT_SUPPORTED_NAN_STRATEGY, - NaNStrategy.REMOVED); - } - - data = null; - this.rankingAlgorithm = rankingAlgorithm; - rankCorrelation = null; - } - - /** - * Create a SpearmansCorrelation from the given data matrix. - * - * @param dataMatrix matrix of data with columns representing - * variables to correlate - */ - public SpearmansCorrelation(final RealMatrix dataMatrix) { - this(dataMatrix, new NaturalRanking()); - } - - /** - * Create a SpearmansCorrelation with the given input data matrix - * and ranking algorithm. - * - * @param dataMatrix matrix of data with columns representing - * variables to correlate - * @param rankingAlgorithm ranking algorithm - * @throws MathIllegalArgumentException if the provided {@link RankingAlgorithm} is of - * type {@link NaturalRanking} and uses a {@link NaNStrategy#REMOVED} strategy - */ - public SpearmansCorrelation(final RealMatrix dataMatrix, final RankingAlgorithm rankingAlgorithm) - throws MathIllegalArgumentException { - - if (rankingAlgorithm instanceof NaturalRanking && - NaNStrategy.REMOVED == ((NaturalRanking) rankingAlgorithm).getNanStrategy()) { - throw new MathIllegalArgumentException(LocalizedFormats.NOT_SUPPORTED_NAN_STRATEGY, - NaNStrategy.REMOVED); - } - - this.rankingAlgorithm = rankingAlgorithm; - this.data = rankTransform(dataMatrix); - rankCorrelation = new PearsonsCorrelation(data); - } - - /** - * Calculate the Spearman Rank Correlation Matrix. - * - * @return Spearman Rank Correlation Matrix - * @throws NullPointerException if this instance was created with no data - */ - public RealMatrix getCorrelationMatrix() { - return rankCorrelation.getCorrelationMatrix(); - } - - /** - * Returns a {@link PearsonsCorrelation} instance constructed from the - * ranked input data. That is, - * new SpearmansCorrelation(matrix).getRankCorrelation() - * is equivalent to - * new PearsonsCorrelation(rankTransform(matrix)) where - * rankTransform(matrix) is the result of applying the - * configured RankingAlgorithm to each of the columns of - * matrix. - * - *

Returns null if this instance was created with no data.

- * - * @return PearsonsCorrelation among ranked column data - */ - public PearsonsCorrelation getRankCorrelation() { - return rankCorrelation; - } - - /** - * Computes the Spearman's rank correlation matrix for the columns of the - * input matrix. - * - * @param matrix matrix with columns representing variables to correlate - * @return correlation matrix - */ - public RealMatrix computeCorrelationMatrix(final RealMatrix matrix) { - final RealMatrix matrixCopy = rankTransform(matrix); - return new PearsonsCorrelation().computeCorrelationMatrix(matrixCopy); - } - - /** - * Computes the Spearman's rank correlation matrix for the columns of the - * input rectangular array. The columns of the array represent values - * of variables to be correlated. - * - * @param matrix matrix with columns representing variables to correlate - * @return correlation matrix - */ - public RealMatrix computeCorrelationMatrix(final double[][] matrix) { - return computeCorrelationMatrix(new BlockRealMatrix(matrix)); - } - - /** - * Computes the Spearman's rank correlation coefficient between the two arrays. - * - * @param xArray first data array - * @param yArray second data array - * @return Returns Spearman's rank correlation coefficient for the two arrays - * @throws DimensionMismatchException if the arrays lengths do not match - * @throws MathIllegalArgumentException if the array length is less than 2 - */ - public double correlation(final double[] xArray, final double[] yArray) { - if (xArray.length != yArray.length) { - throw new DimensionMismatchException(xArray.length, yArray.length); - } else if (xArray.length < 2) { - throw new MathIllegalArgumentException(LocalizedFormats.INSUFFICIENT_DIMENSION, - xArray.length, 2); - } else { - return new PearsonsCorrelation().correlation(rankingAlgorithm.rank(xArray), - rankingAlgorithm.rank(yArray)); - } - } - - /** - * Applies rank transform to each of the columns of matrix - * using the current rankingAlgorithm. - * - * @param matrix matrix to transform - * @return a rank-transformed matrix - */ - private RealMatrix rankTransform(final RealMatrix matrix) { - RealMatrix transformed = matrix.copy(); - for (int i = 0; i < transformed.getColumnDimension(); i++) { - transformed.setColumn(i, rankingAlgorithm.rank(transformed.getColumn(i))); - } - - return transformed; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/StorelessBivariateCovariance.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/StorelessBivariateCovariance.java deleted file mode 100644 index 6f418fb85..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/StorelessBivariateCovariance.java +++ /dev/null @@ -1,138 +0,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. - */ -package org.apache.commons.math4.stat.correlation; - -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Bivariate Covariance implementation that does not require input data to be - * stored in memory. - * - *

This class is based on a paper written by Philippe Pébay: - * - * Formulas for Robust, One-Pass Parallel Computation of Covariances and - * Arbitrary-Order Statistical Moments, 2008, Technical Report SAND2008-6212, - * Sandia National Laboratories. It computes the covariance for a pair of variables. - * Use {@link StorelessCovariance} to estimate an entire covariance matrix.

- * - *

Note: This class is package private as it is only used internally in - * the {@link StorelessCovariance} class.

- * - * @since 3.0 - */ -class StorelessBivariateCovariance { - - /** the mean of variable x */ - private double meanX; - - /** the mean of variable y */ - private double meanY; - - /** number of observations */ - private double n; - - /** the running covariance estimate */ - private double covarianceNumerator; - - /** flag for bias correction */ - private boolean biasCorrected; - - /** - * Create an empty {@link StorelessBivariateCovariance} instance with - * bias correction. - */ - StorelessBivariateCovariance() { - this(true); - } - - /** - * Create an empty {@link StorelessBivariateCovariance} instance. - * - * @param biasCorrection if true the covariance estimate is corrected - * for bias, i.e. n-1 in the denominator, otherwise there is no bias correction, - * i.e. n in the denominator. - */ - StorelessBivariateCovariance(final boolean biasCorrection) { - meanX = meanY = 0.0; - n = 0; - covarianceNumerator = 0.0; - biasCorrected = biasCorrection; - } - - /** - * Update the covariance estimation with a pair of variables (x, y). - * - * @param x the x value - * @param y the y value - */ - public void increment(final double x, final double y) { - n++; - final double deltaX = x - meanX; - final double deltaY = y - meanY; - meanX += deltaX / n; - meanY += deltaY / n; - covarianceNumerator += ((n - 1.0) / n) * deltaX * deltaY; - } - - /** - * Appends another bivariate covariance calculation to this. - * After this operation, statistics returned should be close to what would - * have been obtained by by performing all of the {@link #increment(double, double)} - * operations in {@code cov} directly on this. - * - * @param cov StorelessBivariateCovariance instance to append. - */ - public void append(StorelessBivariateCovariance cov) { - double oldN = n; - n += cov.n; - final double deltaX = cov.meanX - meanX; - final double deltaY = cov.meanY - meanY; - meanX += deltaX * cov.n / n; - meanY += deltaY * cov.n / n; - covarianceNumerator += cov.covarianceNumerator + oldN * cov.n / n * deltaX * deltaY; - } - - /** - * Returns the number of observations. - * - * @return number of observations - */ - public double getN() { - return n; - } - - /** - * Return the current covariance estimate. - * - * @return the current covariance - * @throws NumberIsTooSmallException if the number of observations - * is < 2 - */ - public double getResult() throws NumberIsTooSmallException { - if (n < 2) { - throw new NumberIsTooSmallException(LocalizedFormats.INSUFFICIENT_DIMENSION, - n, 2, true); - } - if (biasCorrected) { - return covarianceNumerator / (n - 1d); - } else { - return covarianceNumerator / n; - } - } -} - diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/StorelessCovariance.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/StorelessCovariance.java deleted file mode 100644 index 0d3b50199..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/StorelessCovariance.java +++ /dev/null @@ -1,229 +0,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. - */ -package org.apache.commons.math4.stat.correlation; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathUnsupportedOperationException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.linear.MatrixUtils; -import org.apache.commons.math4.linear.RealMatrix; - -/** - * Covariance implementation that does not require input data to be - * stored in memory. The size of the covariance matrix is specified in the - * constructor. Specific elements of the matrix are incrementally updated with - * calls to incrementRow() or increment Covariance(). - * - *

This class is based on a paper written by Philippe Pébay: - * - * Formulas for Robust, One-Pass Parallel Computation of Covariances and - * Arbitrary-Order Statistical Moments, 2008, Technical Report SAND2008-6212, - * Sandia National Laboratories.

- * - *

Note: the underlying covariance matrix is symmetric, thus only the - * upper triangular part of the matrix is stored and updated each increment.

- * - * @since 3.0 - */ -public class StorelessCovariance extends Covariance { - - /** the square covariance matrix (upper triangular part) */ - private StorelessBivariateCovariance[] covMatrix; - - /** dimension of the square covariance matrix */ - private int dimension; - - /** - * Create a bias corrected covariance matrix with a given dimension. - * - * @param dim the dimension of the square covariance matrix - */ - public StorelessCovariance(final int dim) { - this(dim, true); - } - - /** - * Create a covariance matrix with a given number of rows and columns and the - * indicated bias correction. - * - * @param dim the dimension of the covariance matrix - * @param biasCorrected if true the covariance estimate is corrected - * for bias, i.e. n-1 in the denominator, otherwise there is no bias correction, - * i.e. n in the denominator. - */ - public StorelessCovariance(final int dim, final boolean biasCorrected) { - dimension = dim; - covMatrix = new StorelessBivariateCovariance[dimension * (dimension + 1) / 2]; - initializeMatrix(biasCorrected); - } - - /** - * Initialize the internal two-dimensional array of - * {@link StorelessBivariateCovariance} instances. - * - * @param biasCorrected if the covariance estimate shall be corrected for bias - */ - private void initializeMatrix(final boolean biasCorrected) { - for(int i = 0; i < dimension; i++){ - for(int j = 0; j < dimension; j++){ - setElement(i, j, new StorelessBivariateCovariance(biasCorrected)); - } - } - } - - /** - * Returns the index (i, j) translated into the one-dimensional - * array used to store the upper triangular part of the symmetric - * covariance matrix. - * - * @param i the row index - * @param j the column index - * @return the corresponding index in the matrix array - */ - private int indexOf(final int i, final int j) { - return j < i ? i * (i + 1) / 2 + j : j * (j + 1) / 2 + i; - } - - /** - * Gets the element at index (i, j) from the covariance matrix - * @param i the row index - * @param j the column index - * @return the {@link StorelessBivariateCovariance} element at the given index - */ - private StorelessBivariateCovariance getElement(final int i, final int j) { - return covMatrix[indexOf(i, j)]; - } - - /** - * Sets the covariance element at index (i, j) in the covariance matrix - * @param i the row index - * @param j the column index - * @param cov the {@link StorelessBivariateCovariance} element to be set - */ - private void setElement(final int i, final int j, - final StorelessBivariateCovariance cov) { - covMatrix[indexOf(i, j)] = cov; - } - - /** - * Get the covariance for an individual element of the covariance matrix. - * - * @param xIndex row index in the covariance matrix - * @param yIndex column index in the covariance matrix - * @return the covariance of the given element - * @throws NumberIsTooSmallException if the number of observations - * in the cell is < 2 - */ - public double getCovariance(final int xIndex, - final int yIndex) - throws NumberIsTooSmallException { - - return getElement(xIndex, yIndex).getResult(); - - } - - /** - * Increment the covariance matrix with one row of data. - * - * @param data array representing one row of data. - * @throws DimensionMismatchException if the length of rowData - * does not match with the covariance matrix - */ - public void increment(final double[] data) - throws DimensionMismatchException { - - int length = data.length; - if (length != dimension) { - throw new DimensionMismatchException(length, dimension); - } - - // only update the upper triangular part of the covariance matrix - // as only these parts are actually stored - for (int i = 0; i < length; i++){ - for (int j = i; j < length; j++){ - getElement(i, j).increment(data[i], data[j]); - } - } - - } - - /** - * Appends {@code sc} to this, effectively aggregating the computations in {@code sc} - * with this. After invoking this method, covariances returned should be close - * to what would have been obtained by performing all of the {@link #increment(double[])} - * operations in {@code sc} directly on this. - * - * @param sc externally computed StorelessCovariance to add to this - * @throws DimensionMismatchException if the dimension of sc does not match this - * @since 3.3 - */ - public void append(StorelessCovariance sc) throws DimensionMismatchException { - if (sc.dimension != dimension) { - throw new DimensionMismatchException(sc.dimension, dimension); - } - - // only update the upper triangular part of the covariance matrix - // as only these parts are actually stored - for (int i = 0; i < dimension; i++) { - for (int j = i; j < dimension; j++) { - getElement(i, j).append(sc.getElement(i, j)); - } - } - } - - /** - * {@inheritDoc} - * @throws NumberIsTooSmallException if the number of observations - * in a cell is < 2 - */ - @Override - public RealMatrix getCovarianceMatrix() throws NumberIsTooSmallException { - return MatrixUtils.createRealMatrix(getData()); - } - - /** - * Return the covariance matrix as two-dimensional array. - * - * @return a two-dimensional double array of covariance values - * @throws NumberIsTooSmallException if the number of observations - * for a cell is < 2 - */ - public double[][] getData() throws NumberIsTooSmallException { - final double[][] data = new double[dimension][dimension]; - for (int i = 0; i < dimension; i++) { - for (int j = 0; j < dimension; j++) { - data[i][j] = getElement(i, j).getResult(); - } - } - return data; - } - - /** - * This {@link Covariance} method is not supported by a {@link StorelessCovariance}, - * since the number of bivariate observations does not have to be the same for different - * pairs of covariates - i.e., N as defined in {@link Covariance#getN()} is undefined. - * - * @return nothing as this implementation always throws a - * {@link MathUnsupportedOperationException} - * @throws MathUnsupportedOperationException in all cases - */ - @Override - public int getN() - throws MathUnsupportedOperationException { - throw new MathUnsupportedOperationException(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/package-info.java deleted file mode 100644 index 2d5ee305e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/correlation/package-info.java +++ /dev/null @@ -1,22 +0,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. - */ -/** - * - * Correlations/Covariance computations. - * - */ -package org.apache.commons.math4.stat.correlation; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/AbstractStorelessUnivariateStatistic.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/AbstractStorelessUnivariateStatistic.java deleted file mode 100644 index 26b38047d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/AbstractStorelessUnivariateStatistic.java +++ /dev/null @@ -1,192 +0,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. - */ -package org.apache.commons.math4.stat.descriptive; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; -import org.apache.commons.numbers.core.Precision; - -/** - * Abstract base class for implementations of the - * {@link StorelessUnivariateStatistic} interface. - *

- * Provides default {@code evaluate(double[],...)} and {@code incrementAll(double[])} - * implementations. - *

- * Note that these implementations are not synchronized. - */ -public abstract class AbstractStorelessUnivariateStatistic - implements StorelessUnivariateStatistic { - - /** - * This default implementation creates a copy of this {@link StorelessUnivariateStatistic} - * instance, calls {@link #clear} on it, then calls {@link #incrementAll} with the specified - * portion of the input array, and then uses {@link #getResult} to compute the return value. - *

- * Note that this implementation does not change the internal state of the statistic. - *

- * Implementations may override this method with a more efficient and possibly more - * accurate implementation that works directly with the input array. - *

- * If the array is null, a MathIllegalArgumentException is thrown. - * - * @param values input array - * @return the value of the statistic applied to the input array - * @throws MathIllegalArgumentException if values is null - * @see UnivariateStatistic#evaluate(double[]) - */ - @Override - public double evaluate(final double[] values) throws MathIllegalArgumentException { - if (values == null) { - throw new NullArgumentException(LocalizedFormats.INPUT_ARRAY); - } - return evaluate(values, 0, values.length); - } - - /** - * This default implementation creates a copy of this {@link StorelessUnivariateStatistic} - * instance, calls {@link #clear} on it, then calls {@link #incrementAll} with the specified - * portion of the input array, and then uses {@link #getResult} to compute the return value. - *

- * Note that this implementation does not change the internal state of the statistic. - *

- * Implementations may override this method with a more efficient and possibly more - * accurate implementation that works directly with the input array. - *

- * If the array is null or the index parameters are not valid, an - * MathIllegalArgumentException is thrown. - * - * @param values the input array - * @param begin the index of the first element to include - * @param length the number of elements to include - * @return the value of the statistic applied to the included array entries - * @throws MathIllegalArgumentException if the array is null or the indices are not valid - * @see UnivariateStatistic#evaluate(double[], int, int) - */ - @Override - public double evaluate(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - - if (MathArrays.verifyValues(values, begin, length)) { - final StorelessUnivariateStatistic stat = copy(); - stat.clear(); - stat.incrementAll(values, begin, length); - return stat.getResult(); - } - return Double.NaN; - } - - /** - * {@inheritDoc} - */ - @Override - public abstract StorelessUnivariateStatistic copy(); - - /** - * {@inheritDoc} - */ - @Override - public abstract void clear(); - - /** - * {@inheritDoc} - */ - @Override - public abstract double getResult(); - - /** - * {@inheritDoc} - */ - @Override - public abstract void increment(final double d); - - /** - * This default implementation just calls {@link #increment} in a loop over - * the input array. - *

- * Throws IllegalArgumentException if the input values array is null. - * - * @param values values to add - * @throws MathIllegalArgumentException if values is null - * @see StorelessUnivariateStatistic#incrementAll(double[]) - */ - @Override - public void incrementAll(double[] values) throws MathIllegalArgumentException { - if (values == null) { - throw new NullArgumentException(LocalizedFormats.INPUT_ARRAY); - } - incrementAll(values, 0, values.length); - } - - /** - * This default implementation just calls {@link #increment} in a loop over - * the specified portion of the input array. - *

- * Throws IllegalArgumentException if the input values array is null. - * - * @param values array holding values to add - * @param begin index of the first array element to add - * @param length number of array elements to add - * @throws MathIllegalArgumentException if values is null - * @see StorelessUnivariateStatistic#incrementAll(double[], int, int) - */ - @Override - public void incrementAll(double[] values, int begin, int length) throws MathIllegalArgumentException { - if (MathArrays.verifyValues(values, begin, length)) { - int k = begin + length; - for (int i = begin; i < k; i++) { - increment(values[i]); - } - } - } - - /** - * Returns true iff object is the same type of - * {@link StorelessUnivariateStatistic} (the object's class equals this - * instance) returning the same values as this for getResult() - * and getN(). - * - * @param object object to test equality against. - * @return true if object returns the same value as this - */ - @Override - public boolean equals(Object object) { - if (object == this ) { - return true; - } - if (object == null || object.getClass() != this.getClass()) { - return false; - } - StorelessUnivariateStatistic stat = (StorelessUnivariateStatistic) object; - return Precision.equalsIncludingNaN(stat.getResult(), this.getResult()) && - Precision.equalsIncludingNaN(stat.getN(), this.getN()); - } - - /** - * Returns hash code based on getResult() and getN(). - * - * @return hash code - */ - @Override - public int hashCode() { - return 31 * (31 + MathUtils.hash(getResult())) + MathUtils.hash(getN()); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/AbstractUnivariateStatistic.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/AbstractUnivariateStatistic.java deleted file mode 100644 index e953aed02..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/AbstractUnivariateStatistic.java +++ /dev/null @@ -1,132 +0,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. - */ -package org.apache.commons.math4.stat.descriptive; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.MathArrays; - -/** - * Abstract base class for implementations of the {@link UnivariateStatistic} interface. - *

- * Provides a default implementation of evaluate(double[]), - * delegating to evaluate(double[], int, int) in the natural way. - */ -public abstract class AbstractUnivariateStatistic - implements UnivariateStatistic { - - /** Stored data. */ - private double[] storedData; - - /** - * {@inheritDoc} - */ - @Override - public double evaluate(final double[] values) throws MathIllegalArgumentException { - MathArrays.verifyValues(values, 0, 0); - return evaluate(values, 0, values.length); - } - - /** - * {@inheritDoc} - */ - @Override - public abstract double evaluate(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException; - - /** - * {@inheritDoc} - */ - @Override - public abstract UnivariateStatistic copy(); - - /** - * Set the data array. - *

- * The stored value is a copy of the parameter array, not the array itself. - *

- * @param values data array to store (may be null to remove stored data) - * @see #evaluate() - */ - public void setData(final double[] values) { - storedData = (values == null) ? null : values.clone(); - } - - /** - * Get a copy of the stored data array. - * @return copy of the stored data array (may be null) - */ - public double[] getData() { - return (storedData == null) ? null : storedData.clone(); - } - - /** - * Get a reference to the stored data array. - * @return reference to the stored data array (may be null) - */ - protected double[] getDataRef() { - return storedData; - } - - /** - * Set the data array. The input array is copied, not referenced. - * - * @param values data array to store - * @param begin the index of the first element to include - * @param length the number of elements to include - * @throws MathIllegalArgumentException if values is null or the indices - * are not valid - * @see #evaluate() - */ - public void setData(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - if (values == null) { - throw new NullArgumentException(LocalizedFormats.INPUT_ARRAY); - } - - if (begin < 0) { - throw new NotPositiveException(LocalizedFormats.START_POSITION, begin); - } - - if (length < 0) { - throw new NotPositiveException(LocalizedFormats.LENGTH, length); - } - - if (begin + length > values.length) { - throw new NumberIsTooLargeException(LocalizedFormats.SUBARRAY_ENDS_AFTER_ARRAY_END, - begin + length, values.length, true); - } - storedData = new double[length]; - System.arraycopy(values, begin, storedData, 0, length); - } - - /** - * Returns the result of evaluating the statistic over the stored data. - *

- * The stored array is the one which was set by previous calls to {@link #setData(double[])}. - *

- * @return the value of the statistic applied to the stored data - * @throws MathIllegalArgumentException if the stored data array is null - */ - public double evaluate() throws MathIllegalArgumentException { - return evaluate(storedData); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/AggregateSummaryStatistics.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/AggregateSummaryStatistics.java deleted file mode 100644 index 18a61c8a1..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/AggregateSummaryStatistics.java +++ /dev/null @@ -1,430 +0,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. - */ - -package org.apache.commons.math4.stat.descriptive; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Iterator; - -import org.apache.commons.math4.exception.NullArgumentException; - -/** - *

- * An aggregator for {@code SummaryStatistics} from several data sets or - * data set partitions. In its simplest usage mode, the client creates an - * instance via the zero-argument constructor, then uses - * {@link #createContributingStatistics()} to obtain a {@code SummaryStatistics} - * for each individual data set / partition. The per-set statistics objects - * are used as normal, and at any time the aggregate statistics for all the - * contributors can be obtained from this object. - *

- * Clients with specialized requirements can use alternative constructors to - * control the statistics implementations and initial values used by the - * contributing and the internal aggregate {@code SummaryStatistics} objects. - *

- * A static {@link #aggregate(Collection)} method is also included that computes - * aggregate statistics directly from a Collection of SummaryStatistics instances. - *

- * When {@link #createContributingStatistics()} is used to create SummaryStatistics - * instances to be aggregated concurrently, the created instances' - * {@link SummaryStatistics#addValue(double)} methods must synchronize on the aggregating - * instance maintained by this class. In multithreaded environments, if the functionality - * provided by {@link #aggregate(Collection)} is adequate, that method should be used - * to avoid unnecessary computation and synchronization delays.

- * - * @since 2.0 - * - */ -public class AggregateSummaryStatistics implements StatisticalSummary, - Serializable { - - - /** Serializable version identifier */ - private static final long serialVersionUID = -8207112444016386906L; - - /** - * A SummaryStatistics serving as a prototype for creating SummaryStatistics - * contributing to this aggregate - */ - private final SummaryStatistics statisticsPrototype; - - /** - * The SummaryStatistics in which aggregate statistics are accumulated. - */ - private final SummaryStatistics statistics; - - /** - * Initializes a new AggregateSummaryStatistics with default statistics - * implementations. - * - */ - public AggregateSummaryStatistics() { - // No try-catch or throws NAE because arg is guaranteed non-null - this(new SummaryStatistics()); - } - - /** - * Initializes a new AggregateSummaryStatistics with the specified statistics - * object as a prototype for contributing statistics and for the internal - * aggregate statistics. This provides for customized statistics implementations - * to be used by contributing and aggregate statistics. - * - * @param prototypeStatistics a {@code SummaryStatistics} serving as a - * prototype both for the internal aggregate statistics and for - * contributing statistics obtained via the - * {@code createContributingStatistics()} method. Being a prototype - * means that other objects are initialized by copying this object's state. - * If {@code null}, a new, default statistics object is used. Any statistic - * values in the prototype are propagated to contributing statistics - * objects and (once) into these aggregate statistics. - * @throws NullArgumentException if prototypeStatistics is null - * @see #createContributingStatistics() - */ - public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics) throws NullArgumentException { - this(prototypeStatistics, - prototypeStatistics == null ? null : new SummaryStatistics(prototypeStatistics)); - } - - /** - * Initializes a new AggregateSummaryStatistics with the specified statistics - * object as a prototype for contributing statistics and for the internal - * aggregate statistics. This provides for different statistics implementations - * to be used by contributing and aggregate statistics and for an initial - * state to be supplied for the aggregate statistics. - * - * @param prototypeStatistics a {@code SummaryStatistics} serving as a - * prototype both for the internal aggregate statistics and for - * contributing statistics obtained via the - * {@code createContributingStatistics()} method. Being a prototype - * means that other objects are initialized by copying this object's state. - * If {@code null}, a new, default statistics object is used. Any statistic - * values in the prototype are propagated to contributing statistics - * objects, but not into these aggregate statistics. - * @param initialStatistics a {@code SummaryStatistics} to serve as the - * internal aggregate statistics object. If {@code null}, a new, default - * statistics object is used. - * @see #createContributingStatistics() - */ - public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics, - SummaryStatistics initialStatistics) { - this.statisticsPrototype = - (prototypeStatistics == null) ? new SummaryStatistics() : prototypeStatistics; - this.statistics = - (initialStatistics == null) ? new SummaryStatistics() : initialStatistics; - } - - /** - * {@inheritDoc}. This version returns the maximum over all the aggregated - * data. - * - * @see StatisticalSummary#getMax() - */ - @Override - public double getMax() { - synchronized (statistics) { - return statistics.getMax(); - } - } - - /** - * {@inheritDoc}. This version returns the mean of all the aggregated data. - * - * @see StatisticalSummary#getMean() - */ - @Override - public double getMean() { - synchronized (statistics) { - return statistics.getMean(); - } - } - - /** - * {@inheritDoc}. This version returns the minimum over all the aggregated - * data. - * - * @see StatisticalSummary#getMin() - */ - @Override - public double getMin() { - synchronized (statistics) { - return statistics.getMin(); - } - } - - /** - * {@inheritDoc}. This version returns a count of all the aggregated data. - * - * @see StatisticalSummary#getN() - */ - @Override - public long getN() { - synchronized (statistics) { - return statistics.getN(); - } - } - - /** - * {@inheritDoc}. This version returns the standard deviation of all the - * aggregated data. - * - * @see StatisticalSummary#getStandardDeviation() - */ - @Override - public double getStandardDeviation() { - synchronized (statistics) { - return statistics.getStandardDeviation(); - } - } - - /** - * {@inheritDoc}. This version returns a sum of all the aggregated data. - * - * @see StatisticalSummary#getSum() - */ - @Override - public double getSum() { - synchronized (statistics) { - return statistics.getSum(); - } - } - - /** - * {@inheritDoc}. This version returns the variance of all the aggregated - * data. - * - * @see StatisticalSummary#getVariance() - */ - @Override - public double getVariance() { - synchronized (statistics) { - return statistics.getVariance(); - } - } - - /** - * Returns the sum of the logs of all the aggregated data. - * - * @return the sum of logs - * @see SummaryStatistics#getSumOfLogs() - */ - public double getSumOfLogs() { - synchronized (statistics) { - return statistics.getSumOfLogs(); - } - } - - /** - * Returns the geometric mean of all the aggregated data. - * - * @return the geometric mean - * @see SummaryStatistics#getGeometricMean() - */ - public double getGeometricMean() { - synchronized (statistics) { - return statistics.getGeometricMean(); - } - } - - /** - * Returns the sum of the squares of all the aggregated data. - * - * @return The sum of squares - * @see SummaryStatistics#getSumsq() - */ - public double getSumsq() { - synchronized (statistics) { - return statistics.getSumsq(); - } - } - - /** - * Returns a statistic related to the Second Central Moment. Specifically, - * what is returned is the sum of squared deviations from the sample mean - * among the all of the aggregated data. - * - * @return second central moment statistic - * @see SummaryStatistics#getSecondMoment() - */ - public double getSecondMoment() { - synchronized (statistics) { - return statistics.getSecondMoment(); - } - } - - /** - * Return a {@link StatisticalSummaryValues} instance reporting current - * aggregate statistics. - * - * @return Current values of aggregate statistics - */ - public StatisticalSummary getSummary() { - synchronized (statistics) { - return new StatisticalSummaryValues(getMean(), getVariance(), getN(), - getMax(), getMin(), getSum()); - } - } - - /** - * Creates and returns a {@code SummaryStatistics} whose data will be - * aggregated with those of this {@code AggregateSummaryStatistics}. - * - * @return a {@code SummaryStatistics} whose data will be aggregated with - * those of this {@code AggregateSummaryStatistics}. The initial state - * is a copy of the configured prototype statistics. - */ - public SummaryStatistics createContributingStatistics() { - SummaryStatistics contributingStatistics - = new AggregatingSummaryStatistics(statistics); - - // No try - catch or advertising NAE because neither argument will ever be null - SummaryStatistics.copy(statisticsPrototype, contributingStatistics); - - return contributingStatistics; - } - - /** - * Computes aggregate summary statistics. This method can be used to combine statistics - * computed over partitions or subsamples - i.e., the StatisticalSummaryValues returned - * should contain the same values that would have been obtained by computing a single - * StatisticalSummary over the combined dataset. - *

- * Returns null if the collection is empty or null. - *

- * - * @param statistics collection of SummaryStatistics to aggregate - * @return summary statistics for the combined dataset - */ - // TODO - we need a unit test around this one. - public static StatisticalSummaryValues aggregate(Collection statistics) { - if (statistics == null) { - return null; - } - Iterator iterator = statistics.iterator(); - if (!iterator.hasNext()) { - return null; - } - StatisticalSummary current = iterator.next(); - long n = current.getN(); - double min = current.getMin(); - double sum = current.getSum(); - double max = current.getMax(); - double var = current.getVariance(); - double m2 = var * (n - 1d); - double mean = current.getMean(); - while (iterator.hasNext()) { - current = iterator.next(); - if (current.getMin() < min || Double.isNaN(min)) { - min = current.getMin(); - } - if (current.getMax() > max || Double.isNaN(max)) { - max = current.getMax(); - } - sum += current.getSum(); - final double oldN = n; - final long curN = current.getN(); - n += curN; - final double meanDiff = current.getMean() - mean; - mean = sum / n; - final double curM2 = current.getVariance() * (curN - 1d); - m2 = m2 + curM2 + meanDiff * meanDiff * oldN * curN / n; - } - final double variance; - if (n == 0) { - variance = Double.NaN; - } else if (n == 1) { - variance = 0d; - } else { - variance = m2 / (n - 1); - } - return new StatisticalSummaryValues(mean, variance, n, max, min, sum); - } - - /** - * A SummaryStatistics that also forwards all values added to it to a second - * {@code SummaryStatistics} for aggregation. - * - * @since 2.0 - */ - private static class AggregatingSummaryStatistics extends SummaryStatistics { - - /** - * The serialization version of this class - */ - private static final long serialVersionUID = 1L; - - /** - * An additional SummaryStatistics into which values added to these - * statistics (and possibly others) are aggregated - */ - private final SummaryStatistics aggregateStatistics; - - /** - * Initializes a new AggregatingSummaryStatistics with the specified - * aggregate statistics object - * - * @param aggregateStatistics a {@code SummaryStatistics} into which - * values added to this statistics object should be aggregated - */ - AggregatingSummaryStatistics(SummaryStatistics aggregateStatistics) { - this.aggregateStatistics = aggregateStatistics; - } - - /** - * {@inheritDoc}. This version adds the provided value to the configured - * aggregate after adding it to these statistics. - * - * @see SummaryStatistics#addValue(double) - */ - @Override - public void addValue(double value) { - super.addValue(value); - synchronized (aggregateStatistics) { - aggregateStatistics.addValue(value); - } - } - - /** - * Returns true iff object is a - * SummaryStatistics instance and all statistics have the - * same values as this. - * @param object the object to test equality against. - * @return true if object equals this - */ - @Override - public boolean equals(Object object) { - if (object == this) { - return true; - } - if (object instanceof AggregatingSummaryStatistics == false) { - return false; - } - AggregatingSummaryStatistics stat = (AggregatingSummaryStatistics)object; - return super.equals(stat) && - aggregateStatistics.equals(stat.aggregateStatistics); - } - - /** - * Returns hash code based on values of statistics - * @return hash code - */ - @Override - public int hashCode() { - return 123 + super.hashCode() + aggregateStatistics.hashCode(); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/DescriptiveStatistics.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/DescriptiveStatistics.java deleted file mode 100644 index 2c555c1ab..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/DescriptiveStatistics.java +++ /dev/null @@ -1,802 +0,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. - */ -package org.apache.commons.math4.stat.descriptive; - -import java.io.Serializable; -import java.lang.reflect.InvocationTargetException; -import java.util.Arrays; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.MathIllegalStateException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.stat.descriptive.moment.GeometricMean; -import org.apache.commons.math4.stat.descriptive.moment.Kurtosis; -import org.apache.commons.math4.stat.descriptive.moment.Mean; -import org.apache.commons.math4.stat.descriptive.moment.Skewness; -import org.apache.commons.math4.stat.descriptive.moment.Variance; -import org.apache.commons.math4.stat.descriptive.rank.Max; -import org.apache.commons.math4.stat.descriptive.rank.Min; -import org.apache.commons.math4.stat.descriptive.rank.Percentile; -import org.apache.commons.math4.stat.descriptive.summary.Sum; -import org.apache.commons.math4.stat.descriptive.summary.SumOfSquares; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathUtils; -import org.apache.commons.math4.util.ResizableDoubleArray; - - -/** - * Maintains a dataset of values of a single variable and computes descriptive - * statistics based on stored data. - *

- * The {@link #getWindowSize() windowSize} - * property sets a limit on the number of values that can be stored in the - * dataset. The default value, INFINITE_WINDOW, puts no limit on the size of - * the dataset. This value should be used with caution, as the backing store - * will grow without bound in this case. For very large datasets, - * {@link SummaryStatistics}, which does not store the dataset, should be used - * instead of this class. If windowSize is not INFINITE_WINDOW and - * more values are added than can be stored in the dataset, new values are - * added in a "rolling" manner, with new values replacing the "oldest" values - * in the dataset. - *

- * Note: this class is not threadsafe. Use - * {@link SynchronizedDescriptiveStatistics} if concurrent access from multiple - * threads is required. - */ -public class DescriptiveStatistics implements StatisticalSummary, Serializable { - - /** - * Represents an infinite window size. When the {@link #getWindowSize()} - * returns this value, there is no limit to the number of data values - * that can be stored in the dataset. - */ - public static final int INFINITE_WINDOW = -1; - - /** Serialization UID */ - private static final long serialVersionUID = 4133067267405273064L; - - /** Name of the setQuantile method. */ - private static final String SET_QUANTILE_METHOD_NAME = "setQuantile"; - - /** hold the window size **/ - private int windowSize = INFINITE_WINDOW; - - /** Stored data values. */ - private ResizableDoubleArray eDA = new ResizableDoubleArray(); - - /** Mean statistic implementation - can be reset by setter. */ - private UnivariateStatistic meanImpl = new Mean(); - - /** Geometric mean statistic implementation - can be reset by setter. */ - private UnivariateStatistic geometricMeanImpl = new GeometricMean(); - - /** Kurtosis statistic implementation - can be reset by setter. */ - private UnivariateStatistic kurtosisImpl = new Kurtosis(); - - /** Maximum statistic implementation - can be reset by setter. */ - private UnivariateStatistic maxImpl = new Max(); - - /** Minimum statistic implementation - can be reset by setter. */ - private UnivariateStatistic minImpl = new Min(); - - /** Percentile statistic implementation - can be reset by setter. */ - private UnivariateStatistic percentileImpl = new Percentile(); - - /** Skewness statistic implementation - can be reset by setter. */ - private UnivariateStatistic skewnessImpl = new Skewness(); - - /** Variance statistic implementation - can be reset by setter. */ - private UnivariateStatistic varianceImpl = new Variance(); - - /** Sum of squares statistic implementation - can be reset by setter. */ - private UnivariateStatistic sumsqImpl = new SumOfSquares(); - - /** Sum statistic implementation - can be reset by setter. */ - private UnivariateStatistic sumImpl = new Sum(); - - /** - * Construct a {@code DescriptiveStatistics} instance with an infinite - * window. - */ - public DescriptiveStatistics() { - } - - /** - * Construct a {@code DescriptiveStatistics} instance with the specified - * window. - * - * @param window the window size. - * @throws MathIllegalArgumentException if window size is less than 1 but - * not equal to {@link #INFINITE_WINDOW} - */ - public DescriptiveStatistics(int window) throws MathIllegalArgumentException { - setWindowSize(window); - } - - /** - * Construct a {@code DescriptiveStatistics} instance with an infinite - * window and the initial data values in {@code initialDoubleArray}. - * If {@code initialDoubleArray} is {@code null}, then this constructor - * corresponds to the {@link #DescriptiveStatistics() default constructor}. - * - * @param initialDoubleArray the initial double[]. - */ - public DescriptiveStatistics(double[] initialDoubleArray) { - if (initialDoubleArray != null) { - eDA = new ResizableDoubleArray(initialDoubleArray); - } - } - - /** - * Construct a DescriptiveStatistics instance with an infinite window - * and the initial data values in {@code initialDoubleArray}. - * If {@code initialDoubleArray} is {@code null}, then this constructor - * corresponds to {@link #DescriptiveStatistics() }. - * - * @param initialDoubleArray the initial Double[]. - */ - public DescriptiveStatistics(Double[] initialDoubleArray) { - if (initialDoubleArray != null) { - eDA = new ResizableDoubleArray(initialDoubleArray.length); - for(double initialValue : initialDoubleArray) { - eDA.addElement(initialValue); - } - } - } - - /** - * Copy constructor. Construct a new {@code DescriptiveStatistics} instance - * that is a copy of {@code original}. - * - * @param original DescriptiveStatistics instance to copy - * @throws NullArgumentException if original is null - */ - public DescriptiveStatistics(DescriptiveStatistics original) throws NullArgumentException { - copy(original, this); - } - - /** - * Adds the value to the dataset. If the dataset is at the maximum size - * (i.e., the number of stored elements equals the currently configured - * windowSize), the first (oldest) element in the dataset is discarded - * to make room for the new value. - * - * @param v the value to be added - */ - public void addValue(double v) { - if (windowSize != INFINITE_WINDOW) { - if (getN() == windowSize) { - eDA.addElementRolling(v); - } else if (getN() < windowSize) { - eDA.addElement(v); - } - } else { - eDA.addElement(v); - } - } - - /** - * Removes the most recent value from the dataset. - * - * @throws MathIllegalStateException if there are no elements stored - */ - public void removeMostRecentValue() throws MathIllegalStateException { - try { - eDA.discardMostRecentElements(1); - } catch (MathIllegalArgumentException ex) { - throw new MathIllegalStateException(LocalizedFormats.NO_DATA); - } - } - - /** - * Replaces the most recently stored value with the given value. - * There must be at least one element stored to call this method. - * - * @param v the value to replace the most recent stored value - * @return replaced value - * @throws MathIllegalStateException if there are no elements stored - */ - public double replaceMostRecentValue(double v) throws MathIllegalStateException { - return eDA.substituteMostRecentElement(v); - } - - /** - * Returns the - * arithmetic mean of the available values - * @return The mean or Double.NaN if no values have been added. - */ - @Override - public double getMean() { - return apply(meanImpl); - } - - /** - * Returns the - * geometric mean of the available values. - *

- * See {@link GeometricMean} for details on the computing algorithm.

- * - * @return The geometricMean, Double.NaN if no values have been added, - * or if any negative values have been added. - */ - public double getGeometricMean() { - return apply(geometricMeanImpl); - } - - /** - * Returns the (sample) variance of the available values. - * - *

This method returns the bias-corrected sample variance (using {@code n - 1} in - * the denominator). Use {@link #getPopulationVariance()} for the non-bias-corrected - * population variance.

- * - * @return The variance, Double.NaN if no values have been added - * or 0.0 for a single value set. - */ - @Override - public double getVariance() { - return apply(varianceImpl); - } - - /** - * Returns the - * population variance of the available values. - * - * @return The population variance, Double.NaN if no values have been added, - * or 0.0 for a single value set. - */ - public double getPopulationVariance() { - return apply(new Variance(false)); - } - - /** - * Returns the standard deviation of the available values. - * @return The standard deviation, Double.NaN if no values have been added - * or 0.0 for a single value set. - */ - @Override - public double getStandardDeviation() { - double stdDev = Double.NaN; - if (getN() > 0) { - if (getN() > 1) { - stdDev = FastMath.sqrt(getVariance()); - } else { - stdDev = 0.0; - } - } - return stdDev; - } - - /** - * Returns the quadratic mean, a.k.a. - * - * root-mean-square of the available values - * @return The quadratic mean or {@code Double.NaN} if no values - * have been added. - */ - public double getQuadraticMean() { - final long n = getN(); - return n > 0 ? FastMath.sqrt(getSumsq() / n) : Double.NaN; - } - - /** - * Returns the skewness of the available values. Skewness is a - * measure of the asymmetry of a given distribution. - * - * @return The skewness, Double.NaN if less than 3 values have been added. - */ - public double getSkewness() { - return apply(skewnessImpl); - } - - /** - * Returns the Kurtosis of the available values. Kurtosis is a - * measure of the "peakedness" of a distribution. - * - * @return The kurtosis, Double.NaN if less than 4 values have been added. - */ - public double getKurtosis() { - return apply(kurtosisImpl); - } - - /** - * Returns the maximum of the available values - * @return The max or Double.NaN if no values have been added. - */ - @Override - public double getMax() { - return apply(maxImpl); - } - - /** - * Returns the minimum of the available values - * @return The min or Double.NaN if no values have been added. - */ - @Override - public double getMin() { - return apply(minImpl); - } - - /** - * Returns the number of available values - * @return The number of available values - */ - @Override - public long getN() { - return eDA.getNumElements(); - } - - /** - * Returns the sum of the values that have been added to Univariate. - * @return The sum or Double.NaN if no values have been added - */ - @Override - public double getSum() { - return apply(sumImpl); - } - - /** - * Returns the sum of the squares of the available values. - * @return The sum of the squares or Double.NaN if no - * values have been added. - */ - public double getSumsq() { - return apply(sumsqImpl); - } - - /** - * Resets all statistics and storage - */ - public void clear() { - eDA.clear(); - } - - - /** - * Returns the maximum number of values that can be stored in the - * dataset, or INFINITE_WINDOW (-1) if there is no limit. - * - * @return The current window size or -1 if its Infinite. - */ - public int getWindowSize() { - return windowSize; - } - - /** - * WindowSize controls the number of values that contribute to the - * reported statistics. For example, if windowSize is set to 3 and the - * values {1,2,3,4,5} have been added in that order then - * the available values are {3,4,5} and all reported statistics will - * be based on these values. If {@code windowSize} is decreased as a result - * of this call and there are more than the new value of elements in the - * current dataset, values from the front of the array are discarded to - * reduce the dataset to {@code windowSize} elements. - * - * @param windowSize sets the size of the window. - * @throws MathIllegalArgumentException if window size is less than 1 but - * not equal to {@link #INFINITE_WINDOW} - */ - public void setWindowSize(int windowSize) throws MathIllegalArgumentException { - if (windowSize < 1 && windowSize != INFINITE_WINDOW) { - throw new MathIllegalArgumentException( - LocalizedFormats.NOT_POSITIVE_WINDOW_SIZE, windowSize); - } - - this.windowSize = windowSize; - - // We need to check to see if we need to discard elements - // from the front of the array. If the windowSize is less than - // the current number of elements. - if (windowSize != INFINITE_WINDOW && windowSize < eDA.getNumElements()) { - eDA.discardFrontElements(eDA.getNumElements() - windowSize); - } - } - - /** - * Returns the current set of values in an array of double primitives. - * The order of addition is preserved. The returned array is a fresh - * copy of the underlying data -- i.e., it is not a reference to the - * stored data. - * - * @return returns the current set of numbers in the order in which they - * were added to this set - */ - public double[] getValues() { - return eDA.getElements(); - } - - /** - * Returns the current set of values in an array of double primitives, - * sorted in ascending order. The returned array is a fresh - * copy of the underlying data -- i.e., it is not a reference to the - * stored data. - * @return returns the current set of - * numbers sorted in ascending order - */ - public double[] getSortedValues() { - double[] sort = getValues(); - Arrays.sort(sort); - return sort; - } - - /** - * Returns the element at the specified index - * @param index The Index of the element - * @return return the element at the specified index - */ - public double getElement(int index) { - return eDA.getElement(index); - } - - /** - * Returns an estimate for the pth percentile of the stored values. - *

- * The implementation provided here follows the first estimation procedure presented - * here. - *

- * Preconditions:

    - *
  • 0 < p ≤ 100 (otherwise an - * MathIllegalArgumentException is thrown)
  • - *
  • at least one value must be stored (returns Double.NaN - * otherwise)
  • - *
- * - * @param p the requested percentile (scaled from 0 - 100) - * @return An estimate for the pth percentile of the stored data - * @throws MathIllegalStateException if percentile implementation has been - * overridden and the supplied implementation does not support setQuantile - * @throws MathIllegalArgumentException if p is not a valid quantile - */ - public double getPercentile(double p) throws MathIllegalStateException, MathIllegalArgumentException { - if (percentileImpl instanceof Percentile) { - ((Percentile) percentileImpl).setQuantile(p); - } else { - try { - percentileImpl.getClass().getMethod(SET_QUANTILE_METHOD_NAME, - new Class[] {Double.TYPE}).invoke(percentileImpl, - new Object[] {Double.valueOf(p)}); - } catch (NoSuchMethodException e1) { // Setter guard should prevent - throw new MathIllegalStateException( - LocalizedFormats.PERCENTILE_IMPLEMENTATION_UNSUPPORTED_METHOD, - percentileImpl.getClass().getName(), SET_QUANTILE_METHOD_NAME); - } catch (IllegalAccessException e2) { - throw new MathIllegalStateException( - LocalizedFormats.PERCENTILE_IMPLEMENTATION_CANNOT_ACCESS_METHOD, - SET_QUANTILE_METHOD_NAME, percentileImpl.getClass().getName()); - } catch (InvocationTargetException e3) { - throw new IllegalStateException(e3.getCause()); - } - } - return apply(percentileImpl); - } - - /** - * Generates a text report displaying univariate statistics from values - * that have been added. Each statistic is displayed on a separate - * line. - * - * @return String with line feeds displaying statistics - */ - @Override - public String toString() { - StringBuilder outBuffer = new StringBuilder(); - String endl = "\n"; - outBuffer.append("DescriptiveStatistics:").append(endl); - outBuffer.append("n: ").append(getN()).append(endl); - outBuffer.append("min: ").append(getMin()).append(endl); - outBuffer.append("max: ").append(getMax()).append(endl); - outBuffer.append("mean: ").append(getMean()).append(endl); - outBuffer.append("std dev: ").append(getStandardDeviation()) - .append(endl); - try { - // No catch for MIAE because actual parameter is valid below - outBuffer.append("median: ").append(getPercentile(50)).append(endl); - } catch (MathIllegalStateException ex) { - outBuffer.append("median: unavailable").append(endl); - } - outBuffer.append("skewness: ").append(getSkewness()).append(endl); - outBuffer.append("kurtosis: ").append(getKurtosis()).append(endl); - return outBuffer.toString(); - } - - /** - * Apply the given statistic to the data associated with this set of statistics. - * @param stat the statistic to apply - * @return the computed value of the statistic. - */ - public double apply(UnivariateStatistic stat) { - // No try-catch or advertised exception here because arguments are guaranteed valid - return eDA.compute(stat); - } - - // Implementation getters and setter - - /** - * Returns the currently configured mean implementation. - * - * @return the UnivariateStatistic implementing the mean - * @since 1.2 - */ - public synchronized UnivariateStatistic getMeanImpl() { - return meanImpl; - } - - /** - *

Sets the implementation for the mean.

- * - * @param meanImpl the UnivariateStatistic instance to use - * for computing the mean - * @since 1.2 - */ - public synchronized void setMeanImpl(UnivariateStatistic meanImpl) { - this.meanImpl = meanImpl; - } - - /** - * Returns the currently configured geometric mean implementation. - * - * @return the UnivariateStatistic implementing the geometric mean - * @since 1.2 - */ - public synchronized UnivariateStatistic getGeometricMeanImpl() { - return geometricMeanImpl; - } - - /** - * Sets the implementation for the geometric mean. - * - * @param geometricMeanImpl the UnivariateStatistic instance to use - * for computing the geometric mean - * @since 1.2 - */ - public synchronized void setGeometricMeanImpl( - UnivariateStatistic geometricMeanImpl) { - this.geometricMeanImpl = geometricMeanImpl; - } - - /** - * Returns the currently configured kurtosis implementation. - * - * @return the UnivariateStatistic implementing the kurtosis - * @since 1.2 - */ - public synchronized UnivariateStatistic getKurtosisImpl() { - return kurtosisImpl; - } - - /** - * Sets the implementation for the kurtosis. - * - * @param kurtosisImpl the UnivariateStatistic instance to use - * for computing the kurtosis - * @since 1.2 - */ - public synchronized void setKurtosisImpl(UnivariateStatistic kurtosisImpl) { - this.kurtosisImpl = kurtosisImpl; - } - - /** - * Returns the currently configured maximum implementation. - * - * @return the UnivariateStatistic implementing the maximum - * @since 1.2 - */ - public synchronized UnivariateStatistic getMaxImpl() { - return maxImpl; - } - - /** - * Sets the implementation for the maximum. - * - * @param maxImpl the UnivariateStatistic instance to use - * for computing the maximum - * @since 1.2 - */ - public synchronized void setMaxImpl(UnivariateStatistic maxImpl) { - this.maxImpl = maxImpl; - } - - /** - * Returns the currently configured minimum implementation. - * - * @return the UnivariateStatistic implementing the minimum - * @since 1.2 - */ - public synchronized UnivariateStatistic getMinImpl() { - return minImpl; - } - - /** - * Sets the implementation for the minimum. - * - * @param minImpl the UnivariateStatistic instance to use - * for computing the minimum - * @since 1.2 - */ - public synchronized void setMinImpl(UnivariateStatistic minImpl) { - this.minImpl = minImpl; - } - - /** - * Returns the currently configured percentile implementation. - * - * @return the UnivariateStatistic implementing the percentile - * @since 1.2 - */ - public synchronized UnivariateStatistic getPercentileImpl() { - return percentileImpl; - } - - /** - * Sets the implementation to be used by {@link #getPercentile(double)}. - * The supplied UnivariateStatistic must provide a - * setQuantile(double) method; otherwise - * IllegalArgumentException is thrown. - * - * @param percentileImpl the percentileImpl to set - * @throws MathIllegalArgumentException if the supplied implementation does not - * provide a setQuantile method - * @since 1.2 - */ - public synchronized void setPercentileImpl(UnivariateStatistic percentileImpl) - throws MathIllegalArgumentException { - try { - percentileImpl.getClass().getMethod(SET_QUANTILE_METHOD_NAME, - new Class[] {Double.TYPE}).invoke(percentileImpl, - new Object[] {Double.valueOf(50.0d)}); - } catch (NoSuchMethodException e1) { - throw new MathIllegalArgumentException( - LocalizedFormats.PERCENTILE_IMPLEMENTATION_UNSUPPORTED_METHOD, - percentileImpl.getClass().getName(), SET_QUANTILE_METHOD_NAME); - } catch (IllegalAccessException e2) { - throw new MathIllegalArgumentException( - LocalizedFormats.PERCENTILE_IMPLEMENTATION_CANNOT_ACCESS_METHOD, - SET_QUANTILE_METHOD_NAME, percentileImpl.getClass().getName()); - } catch (InvocationTargetException e3) { - throw new IllegalArgumentException(e3.getCause()); - } - this.percentileImpl = percentileImpl; - } - - /** - * Returns the currently configured skewness implementation. - * - * @return the UnivariateStatistic implementing the skewness - * @since 1.2 - */ - public synchronized UnivariateStatistic getSkewnessImpl() { - return skewnessImpl; - } - - /** - * Sets the implementation for the skewness. - * - * @param skewnessImpl the UnivariateStatistic instance to use - * for computing the skewness - * @since 1.2 - */ - public synchronized void setSkewnessImpl( - UnivariateStatistic skewnessImpl) { - this.skewnessImpl = skewnessImpl; - } - - /** - * Returns the currently configured variance implementation. - * - * @return the UnivariateStatistic implementing the variance - * @since 1.2 - */ - public synchronized UnivariateStatistic getVarianceImpl() { - return varianceImpl; - } - - /** - * Sets the implementation for the variance. - * - * @param varianceImpl the UnivariateStatistic instance to use - * for computing the variance - * @since 1.2 - */ - public synchronized void setVarianceImpl( - UnivariateStatistic varianceImpl) { - this.varianceImpl = varianceImpl; - } - - /** - * Returns the currently configured sum of squares implementation. - * - * @return the UnivariateStatistic implementing the sum of squares - * @since 1.2 - */ - public synchronized UnivariateStatistic getSumsqImpl() { - return sumsqImpl; - } - - /** - * Sets the implementation for the sum of squares. - * - * @param sumsqImpl the UnivariateStatistic instance to use - * for computing the sum of squares - * @since 1.2 - */ - public synchronized void setSumsqImpl(UnivariateStatistic sumsqImpl) { - this.sumsqImpl = sumsqImpl; - } - - /** - * Returns the currently configured sum implementation. - * - * @return the UnivariateStatistic implementing the sum - * @since 1.2 - */ - public synchronized UnivariateStatistic getSumImpl() { - return sumImpl; - } - - /** - * Sets the implementation for the sum. - * - * @param sumImpl the UnivariateStatistic instance to use - * for computing the sum - * @since 1.2 - */ - public synchronized void setSumImpl(UnivariateStatistic sumImpl) { - this.sumImpl = sumImpl; - } - - /** - * Returns a copy of this DescriptiveStatistics instance with the same internal state. - * - * @return a copy of this - */ - public DescriptiveStatistics copy() { - DescriptiveStatistics result = new DescriptiveStatistics(); - // No try-catch or advertised exception because parms are guaranteed valid - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source DescriptiveStatistics to copy - * @param dest DescriptiveStatistics to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(DescriptiveStatistics source, DescriptiveStatistics dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - // Copy data and window size - dest.eDA = source.eDA.copy(); - dest.windowSize = source.windowSize; - - // Copy implementations - dest.maxImpl = source.maxImpl.copy(); - dest.meanImpl = source.meanImpl.copy(); - dest.minImpl = source.minImpl.copy(); - dest.sumImpl = source.sumImpl.copy(); - dest.varianceImpl = source.varianceImpl.copy(); - dest.sumsqImpl = source.sumsqImpl.copy(); - dest.geometricMeanImpl = source.geometricMeanImpl.copy(); - dest.kurtosisImpl = source.kurtosisImpl; - dest.skewnessImpl = source.skewnessImpl; - dest.percentileImpl = source.percentileImpl; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/MultivariateSummaryStatistics.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/MultivariateSummaryStatistics.java deleted file mode 100644 index 5248b5c01..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/MultivariateSummaryStatistics.java +++ /dev/null @@ -1,646 +0,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. - */ -package org.apache.commons.math4.stat.descriptive; - -import java.io.Serializable; -import java.util.Arrays; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathIllegalStateException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.linear.RealMatrix; -import org.apache.commons.math4.stat.descriptive.moment.GeometricMean; -import org.apache.commons.math4.stat.descriptive.moment.Mean; -import org.apache.commons.math4.stat.descriptive.moment.VectorialCovariance; -import org.apache.commons.math4.stat.descriptive.rank.Max; -import org.apache.commons.math4.stat.descriptive.rank.Min; -import org.apache.commons.math4.stat.descriptive.summary.Sum; -import org.apache.commons.math4.stat.descriptive.summary.SumOfLogs; -import org.apache.commons.math4.stat.descriptive.summary.SumOfSquares; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; -import org.apache.commons.numbers.core.Precision; - -/** - *

Computes summary statistics for a stream of n-tuples added using the - * {@link #addValue(double[]) addValue} method. The data values are not stored - * in memory, so this class can be used to compute statistics for very large - * n-tuple streams.

- * - *

The {@link StorelessUnivariateStatistic} instances used to maintain - * summary state and compute statistics are configurable via setters. - * For example, the default implementation for the mean can be overridden by - * calling {@link #setMeanImpl(StorelessUnivariateStatistic[])}. Actual - * parameters to these methods must implement the - * {@link StorelessUnivariateStatistic} interface and configuration must be - * completed before addValue is called. No configuration is - * necessary to use the default, commons-math provided implementations.

- * - *

To compute statistics for a stream of n-tuples, construct a - * MultivariateStatistics instance with dimension n and then use - * {@link #addValue(double[])} to add n-tuples. The getXxx - * methods where Xxx is a statistic return an array of double - * values, where for i = 0,...,n-1 the ith array element is the - * value of the given statistic for data range consisting of the ith element of - * each of the input n-tuples. For example, if addValue is called - * with actual parameters {0, 1, 2}, then {3, 4, 5} and finally {6, 7, 8}, - * getSum will return a three-element array with values - * {0+3+6, 1+4+7, 2+5+8}

- * - *

Note: This class is not thread-safe. Use - * {@link SynchronizedMultivariateSummaryStatistics} if concurrent access from multiple - * threads is required.

- * - * @since 1.2 - */ -public class MultivariateSummaryStatistics - implements StatisticalMultivariateSummary, Serializable { - - /** Serialization UID */ - private static final long serialVersionUID = 2271900808994826718L; - - /** Dimension of the data. */ - private final int k; - - /** Count of values that have been added */ - private long n = 0; - - /** Sum statistic implementation - can be reset by setter. */ - private final StorelessUnivariateStatistic[] sumImpl; - - /** Sum of squares statistic implementation - can be reset by setter. */ - private final StorelessUnivariateStatistic[] sumSqImpl; - - /** Minimum statistic implementation - can be reset by setter. */ - private final StorelessUnivariateStatistic[] minImpl; - - /** Maximum statistic implementation - can be reset by setter. */ - private final StorelessUnivariateStatistic[] maxImpl; - - /** Sum of log statistic implementation - can be reset by setter. */ - private final StorelessUnivariateStatistic[] sumLogImpl; - - /** Geometric mean statistic implementation - can be reset by setter. */ - private final StorelessUnivariateStatistic[] geoMeanImpl; - - /** Mean statistic implementation - can be reset by setter. */ - private final StorelessUnivariateStatistic[] meanImpl; - - /** Covariance statistic implementation - cannot be reset. */ - private final VectorialCovariance covarianceImpl; - - /** - * Construct a MultivariateSummaryStatistics instance - * @param k dimension of the data - * @param isCovarianceBiasCorrected if true, the unbiased sample - * covariance is computed, otherwise the biased population covariance - * is computed - */ - public MultivariateSummaryStatistics(int k, boolean isCovarianceBiasCorrected) { - this.k = k; - - sumImpl = new StorelessUnivariateStatistic[k]; - sumSqImpl = new StorelessUnivariateStatistic[k]; - minImpl = new StorelessUnivariateStatistic[k]; - maxImpl = new StorelessUnivariateStatistic[k]; - sumLogImpl = new StorelessUnivariateStatistic[k]; - geoMeanImpl = new StorelessUnivariateStatistic[k]; - meanImpl = new StorelessUnivariateStatistic[k]; - - for (int i = 0; i < k; ++i) { - sumImpl[i] = new Sum(); - sumSqImpl[i] = new SumOfSquares(); - minImpl[i] = new Min(); - maxImpl[i] = new Max(); - sumLogImpl[i] = new SumOfLogs(); - geoMeanImpl[i] = new GeometricMean(); - meanImpl[i] = new Mean(); - } - - covarianceImpl = - new VectorialCovariance(k, isCovarianceBiasCorrected); - - } - - /** - * Add an n-tuple to the data - * - * @param value the n-tuple to add - * @throws DimensionMismatchException if the length of the array - * does not match the one used at construction - */ - public void addValue(double[] value) throws DimensionMismatchException { - checkDimension(value.length); - for (int i = 0; i < k; ++i) { - double v = value[i]; - sumImpl[i].increment(v); - sumSqImpl[i].increment(v); - minImpl[i].increment(v); - maxImpl[i].increment(v); - sumLogImpl[i].increment(v); - geoMeanImpl[i].increment(v); - meanImpl[i].increment(v); - } - covarianceImpl.increment(value); - n++; - } - - /** - * Returns the dimension of the data - * @return The dimension of the data - */ - @Override - public int getDimension() { - return k; - } - - /** - * Returns the number of available values - * @return The number of available values - */ - @Override - public long getN() { - return n; - } - - /** - * Returns an array of the results of a statistic. - * @param stats univariate statistic array - * @return results array - */ - private double[] getResults(StorelessUnivariateStatistic[] stats) { - double[] results = new double[stats.length]; - for (int i = 0; i < results.length; ++i) { - results[i] = stats[i].getResult(); - } - return results; - } - - /** - * Returns an array whose ith entry is the sum of the - * ith entries of the arrays that have been added using - * {@link #addValue(double[])} - * - * @return the array of component sums - */ - @Override - public double[] getSum() { - return getResults(sumImpl); - } - - /** - * Returns an array whose ith entry is the sum of squares of the - * ith entries of the arrays that have been added using - * {@link #addValue(double[])} - * - * @return the array of component sums of squares - */ - @Override - public double[] getSumSq() { - return getResults(sumSqImpl); - } - - /** - * Returns an array whose ith entry is the sum of logs of the - * ith entries of the arrays that have been added using - * {@link #addValue(double[])} - * - * @return the array of component log sums - */ - @Override - public double[] getSumLog() { - return getResults(sumLogImpl); - } - - /** - * Returns an array whose ith entry is the mean of the - * ith entries of the arrays that have been added using - * {@link #addValue(double[])} - * - * @return the array of component means - */ - @Override - public double[] getMean() { - return getResults(meanImpl); - } - - /** - * Returns an array whose ith entry is the standard deviation of the - * ith entries of the arrays that have been added using - * {@link #addValue(double[])} - * - * @return the array of component standard deviations - */ - @Override - public double[] getStandardDeviation() { - double[] stdDev = new double[k]; - if (getN() < 1) { - Arrays.fill(stdDev, Double.NaN); - } else if (getN() < 2) { - Arrays.fill(stdDev, 0.0); - } else { - RealMatrix matrix = covarianceImpl.getResult(); - for (int i = 0; i < k; ++i) { - stdDev[i] = FastMath.sqrt(matrix.getEntry(i, i)); - } - } - return stdDev; - } - - /** - * Returns the covariance matrix of the values that have been added. - * - * @return the covariance matrix - */ - @Override - public RealMatrix getCovariance() { - return covarianceImpl.getResult(); - } - - /** - * Returns an array whose ith entry is the maximum of the - * ith entries of the arrays that have been added using - * {@link #addValue(double[])} - * - * @return the array of component maxima - */ - @Override - public double[] getMax() { - return getResults(maxImpl); - } - - /** - * Returns an array whose ith entry is the minimum of the - * ith entries of the arrays that have been added using - * {@link #addValue(double[])} - * - * @return the array of component minima - */ - @Override - public double[] getMin() { - return getResults(minImpl); - } - - /** - * Returns an array whose ith entry is the geometric mean of the - * ith entries of the arrays that have been added using - * {@link #addValue(double[])} - * - * @return the array of component geometric means - */ - @Override - public double[] getGeometricMean() { - return getResults(geoMeanImpl); - } - - /** - * Generates a text report displaying - * summary statistics from values that - * have been added. - * @return String with line feeds displaying statistics - */ - @Override - public String toString() { - final String separator = ", "; - final String suffix = System.getProperty("line.separator"); - StringBuilder outBuffer = new StringBuilder(); - outBuffer.append("MultivariateSummaryStatistics:").append(suffix); - outBuffer.append("n: ").append(getN()).append(suffix); - append(outBuffer, getMin(), "min: ", separator, suffix); - append(outBuffer, getMax(), "max: ", separator, suffix); - append(outBuffer, getMean(), "mean: ", separator, suffix); - append(outBuffer, getGeometricMean(), "geometric mean: ", separator, suffix); - append(outBuffer, getSumSq(), "sum of squares: ", separator, suffix); - append(outBuffer, getSumLog(), "sum of logarithms: ", separator, suffix); - append(outBuffer, getStandardDeviation(), "standard deviation: ", separator, suffix); - outBuffer.append("covariance: ").append(getCovariance()).append(suffix); - return outBuffer.toString(); - } - - /** - * Append a text representation of an array to a buffer. - * @param buffer buffer to fill - * @param data data array - * @param prefix text prefix - * @param separator elements separator - * @param suffix text suffix - */ - private void append(StringBuilder buffer, double[] data, - String prefix, String separator, String suffix) { - buffer.append(prefix); - for (int i = 0; i < data.length; ++i) { - if (i > 0) { - buffer.append(separator); - } - buffer.append(data[i]); - } - buffer.append(suffix); - } - - /** - * Resets all statistics and storage - */ - public void clear() { - this.n = 0; - for (int i = 0; i < k; ++i) { - minImpl[i].clear(); - maxImpl[i].clear(); - sumImpl[i].clear(); - sumLogImpl[i].clear(); - sumSqImpl[i].clear(); - geoMeanImpl[i].clear(); - meanImpl[i].clear(); - } - covarianceImpl.clear(); - } - - /** - * Returns true iff object is a MultivariateSummaryStatistics - * instance and all statistics have the same values as this. - * @param object the object to test equality against. - * @return true if object equals this - */ - @Override - public boolean equals(Object object) { - if (object == this ) { - return true; - } - if (object instanceof MultivariateSummaryStatistics == false) { - return false; - } - MultivariateSummaryStatistics stat = (MultivariateSummaryStatistics) object; - return MathArrays.equalsIncludingNaN(stat.getGeometricMean(), getGeometricMean()) && - MathArrays.equalsIncludingNaN(stat.getMax(), getMax()) && - MathArrays.equalsIncludingNaN(stat.getMean(), getMean()) && - MathArrays.equalsIncludingNaN(stat.getMin(), getMin()) && - Precision.equalsIncludingNaN(stat.getN(), getN()) && - MathArrays.equalsIncludingNaN(stat.getSum(), getSum()) && - MathArrays.equalsIncludingNaN(stat.getSumSq(), getSumSq()) && - MathArrays.equalsIncludingNaN(stat.getSumLog(), getSumLog()) && - stat.getCovariance().equals( getCovariance()); - } - - /** - * Returns hash code based on values of statistics - * - * @return hash code - */ - @Override - public int hashCode() { - int result = 31 + MathUtils.hash(getGeometricMean()); - result = result * 31 + MathUtils.hash(getGeometricMean()); - result = result * 31 + MathUtils.hash(getMax()); - result = result * 31 + MathUtils.hash(getMean()); - result = result * 31 + MathUtils.hash(getMin()); - result = result * 31 + MathUtils.hash(getN()); - result = result * 31 + MathUtils.hash(getSum()); - result = result * 31 + MathUtils.hash(getSumSq()); - result = result * 31 + MathUtils.hash(getSumLog()); - result = result * 31 + getCovariance().hashCode(); - return result; - } - - // Getters and setters for statistics implementations - /** - * Sets statistics implementations. - * @param newImpl new implementations for statistics - * @param oldImpl old implementations for statistics - * @throws DimensionMismatchException if the array dimension - * does not match the one used at construction - * @throws MathIllegalStateException if data has already been added - * (i.e. if n > 0) - */ - private void setImpl(StorelessUnivariateStatistic[] newImpl, - StorelessUnivariateStatistic[] oldImpl) throws MathIllegalStateException, - DimensionMismatchException { - checkEmpty(); - checkDimension(newImpl.length); - System.arraycopy(newImpl, 0, oldImpl, 0, newImpl.length); - } - - /** - * Returns the currently configured Sum implementation - * - * @return the StorelessUnivariateStatistic implementing the sum - */ - public StorelessUnivariateStatistic[] getSumImpl() { - return sumImpl.clone(); - } - - /** - *

Sets the implementation for the Sum.

- *

This method must be activated before any data has been added - i.e., - * before {@link #addValue(double[]) addValue} has been used to add data; - * otherwise an IllegalStateException will be thrown.

- * - * @param sumImpl the StorelessUnivariateStatistic instance to use - * for computing the Sum - * @throws DimensionMismatchException if the array dimension - * does not match the one used at construction - * @throws MathIllegalStateException if data has already been added - * (i.e if n > 0) - */ - public void setSumImpl(StorelessUnivariateStatistic[] sumImpl) - throws MathIllegalStateException, DimensionMismatchException { - setImpl(sumImpl, this.sumImpl); - } - - /** - * Returns the currently configured sum of squares implementation - * - * @return the StorelessUnivariateStatistic implementing the sum of squares - */ - public StorelessUnivariateStatistic[] getSumsqImpl() { - return sumSqImpl.clone(); - } - - /** - *

Sets the implementation for the sum of squares.

- *

This method must be activated before any data has been added - i.e., - * before {@link #addValue(double[]) addValue} has been used to add data; - * otherwise an IllegalStateException will be thrown.

- * - * @param sumsqImpl the StorelessUnivariateStatistic instance to use - * for computing the sum of squares - * @throws DimensionMismatchException if the array dimension - * does not match the one used at construction - * @throws MathIllegalStateException if data has already been added - * (i.e if n > 0) - */ - public void setSumsqImpl(StorelessUnivariateStatistic[] sumsqImpl) - throws MathIllegalStateException, DimensionMismatchException { - setImpl(sumsqImpl, this.sumSqImpl); - } - - /** - * Returns the currently configured minimum implementation - * - * @return the StorelessUnivariateStatistic implementing the minimum - */ - public StorelessUnivariateStatistic[] getMinImpl() { - return minImpl.clone(); - } - - /** - *

Sets the implementation for the minimum.

- *

This method must be activated before any data has been added - i.e., - * before {@link #addValue(double[]) addValue} has been used to add data; - * otherwise an IllegalStateException will be thrown.

- * - * @param minImpl the StorelessUnivariateStatistic instance to use - * for computing the minimum - * @throws DimensionMismatchException if the array dimension - * does not match the one used at construction - * @throws MathIllegalStateException if data has already been added - * (i.e if n > 0) - */ - public void setMinImpl(StorelessUnivariateStatistic[] minImpl) - throws MathIllegalStateException, DimensionMismatchException { - setImpl(minImpl, this.minImpl); - } - - /** - * Returns the currently configured maximum implementation - * - * @return the StorelessUnivariateStatistic implementing the maximum - */ - public StorelessUnivariateStatistic[] getMaxImpl() { - return maxImpl.clone(); - } - - /** - *

Sets the implementation for the maximum.

- *

This method must be activated before any data has been added - i.e., - * before {@link #addValue(double[]) addValue} has been used to add data; - * otherwise an IllegalStateException will be thrown.

- * - * @param maxImpl the StorelessUnivariateStatistic instance to use - * for computing the maximum - * @throws DimensionMismatchException if the array dimension - * does not match the one used at construction - * @throws MathIllegalStateException if data has already been added - * (i.e if n > 0) - */ - public void setMaxImpl(StorelessUnivariateStatistic[] maxImpl) - throws MathIllegalStateException, DimensionMismatchException{ - setImpl(maxImpl, this.maxImpl); - } - - /** - * Returns the currently configured sum of logs implementation - * - * @return the StorelessUnivariateStatistic implementing the log sum - */ - public StorelessUnivariateStatistic[] getSumLogImpl() { - return sumLogImpl.clone(); - } - - /** - *

Sets the implementation for the sum of logs.

- *

This method must be activated before any data has been added - i.e., - * before {@link #addValue(double[]) addValue} has been used to add data; - * otherwise an IllegalStateException will be thrown.

- * - * @param sumLogImpl the StorelessUnivariateStatistic instance to use - * for computing the log sum - * @throws DimensionMismatchException if the array dimension - * does not match the one used at construction - * @throws MathIllegalStateException if data has already been added - * (i.e if n > 0) - */ - public void setSumLogImpl(StorelessUnivariateStatistic[] sumLogImpl) - throws MathIllegalStateException, DimensionMismatchException{ - setImpl(sumLogImpl, this.sumLogImpl); - } - - /** - * Returns the currently configured geometric mean implementation - * - * @return the StorelessUnivariateStatistic implementing the geometric mean - */ - public StorelessUnivariateStatistic[] getGeoMeanImpl() { - return geoMeanImpl.clone(); - } - - /** - *

Sets the implementation for the geometric mean.

- *

This method must be activated before any data has been added - i.e., - * before {@link #addValue(double[]) addValue} has been used to add data; - * otherwise an IllegalStateException will be thrown.

- * - * @param geoMeanImpl the StorelessUnivariateStatistic instance to use - * for computing the geometric mean - * @throws DimensionMismatchException if the array dimension - * does not match the one used at construction - * @throws MathIllegalStateException if data has already been added - * (i.e if n > 0) - */ - public void setGeoMeanImpl(StorelessUnivariateStatistic[] geoMeanImpl) - throws MathIllegalStateException, DimensionMismatchException { - setImpl(geoMeanImpl, this.geoMeanImpl); - } - - /** - * Returns the currently configured mean implementation - * - * @return the StorelessUnivariateStatistic implementing the mean - */ - public StorelessUnivariateStatistic[] getMeanImpl() { - return meanImpl.clone(); - } - - /** - *

Sets the implementation for the mean.

- *

This method must be activated before any data has been added - i.e., - * before {@link #addValue(double[]) addValue} has been used to add data; - * otherwise an IllegalStateException will be thrown.

- * - * @param meanImpl the StorelessUnivariateStatistic instance to use - * for computing the mean - * @throws DimensionMismatchException if the array dimension - * does not match the one used at construction - * @throws MathIllegalStateException if data has already been added - * (i.e if n > 0) - */ - public void setMeanImpl(StorelessUnivariateStatistic[] meanImpl) - throws MathIllegalStateException, DimensionMismatchException{ - setImpl(meanImpl, this.meanImpl); - } - - /** - * Throws MathIllegalStateException if the statistic is not empty. - * @throws MathIllegalStateException if n > 0. - */ - private void checkEmpty() throws MathIllegalStateException { - if (n > 0) { - throw new MathIllegalStateException( - LocalizedFormats.VALUES_ADDED_BEFORE_CONFIGURING_STATISTIC, n); - } - } - - /** - * Throws DimensionMismatchException if dimension != k. - * @param dimension dimension to check - * @throws DimensionMismatchException if dimension != k - */ - private void checkDimension(int dimension) throws DimensionMismatchException { - if (dimension != k) { - throw new DimensionMismatchException(dimension, k); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/StatisticalMultivariateSummary.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/StatisticalMultivariateSummary.java deleted file mode 100644 index 64fa55f9e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/StatisticalMultivariateSummary.java +++ /dev/null @@ -1,119 +0,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. - */ -package org.apache.commons.math4.stat.descriptive; - -import org.apache.commons.math4.linear.RealMatrix; - -/** - * Reporting interface for basic multivariate statistics. - * - * @since 1.2 - */ -public interface StatisticalMultivariateSummary { - - /** - * Returns the dimension of the data - * @return The dimension of the data - */ - int getDimension(); - - /** - * Returns an array whose ith entry is the - * mean of the ith entries of the arrays - * that correspond to each multivariate sample - * - * @return the array of component means - */ - double[] getMean(); - - /** - * Returns the covariance of the available values. - * @return The covariance, null if no multivariate sample - * have been added or a zeroed matrix for a single value set. - */ - RealMatrix getCovariance(); - - /** - * Returns an array whose ith entry is the - * standard deviation of the ith entries of the arrays - * that correspond to each multivariate sample - * - * @return the array of component standard deviations - */ - double[] getStandardDeviation(); - - /** - * Returns an array whose ith entry is the - * maximum of the ith entries of the arrays - * that correspond to each multivariate sample - * - * @return the array of component maxima - */ - double[] getMax(); - - /** - * Returns an array whose ith entry is the - * minimum of the ith entries of the arrays - * that correspond to each multivariate sample - * - * @return the array of component minima - */ - double[] getMin(); - - /** - * Returns the number of available values - * @return The number of available values - */ - long getN(); - - /** - * Returns an array whose ith entry is the - * geometric mean of the ith entries of the arrays - * that correspond to each multivariate sample - * - * @return the array of component geometric means - */ - double[] getGeometricMean(); - - /** - * Returns an array whose ith entry is the - * sum of the ith entries of the arrays - * that correspond to each multivariate sample - * - * @return the array of component sums - */ - double[] getSum(); - - /** - * Returns an array whose ith entry is the - * sum of squares of the ith entries of the arrays - * that correspond to each multivariate sample - * - * @return the array of component sums of squares - */ - double[] getSumSq(); - - /** - * Returns an array whose ith entry is the - * sum of logs of the ith entries of the arrays - * that correspond to each multivariate sample - * - * @return the array of component log sums - */ - double[] getSumLog(); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/StatisticalSummary.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/StatisticalSummary.java deleted file mode 100644 index e4b71ab3e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/StatisticalSummary.java +++ /dev/null @@ -1,64 +0,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. - */ -package org.apache.commons.math4.stat.descriptive; - -/** - * Reporting interface for basic univariate statistics. - * - */ -public interface StatisticalSummary { - - /** - * Returns the - * arithmetic mean of the available values - * @return The mean or Double.NaN if no values have been added. - */ - double getMean(); - /** - * Returns the variance of the available values. - * @return The variance, Double.NaN if no values have been added - * or 0.0 for a single value set. - */ - double getVariance(); - /** - * Returns the standard deviation of the available values. - * @return The standard deviation, Double.NaN if no values have been added - * or 0.0 for a single value set. - */ - double getStandardDeviation(); - /** - * Returns the maximum of the available values - * @return The max or Double.NaN if no values have been added. - */ - double getMax(); - /** - * Returns the minimum of the available values - * @return The min or Double.NaN if no values have been added. - */ - double getMin(); - /** - * Returns the number of available values - * @return The number of available values - */ - long getN(); - /** - * Returns the sum of the values that have been added to Univariate. - * @return The sum or Double.NaN if no values have been added - */ - double getSum(); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/StatisticalSummaryValues.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/StatisticalSummaryValues.java deleted file mode 100644 index d1aa197ee..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/StatisticalSummaryValues.java +++ /dev/null @@ -1,193 +0,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. - */ -package org.apache.commons.math4.stat.descriptive; - -import java.io.Serializable; - -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathUtils; -import org.apache.commons.numbers.core.Precision; - -/** - * Value object representing the results of a univariate statistical summary. - * - */ -public class StatisticalSummaryValues implements Serializable, - StatisticalSummary { - - /** Serialization id */ - private static final long serialVersionUID = -5108854841843722536L; - - /** The sample mean */ - private final double mean; - - /** The sample variance */ - private final double variance; - - /** The number of observations in the sample */ - private final long n; - - /** The maximum value */ - private final double max; - - /** The minimum value */ - private final double min; - - /** The sum of the sample values */ - private final double sum; - - /** - * Constructor - * - * @param mean the sample mean - * @param variance the sample variance - * @param n the number of observations in the sample - * @param max the maximum value - * @param min the minimum value - * @param sum the sum of the values - */ - public StatisticalSummaryValues(double mean, double variance, long n, - double max, double min, double sum) { - super(); - this.mean = mean; - this.variance = variance; - this.n = n; - this.max = max; - this.min = min; - this.sum = sum; - } - - /** - * @return Returns the max. - */ - @Override - public double getMax() { - return max; - } - - /** - * @return Returns the mean. - */ - @Override - public double getMean() { - return mean; - } - - /** - * @return Returns the min. - */ - @Override - public double getMin() { - return min; - } - - /** - * @return Returns the number of values. - */ - @Override - public long getN() { - return n; - } - - /** - * @return Returns the sum. - */ - @Override - public double getSum() { - return sum; - } - - /** - * @return Returns the standard deviation - */ - @Override - public double getStandardDeviation() { - return FastMath.sqrt(variance); - } - - /** - * @return Returns the variance. - */ - @Override - public double getVariance() { - return variance; - } - - /** - * Returns true iff object is a - * StatisticalSummaryValues instance and all statistics have - * the same values as this. - * - * @param object the object to test equality against. - * @return true if object equals this - */ - @Override - public boolean equals(Object object) { - if (object == this ) { - return true; - } - if (object instanceof StatisticalSummaryValues == false) { - return false; - } - StatisticalSummaryValues stat = (StatisticalSummaryValues) object; - return Precision.equalsIncludingNaN(stat.getMax(), getMax()) && - Precision.equalsIncludingNaN(stat.getMean(), getMean()) && - Precision.equalsIncludingNaN(stat.getMin(), getMin()) && - Precision.equalsIncludingNaN(stat.getN(), getN()) && - Precision.equalsIncludingNaN(stat.getSum(), getSum()) && - Precision.equalsIncludingNaN(stat.getVariance(), getVariance()); - } - - /** - * Returns hash code based on values of statistics - * - * @return hash code - */ - @Override - public int hashCode() { - int result = 31 + MathUtils.hash(getMax()); - result = result * 31 + MathUtils.hash(getMean()); - result = result * 31 + MathUtils.hash(getMin()); - result = result * 31 + MathUtils.hash(getN()); - result = result * 31 + MathUtils.hash(getSum()); - result = result * 31 + MathUtils.hash(getVariance()); - return result; - } - - /** - * Generates a text report displaying values of statistics. - * Each statistic is displayed on a separate line. - * - * @return String with line feeds displaying statistics - */ - @Override - public String toString() { - StringBuffer outBuffer = new StringBuffer(); - String endl = "\n"; - outBuffer.append("StatisticalSummaryValues:").append(endl); - outBuffer.append("n: ").append(getN()).append(endl); - outBuffer.append("min: ").append(getMin()).append(endl); - outBuffer.append("max: ").append(getMax()).append(endl); - outBuffer.append("mean: ").append(getMean()).append(endl); - outBuffer.append("std dev: ").append(getStandardDeviation()) - .append(endl); - outBuffer.append("variance: ").append(getVariance()).append(endl); - outBuffer.append("sum: ").append(getSum()).append(endl); - return outBuffer.toString(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/StorelessUnivariateStatistic.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/StorelessUnivariateStatistic.java deleted file mode 100644 index e3db965f9..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/StorelessUnivariateStatistic.java +++ /dev/null @@ -1,91 +0,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. - */ -package org.apache.commons.math4.stat.descriptive; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; - -/** - * Extends the definition of {@link UnivariateStatistic} with - * {@link #increment} and {@link #incrementAll(double[])} methods for adding - * values and updating internal state. - *

- * This interface is designed to be used for calculating statistics that can be - * computed in one pass through the data without storing the full array of - * sample values. - *

- * Note: unless otherwise stated, the {@link #evaluate(double[])} and - * {@link #evaluate(double[], int, int)} methods do NOT alter the internal - * state of the respective statistic. - */ -public interface StorelessUnivariateStatistic extends UnivariateStatistic { - - /** - * Updates the internal state of the statistic to reflect the addition of the new value. - * @param d the new value. - */ - void increment(double d); - - /** - * Updates the internal state of the statistic to reflect addition of - * all values in the values array. Does not clear the statistic first -- - * i.e., the values are added incrementally to the dataset. - * - * @param values array holding the new values to add - * @throws MathIllegalArgumentException if the array is null - */ - void incrementAll(double[] values) throws MathIllegalArgumentException; - - /** - * Updates the internal state of the statistic to reflect addition of - * the values in the designated portion of the values array. Does not - * clear the statistic first -- i.e., the values are added - * incrementally to the dataset. - * - * @param values array holding the new values to add - * @param start the array index of the first value to add - * @param length the number of elements to add - * @throws MathIllegalArgumentException if the array is null or the index - */ - void incrementAll(double[] values, int start, int length) throws MathIllegalArgumentException; - - /** - * Returns the current value of the Statistic. - * @return value of the statistic, Double.NaN if it - * has been cleared or just instantiated. - */ - double getResult(); - - /** - * Returns the number of values that have been added. - * @return the number of values. - */ - long getN(); - - /** - * Clears the internal state of the Statistic - */ - void clear(); - - /** - * Returns a copy of the statistic with the same internal state. - * - * @return a copy of the statistic - */ - @Override - StorelessUnivariateStatistic copy(); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/SummaryStatistics.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/SummaryStatistics.java deleted file mode 100644 index 9ab88c174..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/SummaryStatistics.java +++ /dev/null @@ -1,772 +0,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. - */ -package org.apache.commons.math4.stat.descriptive; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalStateException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.stat.descriptive.moment.GeometricMean; -import org.apache.commons.math4.stat.descriptive.moment.Mean; -import org.apache.commons.math4.stat.descriptive.moment.SecondMoment; -import org.apache.commons.math4.stat.descriptive.moment.Variance; -import org.apache.commons.math4.stat.descriptive.rank.Max; -import org.apache.commons.math4.stat.descriptive.rank.Min; -import org.apache.commons.math4.stat.descriptive.summary.Sum; -import org.apache.commons.math4.stat.descriptive.summary.SumOfLogs; -import org.apache.commons.math4.stat.descriptive.summary.SumOfSquares; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathUtils; -import org.apache.commons.numbers.core.Precision; - -/** - *

- * Computes summary statistics for a stream of data values added using the - * {@link #addValue(double) addValue} method. The data values are not stored in - * memory, so this class can be used to compute statistics for very large data - * streams. - *

- *

- * The {@link StorelessUnivariateStatistic} instances used to maintain summary - * state and compute statistics are configurable via setters. For example, the - * default implementation for the variance can be overridden by calling - * {@link #setVarianceImpl(StorelessUnivariateStatistic)}. Actual parameters to - * these methods must implement the {@link StorelessUnivariateStatistic} - * interface and configuration must be completed before addValue - * is called. No configuration is necessary to use the default, commons-math - * provided implementations. - *

- *

- * Note: This class is not thread-safe. Use - * {@link SynchronizedSummaryStatistics} if concurrent access from multiple - * threads is required. - *

- */ -public class SummaryStatistics implements StatisticalSummary, Serializable { - - /** Serialization UID */ - private static final long serialVersionUID = -2021321786743555871L; - - /** count of values that have been added */ - private long n = 0; - - /** SecondMoment is used to compute the mean and variance */ - private SecondMoment secondMoment = new SecondMoment(); - - /** sum of values that have been added */ - private Sum sum = new Sum(); - - /** sum of the square of each value that has been added */ - private SumOfSquares sumsq = new SumOfSquares(); - - /** min of values that have been added */ - private Min min = new Min(); - - /** max of values that have been added */ - private Max max = new Max(); - - /** sumLog of values that have been added */ - private SumOfLogs sumLog = new SumOfLogs(); - - /** geoMean of values that have been added */ - private GeometricMean geoMean = new GeometricMean(sumLog); - - /** mean of values that have been added */ - private Mean mean = new Mean(secondMoment); - - /** variance of values that have been added */ - private Variance variance = new Variance(secondMoment); - - /** Sum statistic implementation - can be reset by setter. */ - private StorelessUnivariateStatistic sumImpl = sum; - - /** Sum of squares statistic implementation - can be reset by setter. */ - private StorelessUnivariateStatistic sumsqImpl = sumsq; - - /** Minimum statistic implementation - can be reset by setter. */ - private StorelessUnivariateStatistic minImpl = min; - - /** Maximum statistic implementation - can be reset by setter. */ - private StorelessUnivariateStatistic maxImpl = max; - - /** Sum of log statistic implementation - can be reset by setter. */ - private StorelessUnivariateStatistic sumLogImpl = sumLog; - - /** Geometric mean statistic implementation - can be reset by setter. */ - private StorelessUnivariateStatistic geoMeanImpl = geoMean; - - /** Mean statistic implementation - can be reset by setter. */ - private StorelessUnivariateStatistic meanImpl = mean; - - /** Variance statistic implementation - can be reset by setter. */ - private StorelessUnivariateStatistic varianceImpl = variance; - - /** - * Construct a SummaryStatistics instance - */ - public SummaryStatistics() { - } - - /** - * A copy constructor. Creates a deep-copy of the {@code original}. - * - * @param original the {@code SummaryStatistics} instance to copy - * @throws NullArgumentException if original is null - */ - public SummaryStatistics(SummaryStatistics original) throws NullArgumentException { - copy(original, this); - } - - /** - * Return a {@link StatisticalSummaryValues} instance reporting current - * statistics. - * @return Current values of statistics - */ - public StatisticalSummary getSummary() { - return new StatisticalSummaryValues(getMean(), getVariance(), getN(), - getMax(), getMin(), getSum()); - } - - /** - * Add a value to the data - * @param value the value to add - */ - public void addValue(double value) { - sumImpl.increment(value); - sumsqImpl.increment(value); - minImpl.increment(value); - maxImpl.increment(value); - sumLogImpl.increment(value); - secondMoment.increment(value); - // If mean, variance or geomean have been overridden, - // need to increment these - if (meanImpl != mean) { - meanImpl.increment(value); - } - if (varianceImpl != variance) { - varianceImpl.increment(value); - } - if (geoMeanImpl != geoMean) { - geoMeanImpl.increment(value); - } - n++; - } - - /** - * Returns the number of available values - * @return The number of available values - */ - @Override - public long getN() { - return n; - } - - /** - * Returns the sum of the values that have been added - * @return The sum or Double.NaN if no values have been added - */ - @Override - public double getSum() { - return sumImpl.getResult(); - } - - /** - * Returns the sum of the squares of the values that have been added. - *

- * Double.NaN is returned if no values have been added. - *

- * @return The sum of squares - */ - public double getSumsq() { - return sumsqImpl.getResult(); - } - - /** - * Returns the mean of the values that have been added. - *

- * Double.NaN is returned if no values have been added. - *

- * @return the mean - */ - @Override - public double getMean() { - return meanImpl.getResult(); - } - - /** - * Returns the standard deviation of the values that have been added. - *

- * Double.NaN is returned if no values have been added. - *

- * @return the standard deviation - */ - @Override - public double getStandardDeviation() { - double stdDev = Double.NaN; - if (getN() > 0) { - if (getN() > 1) { - stdDev = FastMath.sqrt(getVariance()); - } else { - stdDev = 0.0; - } - } - return stdDev; - } - - /** - * Returns the quadratic mean, a.k.a. - * - * root-mean-square of the available values - * @return The quadratic mean or {@code Double.NaN} if no values - * have been added. - */ - public double getQuadraticMean() { - final long size = getN(); - return size > 0 ? FastMath.sqrt(getSumsq() / size) : Double.NaN; - } - - /** - * Returns the (sample) variance of the available values. - * - *

This method returns the bias-corrected sample variance (using {@code n - 1} in - * the denominator). Use {@link #getPopulationVariance()} for the non-bias-corrected - * population variance.

- * - *

Double.NaN is returned if no values have been added.

- * - * @return the variance - */ - @Override - public double getVariance() { - return varianceImpl.getResult(); - } - - /** - * Returns the - * population variance of the values that have been added. - * - *

Double.NaN is returned if no values have been added.

- * - * @return the population variance - */ - public double getPopulationVariance() { - Variance populationVariance = new Variance(secondMoment); - populationVariance.setBiasCorrected(false); - return populationVariance.getResult(); - } - - /** - * Returns the maximum of the values that have been added. - *

- * Double.NaN is returned if no values have been added. - *

- * @return the maximum - */ - @Override - public double getMax() { - return maxImpl.getResult(); - } - - /** - * Returns the minimum of the values that have been added. - *

- * Double.NaN is returned if no values have been added. - *

- * @return the minimum - */ - @Override - public double getMin() { - return minImpl.getResult(); - } - - /** - * Returns the geometric mean of the values that have been added. - *

- * Double.NaN is returned if no values have been added. - *

- * @return the geometric mean - */ - public double getGeometricMean() { - return geoMeanImpl.getResult(); - } - - /** - * Returns the sum of the logs of the values that have been added. - *

- * Double.NaN is returned if no values have been added. - *

- * @return the sum of logs - * @since 1.2 - */ - public double getSumOfLogs() { - return sumLogImpl.getResult(); - } - - /** - * Returns a statistic related to the Second Central Moment. Specifically, - * what is returned is the sum of squared deviations from the sample mean - * among the values that have been added. - *

- * Returns Double.NaN if no data values have been added and - * returns 0 if there is just one value in the data set.

- *

- * @return second central moment statistic - * @since 2.0 - */ - public double getSecondMoment() { - return secondMoment.getResult(); - } - - /** - * Generates a text report displaying summary statistics from values that - * have been added. - * @return String with line feeds displaying statistics - * @since 1.2 - */ - @Override - public String toString() { - StringBuilder outBuffer = new StringBuilder(); - String endl = "\n"; - outBuffer.append("SummaryStatistics:").append(endl); - outBuffer.append("n: ").append(getN()).append(endl); - outBuffer.append("min: ").append(getMin()).append(endl); - outBuffer.append("max: ").append(getMax()).append(endl); - outBuffer.append("sum: ").append(getSum()).append(endl); - outBuffer.append("mean: ").append(getMean()).append(endl); - outBuffer.append("geometric mean: ").append(getGeometricMean()) - .append(endl); - outBuffer.append("variance: ").append(getVariance()).append(endl); - outBuffer.append("population variance: ").append(getPopulationVariance()).append(endl); - outBuffer.append("second moment: ").append(getSecondMoment()).append(endl); - outBuffer.append("sum of squares: ").append(getSumsq()).append(endl); - outBuffer.append("standard deviation: ").append(getStandardDeviation()) - .append(endl); - outBuffer.append("sum of logs: ").append(getSumOfLogs()).append(endl); - return outBuffer.toString(); - } - - /** - * Resets all statistics and storage - */ - public void clear() { - this.n = 0; - minImpl.clear(); - maxImpl.clear(); - sumImpl.clear(); - sumLogImpl.clear(); - sumsqImpl.clear(); - geoMeanImpl.clear(); - secondMoment.clear(); - if (meanImpl != mean) { - meanImpl.clear(); - } - if (varianceImpl != variance) { - varianceImpl.clear(); - } - } - - /** - * Returns true iff object is a - * SummaryStatistics instance and all statistics have the - * same values as this. - * @param object the object to test equality against. - * @return true if object equals this - */ - @Override - public boolean equals(Object object) { - if (object == this) { - return true; - } - if (object instanceof SummaryStatistics == false) { - return false; - } - SummaryStatistics stat = (SummaryStatistics)object; - return Precision.equalsIncludingNaN(stat.getGeometricMean(), getGeometricMean()) && - Precision.equalsIncludingNaN(stat.getMax(), getMax()) && - Precision.equalsIncludingNaN(stat.getMean(), getMean()) && - Precision.equalsIncludingNaN(stat.getMin(), getMin()) && - Precision.equalsIncludingNaN(stat.getN(), getN()) && - Precision.equalsIncludingNaN(stat.getSum(), getSum()) && - Precision.equalsIncludingNaN(stat.getSumsq(), getSumsq()) && - Precision.equalsIncludingNaN(stat.getVariance(), getVariance()); - } - - /** - * Returns hash code based on values of statistics - * @return hash code - */ - @Override - public int hashCode() { - int result = 31 + MathUtils.hash(getGeometricMean()); - result = result * 31 + MathUtils.hash(getGeometricMean()); - result = result * 31 + MathUtils.hash(getMax()); - result = result * 31 + MathUtils.hash(getMean()); - result = result * 31 + MathUtils.hash(getMin()); - result = result * 31 + MathUtils.hash(getN()); - result = result * 31 + MathUtils.hash(getSum()); - result = result * 31 + MathUtils.hash(getSumsq()); - result = result * 31 + MathUtils.hash(getVariance()); - return result; - } - - // Getters and setters for statistics implementations - /** - * Returns the currently configured Sum implementation - * @return the StorelessUnivariateStatistic implementing the sum - * @since 1.2 - */ - public StorelessUnivariateStatistic getSumImpl() { - return sumImpl; - } - - /** - *

- * Sets the implementation for the Sum. - *

- *

- * This method cannot be activated after data has been added - i.e., - * after {@link #addValue(double) addValue} has been used to add data. - * If it is activated after data has been added, an IllegalStateException - * will be thrown. - *

- * @param sumImpl the StorelessUnivariateStatistic instance to use for - * computing the Sum - * @throws MathIllegalStateException if data has already been added (i.e if n >0) - * @since 1.2 - */ - public void setSumImpl(StorelessUnivariateStatistic sumImpl) - throws MathIllegalStateException { - checkEmpty(); - this.sumImpl = sumImpl; - } - - /** - * Returns the currently configured sum of squares implementation - * @return the StorelessUnivariateStatistic implementing the sum of squares - * @since 1.2 - */ - public StorelessUnivariateStatistic getSumsqImpl() { - return sumsqImpl; - } - - /** - *

- * Sets the implementation for the sum of squares. - *

- *

- * This method cannot be activated after data has been added - i.e., - * after {@link #addValue(double) addValue} has been used to add data. - * If it is activated after data has been added, an IllegalStateException - * will be thrown. - *

- * @param sumsqImpl the StorelessUnivariateStatistic instance to use for - * computing the sum of squares - * @throws MathIllegalStateException if data has already been added (i.e if n > 0) - * @since 1.2 - */ - public void setSumsqImpl(StorelessUnivariateStatistic sumsqImpl) - throws MathIllegalStateException { - checkEmpty(); - this.sumsqImpl = sumsqImpl; - } - - /** - * Returns the currently configured minimum implementation - * @return the StorelessUnivariateStatistic implementing the minimum - * @since 1.2 - */ - public StorelessUnivariateStatistic getMinImpl() { - return minImpl; - } - - /** - *

- * Sets the implementation for the minimum. - *

- *

- * This method cannot be activated after data has been added - i.e., - * after {@link #addValue(double) addValue} has been used to add data. - * If it is activated after data has been added, an IllegalStateException - * will be thrown. - *

- * @param minImpl the StorelessUnivariateStatistic instance to use for - * computing the minimum - * @throws MathIllegalStateException if data has already been added (i.e if n > 0) - * @since 1.2 - */ - public void setMinImpl(StorelessUnivariateStatistic minImpl) - throws MathIllegalStateException { - checkEmpty(); - this.minImpl = minImpl; - } - - /** - * Returns the currently configured maximum implementation - * @return the StorelessUnivariateStatistic implementing the maximum - * @since 1.2 - */ - public StorelessUnivariateStatistic getMaxImpl() { - return maxImpl; - } - - /** - *

- * Sets the implementation for the maximum. - *

- *

- * This method cannot be activated after data has been added - i.e., - * after {@link #addValue(double) addValue} has been used to add data. - * If it is activated after data has been added, an IllegalStateException - * will be thrown. - *

- * @param maxImpl the StorelessUnivariateStatistic instance to use for - * computing the maximum - * @throws MathIllegalStateException if data has already been added (i.e if n > 0) - * @since 1.2 - */ - public void setMaxImpl(StorelessUnivariateStatistic maxImpl) - throws MathIllegalStateException { - checkEmpty(); - this.maxImpl = maxImpl; - } - - /** - * Returns the currently configured sum of logs implementation - * @return the StorelessUnivariateStatistic implementing the log sum - * @since 1.2 - */ - public StorelessUnivariateStatistic getSumLogImpl() { - return sumLogImpl; - } - - /** - *

- * Sets the implementation for the sum of logs. - *

- *

- * This method cannot be activated after data has been added - i.e., - * after {@link #addValue(double) addValue} has been used to add data. - * If it is activated after data has been added, an IllegalStateException - * will be thrown. - *

- * @param sumLogImpl the StorelessUnivariateStatistic instance to use for - * computing the log sum - * @throws MathIllegalStateException if data has already been added (i.e if n > 0) - * @since 1.2 - */ - public void setSumLogImpl(StorelessUnivariateStatistic sumLogImpl) - throws MathIllegalStateException { - checkEmpty(); - this.sumLogImpl = sumLogImpl; - geoMean.setSumLogImpl(sumLogImpl); - } - - /** - * Returns the currently configured geometric mean implementation - * @return the StorelessUnivariateStatistic implementing the geometric mean - * @since 1.2 - */ - public StorelessUnivariateStatistic getGeoMeanImpl() { - return geoMeanImpl; - } - - /** - *

- * Sets the implementation for the geometric mean. - *

- *

- * This method cannot be activated after data has been added - i.e., - * after {@link #addValue(double) addValue} has been used to add data. - * If it is activated after data has been added, an IllegalStateException - * will be thrown. - *

- * @param geoMeanImpl the StorelessUnivariateStatistic instance to use for - * computing the geometric mean - * @throws MathIllegalStateException if data has already been added (i.e if n > 0) - * @since 1.2 - */ - public void setGeoMeanImpl(StorelessUnivariateStatistic geoMeanImpl) - throws MathIllegalStateException { - checkEmpty(); - this.geoMeanImpl = geoMeanImpl; - } - - /** - * Returns the currently configured mean implementation - * @return the StorelessUnivariateStatistic implementing the mean - * @since 1.2 - */ - public StorelessUnivariateStatistic getMeanImpl() { - return meanImpl; - } - - /** - *

- * Sets the implementation for the mean. - *

- *

- * This method cannot be activated after data has been added - i.e., - * after {@link #addValue(double) addValue} has been used to add data. - * If it is activated after data has been added, an IllegalStateException - * will be thrown. - *

- * @param meanImpl the StorelessUnivariateStatistic instance to use for - * computing the mean - * @throws MathIllegalStateException if data has already been added (i.e if n > 0) - * @since 1.2 - */ - public void setMeanImpl(StorelessUnivariateStatistic meanImpl) - throws MathIllegalStateException { - checkEmpty(); - this.meanImpl = meanImpl; - } - - /** - * Returns the currently configured variance implementation - * @return the StorelessUnivariateStatistic implementing the variance - * @since 1.2 - */ - public StorelessUnivariateStatistic getVarianceImpl() { - return varianceImpl; - } - - /** - *

- * Sets the implementation for the variance. - *

- *

- * This method cannot be activated after data has been added - i.e., - * after {@link #addValue(double) addValue} has been used to add data. - * If it is activated after data has been added, an IllegalStateException - * will be thrown. - *

- * @param varianceImpl the StorelessUnivariateStatistic instance to use for - * computing the variance - * @throws MathIllegalStateException if data has already been added (i.e if n > 0) - * @since 1.2 - */ - public void setVarianceImpl(StorelessUnivariateStatistic varianceImpl) - throws MathIllegalStateException { - checkEmpty(); - this.varianceImpl = varianceImpl; - } - - /** - * Throws IllegalStateException if n > 0. - * @throws MathIllegalStateException if data has been added - */ - private void checkEmpty() throws MathIllegalStateException { - if (n > 0) { - throw new MathIllegalStateException( - LocalizedFormats.VALUES_ADDED_BEFORE_CONFIGURING_STATISTIC, n); - } - } - - /** - * Returns a copy of this SummaryStatistics instance with the same internal state. - * - * @return a copy of this - */ - public SummaryStatistics copy() { - SummaryStatistics result = new SummaryStatistics(); - // No try-catch or advertised exception because arguments are guaranteed non-null - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source SummaryStatistics to copy - * @param dest SummaryStatistics to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(SummaryStatistics source, SummaryStatistics dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - dest.maxImpl = source.maxImpl.copy(); - dest.minImpl = source.minImpl.copy(); - dest.sumImpl = source.sumImpl.copy(); - dest.sumLogImpl = source.sumLogImpl.copy(); - dest.sumsqImpl = source.sumsqImpl.copy(); - dest.secondMoment = source.secondMoment.copy(); - dest.n = source.n; - - // Keep commons-math supplied statistics with embedded moments in synch - if (source.getVarianceImpl() instanceof Variance) { - dest.varianceImpl = new Variance(dest.secondMoment); - } else { - dest.varianceImpl = source.varianceImpl.copy(); - } - if (source.meanImpl instanceof Mean) { - dest.meanImpl = new Mean(dest.secondMoment); - } else { - dest.meanImpl = source.meanImpl.copy(); - } - if (source.getGeoMeanImpl() instanceof GeometricMean) { - dest.geoMeanImpl = new GeometricMean((SumOfLogs) dest.sumLogImpl); - } else { - dest.geoMeanImpl = source.geoMeanImpl.copy(); - } - - // Make sure that if stat == statImpl in source, same - // holds in dest; otherwise copy stat - if (source.geoMean == source.geoMeanImpl) { - dest.geoMean = (GeometricMean) dest.geoMeanImpl; - } else { - GeometricMean.copy(source.geoMean, dest.geoMean); - } - if (source.max == source.maxImpl) { - dest.max = (Max) dest.maxImpl; - } else { - Max.copy(source.max, dest.max); - } - if (source.mean == source.meanImpl) { - dest.mean = (Mean) dest.meanImpl; - } else { - Mean.copy(source.mean, dest.mean); - } - if (source.min == source.minImpl) { - dest.min = (Min) dest.minImpl; - } else { - Min.copy(source.min, dest.min); - } - if (source.sum == source.sumImpl) { - dest.sum = (Sum) dest.sumImpl; - } else { - Sum.copy(source.sum, dest.sum); - } - if (source.variance == source.varianceImpl) { - dest.variance = (Variance) dest.varianceImpl; - } else { - Variance.copy(source.variance, dest.variance); - } - if (source.sumLog == source.sumLogImpl) { - dest.sumLog = (SumOfLogs) dest.sumLogImpl; - } else { - SumOfLogs.copy(source.sumLog, dest.sumLog); - } - if (source.sumsq == source.sumsqImpl) { - dest.sumsq = (SumOfSquares) dest.sumsqImpl; - } else { - SumOfSquares.copy(source.sumsq, dest.sumsq); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/SynchronizedDescriptiveStatistics.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/SynchronizedDescriptiveStatistics.java deleted file mode 100644 index a5f12be04..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/SynchronizedDescriptiveStatistics.java +++ /dev/null @@ -1,192 +0,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. - */ -package org.apache.commons.math4.stat.descriptive; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.util.MathUtils; - -/** - * Implementation of - * {@link DescriptiveStatistics} that - * is safe to use in a multithreaded environment. Multiple threads can safely - * operate on a single instance without causing runtime exceptions due to race - * conditions. In effect, this implementation makes modification and access - * methods atomic operations for a single instance. That is to say, as one - * thread is computing a statistic from the instance, no other thread can modify - * the instance nor compute another statistic. - * - * @since 1.2 - */ -public class SynchronizedDescriptiveStatistics extends DescriptiveStatistics { - - /** Serialization UID */ - private static final long serialVersionUID = 1L; - - /** - * Construct an instance with infinite window - */ - public SynchronizedDescriptiveStatistics() { - // no try-catch or advertized IAE because arg is valid - this(INFINITE_WINDOW); - } - - /** - * Construct an instance with finite window - * @param window the finite window size. - * @throws MathIllegalArgumentException if window size is less than 1 but - * not equal to {@link #INFINITE_WINDOW} - */ - public SynchronizedDescriptiveStatistics(int window) throws MathIllegalArgumentException { - super(window); - } - - /** - * A copy constructor. Creates a deep-copy of the {@code original}. - * - * @param original the {@code SynchronizedDescriptiveStatistics} instance to copy - * @throws NullArgumentException if original is null - */ - public SynchronizedDescriptiveStatistics(SynchronizedDescriptiveStatistics original) - throws NullArgumentException { - copy(original, this); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void addValue(double v) { - super.addValue(v); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double apply(UnivariateStatistic stat) { - return super.apply(stat); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void clear() { - super.clear(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double getElement(int index) { - return super.getElement(index); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized long getN() { - return super.getN(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double getStandardDeviation() { - return super.getStandardDeviation(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double getQuadraticMean() { - return super.getQuadraticMean(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double[] getValues() { - return super.getValues(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized int getWindowSize() { - return super.getWindowSize(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setWindowSize(int windowSize) throws MathIllegalArgumentException { - super.setWindowSize(windowSize); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized String toString() { - return super.toString(); - } - - /** - * Returns a copy of this SynchronizedDescriptiveStatistics instance with the - * same internal state. - * - * @return a copy of this - */ - @Override - public synchronized SynchronizedDescriptiveStatistics copy() { - SynchronizedDescriptiveStatistics result = - new SynchronizedDescriptiveStatistics(); - // No try-catch or advertised exception because arguments are guaranteed non-null - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- *

Acquires synchronization lock on source, then dest before copying.

- * - * @param source SynchronizedDescriptiveStatistics to copy - * @param dest SynchronizedDescriptiveStatistics to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(SynchronizedDescriptiveStatistics source, - SynchronizedDescriptiveStatistics dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - synchronized (source) { - synchronized (dest) { - DescriptiveStatistics.copy(source, dest); - } - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/SynchronizedMultivariateSummaryStatistics.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/SynchronizedMultivariateSummaryStatistics.java deleted file mode 100644 index 09a8c269d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/SynchronizedMultivariateSummaryStatistics.java +++ /dev/null @@ -1,297 +0,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. - */ -package org.apache.commons.math4.stat.descriptive; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathIllegalStateException; -import org.apache.commons.math4.linear.RealMatrix; - -/** - * Implementation of - * {@link MultivariateSummaryStatistics} that - * is safe to use in a multithreaded environment. Multiple threads can safely - * operate on a single instance without causing runtime exceptions due to race - * conditions. In effect, this implementation makes modification and access - * methods atomic operations for a single instance. That is to say, as one - * thread is computing a statistic from the instance, no other thread can modify - * the instance nor compute another statistic. - * @since 1.2 - */ -public class SynchronizedMultivariateSummaryStatistics - extends MultivariateSummaryStatistics { - - /** Serialization UID */ - private static final long serialVersionUID = 7099834153347155363L; - - /** - * Construct a SynchronizedMultivariateSummaryStatistics instance - * @param k dimension of the data - * @param isCovarianceBiasCorrected if true, the unbiased sample - * covariance is computed, otherwise the biased population covariance - * is computed - */ - public SynchronizedMultivariateSummaryStatistics(int k, boolean isCovarianceBiasCorrected) { - super(k, isCovarianceBiasCorrected); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void addValue(double[] value) throws DimensionMismatchException { - super.addValue(value); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized int getDimension() { - return super.getDimension(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized long getN() { - return super.getN(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double[] getSum() { - return super.getSum(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double[] getSumSq() { - return super.getSumSq(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double[] getSumLog() { - return super.getSumLog(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double[] getMean() { - return super.getMean(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double[] getStandardDeviation() { - return super.getStandardDeviation(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized RealMatrix getCovariance() { - return super.getCovariance(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double[] getMax() { - return super.getMax(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double[] getMin() { - return super.getMin(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double[] getGeometricMean() { - return super.getGeometricMean(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized String toString() { - return super.toString(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void clear() { - super.clear(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized boolean equals(Object object) { - return super.equals(object); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized int hashCode() { - return super.hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized StorelessUnivariateStatistic[] getSumImpl() { - return super.getSumImpl(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setSumImpl(StorelessUnivariateStatistic[] sumImpl) - throws DimensionMismatchException, MathIllegalStateException { - super.setSumImpl(sumImpl); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized StorelessUnivariateStatistic[] getSumsqImpl() { - return super.getSumsqImpl(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setSumsqImpl(StorelessUnivariateStatistic[] sumsqImpl) - throws DimensionMismatchException, MathIllegalStateException { - super.setSumsqImpl(sumsqImpl); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized StorelessUnivariateStatistic[] getMinImpl() { - return super.getMinImpl(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setMinImpl(StorelessUnivariateStatistic[] minImpl) - throws DimensionMismatchException, MathIllegalStateException { - super.setMinImpl(minImpl); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized StorelessUnivariateStatistic[] getMaxImpl() { - return super.getMaxImpl(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setMaxImpl(StorelessUnivariateStatistic[] maxImpl) - throws DimensionMismatchException, MathIllegalStateException{ - super.setMaxImpl(maxImpl); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized StorelessUnivariateStatistic[] getSumLogImpl() { - return super.getSumLogImpl(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setSumLogImpl(StorelessUnivariateStatistic[] sumLogImpl) - throws DimensionMismatchException, MathIllegalStateException { - super.setSumLogImpl(sumLogImpl); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized StorelessUnivariateStatistic[] getGeoMeanImpl() { - return super.getGeoMeanImpl(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setGeoMeanImpl(StorelessUnivariateStatistic[] geoMeanImpl) - throws DimensionMismatchException, MathIllegalStateException { - super.setGeoMeanImpl(geoMeanImpl); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized StorelessUnivariateStatistic[] getMeanImpl() { - return super.getMeanImpl(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setMeanImpl(StorelessUnivariateStatistic[] meanImpl) - throws DimensionMismatchException, MathIllegalStateException { - super.setMeanImpl(meanImpl); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/SynchronizedSummaryStatistics.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/SynchronizedSummaryStatistics.java deleted file mode 100644 index 01c1ae6da..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/SynchronizedSummaryStatistics.java +++ /dev/null @@ -1,366 +0,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. - */ -package org.apache.commons.math4.stat.descriptive; - -import org.apache.commons.math4.exception.MathIllegalStateException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.util.MathUtils; - -/** - * Implementation of - * {@link SummaryStatistics} that - * is safe to use in a multithreaded environment. Multiple threads can safely - * operate on a single instance without causing runtime exceptions due to race - * conditions. In effect, this implementation makes modification and access - * methods atomic operations for a single instance. That is to say, as one - * thread is computing a statistic from the instance, no other thread can modify - * the instance nor compute another statistic. - * - * @since 1.2 - */ -public class SynchronizedSummaryStatistics extends SummaryStatistics { - - /** Serialization UID */ - private static final long serialVersionUID = 1909861009042253704L; - - /** - * Construct a SynchronizedSummaryStatistics instance - */ - public SynchronizedSummaryStatistics() { - super(); - } - - /** - * A copy constructor. Creates a deep-copy of the {@code original}. - * - * @param original the {@code SynchronizedSummaryStatistics} instance to copy - * @throws NullArgumentException if original is null - */ - public SynchronizedSummaryStatistics(SynchronizedSummaryStatistics original) - throws NullArgumentException { - copy(original, this); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized StatisticalSummary getSummary() { - return super.getSummary(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void addValue(double value) { - super.addValue(value); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized long getN() { - return super.getN(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double getSum() { - return super.getSum(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double getSumsq() { - return super.getSumsq(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double getMean() { - return super.getMean(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double getStandardDeviation() { - return super.getStandardDeviation(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double getQuadraticMean() { - return super.getQuadraticMean(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double getVariance() { - return super.getVariance(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double getPopulationVariance() { - return super.getPopulationVariance(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double getMax() { - return super.getMax(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double getMin() { - return super.getMin(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized double getGeometricMean() { - return super.getGeometricMean(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized String toString() { - return super.toString(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void clear() { - super.clear(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized boolean equals(Object object) { - return super.equals(object); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized int hashCode() { - return super.hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized StorelessUnivariateStatistic getSumImpl() { - return super.getSumImpl(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setSumImpl(StorelessUnivariateStatistic sumImpl) - throws MathIllegalStateException { - super.setSumImpl(sumImpl); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized StorelessUnivariateStatistic getSumsqImpl() { - return super.getSumsqImpl(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setSumsqImpl(StorelessUnivariateStatistic sumsqImpl) - throws MathIllegalStateException { - super.setSumsqImpl(sumsqImpl); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized StorelessUnivariateStatistic getMinImpl() { - return super.getMinImpl(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setMinImpl(StorelessUnivariateStatistic minImpl) - throws MathIllegalStateException { - super.setMinImpl(minImpl); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized StorelessUnivariateStatistic getMaxImpl() { - return super.getMaxImpl(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setMaxImpl(StorelessUnivariateStatistic maxImpl) - throws MathIllegalStateException { - super.setMaxImpl(maxImpl); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized StorelessUnivariateStatistic getSumLogImpl() { - return super.getSumLogImpl(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setSumLogImpl(StorelessUnivariateStatistic sumLogImpl) - throws MathIllegalStateException { - super.setSumLogImpl(sumLogImpl); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized StorelessUnivariateStatistic getGeoMeanImpl() { - return super.getGeoMeanImpl(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setGeoMeanImpl(StorelessUnivariateStatistic geoMeanImpl) - throws MathIllegalStateException { - super.setGeoMeanImpl(geoMeanImpl); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized StorelessUnivariateStatistic getMeanImpl() { - return super.getMeanImpl(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setMeanImpl(StorelessUnivariateStatistic meanImpl) - throws MathIllegalStateException { - super.setMeanImpl(meanImpl); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized StorelessUnivariateStatistic getVarianceImpl() { - return super.getVarianceImpl(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setVarianceImpl(StorelessUnivariateStatistic varianceImpl) - throws MathIllegalStateException { - super.setVarianceImpl(varianceImpl); - } - - /** - * Returns a copy of this SynchronizedSummaryStatistics instance with the - * same internal state. - * - * @return a copy of this - */ - @Override - public synchronized SynchronizedSummaryStatistics copy() { - SynchronizedSummaryStatistics result = - new SynchronizedSummaryStatistics(); - // No try-catch or advertised exception because arguments are guaranteed non-null - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- *

Acquires synchronization lock on source, then dest before copying.

- * - * @param source SynchronizedSummaryStatistics to copy - * @param dest SynchronizedSummaryStatistics to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(SynchronizedSummaryStatistics source, - SynchronizedSummaryStatistics dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - synchronized (source) { - synchronized (dest) { - SummaryStatistics.copy(source, dest); - } - } - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/UnivariateStatistic.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/UnivariateStatistic.java deleted file mode 100644 index 3a07a92ee..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/UnivariateStatistic.java +++ /dev/null @@ -1,56 +0,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. - */ -package org.apache.commons.math4.stat.descriptive; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.util.MathArrays; - - -/** - * Base interface implemented by all statistics. - */ -public interface UnivariateStatistic extends MathArrays.Function { - /** - * Returns the result of evaluating the statistic over the input array. - * - * @param values input array - * @return the value of the statistic applied to the input array - * @throws MathIllegalArgumentException if values is null - */ - @Override - double evaluate(double[] values) throws MathIllegalArgumentException; - - /** - * Returns the result of evaluating the statistic over the specified entries - * in the input array. - * - * @param values the input array - * @param begin the index of the first element to include - * @param length the number of elements to include - * @return the value of the statistic applied to the included array entries - * @throws MathIllegalArgumentException if values is null or the indices are invalid - */ - @Override - double evaluate(double[] values, int begin, int length) throws MathIllegalArgumentException; - - /** - * Returns a copy of the statistic with the same internal state. - * - * @return a copy of the statistic - */ - UnivariateStatistic copy(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/WeightedEvaluation.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/WeightedEvaluation.java deleted file mode 100644 index 5bd512baf..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/WeightedEvaluation.java +++ /dev/null @@ -1,57 +0,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. - */ -package org.apache.commons.math4.stat.descriptive; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; - -/** - * Weighted evaluation for statistics. - * - * @since 2.1 - */ -public interface WeightedEvaluation { - - /** - * Returns the result of evaluating the statistic over the input array, - * using the supplied weights. - * - * @param values input array - * @param weights array of weights - * @return the value of the weighted statistic applied to the input array - * @throws MathIllegalArgumentException if either array is null, lengths - * do not match, weights contain NaN, negative or infinite values, or - * weights does not include at least on positive value - */ - double evaluate(double[] values, double[] weights) throws MathIllegalArgumentException; - - /** - * Returns the result of evaluating the statistic over the specified entries - * in the input array, using corresponding entries in the supplied weights array. - * - * @param values the input array - * @param weights array of weights - * @param begin the index of the first element to include - * @param length the number of elements to include - * @return the value of the weighted statistic applied to the included array entries - * @throws MathIllegalArgumentException if either array is null, lengths - * do not match, indices are invalid, weights contain NaN, negative or - * infinite values, or weights does not include at least on positive value - */ - double evaluate(double[] values, double[] weights, int begin, int length) - throws MathIllegalArgumentException; - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/FirstMoment.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/FirstMoment.java deleted file mode 100644 index e02a7cb80..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/FirstMoment.java +++ /dev/null @@ -1,166 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.moment; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.stat.descriptive.AbstractStorelessUnivariateStatistic; -import org.apache.commons.math4.util.MathUtils; - -/** - * Computes the first moment (arithmetic mean). Uses the definitional formula: - *

- * mean = sum(x_i) / n

- *

- * where n is the number of observations.

- *

- * To limit numeric errors, the value of the statistic is computed using the - * following recursive updating algorithm:

- *
    - *
  1. Initialize m = the first value
  2. - *
  3. For each additional value, update using
    - * m = m + (new value - m) / (number of observations)
  4. - *
- *

- * Returns Double.NaN if the dataset is empty. Note that - * Double.NaN may also be returned if the input includes NaN and / or infinite - * values.

- *

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally.

- */ -class FirstMoment extends AbstractStorelessUnivariateStatistic - implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /** Count of values that have been added */ - protected long n; - - /** First moment of values that have been added */ - protected double m1; - - /** - * Deviation of most recently added value from previous first moment. - * Retained to prevent repeated computation in higher order moments. - */ - protected double dev; - - /** - * Deviation of most recently added value from previous first moment, - * normalized by previous sample size. Retained to prevent repeated - * computation in higher order moments - */ - protected double nDev; - - /** - * Create a FirstMoment instance - */ - FirstMoment() { - n = 0; - m1 = Double.NaN; - dev = Double.NaN; - nDev = Double.NaN; - } - - /** - * Copy constructor, creates a new {@code FirstMoment} identical - * to the {@code original} - * - * @param original the {@code FirstMoment} instance to copy - * @throws NullArgumentException if original is null - */ - FirstMoment(FirstMoment original) throws NullArgumentException { - super(); - copy(original, this); - } - - /** - * {@inheritDoc} - */ - @Override - public void increment(final double d) { - if (n == 0) { - m1 = 0.0; - } - n++; - double n0 = n; - dev = d - m1; - nDev = dev / n0; - m1 += nDev; - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - m1 = Double.NaN; - n = 0; - dev = Double.NaN; - nDev = Double.NaN; - } - - /** - * {@inheritDoc} - */ - @Override - public double getResult() { - return m1; - } - - /** - * {@inheritDoc} - */ - @Override - public long getN() { - return n; - } - - /** - * {@inheritDoc} - */ - @Override - public FirstMoment copy() { - FirstMoment result = new FirstMoment(); - // No try-catch or advertised exception because args are guaranteed non-null - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source FirstMoment to copy - * @param dest FirstMoment to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(FirstMoment source, FirstMoment dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - dest.n = source.n; - dest.m1 = source.m1; - dest.dev = source.dev; - dest.nDev = source.nDev; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/FourthMoment.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/FourthMoment.java deleted file mode 100644 index c6eede02d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/FourthMoment.java +++ /dev/null @@ -1,150 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.moment; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.util.MathUtils; - -/** - * Computes a statistic related to the Fourth Central Moment. Specifically, - * what is computed is the sum of - *

- * (x_i - xbar) ^ 4,

- *

- * where the x_i are the - * sample observations and xbar is the sample mean.

- *

- * The following recursive updating formula is used:

- *

- * Let

    - *
  • dev = (current obs - previous mean)
  • - *
  • m2 = previous value of {@link SecondMoment}
  • - *
  • m2 = previous value of {@link ThirdMoment}
  • - *
  • n = number of observations (including current obs)
  • - *
- * Then - *

- * new value = old value - 4 * (dev/n) * m3 + 6 * (dev/n)^2 * m2 +
- * [n^2 - 3 * (n-1)] * dev^4 * (n-1) / n^3

- *

- * Returns Double.NaN if no data values have been added and - * returns 0 if there is just one value in the data set. Note that - * Double.NaN may also be returned if the input includes NaN and / or infinite - * values.

- *

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally.

- */ -class FourthMoment extends ThirdMoment implements Serializable{ - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /** fourth moment of values that have been added */ - private double m4; - - /** - * Create a FourthMoment instance - */ - FourthMoment() { - super(); - m4 = Double.NaN; - } - - /** - * Copy constructor, creates a new {@code FourthMoment} identical - * to the {@code original}. - * - * @param original the {@code FourthMoment} instance to copy - * @throws NullArgumentException if original is null - */ - FourthMoment(FourthMoment original) throws NullArgumentException { - super(); - copy(original, this); - } - - /** - * {@inheritDoc} - */ - @Override - public void increment(final double d) { - if (n < 1) { - m4 = 0.0; - m3 = 0.0; - m2 = 0.0; - m1 = 0.0; - } - - double prevM3 = m3; - double prevM2 = m2; - - super.increment(d); - - double n0 = n; - - m4 = m4 - 4.0 * nDev * prevM3 + 6.0 * nDevSq * prevM2 + - ((n0 * n0) - 3 * (n0 -1)) * (nDevSq * nDevSq * (n0 - 1) * n0); - } - - /** - * {@inheritDoc} - */ - @Override - public double getResult() { - return m4; - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - super.clear(); - m4 = Double.NaN; - } - - /** - * {@inheritDoc} - */ - @Override - public FourthMoment copy() { - FourthMoment result = new FourthMoment(); - // No try-catch or advertised exception because args are guaranteed non-null - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source FourthMoment to copy - * @param dest FourthMoment to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(FourthMoment source, FourthMoment dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - ThirdMoment.copy(source, dest); - dest.m4 = source.m4; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/GeometricMean.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/GeometricMean.java deleted file mode 100644 index 874274832..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/GeometricMean.java +++ /dev/null @@ -1,209 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.moment; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.MathIllegalStateException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.stat.descriptive.AbstractStorelessUnivariateStatistic; -import org.apache.commons.math4.stat.descriptive.StorelessUnivariateStatistic; -import org.apache.commons.math4.stat.descriptive.summary.SumOfLogs; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathUtils; - -/** - * Returns the - * geometric mean of the available values. - *

- * Uses a {@link SumOfLogs} instance to compute sum of logs and returns - * exp( 1/n (sum of logs) ). Therefore,

- *
    - *
  • If any of values are {@code < 0}, the result is NaN.
  • - *
  • If all values are non-negative and less than - * Double.POSITIVE_INFINITY, but at least one value is 0, the - * result is 0.
  • - *
  • If both Double.POSITIVE_INFINITY and - * Double.NEGATIVE_INFINITY are among the values, the result is - * NaN.
  • - *
- *

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally.

- */ -public class GeometricMean extends AbstractStorelessUnivariateStatistic implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /** Wrapped SumOfLogs instance */ - private StorelessUnivariateStatistic sumOfLogs; - - /** - * Create a GeometricMean instance. - */ - public GeometricMean() { - sumOfLogs = new SumOfLogs(); - } - - /** - * Copy constructor, creates a new {@code GeometricMean} identical - * to the {@code original}. - * - * @param original the {@code GeometricMean} instance to copy - * @throws NullArgumentException if original is null - */ - public GeometricMean(GeometricMean original) throws NullArgumentException { - super(); - copy(original, this); - } - - /** - * Create a GeometricMean instance using the given SumOfLogs instance - * @param sumOfLogs sum of logs instance to use for computation. - */ - public GeometricMean(SumOfLogs sumOfLogs) { - this.sumOfLogs = sumOfLogs; - } - - /** - * {@inheritDoc} - */ - @Override - public GeometricMean copy() { - GeometricMean result = new GeometricMean(); - // no try-catch or advertised exception because args guaranteed non-null - copy(this, result); - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public void increment(final double d) { - sumOfLogs.increment(d); - } - - /** - * {@inheritDoc} - */ - @Override - public double getResult() { - if (sumOfLogs.getN() > 0) { - return FastMath.exp(sumOfLogs.getResult() / sumOfLogs.getN()); - } else { - return Double.NaN; - } - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - sumOfLogs.clear(); - } - - /** - * Returns the geometric mean of the entries in the specified portion - * of the input array. - *

- * See {@link GeometricMean} for details on the computing algorithm.

- *

- * Throws IllegalArgumentException if the array is null.

- * - * @param values input array containing the values - * @param begin first array element to include - * @param length the number of elements to include - * @return the geometric mean or Double.NaN if length = 0 or - * any of the values are <= 0. - * @throws MathIllegalArgumentException if the input array is null or the array - * index parameters are not valid - */ - @Override - public double evaluate(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - return FastMath.exp(sumOfLogs.evaluate(values, begin, length) / length); - } - - /** - * {@inheritDoc} - */ - @Override - public long getN() { - return sumOfLogs.getN(); - } - - /** - *

Sets the implementation for the sum of logs.

- *

This method must be activated before any data has been added - i.e., - * before {@link #increment(double) increment} has been used to add data; - * otherwise an IllegalStateException will be thrown.

- * - * @param sumLogImpl the StorelessUnivariateStatistic instance to use - * for computing the log sum - * @throws MathIllegalStateException if data has already been added - * (i.e if n > 0) - */ - public void setSumLogImpl(StorelessUnivariateStatistic sumLogImpl) - throws MathIllegalStateException { - checkEmpty(); - this.sumOfLogs = sumLogImpl; - } - - /** - * Returns the currently configured sum of logs implementation. - * - * @return the StorelessUnivariateStatistic implementing the log sum - */ - public StorelessUnivariateStatistic getSumLogImpl() { - return sumOfLogs; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source GeometricMean to copy - * @param dest GeometricMean to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(GeometricMean source, GeometricMean dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - dest.sumOfLogs = source.sumOfLogs.copy(); - } - - /** - * Throws MathIllegalStateException if n > 0. - * @throws MathIllegalStateException if data has been added to this statistic - */ - private void checkEmpty() throws MathIllegalStateException { - if (getN() > 0) { - throw new MathIllegalStateException( - LocalizedFormats.VALUES_ADDED_BEFORE_CONFIGURING_STATISTIC, - getN()); - } - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/Kurtosis.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/Kurtosis.java deleted file mode 100644 index a9a0cc51e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/Kurtosis.java +++ /dev/null @@ -1,226 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.moment; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.stat.descriptive.AbstractStorelessUnivariateStatistic; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - - -/** - * Computes the Kurtosis of the available values. - *

- * We use the following (unbiased) formula to define kurtosis:

- *

- * kurtosis = { [n(n+1) / (n -1)(n - 2)(n-3)] sum[(x_i - mean)^4] / std^4 } - [3(n-1)^2 / (n-2)(n-3)] - *

- * where n is the number of values, mean is the {@link Mean} and std is the - * {@link StandardDeviation}

- *

- * Note that this statistic is undefined for {@code n < 4}. Double.Nan - * is returned when there is not sufficient data to compute the statistic. - * Note that Double.NaN may also be returned if the input includes NaN - * and / or infinite values.

- *

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally.

- */ -public class Kurtosis extends AbstractStorelessUnivariateStatistic implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /**Fourth Moment on which this statistic is based */ - protected FourthMoment moment; - - /** - * Determines whether or not this statistic can be incremented or cleared. - *

- * Statistics based on (constructed from) external moments cannot - * be incremented or cleared.

- */ - protected boolean incMoment; - - /** - * Construct a Kurtosis. - */ - public Kurtosis() { - incMoment = true; - moment = new FourthMoment(); - } - - /** - * Construct a Kurtosis from an external moment. - * - * @param m4 external Moment - */ - public Kurtosis(final FourthMoment m4) { - incMoment = false; - this.moment = m4; - } - - /** - * Copy constructor, creates a new {@code Kurtosis} identical - * to the {@code original}. - * - * @param original the {@code Kurtosis} instance to copy - * @throws NullArgumentException if original is null - */ - public Kurtosis(Kurtosis original) throws NullArgumentException { - copy(original, this); - } - - /** - * {@inheritDoc} - *

Note that when {@link #Kurtosis(FourthMoment)} is used to - * create a Variance, this method does nothing. In that case, the - * FourthMoment should be incremented directly.

- */ - @Override - public void increment(final double d) { - if (incMoment) { - moment.increment(d); - } - } - - /** - * {@inheritDoc} - */ - @Override - public double getResult() { - double kurtosis = Double.NaN; - if (moment.getN() > 3) { - double variance = moment.m2 / (moment.n - 1); - if (moment.n <= 3 || variance < 10E-20) { - kurtosis = 0.0; - } else { - double n = moment.n; - kurtosis = - (n * (n + 1) * moment.getResult() - - 3 * moment.m2 * moment.m2 * (n - 1)) / - ((n - 1) * (n -2) * (n -3) * variance * variance); - } - } - return kurtosis; - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - if (incMoment) { - moment.clear(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public long getN() { - return moment.getN(); - } - - /* UnvariateStatistic Approach */ - - /** - * Returns the kurtosis of the entries in the specified portion of the - * input array. - *

- * See {@link Kurtosis} for details on the computing algorithm.

- *

- * Throws IllegalArgumentException if the array is null.

- * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the kurtosis of the values or Double.NaN if length is less than 4 - * @throws MathIllegalArgumentException if the input array is null or the array - * index parameters are not valid - */ - @Override - public double evaluate(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - - // Initialize the kurtosis - double kurt = Double.NaN; - - if (MathArrays.verifyValues(values, begin, length) && length > 3) { - // Compute the mean and standard deviation - Variance variance = new Variance(); - variance.incrementAll(values, begin, length); - double mean = variance.moment.m1; - double stdDev = FastMath.sqrt(variance.getResult()); - - // Sum the ^4 of the distance from the mean divided by the - // standard deviation - double accum3 = 0.0; - for (int i = begin; i < begin + length; i++) { - accum3 += FastMath.pow(values[i] - mean, 4.0); - } - accum3 /= FastMath.pow(stdDev, 4.0d); - - // Get N - double n0 = length; - - double coefficientOne = - (n0 * (n0 + 1)) / ((n0 - 1) * (n0 - 2) * (n0 - 3)); - double termTwo = - (3 * FastMath.pow(n0 - 1, 2.0)) / ((n0 - 2) * (n0 - 3)); - - // Calculate kurtosis - kurt = (coefficientOne * accum3) - termTwo; - } - return kurt; - } - - /** - * {@inheritDoc} - */ - @Override - public Kurtosis copy() { - Kurtosis result = new Kurtosis(); - // No try-catch because args are guaranteed non-null - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source Kurtosis to copy - * @param dest Kurtosis to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(Kurtosis source, Kurtosis dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - dest.moment = source.moment.copy(); - dest.incMoment = source.incMoment; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/Mean.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/Mean.java deleted file mode 100644 index 250303974..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/Mean.java +++ /dev/null @@ -1,288 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.moment; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.stat.descriptive.AbstractStorelessUnivariateStatistic; -import org.apache.commons.math4.stat.descriptive.WeightedEvaluation; -import org.apache.commons.math4.stat.descriptive.summary.Sum; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - -/** - * Computes the arithmetic mean of a set of values. Uses the definitional - * formula: - *

- * mean = sum(x_i) / n - *

- *

where n is the number of observations. - *

- *

When {@link #increment(double)} is used to add data incrementally from a - * stream of (unstored) values, the value of the statistic that - * {@link #getResult()} returns is computed using the following recursive - * updating algorithm:

- *
    - *
  1. Initialize m = the first value
  2. - *
  3. For each additional value, update using
    - * m = m + (new value - m) / (number of observations)
  4. - *
- *

If {@link #evaluate(double[])} is used to compute the mean of an array - * of stored values, a two-pass, corrected algorithm is used, starting with - * the definitional formula computed using the array of stored values and then - * correcting this by adding the mean deviation of the data values from the - * arithmetic mean. See, e.g. "Comparison of Several Algorithms for Computing - * Sample Means and Variances," Robert F. Ling, Journal of the American - * Statistical Association, Vol. 69, No. 348 (Dec., 1974), pp. 859-866.

- *

- * Returns Double.NaN if the dataset is empty. Note that - * Double.NaN may also be returned if the input includes NaN and / or infinite - * values. - *

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally. - */ -public class Mean extends AbstractStorelessUnivariateStatistic - implements Serializable, WeightedEvaluation { - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /** First moment on which this statistic is based. */ - protected FirstMoment moment; - - /** - * Determines whether or not this statistic can be incremented or cleared. - *

- * Statistics based on (constructed from) external moments cannot - * be incremented or cleared.

- */ - protected boolean incMoment; - - /** Constructs a Mean. */ - public Mean() { - incMoment = true; - moment = new FirstMoment(); - } - - /** - * Constructs a Mean with an External Moment. - * - * @param m1 the moment - */ - public Mean(final FirstMoment m1) { - this.moment = m1; - incMoment = false; - } - - /** - * Copy constructor, creates a new {@code Mean} identical - * to the {@code original}. - * - * @param original the {@code Mean} instance to copy - * @throws NullArgumentException if original is null - */ - public Mean(Mean original) throws NullArgumentException { - copy(original, this); - } - - /** - * {@inheritDoc} - *

Note that when {@link #Mean(FirstMoment)} is used to - * create a Mean, this method does nothing. In that case, the - * FirstMoment should be incremented directly.

- */ - @Override - public void increment(final double d) { - if (incMoment) { - moment.increment(d); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - if (incMoment) { - moment.clear(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public double getResult() { - return moment.m1; - } - - /** - * {@inheritDoc} - */ - @Override - public long getN() { - return moment.getN(); - } - - /** - * Returns the arithmetic mean of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray - * is empty. - *

- * Throws IllegalArgumentException if the array is null.

- *

- * See {@link Mean} for details on the computing algorithm.

- * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the mean of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - @Override - public double evaluate(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - - if (MathArrays.verifyValues(values, begin, length)) { - Sum sum = new Sum(); - double sampleSize = length; - - // Compute initial estimate using definitional formula - double xbar = sum.evaluate(values, begin, length) / sampleSize; - - // Compute correction factor in second pass - double correction = 0; - for (int i = begin; i < begin + length; i++) { - correction += values[i] - xbar; - } - return xbar + (correction/sampleSize); - } - return Double.NaN; - } - - /** - * Returns the weighted arithmetic mean of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray - * is empty. - *

- * Throws IllegalArgumentException if either array is null.

- *

- * See {@link Mean} for details on the computing algorithm. The two-pass algorithm - * described above is used here, with weights applied in computing both the original - * estimate and the correction factor.

- *

- * Throws IllegalArgumentException if any of the following are true: - *

  • the values array is null
  • - *
  • the weights array is null
  • - *
  • the weights array does not have the same length as the values array
  • - *
  • the weights array contains one or more infinite values
  • - *
  • the weights array contains one or more NaN values
  • - *
  • the weights array contains negative values
  • - *
  • the start and length arguments do not determine a valid array
  • - *
- * - * @param values the input array - * @param weights the weights array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the mean of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the parameters are not valid - * @since 2.1 - */ - @Override - public double evaluate(final double[] values, final double[] weights, - final int begin, final int length) throws MathIllegalArgumentException { - if (MathArrays.verifyValues(values, weights, begin, length)) { - Sum sum = new Sum(); - - // Compute initial estimate using definitional formula - double sumw = sum.evaluate(weights,begin,length); - double xbarw = sum.evaluate(values, weights, begin, length) / sumw; - - // Compute correction factor in second pass - double correction = 0; - for (int i = begin; i < begin + length; i++) { - correction += weights[i] * (values[i] - xbarw); - } - return xbarw + (correction/sumw); - } - return Double.NaN; - } - - /** - * Returns the weighted arithmetic mean of the entries in the input array. - *

- * Throws MathIllegalArgumentException if either array is null.

- *

- * See {@link Mean} for details on the computing algorithm. The two-pass algorithm - * described above is used here, with weights applied in computing both the original - * estimate and the correction factor.

- *

- * Throws MathIllegalArgumentException if any of the following are true: - *

  • the values array is null
  • - *
  • the weights array is null
  • - *
  • the weights array does not have the same length as the values array
  • - *
  • the weights array contains one or more infinite values
  • - *
  • the weights array contains one or more NaN values
  • - *
  • the weights array contains negative values
  • - *
- * - * @param values the input array - * @param weights the weights array - * @return the mean of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the parameters are not valid - * @since 2.1 - */ - @Override - public double evaluate(final double[] values, final double[] weights) - throws MathIllegalArgumentException { - return evaluate(values, weights, 0, values.length); - } - - /** - * {@inheritDoc} - */ - @Override - public Mean copy() { - Mean result = new Mean(); - // No try-catch or advertised exception because args are guaranteed non-null - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source Mean to copy - * @param dest Mean to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(Mean source, Mean dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - dest.incMoment = source.incMoment; - dest.moment = source.moment.copy(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/SecondMoment.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/SecondMoment.java deleted file mode 100644 index 878ebe4e4..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/SecondMoment.java +++ /dev/null @@ -1,132 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.moment; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.util.MathUtils; - -/** - * Computes a statistic related to the Second Central Moment. Specifically, - * what is computed is the sum of squared deviations from the sample mean. - *

- * The following recursive updating formula is used:

- *

- * Let

    - *
  • dev = (current obs - previous mean)
  • - *
  • n = number of observations (including current obs)
  • - *
- * Then - *

- * new value = old value + dev^2 * (n -1) / n.

- *

- * Returns Double.NaN if no data values have been added and - * returns 0 if there is just one value in the data set. - * Note that Double.NaN may also be returned if the input includes NaN - * and / or infinite values.

- *

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally.

- */ -public class SecondMoment extends FirstMoment implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /** second moment of values that have been added */ - protected double m2; - - /** - * Create a SecondMoment instance. - */ - public SecondMoment() { - super(); - m2 = Double.NaN; - } - - /** - * Copy constructor, creates a new {@code SecondMoment} identical - * to the {@code original}. - * - * @param original the {@code SecondMoment} instance to copy - * @throws NullArgumentException if original is null - */ - public SecondMoment(SecondMoment original) throws NullArgumentException { - super(original); - this.m2 = original.m2; - } - - /** - * {@inheritDoc} - */ - @Override - public void increment(final double d) { - if (n < 1) { - m1 = m2 = 0.0; - } - super.increment(d); - m2 += ((double) n - 1) * dev * nDev; - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - super.clear(); - m2 = Double.NaN; - } - - /** - * {@inheritDoc} - */ - @Override - public double getResult() { - return m2; - } - - /** - * {@inheritDoc} - */ - @Override - public SecondMoment copy() { - SecondMoment result = new SecondMoment(); - // no try-catch or advertised NAE because args are guaranteed non-null - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source SecondMoment to copy - * @param dest SecondMoment to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(SecondMoment source, SecondMoment dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - FirstMoment.copy(source, dest); - dest.m2 = source.m2; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/SemiVariance.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/SemiVariance.java deleted file mode 100644 index 8008d884a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/SemiVariance.java +++ /dev/null @@ -1,363 +0,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. - */ - -package org.apache.commons.math4.stat.descriptive.moment; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.stat.descriptive.AbstractUnivariateStatistic; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - -/** - *

Computes the semivariance of a set of values with respect to a given cutoff value. - * We define the downside semivariance of a set of values x - * against the cutoff value cutoff to be
- * Σ (x[i] - target)2 / df
- * where the sum is taken over all i such that {@code x[i] < cutoff} - * and df is the length of x (non-bias-corrected) or - * one less than this number (bias corrected). The upside semivariance - * is defined similarly, with the sum taken over values of x that - * exceed the cutoff value.

- * - *

The cutoff value defaults to the mean, bias correction defaults to true - * and the "variance direction" (upside or downside) defaults to downside. The variance direction - * and bias correction may be set using property setters or their values can provided as - * parameters to {@link #evaluate(double[], double, Direction, boolean, int, int)}.

- * - *

If the input array is null, evaluate methods throw - * IllegalArgumentException. If the array has length 1, 0 - * is returned, regardless of the value of the cutoff. - * - *

Note that this class is not intended to be threadsafe. If - * multiple threads access an instance of this class concurrently, and one or - * more of these threads invoke property setters, external synchronization must - * be provided to ensure correct results.

- * - * @since 2.1 - */ -public class SemiVariance extends AbstractUnivariateStatistic implements Serializable { - - /** - * The UPSIDE Direction is used to specify that the observations above the - * cutoff point will be used to calculate SemiVariance. - */ - public static final Direction UPSIDE_VARIANCE = Direction.UPSIDE; - - /** - * The DOWNSIDE Direction is used to specify that the observations below - * the cutoff point will be used to calculate SemiVariance - */ - public static final Direction DOWNSIDE_VARIANCE = Direction.DOWNSIDE; - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /** - * Determines whether or not bias correction is applied when computing the - * value of the statistic. True means that bias is corrected. - */ - private boolean biasCorrected = true; - - /** - * Determines whether to calculate downside or upside SemiVariance. - */ - private Direction varianceDirection = Direction.DOWNSIDE; - - /** - * Constructs a SemiVariance with default (true) biasCorrected - * property and default (Downside) varianceDirection property. - */ - public SemiVariance() { - } - - /** - * Constructs a SemiVariance with the specified biasCorrected - * property and default (Downside) varianceDirection property. - * - * @param biasCorrected setting for bias correction - true means - * bias will be corrected and is equivalent to using the argumentless - * constructor - */ - public SemiVariance(final boolean biasCorrected) { - this.biasCorrected = biasCorrected; - } - - /** - * Constructs a SemiVariance with the specified Direction property - * and default (true) biasCorrected property - * - * @param direction setting for the direction of the SemiVariance - * to calculate - */ - public SemiVariance(final Direction direction) { - this.varianceDirection = direction; - } - - /** - * Constructs a SemiVariance with the specified isBiasCorrected - * property and the specified Direction property. - * - * @param corrected setting for bias correction - true means - * bias will be corrected and is equivalent to using the argumentless - * constructor - * - * @param direction setting for the direction of the SemiVariance - * to calculate - */ - public SemiVariance(final boolean corrected, final Direction direction) { - this.biasCorrected = corrected; - this.varianceDirection = direction; - } - - /** - * Copy constructor, creates a new {@code SemiVariance} identical - * to the {@code original}. - * - * @param original the {@code SemiVariance} instance to copy - * @throws NullArgumentException if original is null - */ - public SemiVariance(final SemiVariance original) throws NullArgumentException { - copy(original, this); - } - - /** - * {@inheritDoc} - */ - @Override - public SemiVariance copy() { - SemiVariance result = new SemiVariance(); - // No try-catch or advertised exception because args are guaranteed non-null - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source SemiVariance to copy - * @param dest SemiVariance to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(final SemiVariance source, SemiVariance dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - dest.biasCorrected = source.biasCorrected; - dest.varianceDirection = source.varianceDirection; - } - - /** - *

Returns the {@link SemiVariance} of the designated values against the mean, using - * instance properties varianceDirection and biasCorrection.

- * - *

Returns NaN if the array is empty and throws - * IllegalArgumentException if the array is null.

- * - * @param values the input array - * @param start index of the first array element to include - * @param length the number of elements to include - * @return the SemiVariance - * @throws MathIllegalArgumentException if the parameters are not valid - * - */ - @Override - public double evaluate(final double[] values, final int start, final int length) - throws MathIllegalArgumentException { - double m = (new Mean()).evaluate(values, start, length); - return evaluate(values, m, varianceDirection, biasCorrected, 0, values.length); - } - - /** - * This method calculates {@link SemiVariance} for the entire array against the mean, using - * the current value of the biasCorrection instance property. - * - * @param values the input array - * @param direction the {@link Direction} of the semivariance - * @return the SemiVariance - * @throws MathIllegalArgumentException if values is null - * - */ - public double evaluate(final double[] values, Direction direction) - throws MathIllegalArgumentException { - double m = (new Mean()).evaluate(values); - return evaluate(values, m, direction, biasCorrected, 0, values.length); - } - - /** - *

Returns the {@link SemiVariance} of the designated values against the cutoff, using - * instance properties variancDirection and biasCorrection.

- * - *

Returns NaN if the array is empty and throws - * MathIllegalArgumentException if the array is null.

- * - * @param values the input array - * @param cutoff the reference point - * @return the SemiVariance - * @throws MathIllegalArgumentException if values is null - */ - public double evaluate(final double[] values, final double cutoff) - throws MathIllegalArgumentException { - return evaluate(values, cutoff, varianceDirection, biasCorrected, 0, values.length); - } - - /** - *

Returns the {@link SemiVariance} of the designated values against the cutoff in the - * given direction, using the current value of the biasCorrection instance property.

- * - *

Returns NaN if the array is empty and throws - * MathIllegalArgumentException if the array is null.

- * - * @param values the input array - * @param cutoff the reference point - * @param direction the {@link Direction} of the semivariance - * @return the SemiVariance - * @throws MathIllegalArgumentException if values is null - */ - public double evaluate(final double[] values, final double cutoff, final Direction direction) - throws MathIllegalArgumentException { - return evaluate(values, cutoff, direction, biasCorrected, 0, values.length); - } - - /** - *

Returns the {@link SemiVariance} of the designated values against the cutoff - * in the given direction with the provided bias correction.

- * - *

Returns NaN if the array is empty and throws - * IllegalArgumentException if the array is null.

- * - * @param values the input array - * @param cutoff the reference point - * @param direction the {@link Direction} of the semivariance - * @param corrected the BiasCorrection flag - * @param start index of the first array element to include - * @param length the number of elements to include - * @return the SemiVariance - * @throws MathIllegalArgumentException if the parameters are not valid - * - */ - public double evaluate (final double[] values, final double cutoff, final Direction direction, - final boolean corrected, final int start, final int length) - throws MathIllegalArgumentException { - - MathArrays.verifyValues(values, start, length); - if (values.length == 0) { - return Double.NaN; - } else { - if (values.length == 1) { - return 0.0; - } else { - final boolean booleanDirection = direction.getDirection(); - - double dev = 0.0; - double sumsq = 0.0; - for (int i = start; i < length; i++) { - if ((values[i] > cutoff) == booleanDirection) { - dev = values[i] - cutoff; - sumsq += dev * dev; - } - } - - if (corrected) { - return sumsq / (length - 1.0); - } else { - return sumsq / length; - } - } - } - } - - /** - * Returns true iff biasCorrected property is set to true. - * - * @return the value of biasCorrected. - */ - public boolean isBiasCorrected() { - return biasCorrected; - } - - /** - * Sets the biasCorrected property. - * - * @param biasCorrected new biasCorrected property value - */ - public void setBiasCorrected(boolean biasCorrected) { - this.biasCorrected = biasCorrected; - } - - /** - * Returns the varianceDirection property. - * - * @return the varianceDirection - */ - public Direction getVarianceDirection () { - return varianceDirection; - } - - /** - * Sets the variance direction - * - * @param varianceDirection the direction of the semivariance - */ - public void setVarianceDirection(Direction varianceDirection) { - this.varianceDirection = varianceDirection; - } - - /** - * The direction of the semivariance - either upside or downside. The direction - * is represented by boolean, with true corresponding to UPSIDE semivariance. - */ - public enum Direction { - /** - * The UPSIDE Direction is used to specify that the observations above the - * cutoff point will be used to calculate SemiVariance - */ - UPSIDE (true), - - /** - * The DOWNSIDE Direction is used to specify that the observations below - * the cutoff point will be used to calculate SemiVariance - */ - DOWNSIDE (false); - - /** - * boolean value UPSIDE <-> true - */ - private final boolean direction; - - /** - * Create a Direction with the given value. - * - * @param b boolean value representing the Direction. True corresponds to UPSIDE. - */ - Direction (boolean b) { - direction = b; - } - - /** - * Returns the value of this Direction. True corresponds to UPSIDE. - * - * @return true if direction is UPSIDE; false otherwise - */ - boolean getDirection () { - return direction; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/Skewness.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/Skewness.java deleted file mode 100644 index 3fcd4bedc..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/Skewness.java +++ /dev/null @@ -1,227 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.moment; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.stat.descriptive.AbstractStorelessUnivariateStatistic; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - -/** - * Computes the skewness of the available values. - *

- * We use the following (unbiased) formula to define skewness:

- *

- * skewness = [n / (n -1) (n - 2)] sum[(x_i - mean)^3] / std^3

- *

- * where n is the number of values, mean is the {@link Mean} and std is the - * {@link StandardDeviation}

- *

- * Note that this statistic is undefined for {@code n < 3}. Double.Nan - * is returned when there is not sufficient data to compute the statistic. - * Double.NaN may also be returned if the input includes NaN and / or - * infinite values.

- *

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally.

- */ -public class Skewness extends AbstractStorelessUnivariateStatistic implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /** Third moment on which this statistic is based */ - protected ThirdMoment moment = null; - - /** - * Determines whether or not this statistic can be incremented or cleared. - *

- * Statistics based on (constructed from) external moments cannot - * be incremented or cleared.

- */ - protected boolean incMoment; - - /** - * Constructs a Skewness. - */ - public Skewness() { - incMoment = true; - moment = new ThirdMoment(); - } - - /** - * Constructs a Skewness with an external moment. - * @param m3 external moment - */ - public Skewness(final ThirdMoment m3) { - incMoment = false; - this.moment = m3; - } - - /** - * Copy constructor, creates a new {@code Skewness} identical - * to the {@code original}. - * - * @param original the {@code Skewness} instance to copy - * @throws NullArgumentException if original is null - */ - public Skewness(Skewness original) throws NullArgumentException { - copy(original, this); - } - - /** - * {@inheritDoc} - *

Note that when {@link #Skewness(ThirdMoment)} is used to - * create a Skewness, this method does nothing. In that case, the - * ThirdMoment should be incremented directly.

- */ - @Override - public void increment(final double d) { - if (incMoment) { - moment.increment(d); - } - } - - /** - * Returns the value of the statistic based on the values that have been added. - *

- * See {@link Skewness} for the definition used in the computation.

- * - * @return the skewness of the available values. - */ - @Override - public double getResult() { - - if (moment.n < 3) { - return Double.NaN; - } - double variance = moment.m2 / (moment.n - 1); - if (variance < 10E-20) { - return 0.0d; - } else { - double n0 = moment.getN(); - return (n0 * moment.m3) / - ((n0 - 1) * (n0 -2) * FastMath.sqrt(variance) * variance); - } - } - - /** - * {@inheritDoc} - */ - @Override - public long getN() { - return moment.getN(); - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - if (incMoment) { - moment.clear(); - } - } - - /** - * Returns the Skewness of the entries in the specified portion of the - * input array. - *

- * See {@link Skewness} for the definition used in the computation.

- *

- * Throws IllegalArgumentException if the array is null.

- * - * @param values the input array - * @param begin the index of the first array element to include - * @param length the number of elements to include - * @return the skewness of the values or Double.NaN if length is less than 3 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - @Override - public double evaluate(final double[] values,final int begin, final int length) - throws MathIllegalArgumentException { - - // Initialize the skewness - double skew = Double.NaN; - - if (MathArrays.verifyValues(values, begin, length) && length > 2 ) { - Mean mean = new Mean(); - // Get the mean and the standard deviation - double m = mean.evaluate(values, begin, length); - - // Calc the std, this is implemented here instead - // of using the standardDeviation method eliminate - // a duplicate pass to get the mean - double accum = 0.0; - double accum2 = 0.0; - for (int i = begin; i < begin + length; i++) { - final double d = values[i] - m; - accum += d * d; - accum2 += d; - } - final double variance = (accum - (accum2 * accum2 / length)) / (length - 1); - - double accum3 = 0.0; - for (int i = begin; i < begin + length; i++) { - final double d = values[i] - m; - accum3 += d * d * d; - } - accum3 /= variance * FastMath.sqrt(variance); - - // Get N - double n0 = length; - - // Calculate skewness - skew = (n0 / ((n0 - 1) * (n0 - 2))) * accum3; - } - return skew; - } - - /** - * {@inheritDoc} - */ - @Override - public Skewness copy() { - Skewness result = new Skewness(); - // No try-catch or advertised exception because args are guaranteed non-null - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source Skewness to copy - * @param dest Skewness to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(Skewness source, Skewness dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - dest.moment = new ThirdMoment(source.moment.copy()); - dest.incMoment = source.incMoment; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/StandardDeviation.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/StandardDeviation.java deleted file mode 100644 index d2f5e8bc2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/StandardDeviation.java +++ /dev/null @@ -1,277 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.moment; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.stat.descriptive.AbstractStorelessUnivariateStatistic; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathUtils; - -/** - * Computes the sample standard deviation. The standard deviation - * is the positive square root of the variance. This implementation wraps a - * {@link Variance} instance. The isBiasCorrected property of the - * wrapped Variance instance is exposed, so that this class can be used to - * compute both the "sample standard deviation" (the square root of the - * bias-corrected "sample variance") or the "population standard deviation" - * (the square root of the non-bias-corrected "population variance"). See - * {@link Variance} for more information. - *

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally.

- */ -public class StandardDeviation extends AbstractStorelessUnivariateStatistic - implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /** Wrapped Variance instance */ - private Variance variance = null; - - /** - * Constructs a StandardDeviation. Sets the underlying {@link Variance} - * instance's isBiasCorrected property to true. - */ - public StandardDeviation() { - variance = new Variance(); - } - - /** - * Constructs a StandardDeviation from an external second moment. - * - * @param m2 the external moment - */ - public StandardDeviation(final SecondMoment m2) { - variance = new Variance(m2); - } - - /** - * Copy constructor, creates a new {@code StandardDeviation} identical - * to the {@code original}. - * - * @param original the {@code StandardDeviation} instance to copy - * @throws NullArgumentException if original is null - */ - public StandardDeviation(StandardDeviation original) throws NullArgumentException { - copy(original, this); - } - - /** - * Constructs a StandardDeviation with the specified value for the - * isBiasCorrected property. If this property is set to - * true, the {@link Variance} used in computing results will - * use the bias-corrected, or "sample" formula. See {@link Variance} for - * details. - * - * @param isBiasCorrected whether or not the variance computation will use - * the bias-corrected formula - */ - public StandardDeviation(boolean isBiasCorrected) { - variance = new Variance(isBiasCorrected); - } - - /** - * Constructs a StandardDeviation with the specified value for the - * isBiasCorrected property and the supplied external moment. - * If isBiasCorrected is set to true, the - * {@link Variance} used in computing results will use the bias-corrected, - * or "sample" formula. See {@link Variance} for details. - * - * @param isBiasCorrected whether or not the variance computation will use - * the bias-corrected formula - * @param m2 the external moment - */ - public StandardDeviation(boolean isBiasCorrected, SecondMoment m2) { - variance = new Variance(isBiasCorrected, m2); - } - - /** - * {@inheritDoc} - */ - @Override - public void increment(final double d) { - variance.increment(d); - } - - /** - * {@inheritDoc} - */ - @Override - public long getN() { - return variance.getN(); - } - - /** - * {@inheritDoc} - */ - @Override - public double getResult() { - return FastMath.sqrt(variance.getResult()); - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - variance.clear(); - } - - /** - * Returns the Standard Deviation of the entries in the input array, or - * Double.NaN if the array is empty. - *

- * Returns 0 for a single-value (i.e. length = 1) sample.

- *

- * Throws MathIllegalArgumentException if the array is null.

- *

- * Does not change the internal state of the statistic.

- * - * @param values the input array - * @return the standard deviation of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null - */ - @Override - public double evaluate(final double[] values) throws MathIllegalArgumentException { - return FastMath.sqrt(variance.evaluate(values)); - } - - /** - * Returns the Standard Deviation of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray - * is empty. - *

- * Returns 0 for a single-value (i.e. length = 1) sample.

- *

- * Throws MathIllegalArgumentException if the array is null.

- *

- * Does not change the internal state of the statistic.

- * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the standard deviation of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - @Override - public double evaluate(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - return FastMath.sqrt(variance.evaluate(values, begin, length)); - } - - /** - * Returns the Standard Deviation of the entries in the specified portion of - * the input array, using the precomputed mean value. Returns - * Double.NaN if the designated subarray is empty. - *

- * Returns 0 for a single-value (i.e. length = 1) sample.

- *

- * The formula used assumes that the supplied mean value is the arithmetic - * mean of the sample data, not a known population parameter. This method - * is supplied only to save computation when the mean has already been - * computed.

- *

- * Throws IllegalArgumentException if the array is null.

- *

- * Does not change the internal state of the statistic.

- * - * @param values the input array - * @param mean the precomputed mean value - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the standard deviation of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - public double evaluate(final double[] values, final double mean, - final int begin, final int length) throws MathIllegalArgumentException { - return FastMath.sqrt(variance.evaluate(values, mean, begin, length)); - } - - /** - * Returns the Standard Deviation of the entries in the input array, using - * the precomputed mean value. Returns - * Double.NaN if the designated subarray is empty. - *

- * Returns 0 for a single-value (i.e. length = 1) sample.

- *

- * The formula used assumes that the supplied mean value is the arithmetic - * mean of the sample data, not a known population parameter. This method - * is supplied only to save computation when the mean has already been - * computed.

- *

- * Throws MathIllegalArgumentException if the array is null.

- *

- * Does not change the internal state of the statistic.

- * - * @param values the input array - * @param mean the precomputed mean value - * @return the standard deviation of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null - */ - public double evaluate(final double[] values, final double mean) - throws MathIllegalArgumentException { - return FastMath.sqrt(variance.evaluate(values, mean)); - } - - /** - * @return Returns the isBiasCorrected. - */ - public boolean isBiasCorrected() { - return variance.isBiasCorrected(); - } - - /** - * @param isBiasCorrected The isBiasCorrected to set. - */ - public void setBiasCorrected(boolean isBiasCorrected) { - variance.setBiasCorrected(isBiasCorrected); - } - - /** - * {@inheritDoc} - */ - @Override - public StandardDeviation copy() { - StandardDeviation result = new StandardDeviation(); - // No try-catch or advertised exception because args are guaranteed non-null - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source StandardDeviation to copy - * @param dest StandardDeviation to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(StandardDeviation source, StandardDeviation dest) throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - dest.variance = source.variance.copy(); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/ThirdMoment.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/ThirdMoment.java deleted file mode 100644 index 99b6f5813..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/ThirdMoment.java +++ /dev/null @@ -1,148 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.moment; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.util.MathUtils; - - -/** - * Computes a statistic related to the Third Central Moment. Specifically, - * what is computed is the sum of cubed deviations from the sample mean. - *

- * The following recursive updating formula is used:

- *

- * Let

    - *
  • dev = (current obs - previous mean)
  • - *
  • m2 = previous value of {@link SecondMoment}
  • - *
  • n = number of observations (including current obs)
  • - *
- * Then - *

- * new value = old value - 3 * (dev/n) * m2 + (n-1) * (n -2) * (dev^3/n^2)

- *

- * Returns Double.NaN if no data values have been added and - * returns 0 if there is just one value in the data set. - * Note that Double.NaN may also be returned if the input includes NaN - * and / or infinite values.

- *

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally.

- * - */ -class ThirdMoment extends SecondMoment implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /** third moment of values that have been added */ - protected double m3; - - /** - * Square of deviation of most recently added value from previous first - * moment, normalized by previous sample size. Retained to prevent - * repeated computation in higher order moments. nDevSq = nDev * nDev. - */ - protected double nDevSq; - - /** - * Create a FourthMoment instance. - */ - ThirdMoment() { - super(); - m3 = Double.NaN; - nDevSq = Double.NaN; - } - - /** - * Copy constructor, creates a new {@code ThirdMoment} identical - * to the {@code original}. - * - * @param original the {@code ThirdMoment} instance to copy - * @throws NullArgumentException if original is null - */ - ThirdMoment(ThirdMoment original) throws NullArgumentException { - copy(original, this); - } - - /** - * {@inheritDoc} - */ - @Override - public void increment(final double d) { - if (n < 1) { - m3 = m2 = m1 = 0.0; - } - - double prevM2 = m2; - super.increment(d); - nDevSq = nDev * nDev; - double n0 = n; - m3 = m3 - 3.0 * nDev * prevM2 + (n0 - 1) * (n0 - 2) * nDevSq * dev; - } - - /** - * {@inheritDoc} - */ - @Override - public double getResult() { - return m3; - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - super.clear(); - m3 = Double.NaN; - nDevSq = Double.NaN; - } - - /** - * {@inheritDoc} - */ - @Override - public ThirdMoment copy() { - ThirdMoment result = new ThirdMoment(); - // No try-catch or advertised exception because args are guaranteed non-null - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source ThirdMoment to copy - * @param dest ThirdMoment to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(ThirdMoment source, ThirdMoment dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - SecondMoment.copy(source, dest); - dest.m3 = source.m3; - dest.nDevSq = source.nDevSq; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/Variance.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/Variance.java deleted file mode 100644 index 7dfab7d73..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/Variance.java +++ /dev/null @@ -1,627 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.moment; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.stat.descriptive.AbstractStorelessUnivariateStatistic; -import org.apache.commons.math4.stat.descriptive.WeightedEvaluation; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - -/** - * Computes the variance of the available values. By default, the unbiased - * "sample variance" definitional formula is used: - *

- * variance = sum((x_i - mean)^2) / (n - 1)

- *

- * where mean is the {@link Mean} and n is the number - * of sample observations.

- *

- * The definitional formula does not have good numerical properties, so - * this implementation does not compute the statistic using the definitional - * formula.

    - *
  • The getResult method computes the variance using - * updating formulas based on West's algorithm, as described in - * Chan, T. F. and - * J. G. Lewis 1979, Communications of the ACM, - * vol. 22 no. 9, pp. 526-531.
  • - *
  • The evaluate methods leverage the fact that they have the - * full array of values in memory to execute a two-pass algorithm. - * Specifically, these methods use the "corrected two-pass algorithm" from - * Chan, Golub, Levesque, Algorithms for Computing the Sample Variance, - * American Statistician, vol. 37, no. 3 (1983) pp. 242-247.
- * Note that adding values using increment or - * incrementAll and then executing getResult will - * sometimes give a different, less accurate, result than executing - * evaluate with the full array of values. The former approach - * should only be used when the full array of values is not available. - *

- * The "population variance" ( sum((x_i - mean)^2) / n ) can also - * be computed using this statistic. The isBiasCorrected - * property determines whether the "population" or "sample" value is - * returned by the evaluate and getResult methods. - * To compute population variances, set this property to false. - *

- *

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally.

- */ -public class Variance extends AbstractStorelessUnivariateStatistic implements Serializable, WeightedEvaluation { - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /** SecondMoment is used in incremental calculation of Variance*/ - protected SecondMoment moment = null; - - /** - * Whether or not {@link #increment(double)} should increment - * the internal second moment. When a Variance is constructed with an - * external SecondMoment as a constructor parameter, this property is - * set to false and increments must be applied to the second moment - * directly. - */ - protected boolean incMoment = true; - - /** - * Whether or not bias correction is applied when computing the - * value of the statistic. True means that bias is corrected. See - * {@link Variance} for details on the formula. - */ - private boolean isBiasCorrected = true; - - /** - * Constructs a Variance with default (true) isBiasCorrected - * property. - */ - public Variance() { - moment = new SecondMoment(); - } - - /** - * Constructs a Variance based on an external second moment. - *

- * When this constructor is used, the statistic may only be - * incremented via the moment, i.e., {@link #increment(double)} - * does nothing; whereas {@code m2.increment(value)} increments - * both {@code m2} and the Variance instance constructed from it. - * - * @param m2 the SecondMoment (Third or Fourth moments work here as well.) - */ - public Variance(final SecondMoment m2) { - incMoment = false; - this.moment = m2; - } - - /** - * Constructs a Variance with the specified isBiasCorrected - * property. - * - * @param isBiasCorrected setting for bias correction - true means - * bias will be corrected and is equivalent to using the argumentless - * constructor - */ - public Variance(boolean isBiasCorrected) { - moment = new SecondMoment(); - this.isBiasCorrected = isBiasCorrected; - } - - /** - * Constructs a Variance with the specified isBiasCorrected - * property and the supplied external second moment. - * - * @param isBiasCorrected setting for bias correction - true means - * bias will be corrected - * @param m2 the SecondMoment (Third or Fourth moments work - * here as well.) - */ - public Variance(boolean isBiasCorrected, SecondMoment m2) { - incMoment = false; - this.moment = m2; - this.isBiasCorrected = isBiasCorrected; - } - - /** - * Copy constructor, creates a new {@code Variance} identical - * to the {@code original}. - * - * @param original the {@code Variance} instance to copy - * @throws NullArgumentException if original is null - */ - public Variance(Variance original) throws NullArgumentException { - copy(original, this); - } - - /** - * {@inheritDoc} - *

If all values are available, it is more accurate to use - * {@link #evaluate(double[])} rather than adding values one at a time - * using this method and then executing {@link #getResult}, since - * evaluate leverages the fact that is has the full - * list of values together to execute a two-pass algorithm. - * See {@link Variance}.

- * - *

Note also that when {@link #Variance(SecondMoment)} is used to - * create a Variance, this method does nothing. In that case, the - * SecondMoment should be incremented directly.

- */ - @Override - public void increment(final double d) { - if (incMoment) { - moment.increment(d); - } - } - - /** - * {@inheritDoc} - */ - @Override - public double getResult() { - if (moment.n == 0) { - return Double.NaN; - } else if (moment.n == 1) { - return 0d; - } else { - if (isBiasCorrected) { - return moment.m2 / (moment.n - 1d); - } else { - return moment.m2 / (moment.n); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public long getN() { - return moment.getN(); - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - if (incMoment) { - moment.clear(); - } - } - - /** - * Returns the variance of the entries in the input array, or - * Double.NaN if the array is empty. - *

- * See {@link Variance} for details on the computing algorithm.

- *

- * Returns 0 for a single-value (i.e. length = 1) sample.

- *

- * Throws MathIllegalArgumentException if the array is null.

- *

- * Does not change the internal state of the statistic.

- * - * @param values the input array - * @return the variance of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null - */ - @Override - public double evaluate(final double[] values) throws MathIllegalArgumentException { - if (values == null) { - throw new NullArgumentException(LocalizedFormats.INPUT_ARRAY); - } - return evaluate(values, 0, values.length); - } - - /** - * Returns the variance of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray - * is empty. Note that Double.NaN may also be returned if the input - * includes NaN and / or infinite values. - *

- * See {@link Variance} for details on the computing algorithm.

- *

- * Returns 0 for a single-value (i.e. length = 1) sample.

- *

- * Does not change the internal state of the statistic.

- *

- * Throws MathIllegalArgumentException if the array is null.

- * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the variance of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - @Override - public double evaluate(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - - double var = Double.NaN; - - if (MathArrays.verifyValues(values, begin, length)) { - if (length == 1) { - var = 0.0; - } else if (length > 1) { - Mean mean = new Mean(); - double m = mean.evaluate(values, begin, length); - var = evaluate(values, m, begin, length); - } - } - return var; - } - - /** - *

Returns the weighted variance of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray - * is empty.

- *

- * Uses the formula

- * Σ(weights[i]*(values[i] - weightedMean)2)/(Σ(weights[i]) - 1) - *
- * where weightedMean is the weighted mean - *

- * This formula will not return the same result as the unweighted variance when all - * weights are equal, unless all weights are equal to 1. The formula assumes that - * weights are to be treated as "expansion values," as will be the case if for example - * the weights represent frequency counts. To normalize weights so that the denominator - * in the variance computation equals the length of the input vector minus one, use

-     *   evaluate(values, MathArrays.normalizeArray(weights, values.length)); 
-     * 
- *

- * Returns 0 for a single-value (i.e. length = 1) sample.

- *

- * Throws IllegalArgumentException if any of the following are true: - *

  • the values array is null
  • - *
  • the weights array is null
  • - *
  • the weights array does not have the same length as the values array
  • - *
  • the weights array contains one or more infinite values
  • - *
  • the weights array contains one or more NaN values
  • - *
  • the weights array contains negative values
  • - *
  • the start and length arguments do not determine a valid array
  • - *
- *

- * Does not change the internal state of the statistic.

- *

- * Throws MathIllegalArgumentException if either array is null.

- * - * @param values the input array - * @param weights the weights array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the weighted variance of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the parameters are not valid - * @since 2.1 - */ - @Override - public double evaluate(final double[] values, final double[] weights, - final int begin, final int length) throws MathIllegalArgumentException { - - double var = Double.NaN; - - if (MathArrays.verifyValues(values, weights,begin, length)) { - if (length == 1) { - var = 0.0; - } else if (length > 1) { - Mean mean = new Mean(); - double m = mean.evaluate(values, weights, begin, length); - var = evaluate(values, weights, m, begin, length); - } - } - return var; - } - - /** - *

- * Returns the weighted variance of the entries in the input array.

- *

- * Uses the formula

- * Σ(weights[i]*(values[i] - weightedMean)2)/(Σ(weights[i]) - 1) - *
- * where weightedMean is the weighted mean - *

- * This formula will not return the same result as the unweighted variance when all - * weights are equal, unless all weights are equal to 1. The formula assumes that - * weights are to be treated as "expansion values," as will be the case if for example - * the weights represent frequency counts. To normalize weights so that the denominator - * in the variance computation equals the length of the input vector minus one, use

-     *   evaluate(values, MathArrays.normalizeArray(weights, values.length)); 
-     * 
- *

- * Returns 0 for a single-value (i.e. length = 1) sample.

- *

- * Throws MathIllegalArgumentException if any of the following are true: - *

  • the values array is null
  • - *
  • the weights array is null
  • - *
  • the weights array does not have the same length as the values array
  • - *
  • the weights array contains one or more infinite values
  • - *
  • the weights array contains one or more NaN values
  • - *
  • the weights array contains negative values
  • - *
- *

- * Does not change the internal state of the statistic.

- *

- * Throws MathIllegalArgumentException if either array is null.

- * - * @param values the input array - * @param weights the weights array - * @return the weighted variance of the values - * @throws MathIllegalArgumentException if the parameters are not valid - * @since 2.1 - */ - @Override - public double evaluate(final double[] values, final double[] weights) - throws MathIllegalArgumentException { - return evaluate(values, weights, 0, values.length); - } - - /** - * Returns the variance of the entries in the specified portion of - * the input array, using the precomputed mean value. Returns - * Double.NaN if the designated subarray is empty. - *

- * See {@link Variance} for details on the computing algorithm.

- *

- * The formula used assumes that the supplied mean value is the arithmetic - * mean of the sample data, not a known population parameter. This method - * is supplied only to save computation when the mean has already been - * computed.

- *

- * Returns 0 for a single-value (i.e. length = 1) sample.

- *

- * Throws MathIllegalArgumentException if the array is null.

- *

- * Does not change the internal state of the statistic.

- * - * @param values the input array - * @param mean the precomputed mean value - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the variance of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - public double evaluate(final double[] values, final double mean, - final int begin, final int length) throws MathIllegalArgumentException { - - double var = Double.NaN; - - if (MathArrays.verifyValues(values, begin, length)) { - if (length == 1) { - var = 0.0; - } else if (length > 1) { - double accum = 0.0; - double dev = 0.0; - double accum2 = 0.0; - for (int i = begin; i < begin + length; i++) { - dev = values[i] - mean; - accum += dev * dev; - accum2 += dev; - } - double len = length; - if (isBiasCorrected) { - var = (accum - (accum2 * accum2 / len)) / (len - 1.0); - } else { - var = (accum - (accum2 * accum2 / len)) / len; - } - } - } - return var; - } - - /** - * Returns the variance of the entries in the input array, using the - * precomputed mean value. Returns Double.NaN if the array - * is empty. - *

- * See {@link Variance} for details on the computing algorithm.

- *

- * If isBiasCorrected is true the formula used - * assumes that the supplied mean value is the arithmetic mean of the - * sample data, not a known population parameter. If the mean is a known - * population parameter, or if the "population" version of the variance is - * desired, set isBiasCorrected to false before - * invoking this method.

- *

- * Returns 0 for a single-value (i.e. length = 1) sample.

- *

- * Throws MathIllegalArgumentException if the array is null.

- *

- * Does not change the internal state of the statistic.

- * - * @param values the input array - * @param mean the precomputed mean value - * @return the variance of the values or Double.NaN if the array is empty - * @throws MathIllegalArgumentException if the array is null - */ - public double evaluate(final double[] values, final double mean) throws MathIllegalArgumentException { - return evaluate(values, mean, 0, values.length); - } - - /** - * Returns the weighted variance of the entries in the specified portion of - * the input array, using the precomputed weighted mean value. Returns - * Double.NaN if the designated subarray is empty. - *

- * Uses the formula

- * Σ(weights[i]*(values[i] - mean)2)/(Σ(weights[i]) - 1) - *
- *

- * The formula used assumes that the supplied mean value is the weighted arithmetic - * mean of the sample data, not a known population parameter. This method - * is supplied only to save computation when the mean has already been - * computed.

- *

- * This formula will not return the same result as the unweighted variance when all - * weights are equal, unless all weights are equal to 1. The formula assumes that - * weights are to be treated as "expansion values," as will be the case if for example - * the weights represent frequency counts. To normalize weights so that the denominator - * in the variance computation equals the length of the input vector minus one, use

-     *   evaluate(values, MathArrays.normalizeArray(weights, values.length), mean); 
-     * 
- *

- * Returns 0 for a single-value (i.e. length = 1) sample.

- *

- * Throws MathIllegalArgumentException if any of the following are true: - *

  • the values array is null
  • - *
  • the weights array is null
  • - *
  • the weights array does not have the same length as the values array
  • - *
  • the weights array contains one or more infinite values
  • - *
  • the weights array contains one or more NaN values
  • - *
  • the weights array contains negative values
  • - *
  • the start and length arguments do not determine a valid array
  • - *
- *

- * Does not change the internal state of the statistic.

- * - * @param values the input array - * @param weights the weights array - * @param mean the precomputed weighted mean value - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the variance of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the parameters are not valid - * @since 2.1 - */ - public double evaluate(final double[] values, final double[] weights, - final double mean, final int begin, final int length) - throws MathIllegalArgumentException { - - double var = Double.NaN; - - if (MathArrays.verifyValues(values, weights, begin, length)) { - if (length == 1) { - var = 0.0; - } else if (length > 1) { - double accum = 0.0; - double dev = 0.0; - double accum2 = 0.0; - for (int i = begin; i < begin + length; i++) { - dev = values[i] - mean; - accum += weights[i] * (dev * dev); - accum2 += weights[i] * dev; - } - - double sumWts = 0; - for (int i = begin; i < begin + length; i++) { - sumWts += weights[i]; - } - - if (isBiasCorrected) { - var = (accum - (accum2 * accum2 / sumWts)) / (sumWts - 1.0); - } else { - var = (accum - (accum2 * accum2 / sumWts)) / sumWts; - } - } - } - return var; - } - - /** - *

Returns the weighted variance of the values in the input array, using - * the precomputed weighted mean value.

- *

- * Uses the formula

- * Σ(weights[i]*(values[i] - mean)2)/(Σ(weights[i]) - 1) - *
- *

- * The formula used assumes that the supplied mean value is the weighted arithmetic - * mean of the sample data, not a known population parameter. This method - * is supplied only to save computation when the mean has already been - * computed.

- *

- * This formula will not return the same result as the unweighted variance when all - * weights are equal, unless all weights are equal to 1. The formula assumes that - * weights are to be treated as "expansion values," as will be the case if for example - * the weights represent frequency counts. To normalize weights so that the denominator - * in the variance computation equals the length of the input vector minus one, use

-     *   evaluate(values, MathArrays.normalizeArray(weights, values.length), mean); 
-     * 
- *

- * Returns 0 for a single-value (i.e. length = 1) sample.

- *

- * Throws MathIllegalArgumentException if any of the following are true: - *

  • the values array is null
  • - *
  • the weights array is null
  • - *
  • the weights array does not have the same length as the values array
  • - *
  • the weights array contains one or more infinite values
  • - *
  • the weights array contains one or more NaN values
  • - *
  • the weights array contains negative values
  • - *
- *

- * Does not change the internal state of the statistic.

- * - * @param values the input array - * @param weights the weights array - * @param mean the precomputed weighted mean value - * @return the variance of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the parameters are not valid - * @since 2.1 - */ - public double evaluate(final double[] values, final double[] weights, final double mean) - throws MathIllegalArgumentException { - return evaluate(values, weights, mean, 0, values.length); - } - - /** - * @return Returns the isBiasCorrected. - */ - public boolean isBiasCorrected() { - return isBiasCorrected; - } - - /** - * @param biasCorrected The isBiasCorrected to set. - */ - public void setBiasCorrected(boolean biasCorrected) { - this.isBiasCorrected = biasCorrected; - } - - /** - * {@inheritDoc} - */ - @Override - public Variance copy() { - Variance result = new Variance(); - // No try-catch or advertised exception because parameters are guaranteed non-null - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source Variance to copy - * @param dest Variance to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(Variance source, Variance dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - dest.moment = source.moment.copy(); - dest.isBiasCorrected = source.isBiasCorrected; - dest.incMoment = source.incMoment; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/VectorialCovariance.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/VectorialCovariance.java deleted file mode 100644 index cf2752264..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/VectorialCovariance.java +++ /dev/null @@ -1,157 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.moment; - -import java.io.Serializable; -import java.util.Arrays; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.linear.MatrixUtils; -import org.apache.commons.math4.linear.RealMatrix; - -/** - * Returns the covariance matrix of the available vectors. - * @since 1.2 - */ -public class VectorialCovariance implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 4118372414238930270L; - - /** Sums for each component. */ - private final double[] sums; - - /** Sums of products for each component. */ - private final double[] productsSums; - - /** Indicator for bias correction. */ - private final boolean isBiasCorrected; - - /** Number of vectors in the sample. */ - private long n; - - /** Constructs a VectorialCovariance. - * @param dimension vectors dimension - * @param isBiasCorrected if true, computed the unbiased sample covariance, - * otherwise computes the biased population covariance - */ - public VectorialCovariance(int dimension, boolean isBiasCorrected) { - sums = new double[dimension]; - productsSums = new double[dimension * (dimension + 1) / 2]; - n = 0; - this.isBiasCorrected = isBiasCorrected; - } - - /** - * Add a new vector to the sample. - * @param v vector to add - * @throws DimensionMismatchException if the vector does not have the right dimension - */ - public void increment(double[] v) throws DimensionMismatchException { - if (v.length != sums.length) { - throw new DimensionMismatchException(v.length, sums.length); - } - int k = 0; - for (int i = 0; i < v.length; ++i) { - sums[i] += v[i]; - for (int j = 0; j <= i; ++j) { - productsSums[k++] += v[i] * v[j]; - } - } - n++; - } - - /** - * Get the covariance matrix. - * @return covariance matrix - */ - public RealMatrix getResult() { - - int dimension = sums.length; - RealMatrix result = MatrixUtils.createRealMatrix(dimension, dimension); - - if (n > 1) { - double c = 1.0 / (n * (isBiasCorrected ? (n - 1) : n)); - int k = 0; - for (int i = 0; i < dimension; ++i) { - for (int j = 0; j <= i; ++j) { - double e = c * (n * productsSums[k++] - sums[i] * sums[j]); - result.setEntry(i, j, e); - result.setEntry(j, i, e); - } - } - } - - return result; - - } - - /** - * Get the number of vectors in the sample. - * @return number of vectors in the sample - */ - public long getN() { - return n; - } - - /** - * Clears the internal state of the Statistic - */ - public void clear() { - n = 0; - Arrays.fill(sums, 0.0); - Arrays.fill(productsSums, 0.0); - } - - /** {@inheritDoc} */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (isBiasCorrected ? 1231 : 1237); - result = prime * result + (int) (n ^ (n >>> 32)); - result = prime * result + Arrays.hashCode(productsSums); - result = prime * result + Arrays.hashCode(sums); - return result; - } - - /** {@inheritDoc} */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof VectorialCovariance)) { - return false; - } - VectorialCovariance other = (VectorialCovariance) obj; - if (isBiasCorrected != other.isBiasCorrected) { - return false; - } - if (n != other.n) { - return false; - } - if (!Arrays.equals(productsSums, other.productsSums)) { - return false; - } - if (!Arrays.equals(sums, other.sums)) { - return false; - } - return true; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/VectorialMean.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/VectorialMean.java deleted file mode 100644 index cdc5a26a2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/VectorialMean.java +++ /dev/null @@ -1,105 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.moment; - -import java.io.Serializable; -import java.util.Arrays; - -import org.apache.commons.math4.exception.DimensionMismatchException; - -/** - * Returns the arithmetic mean of the available vectors. - * @since 1.2 - */ -public class VectorialMean implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 8223009086481006892L; - - /** Means for each component. */ - private final Mean[] means; - - /** Constructs a VectorialMean. - * @param dimension vectors dimension - */ - public VectorialMean(int dimension) { - means = new Mean[dimension]; - for (int i = 0; i < dimension; ++i) { - means[i] = new Mean(); - } - } - - /** - * Add a new vector to the sample. - * @param v vector to add - * @throws DimensionMismatchException if the vector does not have the right dimension - */ - public void increment(double[] v) throws DimensionMismatchException { - if (v.length != means.length) { - throw new DimensionMismatchException(v.length, means.length); - } - for (int i = 0; i < v.length; ++i) { - means[i].increment(v[i]); - } - } - - /** - * Get the mean vector. - * @return mean vector - */ - public double[] getResult() { - double[] result = new double[means.length]; - for (int i = 0; i < result.length; ++i) { - result[i] = means[i].getResult(); - } - return result; - } - - /** - * Get the number of vectors in the sample. - * @return number of vectors in the sample - */ - public long getN() { - return (means.length == 0) ? 0 : means[0].getN(); - } - - /** {@inheritDoc} */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + Arrays.hashCode(means); - return result; - } - - /** {@inheritDoc} */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof VectorialMean)) { - return false; - } - VectorialMean other = (VectorialMean) obj; - if (!Arrays.equals(means, other.means)) { - return false; - } - return true; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/package-info.java deleted file mode 100644 index 48d3ef1be..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/moment/package-info.java +++ /dev/null @@ -1,20 +0,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. - */ -/** - * Summary statistics based on moments. - */ -package org.apache.commons.math4.stat.descriptive.moment; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/package-info.java deleted file mode 100644 index 37397a4e7..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/package-info.java +++ /dev/null @@ -1,44 +0,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. - */ -/** - * - * Generic univariate summary statistic objects. - * - *

UnivariateStatistic API Usage Examples:

- * - *

UnivariateStatistic:

- * /∗ evaluation approach ∗/
- * double[] values = new double[] { 1, 2, 3, 4, 5 };
- * UnivariateStatistic stat = new Mean();
- * out.println("mean = " + stat.evaluate(values));
- *
- * - *

StorelessUnivariateStatistic:

- * /∗ incremental approach ∗/
- * double[] values = new double[] { 1, 2, 3, 4, 5 };
- * StorelessUnivariateStatistic stat = new Mean();
- * out.println("mean before adding a value is NaN = " + stat.getResult());
- * for (int i = 0; i < values.length; i++) {
- *     stat.increment(values[i]);
- *     out.println("current mean = " + stat2.getResult());
- * }
- * stat.clear();
- * out.println("mean after clear is NaN = " + stat.getResult()); - *
- * - */ -package org.apache.commons.math4.stat.descriptive; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/Max.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/Max.java deleted file mode 100644 index 1615003b5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/Max.java +++ /dev/null @@ -1,170 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.rank; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.stat.descriptive.AbstractStorelessUnivariateStatistic; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - -/** - * Returns the maximum of the available values. - *
    - *
  • The result is NaN iff all values are NaN - * (i.e. NaN values have no impact on the value of the statistic).
  • - *
  • If any of the values equals Double.POSITIVE_INFINITY, - * the result is Double.POSITIVE_INFINITY.
  • - *
-*

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally.

- */ -public class Max extends AbstractStorelessUnivariateStatistic implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /** Number of values that have been added */ - private long n; - - /** Current value of the statistic */ - private double value; - - /** - * Create a Max instance. - */ - public Max() { - n = 0; - value = Double.NaN; - } - - /** - * Copy constructor, creates a new {@code Max} identical - * to the {@code original}. - * - * @param original the {@code Max} instance to copy - * @throws NullArgumentException if original is null - */ - public Max(Max original) throws NullArgumentException { - copy(original, this); - } - - /** - * {@inheritDoc} - */ - @Override - public void increment(final double d) { - if (d > value || Double.isNaN(value)) { - value = d; - } - n++; - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - value = Double.NaN; - n = 0; - } - - /** - * {@inheritDoc} - */ - @Override - public double getResult() { - return value; - } - - /** - * {@inheritDoc} - */ - @Override - public long getN() { - return n; - } - - /** - * Returns the maximum of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray - * is empty. - *

- * Throws MathIllegalArgumentException if the array is null or - * the array index parameters are not valid.

- *
    - *
  • The result is NaN iff all values are NaN - * (i.e. NaN values have no impact on the value of the statistic).
  • - *
  • If any of the values equals Double.POSITIVE_INFINITY, - * the result is Double.POSITIVE_INFINITY.
  • - *
- * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the maximum of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - @Override - public double evaluate(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - - double max = Double.NaN; - if (MathArrays.verifyValues(values, begin, length)) { - max = values[begin]; - for (int i = begin; i < begin + length; i++) { - if (!Double.isNaN(values[i])) { - max = (max > values[i]) ? max : values[i]; - } - } - } - return max; - } - - /** - * {@inheritDoc} - */ - @Override - public Max copy() { - Max result = new Max(); - // No try-catch or advertised exception because args are non-null - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source Max to copy - * @param dest Max to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(Max source, Max dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - dest.n = source.n; - dest.value = source.value; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/Median.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/Median.java deleted file mode 100644 index d2a62cc7c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/Median.java +++ /dev/null @@ -1,96 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.rank; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.stat.ranking.NaNStrategy; -import org.apache.commons.math4.util.KthSelector; - - -/** - * Returns the median of the available values. This is the same as the 50th percentile. - * See {@link Percentile} for a description of the algorithm used. - *

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally.

- */ -public class Median extends Percentile implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /** Fixed quantile. */ - private static final double FIXED_QUANTILE_50 = 50.0; - - /** - * Default constructor. - */ - public Median() { - // No try-catch or advertised exception - arg is valid - super(FIXED_QUANTILE_50); - } - - /** - * Copy constructor, creates a new {@code Median} identical - * to the {@code original} - * - * @param original the {@code Median} instance to copy - * @throws NullArgumentException if original is null - */ - public Median(Median original) throws NullArgumentException { - super(original); - } - - /** - * Constructs a Median with the specific {@link EstimationType}, {@link NaNStrategy} and {@link PivotingStrategy}. - * - * @param estimationType one of the percentile {@link EstimationType estimation types} - * @param nanStrategy one of {@link NaNStrategy} to handle with NaNs - * @param kthSelector {@link KthSelector} to use for pivoting during search - * @throws MathIllegalArgumentException if p is not within (0,100] - * @throws NullArgumentException if type or NaNStrategy passed is null - */ - private Median(final EstimationType estimationType, final NaNStrategy nanStrategy, - final KthSelector kthSelector) - throws MathIllegalArgumentException { - super(FIXED_QUANTILE_50, estimationType, nanStrategy, kthSelector); - } - - /** {@inheritDoc} */ - @Override - public Median withEstimationType(final EstimationType newEstimationType) { - return new Median(newEstimationType, getNaNStrategy(), getKthSelector()); - } - - /** {@inheritDoc} */ - @Override - public Median withNaNStrategy(final NaNStrategy newNaNStrategy) { - return new Median(getEstimationType(), newNaNStrategy, getKthSelector()); - } - - /** {@inheritDoc} */ - @Override - public Median withKthSelector(final KthSelector newKthSelector) { - return new Median(getEstimationType(), getNaNStrategy(), newKthSelector); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/Min.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/Min.java deleted file mode 100644 index 479a1f761..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/Min.java +++ /dev/null @@ -1,170 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.rank; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.stat.descriptive.AbstractStorelessUnivariateStatistic; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - -/** - * Returns the minimum of the available values. - *
    - *
  • The result is NaN iff all values are NaN - * (i.e. NaN values have no impact on the value of the statistic).
  • - *
  • If any of the values equals Double.NEGATIVE_INFINITY, - * the result is Double.NEGATIVE_INFINITY.
  • - *
- *

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally.

- */ -public class Min extends AbstractStorelessUnivariateStatistic implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /**Number of values that have been added */ - private long n; - - /**Current value of the statistic */ - private double value; - - /** - * Create a Min instance. - */ - public Min() { - n = 0; - value = Double.NaN; - } - - /** - * Copy constructor, creates a new {@code Min} identical - * to the {@code original}. - * - * @param original the {@code Min} instance to copy - * @throws NullArgumentException if original is null - */ - public Min(Min original) throws NullArgumentException { - copy(original, this); - } - - /** - * {@inheritDoc} - */ - @Override - public void increment(final double d) { - if (d < value || Double.isNaN(value)) { - value = d; - } - n++; - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - value = Double.NaN; - n = 0; - } - - /** - * {@inheritDoc} - */ - @Override - public double getResult() { - return value; - } - - /** - * {@inheritDoc} - */ - @Override - public long getN() { - return n; - } - - /** - * Returns the minimum of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray - * is empty. - *

- * Throws MathIllegalArgumentException if the array is null or - * the array index parameters are not valid.

- *
    - *
  • The result is NaN iff all values are NaN - * (i.e. NaN values have no impact on the value of the statistic).
  • - *
  • If any of the values equals Double.NEGATIVE_INFINITY, - * the result is Double.NEGATIVE_INFINITY.
  • - *
- * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the minimum of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - @Override - public double evaluate(final double[] values,final int begin, final int length) - throws MathIllegalArgumentException { - - double min = Double.NaN; - if (MathArrays.verifyValues(values, begin, length)) { - min = values[begin]; - for (int i = begin; i < begin + length; i++) { - if (!Double.isNaN(values[i])) { - min = (min < values[i]) ? min : values[i]; - } - } - } - return min; - } - - /** - * {@inheritDoc} - */ - @Override - public Min copy() { - Min result = new Min(); - // No try-catch or advertised exception - args are non-null - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source Min to copy - * @param dest Min to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(Min source, Min dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - dest.n = source.n; - dest.value = source.value; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/PSquarePercentile.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/PSquarePercentile.java deleted file mode 100644 index 4a027c6c2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/PSquarePercentile.java +++ /dev/null @@ -1,990 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.rank; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.Serializable; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.apache.commons.math4.analysis.UnivariateFunction; -import org.apache.commons.math4.analysis.interpolation.LinearInterpolator; -import org.apache.commons.math4.analysis.interpolation.NevilleInterpolator; -import org.apache.commons.math4.analysis.interpolation.UnivariateInterpolator; -import org.apache.commons.math4.exception.InsufficientDataException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.stat.descriptive.AbstractStorelessUnivariateStatistic; -import org.apache.commons.math4.stat.descriptive.StorelessUnivariateStatistic; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; -import org.apache.commons.numbers.core.Precision; - -/** - * A {@link StorelessUnivariateStatistic} estimating percentiles using the - * P2 - * Algorithm as explained by Raj - * Jain and Imrich Chlamtac in - * P2 Algorithm - * for Dynamic Calculation of Quantiles and Histogram Without Storing - * Observations. - *

- * Note: This implementation is not synchronized and produces an approximate - * result. For small samples, where data can be stored and processed in memory, - * {@link Percentile} should be used.

- */ -public class PSquarePercentile extends AbstractStorelessUnivariateStatistic - implements StorelessUnivariateStatistic, Serializable { - - /** - * The maximum array size used for psquare algorithm - */ - private static final int PSQUARE_CONSTANT = 5; - - /** - * A Default quantile needed in case if user prefers to use default no - * argument constructor. - */ - private static final double DEFAULT_QUANTILE_DESIRED = 50d; - - /** - * Serial ID - */ - private static final long serialVersionUID = 20150412L; - - /** - * A decimal formatter for print convenience - */ - private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("00.00"); - - /** - * Initial list of 5 numbers corresponding to 5 markers. NOTE:watch - * out for the add methods that are overloaded - */ - private final List initialFive = new FixedCapacityList<>(PSQUARE_CONSTANT); - - /** - * The quantile needed should be in range of 0-1. The constructor - * {@link #PSquarePercentile(double)} ensures that passed in percentile is - * divided by 100. - */ - private final double quantile; - - /** - * lastObservation is the last observation value/input sample. No need to - * serialize - */ - private transient double lastObservation; - - /** - * Markers is the marker collection object which comes to effect - * only after 5 values are inserted - */ - private PSquareMarkers markers = null; - - /** - * Computed p value (i,e percentile value of data set hither to received) - */ - private double pValue = Double.NaN; - - /** - * Counter to count the values/observations accepted into this data set - */ - private long countOfObservations; - - /** - * Constructs a PSquarePercentile with the specific percentile value. - * @param p the percentile - * @throws OutOfRangeException if p is not greater than 0 and less - * than or equal to 100 - */ - public PSquarePercentile(final double p) { - if (p > 100 || p < 0) { - throw new OutOfRangeException(LocalizedFormats.OUT_OF_RANGE, p, 0, 100); - } - this.quantile = p / 100d;// always set it within (0,1] - } - - /** - * Default constructor that assumes a {@link #DEFAULT_QUANTILE_DESIRED - * default quantile} needed. - */ - PSquarePercentile() { - this(DEFAULT_QUANTILE_DESIRED); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - double result = getResult(); - result = Double.isNaN(result) ? 37 : result; - final double markersHash = markers == null ? 0 : markers.hashCode(); - final double[] toHash = {result, quantile, markersHash, countOfObservations}; - return Arrays.hashCode(toHash); - } - - /** - * Returns true iff {@code o} is a {@code PSquarePercentile} returning the - * same values as this for {@code getResult()} and {@code getN()} and also - * having equal markers - * - * @param o object to compare - * @return true if {@code o} is a {@code PSquarePercentile} with - * equivalent internal state - */ - @Override - public boolean equals(Object o) { - boolean result = false; - if (this == o) { - result = true; - } else if (o instanceof PSquarePercentile) { - PSquarePercentile that = (PSquarePercentile) o; - boolean isNotNull = markers != null && that.markers != null; - boolean isNull = markers == null && that.markers == null; - result = isNotNull ? markers.equals(that.markers) : isNull; - // markers as in the case of first - // five observations - result = result && getN() == that.getN(); - } - return result; - } - - /** - * {@inheritDoc}The internal state updated due to the new value in this - * context is basically of the marker positions and computation of the - * approximate quantile. - * - * @param observation the observation currently being added. - */ - @Override - public void increment(final double observation) { - // Increment counter - countOfObservations++; - - // Store last observation - this.lastObservation = observation; - - // 0. Use Brute force for <5 - if (markers == null) { - if (initialFive.add(observation)) { - Collections.sort(initialFive); - pValue = - initialFive - .get((int) (quantile * (initialFive.size() - 1))); - return; - } - // 1. Initialize once after 5th observation - markers = newMarkers(initialFive, quantile); - } - // 2. process a Data Point and return pValue - pValue = markers.processDataPoint(observation); - } - - /** - * Returns a string containing the last observation, the current estimate - * of the quantile and all markers. - * - * @return string representation of state data - */ - @Override - public String toString() { - - if (markers == null) { - return String.format("obs=%s pValue=%s", - DECIMAL_FORMAT.format(lastObservation), - DECIMAL_FORMAT.format(pValue)); - } else { - return String.format("obs=%s markers=%s", - DECIMAL_FORMAT.format(lastObservation), markers.toString()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public long getN() { - return countOfObservations; - } - - /** - * {@inheritDoc} - */ - @Override - public StorelessUnivariateStatistic copy() { - // multiply quantile by 100 now as anyway constructor divides it by 100 - PSquarePercentile copy = new PSquarePercentile(100d * quantile); - - if (markers != null) { - copy.markers = (PSquareMarkers) markers.clone(); - } - copy.countOfObservations = countOfObservations; - copy.pValue = pValue; - copy.initialFive.clear(); - copy.initialFive.addAll(initialFive); - return copy; - } - - /** - * Returns the quantile estimated by this statistic in the range [0.0-1.0] - * - * @return quantile estimated by {@link #getResult()} - */ - public double quantile() { - return quantile; - } - - /** - * {@inheritDoc}. This basically clears all the markers, the - * initialFive list and sets countOfObservations to 0. - */ - @Override - public void clear() { - markers = null; - initialFive.clear(); - countOfObservations = 0L; - pValue = Double.NaN; - } - - /** - * {@inheritDoc} - */ - @Override - public double getResult() { - if (Double.compare(quantile, 1d) == 0) { - pValue = maximum(); - } else if (Double.compare(quantile, 0d) == 0) { - pValue = minimum(); - } - return pValue; - } - - /** - * @return maximum in the data set added to this statistic - */ - private double maximum() { - double val = Double.NaN; - if (markers != null) { - val = markers.height(PSQUARE_CONSTANT); - } else if (!initialFive.isEmpty()) { - val = initialFive.get(initialFive.size() - 1); - } - return val; - } - - /** - * @return minimum in the data set added to this statistic - */ - private double minimum() { - double val = Double.NaN; - if (markers != null) { - val = markers.height(1); - } else if (!initialFive.isEmpty()) { - val = initialFive.get(0); - } - return val; - } - - /** - * Markers is an encapsulation of the five markers/buckets as indicated in - * the original works. - */ - private static class Markers implements PSquareMarkers, Serializable { - /** - * Serial version id - */ - private static final long serialVersionUID = 1L; - - /** Low marker index */ - private static final int LOW = 2; - - /** High marker index */ - private static final int HIGH = 4; - - /** - * Array of 5+1 Markers (The first marker is dummy just so we - * can match the rest of indexes [1-5] indicated in the original works - * which follows unit based index) - */ - private final Marker[] markerArray; - - /** - * Kth cell belonging to [1-5] of the markerArray. No need for - * this to be serialized - */ - private transient int k = -1; - - /** - * Constructor - * - * @param theMarkerArray marker array to be used - */ - private Markers(final Marker[] theMarkerArray) { - MathUtils.checkNotNull(theMarkerArray); - markerArray = theMarkerArray; - for (int i = 1; i < PSQUARE_CONSTANT; i++) { - markerArray[i].previous(markerArray[i - 1]) - .next(markerArray[i + 1]).index(i); - } - markerArray[0].previous(markerArray[0]).next(markerArray[1]) - .index(0); - markerArray[5].previous(markerArray[4]).next(markerArray[5]) - .index(5); - } - - /** - * Constructor - * - * @param initialFive elements required to build Marker - * @param p quantile required to be computed - */ - private Markers(final List initialFive, final double p) { - this(createMarkerArray(initialFive, p)); - } - - /** - * Creates a marker array using initial five elements and a quantile - * - * @param initialFive list of initial five elements - * @param p the pth quantile - * @return Marker array - */ - private static Marker[] createMarkerArray( - final List initialFive, final double p) { - final int countObserved = - initialFive == null ? -1 : initialFive.size(); - if (countObserved < PSQUARE_CONSTANT) { - throw new InsufficientDataException( - LocalizedFormats.INSUFFICIENT_OBSERVED_POINTS_IN_SAMPLE, - countObserved, PSQUARE_CONSTANT); - } - Collections.sort(initialFive); - return new Marker[] { - new Marker(),// Null Marker - new Marker(initialFive.get(0), 1, 0, 1), - new Marker(initialFive.get(1), 1 + 2 * p, p / 2, 2), - new Marker(initialFive.get(2), 1 + 4 * p, p, 3), - new Marker(initialFive.get(3), 3 + 2 * p, (1 + p) / 2, 4), - new Marker(initialFive.get(4), 5, 1, 5) }; - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return Arrays.deepHashCode(markerArray); - } - - /** - * {@inheritDoc}.This equals method basically checks for marker array to - * be deep equals. - * - * @param o is the other object - * @return true if the object compares with this object are equivalent - */ - @Override - public boolean equals(Object o) { - boolean result = false; - if (this == o) { - result = true; - } else if (o instanceof Markers) { - Markers that = (Markers) o; - result = Arrays.deepEquals(markerArray, that.markerArray); - } - return result; - } - - /** - * Process a data point - * - * @param inputDataPoint is the data point passed - * @return computed percentile - */ - @Override - public double processDataPoint(final double inputDataPoint) { - - // 1. Find cell and update minima and maxima - final int kthCell = findCellAndUpdateMinMax(inputDataPoint); - - // 2. Increment positions - incrementPositions(1, kthCell + 1, 5); - - // 2a. Update desired position with increments - updateDesiredPositions(); - - // 3. Adjust heights of m[2-4] if necessary - adjustHeightsOfMarkers(); - - // 4. Return percentile - return getPercentileValue(); - } - - /** - * Returns the percentile computed thus far. - * - * @return height of mid point marker - */ - @Override - public double getPercentileValue() { - return height(3); - } - - /** - * Finds the cell where the input observation / value fits. - * - * @param observation the input value to be checked for - * @return kth cell (of the markers ranging from 1-5) where observed - * sample fits - */ - private int findCellAndUpdateMinMax(final double observation) { - k = -1; - if (observation < height(1)) { - markerArray[1].markerHeight = observation; - k = 1; - } else if (observation < height(2)) { - k = 1; - } else if (observation < height(3)) { - k = 2; - } else if (observation < height(4)) { - k = 3; - } else if (observation <= height(5)) { - k = 4; - } else { - markerArray[5].markerHeight = observation; - k = 4; - } - return k; - } - - /** - * Adjust marker heights by setting quantile estimates to middle markers. - */ - private void adjustHeightsOfMarkers() { - for (int i = LOW; i <= HIGH; i++) { - estimate(i); - } - } - - /** - * {@inheritDoc} - */ - @Override - public double estimate(final int index) { - if (index < LOW || index > HIGH) { - throw new OutOfRangeException(index, LOW, HIGH); - } - return markerArray[index].estimate(); - } - - /** - * Increment positions by d. Refer to algorithm paper for the - * definition of d. - * - * @param d The increment value for the position - * @param startIndex start index of the marker array - * @param endIndex end index of the marker array - */ - private void incrementPositions(final int d, final int startIndex, - final int endIndex) { - for (int i = startIndex; i <= endIndex; i++) { - markerArray[i].incrementPosition(d); - } - } - - /** - * Desired positions incremented by bucket width. The bucket width is - * basically the desired increments. - */ - private void updateDesiredPositions() { - for (int i = 1; i < markerArray.length; i++) { - markerArray[i].updateDesiredPosition(); - } - } - - /** - * Sets previous and next markers after default read is done. - * - * @param anInputStream the input stream to be deserialized - * @throws ClassNotFoundException thrown when a desired class not found - * @throws IOException thrown due to any io errors - */ - private void readObject(ObjectInputStream anInputStream) - throws ClassNotFoundException, IOException { - // always perform the default de-serialization first - anInputStream.defaultReadObject(); - // Build links - for (int i = 1; i < PSQUARE_CONSTANT; i++) { - markerArray[i].previous(markerArray[i - 1]).next(markerArray[i + 1]).index(i); - } - markerArray[0].previous(markerArray[0]).next(markerArray[1]).index(0); - markerArray[5].previous(markerArray[4]).next(markerArray[5]).index(5); - } - - /** - * Return marker height given index - * - * @param markerIndex index of marker within (1,6) - * @return marker height - */ - @Override - public double height(final int markerIndex) { - if (markerIndex >= markerArray.length || markerIndex <= 0) { - throw new OutOfRangeException(markerIndex, 1, markerArray.length); - } - return markerArray[markerIndex].markerHeight; - } - - /** - * {@inheritDoc}.Clone Markers - * - * @return cloned object - */ - @Override - public Object clone() { - return new Markers(new Marker[] { new Marker(), - (Marker) markerArray[1].clone(), - (Marker) markerArray[2].clone(), - (Marker) markerArray[3].clone(), - (Marker) markerArray[4].clone(), - (Marker) markerArray[5].clone() }); - - } - - /** - * Returns string representation of the Marker array. - * - * @return Markers as a string - */ - @Override - public String toString() { - return String.format("m1=[%s],m2=[%s],m3=[%s],m4=[%s],m5=[%s]", - markerArray[1].toString(), markerArray[2].toString(), - markerArray[3].toString(), markerArray[4].toString(), - markerArray[5].toString()); - } - - } - - /** - * The class modeling the attributes of the marker of the P-square algorithm - */ - private static class Marker implements Serializable, Cloneable { - - /** - * Serial Version ID - */ - private static final long serialVersionUID = -3575879478288538431L; - - /** - * The marker index which is just a serial number for the marker in the - * marker array of 5+1. - */ - private int index; - - /** - * The integral marker position. Refer to the variable n in the original - * works. - */ - private double intMarkerPosition; - - /** - * Desired marker position. Refer to the variable n' in the original - * works. - */ - private double desiredMarkerPosition; - - /** - * Marker height or the quantile. Refer to the variable q in the - * original works. - */ - private double markerHeight; - - /** - * Desired marker increment. Refer to the variable dn' in the original - * works. - */ - private double desiredMarkerIncrement; - - /** - * Next and previous markers for easy linked navigation in loops. this - * is not serialized as they can be rebuilt during deserialization. - */ - private transient Marker next; - - /** - * The previous marker links - */ - private transient Marker previous; - - /** - * Nonlinear interpolator - */ - private final UnivariateInterpolator nonLinear = new NevilleInterpolator(); - - /** - * Linear interpolator which is not serializable - */ - private transient UnivariateInterpolator linear = new LinearInterpolator(); - - /** - * Default constructor - */ - private Marker() { - this.next = this.previous = this; - } - - /** - * Constructor of the marker with parameters - * - * @param heightOfMarker represent the quantile value - * @param makerPositionDesired represent the desired marker position - * @param markerPositionIncrement represent increments for position - * @param markerPositionNumber represent the position number of marker - */ - private Marker(double heightOfMarker, double makerPositionDesired, - double markerPositionIncrement, double markerPositionNumber) { - this(); - this.markerHeight = heightOfMarker; - this.desiredMarkerPosition = makerPositionDesired; - this.desiredMarkerIncrement = markerPositionIncrement; - this.intMarkerPosition = markerPositionNumber; - } - - /** - * Sets the previous marker. - * - * @param previousMarker the previous marker to the current marker in - * the array of markers - * @return this instance - */ - private Marker previous(final Marker previousMarker) { - MathUtils.checkNotNull(previousMarker); - this.previous = previousMarker; - return this; - } - - /** - * Sets the next marker. - * - * @param nextMarker the next marker to the current marker in the array - * of markers - * @return this instance - */ - private Marker next(final Marker nextMarker) { - MathUtils.checkNotNull(nextMarker); - this.next = nextMarker; - return this; - } - - /** - * Sets the index of the marker. - * - * @param indexOfMarker the array index of the marker in marker array - * @return this instance - */ - private Marker index(final int indexOfMarker) { - this.index = indexOfMarker; - return this; - } - - /** - * Update desired Position with increment. - */ - private void updateDesiredPosition() { - desiredMarkerPosition += desiredMarkerIncrement; - } - - /** - * Increment Position by d. - * - * @param d a delta value to increment - */ - private void incrementPosition(final int d) { - intMarkerPosition += d; - } - - /** - * Difference between desired and actual position - * - * @return difference between desired and actual position - */ - private double difference() { - return desiredMarkerPosition - intMarkerPosition; - } - - /** - * Estimate the quantile for the current marker. - * - * @return estimated quantile - */ - private double estimate() { - final double di = difference(); - final boolean isNextHigher = - next.intMarkerPosition - intMarkerPosition > 1; - final boolean isPreviousLower = - previous.intMarkerPosition - intMarkerPosition < -1; - - if (di >= 1 && isNextHigher || di <= -1 && isPreviousLower) { - final int d = di >= 0 ? 1 : -1; - final double[] xval = - new double[] { previous.intMarkerPosition, - intMarkerPosition, next.intMarkerPosition }; - final double[] yval = - new double[] { previous.markerHeight, markerHeight, - next.markerHeight }; - final double xD = intMarkerPosition + d; - - UnivariateFunction univariateFunction = - nonLinear.interpolate(xval, yval); - markerHeight = univariateFunction.value(xD); - - // If parabolic estimate is bad then turn linear - if (isEstimateBad(yval, markerHeight)) { - int delta = xD - xval[1] > 0 ? 1 : -1; - final double[] xBad = - new double[] { xval[1], xval[1 + delta] }; - final double[] yBad = - new double[] { yval[1], yval[1 + delta] }; - MathArrays.sortInPlace(xBad, yBad);// since d can be +/- 1 - univariateFunction = linear.interpolate(xBad, yBad); - markerHeight = univariateFunction.value(xD); - } - incrementPosition(d); - } - return markerHeight; - } - - /** - * Check if parabolic/nonlinear estimate is bad by checking if the - * ordinate found is beyond the y[0] and y[2]. - * - * @param y the array to get the bounds - * @param yD the estimate - * @return true if yD is a bad estimate - */ - private boolean isEstimateBad(final double[] y, final double yD) { - return yD <= y[0] || yD >= y[2]; - } - - /** - * {@inheritDoc}This equals method checks for marker attributes and - * as well checks if navigation pointers (next and previous) are the same - * between this and passed in object - * - * @param o Other object - * @return true if this equals passed in other object o - */ - @Override - public boolean equals(Object o) { - boolean result = false; - if (this == o) { - result = true; - } else if (o instanceof Marker) { - Marker that = (Marker) o; - - result = Double.compare(markerHeight, that.markerHeight) == 0; - result = - result && - Double.compare(intMarkerPosition, - that.intMarkerPosition) == 0; - result = - result && - Double.compare(desiredMarkerPosition, - that.desiredMarkerPosition) == 0; - result = - result && - Double.compare(desiredMarkerIncrement, - that.desiredMarkerIncrement) == 0; - - result = result && next.index == that.next.index; - result = result && previous.index == that.previous.index; - } - return result; - } - - /** {@inheritDoc} */ - @Override - public int hashCode() { - return Arrays.hashCode(new double[] {markerHeight, intMarkerPosition, - desiredMarkerIncrement, desiredMarkerPosition, previous.index, next.index}); - } - - /** - * Read Object to deserialize. - * - * @param anInstream Stream Object data - * @throws IOException thrown for IO Errors - * @throws ClassNotFoundException thrown for class not being found - */ - private void readObject(ObjectInputStream anInstream) - throws ClassNotFoundException, IOException { - anInstream.defaultReadObject(); - previous=next=this; - linear = new LinearInterpolator(); - } - - /** - * Clone this instance. - * - * @return cloned marker - */ - @Override - public Object clone() { - return new Marker(markerHeight, desiredMarkerPosition, desiredMarkerIncrement, intMarkerPosition); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return String.format( - "index=%.0f,n=%.0f,np=%.2f,q=%.2f,dn=%.2f,prev=%d,next=%d", - (double) index, Precision.round(intMarkerPosition, 0), - Precision.round(desiredMarkerPosition, 2), - Precision.round(markerHeight, 2), - Precision.round(desiredMarkerIncrement, 2), previous.index, - next.index); - } - } - - /** - * A simple fixed capacity list that has an upper bound to growth. - * Once its capacity is reached, {@code add} is a no-op, returning - * {@code false}. - * - * @param type for fixed capacity list - */ - private static class FixedCapacityList extends ArrayList implements Serializable { - - /** - * Serialization Version Id - */ - private static final long serialVersionUID = 2283952083075725479L; - /** - * Capacity of the list - */ - private final int capacity; - - /** - * This constructor constructs the list with given capacity and as well - * as stores the capacity - * - * @param fixedCapacity the capacity to be fixed for this list - */ - FixedCapacityList(final int fixedCapacity) { - super(fixedCapacity); - this.capacity = fixedCapacity; - } - - /** - * {@inheritDoc} In addition it checks if the {@link #size()} returns a - * size that is within capacity and if true it adds; otherwise the list - * contents are unchanged and {@code false} is returned. - * - * @return true if addition is successful and false otherwise - */ - @Override - public boolean add(final E e) { - return size() < capacity ? super.add(e) : false; - } - - /** - * {@inheritDoc} In addition it checks if the sum of Collection size and - * this instance's {@link #size()} returns a value that is within - * capacity and if true it adds the collection; otherwise the list - * contents are unchanged and {@code false} is returned. - * - * @return true if addition is successful and false otherwise - */ - @Override - public boolean addAll(Collection collection) { - boolean isCollectionLess = - collection != null && - collection.size() + size() <= capacity; - return isCollectionLess ? super.addAll(collection) : false; - } - } - - /** - * A creation method to build Markers - * - * @param initialFive list of initial five elements - * @param p the quantile desired - * @return an instance of PSquareMarkers - */ - public static PSquareMarkers newMarkers(final List initialFive, final double p) { - return new Markers(initialFive, p); - } - - /** - * An interface that encapsulates abstractions of the - * P-square algorithm markers as is explained in the original works. This - * interface is exposed with protected access to help in testability. - */ - protected interface PSquareMarkers extends Cloneable { - /** - * Returns Percentile value computed thus far. - * - * @return percentile - */ - double getPercentileValue(); - - /** - * A clone function to clone the current instance. It's created as an - * interface method as well for convenience though Cloneable is just a - * marker interface. - * - * @return clone of this instance - */ - Object clone(); - - /** - * Returns the marker height (or percentile) of a given marker index. - * - * @param markerIndex is the index of marker in the marker array - * @return percentile value of the marker index passed - * @throws OutOfRangeException in case the index is not within [1-5] - */ - double height(final int markerIndex); - - /** - * Process a data point by moving the marker heights based on estimator. - * - * @param inputDataPoint is the data point passed - * @return computed percentile - */ - double processDataPoint(final double inputDataPoint); - - /** - * An Estimate of the percentile value of a given Marker - * - * @param index the marker's index in the array of markers - * @return percentile estimate - * @throws OutOfRangeException in case if index is not within [1-5] - */ - double estimate(final int index); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/Percentile.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/Percentile.java deleted file mode 100644 index 4c1563725..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/Percentile.java +++ /dev/null @@ -1,1028 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.rank; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.BitSet; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.stat.descriptive.AbstractUnivariateStatistic; -import org.apache.commons.math4.stat.ranking.NaNStrategy; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.KthSelector; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; -import org.apache.commons.math4.util.MedianOf3PivotingStrategy; -import org.apache.commons.math4.util.PivotingStrategyInterface; -import org.apache.commons.numbers.core.Precision; - -/** - * Provides percentile computation. - *

- * There are several commonly used methods for estimating percentiles (a.k.a. - * quantiles) based on sample data. For large samples, the different methods - * agree closely, but when sample sizes are small, different methods will give - * significantly different results. The algorithm implemented here works as follows: - *

    - *
  1. Let n be the length of the (sorted) array and - * 0 < p <= 100 be the desired percentile.
  2. - *
  3. If n = 1 return the unique array element (regardless of - * the value of p); otherwise
  4. - *
  5. Compute the estimated percentile position - * pos = p * (n + 1) / 100 and the difference, d - * between pos and floor(pos) (i.e. the fractional - * part of pos).
  6. - *
  7. If pos < 1 return the smallest element in the array.
  8. - *
  9. Else if pos >= n return the largest element in the array.
  10. - *
  11. Else let lower be the element in position - * floor(pos) in the array and let upper be the - * next element in the array. Return lower + d * (upper - lower) - *
  12. - *
- *

- * To compute percentiles, the data must be at least partially ordered. Input - * arrays are copied and recursively partitioned using an ordering definition. - * The ordering used by Arrays.sort(double[]) is the one determined - * by {@link Double#compareTo(Double)}. This ordering makes - * Double.NaN larger than any other value (including - * Double.POSITIVE_INFINITY). Therefore, for example, the median - * (50th percentile) of - * {0, 1, 2, 3, 4, Double.NaN} evaluates to 2.5.

- *

- * Since percentile estimation usually involves interpolation between array - * elements, arrays containing NaN or infinite values will often - * result in NaN or infinite values returned.

- *

- * Further, to include different estimation types such as R1, R2 as mentioned in - * Quantile page(wikipedia), - * a type specific NaN handling strategy is used to closely match with the - * typically observed results from popular tools like R(R1-R9), Excel(R7).

- *

- * Since 2.2, Percentile uses only selection instead of complete sorting - * and caches selection algorithm state between calls to the various - * {@code evaluate} methods. This greatly improves efficiency, both for a single - * percentile and multiple percentile computations. To maximize performance when - * multiple percentiles are computed based on the same data, users should set the - * data array once using either one of the {@link #evaluate(double[], double)} or - * {@link #setData(double[])} methods and thereafter {@link #evaluate(double)} - * with just the percentile provided. - *

- *

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally.

- */ -public class Percentile extends AbstractUnivariateStatistic implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /** Maximum number of partitioning pivots cached (each level double the number of pivots). */ - private static final int MAX_CACHED_LEVELS = 10; - - /** Maximum number of cached pivots in the pivots cached array */ - private static final int PIVOTS_HEAP_LENGTH = 0x1 << MAX_CACHED_LEVELS - 1; - - /** Default KthSelector used with default pivoting strategy */ - private final KthSelector kthSelector; - - /** Any of the {@link EstimationType}s such as {@link EstimationType#LEGACY CM} can be used. */ - private final EstimationType estimationType; - - /** NaN Handling of the input as defined by {@link NaNStrategy} */ - private final NaNStrategy nanStrategy; - - /** - * Determines what percentile is computed when evaluate() is activated - * with no quantile argument. - */ - private double quantile; - - /** Cached pivots. */ - private int[] cachedPivots; - - /** - * Constructs a Percentile with the following defaults. - *
    - *
  • default quantile: 50.0, can be reset with {@link #setQuantile(double)}
  • - *
  • default estimation type: {@link EstimationType#LEGACY}, - * can be reset with {@link #withEstimationType(EstimationType)}
  • - *
  • default NaN strategy: {@link NaNStrategy#REMOVED}, - * can be reset with {@link #withNaNStrategy(NaNStrategy)}
  • - *
  • a KthSelector that makes use of {@link MedianOf3PivotingStrategy}, - * can be reset with {@link #withKthSelector(KthSelector)}
  • - *
- */ - public Percentile() { - // No try-catch or advertised exception here - arg is valid - this(50.0); - } - - /** - * Constructs a Percentile with the specific quantile value and the following - *
    - *
  • default method type: {@link EstimationType#LEGACY}
  • - *
  • default NaN strategy: {@link NaNStrategy#REMOVED}
  • - *
  • a Kth Selector : {@link KthSelector}
  • - *
- * @param quantile the quantile - * @throws MathIllegalArgumentException if p is not greater than 0 and less - * than or equal to 100 - */ - public Percentile(final double quantile) throws MathIllegalArgumentException { - this(quantile, EstimationType.LEGACY, NaNStrategy.REMOVED, - new KthSelector(new MedianOf3PivotingStrategy())); - } - - /** - * Copy constructor, creates a new {@code Percentile} identical - * to the {@code original} - * - * @param original the {@code Percentile} instance to copy - * @throws NullArgumentException if original is null - */ - public Percentile(final Percentile original) throws NullArgumentException { - - MathUtils.checkNotNull(original); - estimationType = original.getEstimationType(); - nanStrategy = original.getNaNStrategy(); - kthSelector = original.getKthSelector(); - - setData(original.getDataRef()); - if (original.cachedPivots != null) { - System.arraycopy(original.cachedPivots, 0, cachedPivots, 0, original.cachedPivots.length); - } - setQuantile(original.quantile); - - } - - /** - * Constructs a Percentile with the specific quantile value, - * {@link EstimationType}, {@link NaNStrategy} and {@link KthSelector}. - * - * @param quantile the quantile to be computed - * @param estimationType one of the percentile {@link EstimationType estimation types} - * @param nanStrategy one of {@link NaNStrategy} to handle with NaNs - * @param kthSelector a {@link KthSelector} to use for pivoting during search - * @throws MathIllegalArgumentException if p is not within (0,100] - * @throws NullArgumentException if type or NaNStrategy passed is null - */ - protected Percentile(final double quantile, - final EstimationType estimationType, - final NaNStrategy nanStrategy, - final KthSelector kthSelector) - throws MathIllegalArgumentException { - setQuantile(quantile); - cachedPivots = null; - MathUtils.checkNotNull(estimationType); - MathUtils.checkNotNull(nanStrategy); - MathUtils.checkNotNull(kthSelector); - this.estimationType = estimationType; - this.nanStrategy = nanStrategy; - this.kthSelector = kthSelector; - } - - /** {@inheritDoc} */ - @Override - public void setData(final double[] values) { - if (values == null) { - cachedPivots = null; - } else { - cachedPivots = new int[PIVOTS_HEAP_LENGTH]; - Arrays.fill(cachedPivots, -1); - } - super.setData(values); - } - - /** {@inheritDoc} */ - @Override - public void setData(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - if (values == null) { - cachedPivots = null; - } else { - cachedPivots = new int[PIVOTS_HEAP_LENGTH]; - Arrays.fill(cachedPivots, -1); - } - super.setData(values, begin, length); - } - - /** - * Returns the result of evaluating the statistic over the stored data. - *

- * The stored array is the one which was set by previous calls to - * {@link #setData(double[])} - *

- * @param p the percentile value to compute - * @return the value of the statistic applied to the stored data - * @throws MathIllegalArgumentException if p is not a valid quantile value - * (p must be greater than 0 and less than or equal to 100) - */ - public double evaluate(final double p) throws MathIllegalArgumentException { - return evaluate(getDataRef(), p); - } - - /** - * Returns an estimate of the pth percentile of the values - * in the values array. - *

- * Calls to this method do not modify the internal quantile - * state of this statistic.

- *
    - *
  • Returns Double.NaN if values has length - * 0
  • - *
  • Returns (for any value of p) values[0] - * if values has length 1
  • - *
  • Throws MathIllegalArgumentException if values - * is null or p is not a valid quantile value (p must be greater than 0 - * and less than or equal to 100)
  • - *
- *

- * See {@link Percentile} for a description of the percentile estimation - * algorithm used.

- * - * @param values input array of values - * @param p the percentile value to compute - * @return the percentile value or Double.NaN if the array is empty - * @throws MathIllegalArgumentException if values is null or p is invalid - */ - public double evaluate(final double[] values, final double p) - throws MathIllegalArgumentException { - - MathArrays.verifyValues(values, 0, 0); - return evaluate(values, 0, values.length, p); - } - - /** - * Returns an estimate of the quantileth percentile of the - * designated values in the values array. The quantile - * estimated is determined by the quantile property. - *
    - *
  • Returns Double.NaN if length = 0
  • - *
  • Returns (for any value of quantile) - * values[begin] if length = 1
  • - *
  • Throws MathIllegalArgumentException if values - * is null, or start or length is invalid
  • - *
- *

- * See {@link Percentile} for a description of the percentile estimation - * algorithm used.

- * - * @param values the input array - * @param start index of the first array element to include - * @param length the number of elements to include - * @return the percentile value - * @throws MathIllegalArgumentException if the parameters are not valid - * - */ - @Override - public double evaluate(final double[] values, final int start, final int length) - throws MathIllegalArgumentException { - return evaluate(values, start, length, quantile); - } - - /** - * Returns an estimate of the pth percentile of the values - * in the values array, starting with the element in (0-based) - * position begin in the array and including length - * values. - *

- * Calls to this method do not modify the internal quantile - * state of this statistic.

- *
    - *
  • Returns Double.NaN if length = 0
  • - *
  • Returns (for any value of p) values[begin] - * if length = 1
  • - *
  • Throws MathIllegalArgumentException if values - * is null , begin or length is invalid, or - * p is not a valid quantile value (p must be greater than 0 - * and less than or equal to 100)
  • - *
- *

- * See {@link Percentile} for a description of the percentile estimation - * algorithm used.

- * - * @param values array of input values - * @param p the percentile to compute - * @param begin the first (0-based) element to include in the computation - * @param length the number of array elements to include - * @return the percentile value - * @throws MathIllegalArgumentException if the parameters are not valid or the - * input array is null - */ - public double evaluate(final double[] values, final int begin, - final int length, final double p) - throws MathIllegalArgumentException { - - MathArrays.verifyValues(values, begin, length); - if (p > 100 || p <= 0) { - throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUNDS_QUANTILE_VALUE, p, 0, 100); - } - if (length == 0) { - return Double.NaN; - } - if (length == 1) { - return values[begin]; // always return single value for n = 1 - } - - final double[] work = getWorkArray(values, begin, length); - final int[] pivotsHeap = getPivots(values); - return work.length == 0 ? Double.NaN : - estimationType.evaluate(work, pivotsHeap, p, kthSelector); - } - - /** - * Returns the value of the quantile field (determines what percentile is - * computed when evaluate() is called with no quantile argument). - * - * @return quantile set while construction or {@link #setQuantile(double)} - */ - public double getQuantile() { - return quantile; - } - - /** - * Sets the value of the quantile field (determines what percentile is - * computed when evaluate() is called with no quantile argument). - * - * @param p a value between 0 < p <= 100 - * @throws MathIllegalArgumentException if p is not greater than 0 and less - * than or equal to 100 - */ - public void setQuantile(final double p) throws MathIllegalArgumentException { - if (p <= 0 || p > 100) { - throw new OutOfRangeException( - LocalizedFormats.OUT_OF_BOUNDS_QUANTILE_VALUE, p, 0, 100); - } - quantile = p; - } - - /** - * {@inheritDoc} - */ - @Override - public Percentile copy() { - return new Percentile(this); - } - - /** - * Get the work array to operate. Makes use of prior {@code storedData} if - * it exists or else do a check on NaNs and copy a subset of the array - * defined by begin and length parameters. The set {@link #nanStrategy} will - * be used to either retain/remove/replace any NaNs present before returning - * the resultant array. - * - * @param values the array of numbers - * @param begin index to start reading the array - * @param length the length of array to be read from the begin index - * @return work array sliced from values in the range [begin,begin+length) - * @throws MathIllegalArgumentException if values or indices are invalid - */ - protected double[] getWorkArray(final double[] values, final int begin, final int length) { - final double[] work; - if (values == getDataRef()) { - work = getDataRef(); - } else { - switch (nanStrategy) { - case MAXIMAL:// Replace NaNs with +INFs - work = replaceAndSlice(values, begin, length, Double.NaN, Double.POSITIVE_INFINITY); - break; - case MINIMAL:// Replace NaNs with -INFs - work = replaceAndSlice(values, begin, length, Double.NaN, Double.NEGATIVE_INFINITY); - break; - case REMOVED:// Drop NaNs from data - work = removeAndSlice(values, begin, length, Double.NaN); - break; - case FAILED:// just throw exception as NaN is un-acceptable - work = copyOf(values, begin, length); - MathArrays.checkNotNaN(work); - break; - default: //FIXED - work = copyOf(values,begin,length); - break; - } - } - return work; - } - - /** - * Make a copy of the array for the slice defined by array part from - * [begin, begin+length) - * @param values the input array - * @param begin start index of the array to include - * @param length number of elements to include from begin - * @return copy of a slice of the original array - */ - private static double[] copyOf(final double[] values, final int begin, final int length) { - MathArrays.verifyValues(values, begin, length); - return MathArrays.copyOfRange(values, begin, begin + length); - } - - /** - * Replace every occurrence of a given value with a replacement value in a - * copied slice of array defined by array part from [begin, begin+length). - * @param values the input array - * @param begin start index of the array to include - * @param length number of elements to include from begin - * @param original the value to be replaced with - * @param replacement the value to be used for replacement - * @return the copy of sliced array with replaced values - */ - private static double[] replaceAndSlice(final double[] values, - final int begin, final int length, - final double original, - final double replacement) { - final double[] temp = copyOf(values, begin, length); - for(int i = 0; i < length; i++) { - temp[i] = Precision.equalsIncludingNaN(original, temp[i]) ? - replacement : temp[i]; - } - return temp; - } - - /** - * Remove the occurrence of a given value in a copied slice of array - * defined by the array part from [begin, begin+length). - * @param values the input array - * @param begin start index of the array to include - * @param length number of elements to include from begin - * @param removedValue the value to be removed from the sliced array - * @return the copy of the sliced array after removing the removedValue - */ - private static double[] removeAndSlice(final double[] values, - final int begin, final int length, - final double removedValue) { - MathArrays.verifyValues(values, begin, length); - final double[] temp; - //BitSet(length) to indicate where the removedValue is located - final BitSet bits = new BitSet(length); - for (int i = begin; i < begin+length; i++) { - if (Precision.equalsIncludingNaN(removedValue, values[i])) { - bits.set(i - begin); - } - } - //Check if empty then create a new copy - if (bits.isEmpty()) { - temp = copyOf(values, begin, length); // Nothing removed, just copy - } else if(bits.cardinality() == length) { - temp = new double[0]; // All removed, just empty - }else { // Some removable, so new - temp = new double[length - bits.cardinality()]; - int start = begin; //start index from source array (i.e values) - int dest = 0; //dest index in destination array(i.e temp) - int nextOne = -1; //nextOne is the index of bit set of next one - int bitSetPtr = 0; //bitSetPtr is start index pointer of bitset - while ((nextOne = bits.nextSetBit(bitSetPtr)) != -1) { - final int lengthToCopy = nextOne - bitSetPtr; - System.arraycopy(values, start, temp, dest, lengthToCopy); - dest += lengthToCopy; - start = begin + (bitSetPtr = bits.nextClearBit(nextOne)); - } - //Copy any residue past start index till begin+length - if (start < begin + length) { - System.arraycopy(values,start,temp,dest,begin + length - start); - } - } - return temp; - } - - /** - * Get pivots which is either cached or a newly created one - * - * @param values array containing the input numbers - * @return cached pivots or a newly created one - */ - private int[] getPivots(final double[] values) { - final int[] pivotsHeap; - if (values == getDataRef()) { - pivotsHeap = cachedPivots; - } else { - pivotsHeap = new int[PIVOTS_HEAP_LENGTH]; - Arrays.fill(pivotsHeap, -1); - } - return pivotsHeap; - } - - /** - * Get the estimation {@link EstimationType type} used for computation. - * - * @return the {@code estimationType} set - */ - public EstimationType getEstimationType() { - return estimationType; - } - - /** - * Build a new instance similar to the current one except for the - * {@link EstimationType estimation type}. - *

- * This method is intended to be used as part of a fluent-type builder - * pattern. Building finely tune instances should be done as follows: - *

- *
-     *   Percentile customized = new Percentile(quantile).
-     *                           withEstimationType(estimationType).
-     *                           withNaNStrategy(nanStrategy).
-     *                           withKthSelector(kthSelector);
-     * 
- *

- * If any of the {@code withXxx} method is omitted, the default value for - * the corresponding customization parameter will be used. - *

- * @param newEstimationType estimation type for the new instance - * @return a new instance, with changed estimation type - * @throws NullArgumentException when newEstimationType is null - */ - public Percentile withEstimationType(final EstimationType newEstimationType) { - return new Percentile(quantile, newEstimationType, nanStrategy, kthSelector); - } - - /** - * Get the {@link NaNStrategy NaN Handling} strategy used for computation. - * @return {@code NaN Handling} strategy set during construction - */ - public NaNStrategy getNaNStrategy() { - return nanStrategy; - } - - /** - * Build a new instance similar to the current one except for the - * {@link NaNStrategy NaN handling} strategy. - *

- * This method is intended to be used as part of a fluent-type builder - * pattern. Building finely tune instances should be done as follows: - *

- *
-     *   Percentile customized = new Percentile(quantile).
-     *                           withEstimationType(estimationType).
-     *                           withNaNStrategy(nanStrategy).
-     *                           withKthSelector(kthSelector);
-     * 
- *

- * If any of the {@code withXxx} method is omitted, the default value for - * the corresponding customization parameter will be used. - *

- * @param newNaNStrategy NaN strategy for the new instance - * @return a new instance, with changed NaN handling strategy - * @throws NullArgumentException when newNaNStrategy is null - */ - public Percentile withNaNStrategy(final NaNStrategy newNaNStrategy) { - return new Percentile(quantile, estimationType, newNaNStrategy, kthSelector); - } - - /** - * Get the {@link KthSelector kthSelector} used for computation. - * @return the {@code kthSelector} set - */ - public KthSelector getKthSelector() { - return kthSelector; - } - - /** - * Get the {@link PivotingStrategyInterface} used in KthSelector for computation. - * @return the pivoting strategy set - */ - public PivotingStrategyInterface getPivotingStrategy() { - return kthSelector.getPivotingStrategy(); - } - - /** - * Build a new instance similar to the current one except for the - * {@link KthSelector kthSelector} instance specifically set. - *

- * This method is intended to be used as part of a fluent-type builder - * pattern. Building finely tune instances should be done as follows: - *

- *
-     *   Percentile customized = new Percentile(quantile).
-     *                           withEstimationType(estimationType).
-     *                           withNaNStrategy(nanStrategy).
-     *                           withKthSelector(newKthSelector);
-     * 
- *

- * If any of the {@code withXxx} method is omitted, the default value for - * the corresponding customization parameter will be used. - *

- * @param newKthSelector KthSelector for the new instance - * @return a new instance, with changed KthSelector - * @throws NullArgumentException when newKthSelector is null - */ - public Percentile withKthSelector(final KthSelector newKthSelector) { - return new Percentile(quantile, estimationType, nanStrategy, newKthSelector); - } - - /** - * An enum for various estimation strategies of a percentile referred in - * wikipedia on quantile - * with the names of enum matching those of types mentioned in - * wikipedia. - *

- * Each enum corresponding to the specific type of estimation in wikipedia - * implements the respective formulae that specializes in the below aspects - *

    - *
  • An index method to calculate approximate index of the - * estimate
  • - *
  • An estimate method to estimate a value found at the earlier - * computed index
  • - *
  • A minLimit on the quantile for which first element of sorted - * input is returned as an estimate
  • - *
  • A maxLimit on the quantile for which last element of sorted - * input is returned as an estimate
  • - *
- *

- * Users can now create {@link Percentile} by explicitly passing this enum; - * such as by invoking {@link Percentile#withEstimationType(EstimationType)} - *

- * References: - *

    - *
  1. - * Wikipedia on quantile - *
  2. - *
  3. - * - * Hyndman, R. J. and Fan, Y. (1996) Sample quantiles in statistical - * packages, American Statistician 50, 361–365
  4. - *
  5. - * - * R-Manual
  6. - *
- */ - public enum EstimationType { - /** - * This is the default type used in the {@link Percentile}.This method - * has the following formulae for index and estimates
- * \( \begin{align} - * &index = (N+1)p\ \\ - * &estimate = x_{\lceil h\,-\,1/2 \rceil} \\ - * &minLimit = 0 \\ - * &maxLimit = 1 \\ - * \end{align}\) - */ - LEGACY("Legacy Apache Commons Math") { - /** - * {@inheritDoc}.This method in particular makes use of existing - * Apache Commons Math style of picking up the index. - */ - @Override - protected double index(final double p, final int length) { - final double minLimit = 0d; - final double maxLimit = 1d; - return Double.compare(p, minLimit) == 0 ? 0 : - Double.compare(p, maxLimit) == 0 ? - length : p * (length + 1); - } - }, - /** - * The method R_1 has the following formulae for index and estimates
- * \( \begin{align} - * &index= Np + 1/2\, \\ - * &estimate= x_{\lceil h\,-\,1/2 \rceil} \\ - * &minLimit = 0 \\ - * \end{align}\) - */ - R_1("R-1") { - - @Override - protected double index(final double p, final int length) { - final double minLimit = 0d; - return Double.compare(p, minLimit) == 0 ? 0 : length * p + 0.5; - } - - /** - * {@inheritDoc}This method in particular for R_1 uses ceil(pos-0.5) - */ - @Override - protected double estimate(final double[] values, - final int[] pivotsHeap, final double pos, - final int length, final KthSelector selector) { - return super.estimate(values, pivotsHeap, FastMath.ceil(pos - 0.5), length, selector); - } - - }, - /** - * The method R_2 has the following formulae for index and estimates
- * \( \begin{align} - * &index= Np + 1/2\, \\ - * &estimate=\frac{x_{\lceil h\,-\,1/2 \rceil} + - * x_{\lfloor h\,+\,1/2 \rfloor}}{2} \\ - * &minLimit = 0 \\ - * &maxLimit = 1 \\ - * \end{align}\) - */ - R_2("R-2") { - - @Override - protected double index(final double p, final int length) { - final double minLimit = 0d; - final double maxLimit = 1d; - return Double.compare(p, maxLimit) == 0 ? length : - Double.compare(p, minLimit) == 0 ? 0 : length * p + 0.5; - } - - /** - * {@inheritDoc}This method in particular for R_2 averages the - * values at ceil(p+0.5) and floor(p-0.5). - */ - @Override - protected double estimate(final double[] values, - final int[] pivotsHeap, final double pos, - final int length, final KthSelector selector) { - final double low = - super.estimate(values, pivotsHeap, FastMath.ceil(pos - 0.5), length, selector); - final double high = - super.estimate(values, pivotsHeap,FastMath.floor(pos + 0.5), length, selector); - return (low + high) / 2; - } - - }, - /** - * The method R_3 has the following formulae for index and estimates
- * \( \begin{align} - * &index= Np \\ - * &estimate= x_{\lfloor h \rceil}\, \\ - * &minLimit = 0.5/N \\ - * \end{align}\) - */ - R_3("R-3") { - @Override - protected double index(final double p, final int length) { - final double minLimit = 1d/2 / length; - return Double.compare(p, minLimit) <= 0 ? - 0 : FastMath.rint(length * p); - } - - }, - /** - * The method R_4 has the following formulae for index and estimates
- * \( \begin{align} - * &index= Np\, \\ - * &estimate= x_{\lfloor h \rfloor} + (h - - * \lfloor h \rfloor) (x_{\lfloor h \rfloor + 1} - x_{\lfloor h - * \rfloor}) \\ - * &minLimit = 1/N \\ - * &maxLimit = 1 \\ - * \end{align}\) - */ - R_4("R-4") { - @Override - protected double index(final double p, final int length) { - final double minLimit = 1d / length; - final double maxLimit = 1d; - return Double.compare(p, minLimit) < 0 ? 0 : - Double.compare(p, maxLimit) == 0 ? length : length * p; - } - - }, - /** - * The method R_5 has the following formulae for index and estimates
- * \( \begin{align} - * &index= Np + 1/2\\ - * &estimate= x_{\lfloor h \rfloor} + (h - - * \lfloor h \rfloor) (x_{\lfloor h \rfloor + 1} - x_{\lfloor h - * \rfloor}) \\ - * &minLimit = 0.5/N \\ - * &maxLimit = (N-0.5)/N - * \end{align}\) - */ - R_5("R-5") { - - @Override - protected double index(final double p, final int length) { - final double minLimit = 1d/2 / length; - final double maxLimit = (length - 0.5) / length; - return Double.compare(p, minLimit) < 0 ? 0 : - Double.compare(p, maxLimit) >= 0 ? - length : length * p + 0.5; - } - }, - /** - * The method R_6 has the following formulae for index and estimates
- * \( \begin{align} - * &index= (N + 1)p \\ - * &estimate= x_{\lfloor h \rfloor} + (h - - * \lfloor h \rfloor) (x_{\lfloor h \rfloor + 1} - x_{\lfloor h - * \rfloor}) \\ - * &minLimit = 1/(N+1) \\ - * &maxLimit = N/(N+1) \\ - * \end{align}\) - *

- * Note: This method computes the index in a manner very close to - * the default Commons Math Percentile existing implementation. However - * the difference to be noted is in picking up the limits with which - * first element (p<1(N+1)) and last elements (p>N/(N+1))are done. - * While in default case; these are done with p=0 and p=1 respectively. - */ - R_6("R-6") { - - @Override - protected double index(final double p, final int length) { - final double minLimit = 1d / (length + 1); - final double maxLimit = 1d * length / (length + 1); - return Double.compare(p, minLimit) < 0 ? 0 : - Double.compare(p, maxLimit) >= 0 ? - length : (length + 1) * p; - } - }, - - /** - * The method R_7 implements Microsoft Excel style computation has the - * following formulae for index and estimates.
- * \( \begin{align} - * &index = (N-1)p + 1 \\ - * &estimate = x_{\lfloor h \rfloor} + (h - - * \lfloor h \rfloor) (x_{\lfloor h \rfloor + 1} - x_{\lfloor h - * \rfloor}) \\ - * &minLimit = 0 \\ - * &maxLimit = 1 \\ - * \end{align}\) - */ - R_7("R-7") { - @Override - protected double index(final double p, final int length) { - final double minLimit = 0d; - final double maxLimit = 1d; - return Double.compare(p, minLimit) == 0 ? 0 : - Double.compare(p, maxLimit) == 0 ? - length : 1 + (length - 1) * p; - } - - }, - - /** - * The method R_8 has the following formulae for index and estimates
- * \( \begin{align} - * &index = (N + 1/3)p + 1/3 \\ - * &estimate = x_{\lfloor h \rfloor} + (h - - \lfloor h \rfloor) (x_{\lfloor h \rfloor + 1} - x_{\lfloor h - * \rfloor}) \\ - * &minLimit = (2/3)/(N+1/3) \\ - * &maxLimit = (N-1/3)/(N+1/3) \\ - * \end{align}\) - *

- * As per Ref [2,3] this approach is most recommended as it provides - * an approximate median-unbiased estimate regardless of distribution. - */ - R_8("R-8") { - @Override - protected double index(final double p, final int length) { - final double minLimit = 2 * (1d / 3) / (length + 1d / 3); - final double maxLimit = - (length - 1d / 3) / (length + 1d / 3); - return Double.compare(p, minLimit) < 0 ? 0 : - Double.compare(p, maxLimit) >= 0 ? length : - (length + 1d / 3) * p + 1d / 3; - } - }, - - /** - * The method R_9 has the following formulae for index and estimates
- * \( \begin{align} - * &index = (N + 1/4)p + 3/8\\ - * &estimate = x_{\lfloor h \rfloor} + (h - - \lfloor h \rfloor) (x_{\lfloor h \rfloor + 1} - x_{\lfloor h - * \rfloor}) \\ - * &minLimit = (5/8)/(N+1/4) \\ - * &maxLimit = (N-3/8)/(N+1/4) \\ - * \end{align}\) - */ - R_9("R-9") { - @Override - protected double index(final double p, final int length) { - final double minLimit = 5d/8 / (length + 0.25); - final double maxLimit = (length - 3d/8) / (length + 0.25); - return Double.compare(p, minLimit) < 0 ? 0 : - Double.compare(p, maxLimit) >= 0 ? length : - (length + 0.25) * p + 3d/8; - } - - }, - ; - - /** Simple name such as R-1, R-2 corresponding to those in wikipedia. */ - private final String name; - - /** - * Constructor - * - * @param type name of estimation type as per wikipedia - */ - EstimationType(final String type) { - this.name = type; - } - - /** - * Finds the index of array that can be used as starting index to - * {@link #estimate(double[], int[], double, int, KthSelector) estimate} - * percentile. The calculation of index calculation is specific to each - * {@link EstimationType}. - * - * @param p the pth quantile - * @param length the total number of array elements in the work array - * @return a computed real valued index as explained in the wikipedia - */ - protected abstract double index(final double p, final int length); - - /** - * Estimation based on Kth selection. This may be overridden - * in specific enums to compute slightly different estimations. - * - * @param work array of numbers to be used for finding the percentile - * @param pos indicated positional index prior computed from calling - * {@link #index(double, int)} - * @param pivotsHeap an earlier populated cache if exists; will be used - * @param length size of array considered - * @param selector a {@link KthSelector} used for pivoting during search - * @return estimated percentile - */ - protected double estimate(final double[] work, final int[] pivotsHeap, - final double pos, final int length, - final KthSelector selector) { - - final double fpos = FastMath.floor(pos); - final int intPos = (int) fpos; - final double dif = pos - fpos; - - if (pos < 1) { - return selector.select(work, pivotsHeap, 0); - } - if (pos >= length) { - return selector.select(work, pivotsHeap, length - 1); - } - - final double lower = selector.select(work, pivotsHeap, intPos - 1); - final double upper = selector.select(work, pivotsHeap, intPos); - return lower + dif * (upper - lower); - } - - /** - * Evaluate method to compute the percentile for a given bounded array - * using earlier computed pivots heap.
- * This basically calls the {@link #index(double, int) index} and then - * {@link #estimate(double[], int[], double, int, KthSelector) estimate} - * functions to return the estimated percentile value. - * - * @param work array of numbers to be used for finding the percentile - * @param pivotsHeap a prior cached heap which can speed up estimation - * @param p the pth quantile to be computed - * @param selector a {@link KthSelector} used for pivoting during search - * @return estimated percentile - * @throws OutOfRangeException if p is out of range - * @throws NullArgumentException if work array is null - */ - protected double evaluate(final double[] work, final int[] pivotsHeap, final double p, - final KthSelector selector) { - MathUtils.checkNotNull(work); - if (p > 100 || p <= 0) { - throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUNDS_QUANTILE_VALUE, - p, 0, 100); - } - return estimate(work, pivotsHeap, index(p/100d, work.length), work.length, selector); - } - - /** - * Evaluate method to compute the percentile for a given bounded array. - * This basically calls the {@link #index(double, int) index} and then - * {@link #estimate(double[], int[], double, int, KthSelector) estimate} - * functions to return the estimated percentile value. Please - * note that this method does not make use of cached pivots. - * - * @param work array of numbers to be used for finding the percentile - * @param p the pth quantile to be computed - * @return estimated percentile - * @param selector a {@link KthSelector} used for pivoting during search - * @throws OutOfRangeException if length or p is out of range - * @throws NullArgumentException if work array is null - */ - public double evaluate(final double[] work, final double p, final KthSelector selector) { - return this.evaluate(work, null, p, selector); - } - - /** - * Gets the name of the enum - * - * @return the name - */ - String getName() { - return name; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/package-info.java deleted file mode 100644 index 3d8d99a7e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/rank/package-info.java +++ /dev/null @@ -1,20 +0,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. - */ -/** - * Summary statistics based on ranks. - */ -package org.apache.commons.math4.stat.descriptive.rank; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/summary/Product.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/summary/Product.java deleted file mode 100644 index 46340c0ab..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/summary/Product.java +++ /dev/null @@ -1,231 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.summary; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.stat.descriptive.AbstractStorelessUnivariateStatistic; -import org.apache.commons.math4.stat.descriptive.WeightedEvaluation; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - -/** - * Returns the product of the available values. - *

- * If there are no values in the dataset, then 1 is returned. - * If any of the values are - * NaN, then NaN is returned.

- *

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally.

- */ -public class Product extends AbstractStorelessUnivariateStatistic implements Serializable, WeightedEvaluation { - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /**The number of values that have been added */ - private long n; - - /** - * The current Running Product. - */ - private double value; - - /** - * Create a Product instance. - */ - public Product() { - n = 0; - value = 1; - } - - /** - * Copy constructor, creates a new {@code Product} identical - * to the {@code original}. - * - * @param original the {@code Product} instance to copy - * @throws NullArgumentException if original is null - */ - public Product(Product original) throws NullArgumentException { - copy(original, this); - } - - /** - * {@inheritDoc} - */ - @Override - public void increment(final double d) { - value *= d; - n++; - } - - /** - * {@inheritDoc} - */ - @Override - public double getResult() { - return value; - } - - /** - * {@inheritDoc} - */ - @Override - public long getN() { - return n; - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - value = 1; - n = 0; - } - - /** - * Returns the product of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray - * is empty. - *

- * Throws MathIllegalArgumentException if the array is null.

- * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the product of the values or 1 if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - @Override - public double evaluate(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - double product = Double.NaN; - if (MathArrays.verifyValues(values, begin, length, true)) { - product = 1.0; - for (int i = begin; i < begin + length; i++) { - product *= values[i]; - } - } - return product; - } - - /** - *

Returns the weighted product of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray - * is empty.

- * - *

Throws MathIllegalArgumentException if any of the following are true: - *

  • the values array is null
  • - *
  • the weights array is null
  • - *
  • the weights array does not have the same length as the values array
  • - *
  • the weights array contains one or more infinite values
  • - *
  • the weights array contains one or more NaN values
  • - *
  • the weights array contains negative values
  • - *
  • the start and length arguments do not determine a valid array
  • - *
- * - *

Uses the formula,

- * weighted product = ∏values[i]weights[i] - *
- * that is, the weights are applied as exponents when computing the weighted product. - * - * @param values the input array - * @param weights the weights array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the product of the values or 1 if length = 0 - * @throws MathIllegalArgumentException if the parameters are not valid - * @since 2.1 - */ - @Override - public double evaluate(final double[] values, final double[] weights, - final int begin, final int length) throws MathIllegalArgumentException { - double product = Double.NaN; - if (MathArrays.verifyValues(values, weights, begin, length, true)) { - product = 1.0; - for (int i = begin; i < begin + length; i++) { - product *= FastMath.pow(values[i], weights[i]); - } - } - return product; - } - - /** - *

Returns the weighted product of the entries in the input array.

- * - *

Throws MathIllegalArgumentException if any of the following are true: - *

  • the values array is null
  • - *
  • the weights array is null
  • - *
  • the weights array does not have the same length as the values array
  • - *
  • the weights array contains one or more infinite values
  • - *
  • the weights array contains one or more NaN values
  • - *
  • the weights array contains negative values
  • - *
- * - *

Uses the formula, - *

- * weighted product = ∏values[i]weights[i] - *
- * that is, the weights are applied as exponents when computing the weighted product. - * - * @param values the input array - * @param weights the weights array - * @return the product of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the parameters are not valid - * @since 2.1 - */ - @Override - public double evaluate(final double[] values, final double[] weights) throws MathIllegalArgumentException { - return evaluate(values, weights, 0, values.length); - } - - /** - * {@inheritDoc} - */ - @Override - public Product copy() { - Product result = new Product(); - // No try-catch or advertised exception because args are valid - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source Product to copy - * @param dest Product to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(Product source, Product dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - dest.n = source.n; - dest.value = source.value; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/summary/Sum.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/summary/Sum.java deleted file mode 100644 index 19e859c0e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/summary/Sum.java +++ /dev/null @@ -1,225 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.summary; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.stat.descriptive.AbstractStorelessUnivariateStatistic; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - - -/** - * Returns the sum of the available values. - *

- * If there are no values in the dataset, then 0 is returned. - * If any of the values are - * NaN, then NaN is returned.

- *

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally.

- */ -public class Sum extends AbstractStorelessUnivariateStatistic implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /** */ - private long n; - - /** - * The currently running sum. - */ - private double value; - - /** - * Create a Sum instance. - */ - public Sum() { - n = 0; - value = 0; - } - - /** - * Copy constructor, creates a new {@code Sum} identical - * to the {@code original}. - * - * @param original the {@code Sum} instance to copy - * @throws NullArgumentException if original is null - */ - public Sum(Sum original) throws NullArgumentException { - copy(original, this); - } - - /** - * {@inheritDoc} - */ - @Override - public void increment(final double d) { - value += d; - n++; - } - - /** - * {@inheritDoc} - */ - @Override - public double getResult() { - return value; - } - - /** - * {@inheritDoc} - */ - @Override - public long getN() { - return n; - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - value = 0; - n = 0; - } - - /** - * The sum of the entries in the specified portion of the input array, - * or 0 if the designated subarray is empty. - *

- * Throws MathIllegalArgumentException if the array is null.

- * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the sum of the values or 0 if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - @Override - public double evaluate(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - - double sum = Double.NaN; - if (MathArrays.verifyValues(values, begin, length, true)) { - sum = 0.0; - for (int i = begin; i < begin + length; i++) { - sum += values[i]; - } - } - return sum; - } - - /** - * The weighted sum of the entries in the specified portion of - * the input array, or 0 if the designated subarray - * is empty. - *

- * Throws MathIllegalArgumentException if any of the following are true: - *

  • the values array is null
  • - *
  • the weights array is null
  • - *
  • the weights array does not have the same length as the values array
  • - *
  • the weights array contains one or more infinite values
  • - *
  • the weights array contains one or more NaN values
  • - *
  • the weights array contains negative values
  • - *
  • the start and length arguments do not determine a valid array
  • - *
- *

- * Uses the formula,

-     *    weighted sum = Σ(values[i] * weights[i])
-     * 
- * - * @param values the input array - * @param weights the weights array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the sum of the values or 0 if length = 0 - * @throws MathIllegalArgumentException if the parameters are not valid - * @since 2.1 - */ - public double evaluate(final double[] values, final double[] weights, - final int begin, final int length) throws MathIllegalArgumentException { - double sum = Double.NaN; - if (MathArrays.verifyValues(values, weights, begin, length, true)) { - sum = 0.0; - for (int i = begin; i < begin + length; i++) { - sum += values[i] * weights[i]; - } - } - return sum; - } - - /** - * The weighted sum of the entries in the input array. - *

- * Throws MathIllegalArgumentException if any of the following are true: - *

  • the values array is null
  • - *
  • the weights array is null
  • - *
  • the weights array does not have the same length as the values array
  • - *
  • the weights array contains one or more infinite values
  • - *
  • the weights array contains one or more NaN values
  • - *
  • the weights array contains negative values
  • - *
- *

- * Uses the formula,

-     *    weighted sum = Σ(values[i] * weights[i])
-     * 
- * - * @param values the input array - * @param weights the weights array - * @return the sum of the values or Double.NaN if length = 0 - * @throws MathIllegalArgumentException if the parameters are not valid - * @since 2.1 - */ - public double evaluate(final double[] values, final double[] weights) throws MathIllegalArgumentException { - return evaluate(values, weights, 0, values.length); - } - - /** - * {@inheritDoc} - */ - @Override - public Sum copy() { - Sum result = new Sum(); - // No try-catch or advertised exception because args are valid - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source Sum to copy - * @param dest Sum to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(Sum source, Sum dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - dest.n = source.n; - dest.value = source.value; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/summary/SumOfLogs.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/summary/SumOfLogs.java deleted file mode 100644 index ab55e2bfa..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/summary/SumOfLogs.java +++ /dev/null @@ -1,171 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.summary; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.stat.descriptive.AbstractStorelessUnivariateStatistic; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - -/** - * Returns the sum of the natural logs for this collection of values. - *

- * Uses {@link FastMath#log(double)} to compute the logs. - * Therefore, - *

    - *
  • If any of values are < 0, the result is NaN.
  • - *
  • If all values are non-negative and less than - * Double.POSITIVE_INFINITY, but at least one value is 0, the - * result is Double.NEGATIVE_INFINITY.
  • - *
  • If both Double.POSITIVE_INFINITY and - * Double.NEGATIVE_INFINITY are among the values, the result is - * NaN.
  • - *
- *

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally.

- */ -public class SumOfLogs extends AbstractStorelessUnivariateStatistic implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /** Number of values that have been added */ - private int n; - - /** - * The currently running value - */ - private double value; - - /** - * Create a SumOfLogs instance. - */ - public SumOfLogs() { - value = 0d; - n = 0; - } - - /** - * Copy constructor, creates a new {@code SumOfLogs} identical - * to the {@code original}. - * - * @param original the {@code SumOfLogs} instance to copy - * @throws NullArgumentException if original is null - */ - public SumOfLogs(SumOfLogs original) throws NullArgumentException { - copy(original, this); - } - - /** - * {@inheritDoc} - */ - @Override - public void increment(final double d) { - value += FastMath.log(d); - n++; - } - - /** - * {@inheritDoc} - */ - @Override - public double getResult() { - return value; - } - - /** - * {@inheritDoc} - */ - @Override - public long getN() { - return n; - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - value = 0d; - n = 0; - } - - /** - * Returns the sum of the natural logs of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray - * is empty. - *

- * Throws MathIllegalArgumentException if the array is null.

- *

- * See {@link SumOfLogs}.

- * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the sum of the natural logs of the values or 0 if - * length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - @Override - public double evaluate(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - - double sumLog = Double.NaN; - if (MathArrays.verifyValues(values, begin, length, true)) { - sumLog = 0.0; - for (int i = begin; i < begin + length; i++) { - sumLog += FastMath.log(values[i]); - } - } - return sumLog; - } - - /** - * {@inheritDoc} - */ - @Override - public SumOfLogs copy() { - SumOfLogs result = new SumOfLogs(); - // No try-catch or advertised exception here because args are valid - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source SumOfLogs to copy - * @param dest SumOfLogs to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(SumOfLogs source, SumOfLogs dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - dest.n = source.n; - dest.value = source.value; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/summary/SumOfSquares.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/summary/SumOfSquares.java deleted file mode 100644 index d37e35ba7..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/summary/SumOfSquares.java +++ /dev/null @@ -1,160 +0,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. - */ -package org.apache.commons.math4.stat.descriptive.summary; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.stat.descriptive.AbstractStorelessUnivariateStatistic; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - -/** - * Returns the sum of the squares of the available values. - *

- * If there are no values in the dataset, then 0 is returned. - * If any of the values are - * NaN, then NaN is returned.

- *

- * Note that this implementation is not synchronized. If - * multiple threads access an instance of this class concurrently, and at least - * one of the threads invokes the increment() or - * clear() method, it must be synchronized externally.

- */ -public class SumOfSquares extends AbstractStorelessUnivariateStatistic implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 20150412L; - - /** Number of values that have been added */ - private long n; - - /** - * The currently running sumSq - */ - private double value; - - /** - * Create a SumOfSquares instance. - */ - public SumOfSquares() { - n = 0; - value = 0; - } - - /** - * Copy constructor, creates a new {@code SumOfSquares} identical - * to the {@code original}. - * - * @param original the {@code SumOfSquares} instance to copy - * @throws NullArgumentException if original is null - */ - public SumOfSquares(SumOfSquares original) throws NullArgumentException { - copy(original, this); - } - - /** - * {@inheritDoc} - */ - @Override - public void increment(final double d) { - value += d * d; - n++; - } - - /** - * {@inheritDoc} - */ - @Override - public double getResult() { - return value; - } - - /** - * {@inheritDoc} - */ - @Override - public long getN() { - return n; - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - value = 0; - n = 0; - } - - /** - * Returns the sum of the squares of the entries in the specified portion of - * the input array, or Double.NaN if the designated subarray - * is empty. - *

- * Throws MathIllegalArgumentException if the array is null.

- * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return the sum of the squares of the values or 0 if length = 0 - * @throws MathIllegalArgumentException if the array is null or the array index - * parameters are not valid - */ - @Override - public double evaluate(final double[] values,final int begin, final int length) - throws MathIllegalArgumentException { - - double sumSq = Double.NaN; - if (MathArrays.verifyValues(values, begin, length, true)) { - sumSq = 0.0; - for (int i = begin; i < begin + length; i++) { - sumSq += values[i] * values[i]; - } - } - return sumSq; - } - - /** - * {@inheritDoc} - */ - @Override - public SumOfSquares copy() { - SumOfSquares result = new SumOfSquares(); - // no try-catch or advertised exception here because args are valid - copy(this, result); - return result; - } - - /** - * Copies source to dest. - *

Neither source nor dest can be null.

- * - * @param source SumOfSquares to copy - * @param dest SumOfSquares to copy to - * @throws NullArgumentException if either source or dest is null - */ - public static void copy(SumOfSquares source, SumOfSquares dest) - throws NullArgumentException { - MathUtils.checkNotNull(source); - MathUtils.checkNotNull(dest); - dest.n = source.n; - dest.value = source.value; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/summary/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/summary/package-info.java deleted file mode 100644 index 28e7c76dd..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/descriptive/summary/package-info.java +++ /dev/null @@ -1,20 +0,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. - */ -/** - * Other summary statistics. - */ -package org.apache.commons.math4.stat.descriptive.summary; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/AlternativeHypothesis.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/AlternativeHypothesis.java deleted file mode 100644 index 3fb170d56..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/AlternativeHypothesis.java +++ /dev/null @@ -1,40 +0,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. - */ -package org.apache.commons.math4.stat.inference; - -/** - * Represents an alternative hypothesis for a hypothesis test. - * - * @since 3.3 - */ -public enum AlternativeHypothesis { - - /** - * Represents a two-sided test. H0: p=p0, H1: p ≠ p0 - */ - TWO_SIDED, - - /** - * Represents a right-sided test. H0: p ≤ p0, H1: p > p0. - */ - GREATER_THAN, - - /** - * Represents a left-sided test. H0: p ≥ p0, H1: p < p0. - */ - LESS_THAN -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/BinomialTest.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/BinomialTest.java deleted file mode 100644 index 7b773c6a2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/BinomialTest.java +++ /dev/null @@ -1,163 +0,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. - */ -package org.apache.commons.math4.stat.inference; - -import org.apache.commons.statistics.distribution.BinomialDistribution; -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.MathInternalError; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Implements binomial test statistics. - *

- * Exact test for the statistical significance of deviations from a - * theoretically expected distribution of observations into two categories. - * - * @see Binomial test (Wikipedia) - * @since 3.3 - */ -public class BinomialTest { - - /** - * Returns whether the null hypothesis can be rejected with the given confidence level. - *

- * Preconditions: - *

    - *
  • Number of trials must be ≥ 0.
  • - *
  • Number of successes must be ≥ 0.
  • - *
  • Number of successes must be ≤ number of trials.
  • - *
  • Probability must be ≥ 0 and ≤ 1.
  • - *
- * - * @param numberOfTrials number of trials performed - * @param numberOfSuccesses number of successes observed - * @param probability assumed probability of a single trial under the null hypothesis - * @param alternativeHypothesis type of hypothesis being evaluated (one- or two-sided) - * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with confidence {@code 1 - alpha} - * @throws NotPositiveException if {@code numberOfTrials} or {@code numberOfSuccesses} is negative - * @throws OutOfRangeException if {@code probability} is not between 0 and 1 - * @throws MathIllegalArgumentException if {@code numberOfTrials} < {@code numberOfSuccesses} or - * if {@code alternateHypothesis} is null. - * @see AlternativeHypothesis - */ - public boolean binomialTest(int numberOfTrials, int numberOfSuccesses, double probability, - AlternativeHypothesis alternativeHypothesis, double alpha) { - double pValue = binomialTest(numberOfTrials, numberOfSuccesses, probability, alternativeHypothesis); - return pValue < alpha; - } - - /** - * Returns the observed significance level, or - * p-value, - * associated with a Binomial test. - *

- * The number returned is the smallest significance level at which one can reject the null hypothesis. - * The form of the hypothesis depends on {@code alternativeHypothesis}.

- *

- * The p-Value represents the likelihood of getting a result at least as extreme as the sample, - * given the provided {@code probability} of success on a single trial. For single-sided tests, - * this value can be directly derived from the Binomial distribution. For the two-sided test, - * the implementation works as follows: we start by looking at the most extreme cases - * (0 success and n success where n is the number of trials from the sample) and determine their likelihood. - * The lower value is added to the p-Value (if both values are equal, both are added). Then we continue with - * the next extreme value, until we added the value for the actual observed sample.

- *

- * Preconditions: - *

    - *
  • Number of trials must be ≥ 0.
  • - *
  • Number of successes must be ≥ 0.
  • - *
  • Number of successes must be ≤ number of trials.
  • - *
  • Probability must be ≥ 0 and ≤ 1.
  • - *
- * - * @param numberOfTrials number of trials performed - * @param numberOfSuccesses number of successes observed - * @param probability assumed probability of a single trial under the null hypothesis - * @param alternativeHypothesis type of hypothesis being evaluated (one- or two-sided) - * @return p-value - * @throws NotPositiveException if {@code numberOfTrials} or {@code numberOfSuccesses} is negative - * @throws OutOfRangeException if {@code probability} is not between 0 and 1 - * @throws MathIllegalArgumentException if {@code numberOfTrials} < {@code numberOfSuccesses} or - * if {@code alternateHypothesis} is null. - * @see AlternativeHypothesis - */ - public double binomialTest(int numberOfTrials, int numberOfSuccesses, double probability, - AlternativeHypothesis alternativeHypothesis) { - if (numberOfTrials < 0) { - throw new NotPositiveException(numberOfTrials); - } - if (numberOfSuccesses < 0) { - throw new NotPositiveException(numberOfSuccesses); - } - if (probability < 0 || probability > 1) { - throw new OutOfRangeException(probability, 0, 1); - } - if (numberOfTrials < numberOfSuccesses) { - throw new MathIllegalArgumentException( - LocalizedFormats.BINOMIAL_INVALID_PARAMETERS_ORDER, - numberOfTrials, numberOfSuccesses); - } - if (alternativeHypothesis == null) { - throw new NullArgumentException(); - } - - final BinomialDistribution distribution = new BinomialDistribution(numberOfTrials, probability); - switch (alternativeHypothesis) { - case GREATER_THAN: - return 1 - distribution.cumulativeProbability(numberOfSuccesses - 1); - case LESS_THAN: - return distribution.cumulativeProbability(numberOfSuccesses); - case TWO_SIDED: - int criticalValueLow = 0; - int criticalValueHigh = numberOfTrials; - double pTotal = 0; - - while (true) { - double pLow = distribution.probability(criticalValueLow); - double pHigh = distribution.probability(criticalValueHigh); - - if (pLow == pHigh) { - if (criticalValueLow == criticalValueHigh) { - pTotal += pLow; - } else { - pTotal += 2 * pLow; - } - criticalValueLow++; - criticalValueHigh--; - } else if (pLow < pHigh) { - pTotal += pLow; - criticalValueLow++; - } else { - pTotal += pHigh; - criticalValueHigh--; - } - - if (criticalValueLow > numberOfSuccesses || criticalValueHigh < numberOfSuccesses) { - break; - } - } - return pTotal; - default: - throw new MathInternalError(LocalizedFormats. OUT_OF_RANGE_SIMPLE, alternativeHypothesis, - AlternativeHypothesis.TWO_SIDED, AlternativeHypothesis.LESS_THAN); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/ChiSquareTest.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/ChiSquareTest.java deleted file mode 100644 index bdcac6606..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/ChiSquareTest.java +++ /dev/null @@ -1,602 +0,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. - */ -package org.apache.commons.math4.stat.inference; - -import org.apache.commons.statistics.distribution.ChiSquaredDistribution; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.ZeroException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; - -/** - * Implements Chi-Square test statistics. - * - *

This implementation handles both known and unknown distributions.

- * - *

Two samples tests can be used when the distribution is unknown a priori - * but provided by one sample, or when the hypothesis under test is that the two - * samples come from the same underlying distribution.

- * - */ -public class ChiSquareTest { - - /** - * Construct a ChiSquareTest - */ - public ChiSquareTest() { - super(); - } - - /** - * Computes the - * Chi-Square statistic comparing observed and expected - * frequency counts. - *

- * This statistic can be used to perform a Chi-Square test evaluating the null - * hypothesis that the observed counts follow the expected distribution.

- *

- * Preconditions:

    - *
  • Expected counts must all be positive. - *
  • - *
  • Observed counts must all be ≥ 0. - *
  • - *
  • The observed and expected arrays must have the same length and - * their common length must be at least 2. - *

- * If any of the preconditions are not met, an - * IllegalArgumentException is thrown.

- *

Note: This implementation rescales the - * expected array if necessary to ensure that the sum of the - * expected and observed counts are equal.

- * - * @param observed array of observed frequency counts - * @param expected array of expected frequency counts - * @return chiSquare test statistic - * @throws NotPositiveException if observed has negative entries - * @throws NotStrictlyPositiveException if expected has entries that are - * not strictly positive - * @throws DimensionMismatchException if the arrays length is less than 2 - */ - public double chiSquare(final double[] expected, final long[] observed) - throws NotPositiveException, NotStrictlyPositiveException, - DimensionMismatchException { - - if (expected.length < 2) { - throw new DimensionMismatchException(expected.length, 2); - } - if (expected.length != observed.length) { - throw new DimensionMismatchException(expected.length, observed.length); - } - MathArrays.checkPositive(expected); - MathArrays.checkNonNegative(observed); - - double sumExpected = 0d; - double sumObserved = 0d; - for (int i = 0; i < observed.length; i++) { - sumExpected += expected[i]; - sumObserved += observed[i]; - } - double ratio = 1.0d; - boolean rescale = false; - if (FastMath.abs(sumExpected - sumObserved) > 10E-6) { - ratio = sumObserved / sumExpected; - rescale = true; - } - double sumSq = 0.0d; - for (int i = 0; i < observed.length; i++) { - if (rescale) { - final double dev = observed[i] - ratio * expected[i]; - sumSq += dev * dev / (ratio * expected[i]); - } else { - final double dev = observed[i] - expected[i]; - sumSq += dev * dev / expected[i]; - } - } - return sumSq; - - } - - /** - * Returns the observed significance level, or - * p-value, associated with a - * - * Chi-square goodness of fit test comparing the observed - * frequency counts to those in the expected array. - *

- * The number returned is the smallest significance level at which one can reject - * the null hypothesis that the observed counts conform to the frequency distribution - * described by the expected counts.

- *

- * Preconditions:

    - *
  • Expected counts must all be positive. - *
  • - *
  • Observed counts must all be ≥ 0. - *
  • - *
  • The observed and expected arrays must have the same length and - * their common length must be at least 2. - *

- * If any of the preconditions are not met, an - * IllegalArgumentException is thrown.

- *

Note: This implementation rescales the - * expected array if necessary to ensure that the sum of the - * expected and observed counts are equal.

- * - * @param observed array of observed frequency counts - * @param expected array of expected frequency counts - * @return p-value - * @throws NotPositiveException if observed has negative entries - * @throws NotStrictlyPositiveException if expected has entries that are - * not strictly positive - * @throws DimensionMismatchException if the arrays length is less than 2 - * @throws MaxCountExceededException if an error occurs computing the p-value - */ - public double chiSquareTest(final double[] expected, final long[] observed) - throws NotPositiveException, NotStrictlyPositiveException, - DimensionMismatchException, MaxCountExceededException { - - // pass a null rng to avoid unneeded overhead as we will not sample from this distribution - final ChiSquaredDistribution distribution = - new ChiSquaredDistribution(expected.length - 1.0); - return 1.0 - distribution.cumulativeProbability(chiSquare(expected, observed)); - } - - /** - * Performs a - * Chi-square goodness of fit test evaluating the null hypothesis that the - * observed counts conform to the frequency distribution described by the expected - * counts, with significance level alpha. Returns true iff the null - * hypothesis can be rejected with 100 * (1 - alpha) percent confidence. - *

- * Example:
- * To test the hypothesis that observed follows - * expected at the 99% level, use

- * chiSquareTest(expected, observed, 0.01)

- *

- * Preconditions:

    - *
  • Expected counts must all be positive. - *
  • - *
  • Observed counts must all be ≥ 0. - *
  • - *
  • The observed and expected arrays must have the same length and - * their common length must be at least 2. - *
  • 0 < alpha < 0.5 - *

- * If any of the preconditions are not met, an - * IllegalArgumentException is thrown.

- *

Note: This implementation rescales the - * expected array if necessary to ensure that the sum of the - * expected and observed counts are equal.

- * - * @param observed array of observed frequency counts - * @param expected array of expected frequency counts - * @param alpha significance level of the test - * @return true iff null hypothesis can be rejected with confidence - * 1 - alpha - * @throws NotPositiveException if observed has negative entries - * @throws NotStrictlyPositiveException if expected has entries that are - * not strictly positive - * @throws DimensionMismatchException if the arrays length is less than 2 - * @throws OutOfRangeException if alpha is not in the range (0, 0.5] - * @throws MaxCountExceededException if an error occurs computing the p-value - */ - public boolean chiSquareTest(final double[] expected, final long[] observed, - final double alpha) - throws NotPositiveException, NotStrictlyPositiveException, - DimensionMismatchException, OutOfRangeException, MaxCountExceededException { - - if ((alpha <= 0) || (alpha > 0.5)) { - throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, - alpha, 0, 0.5); - } - return chiSquareTest(expected, observed) < alpha; - - } - - /** - * Computes the Chi-Square statistic associated with a - * - * chi-square test of independence based on the input counts - * array, viewed as a two-way table. - *

- * The rows of the 2-way table are - * count[0], ... , count[count.length - 1]

- *

- * Preconditions:

    - *
  • All counts must be ≥ 0. - *
  • - *
  • The count array must be rectangular (i.e. all count[i] subarrays - * must have the same length). - *
  • - *
  • The 2-way table represented by counts must have at - * least 2 columns and at least 2 rows. - *
  • - *

- * If any of the preconditions are not met, an - * IllegalArgumentException is thrown.

- * - * @param counts array representation of 2-way table - * @return chiSquare test statistic - * @throws NullArgumentException if the array is null - * @throws DimensionMismatchException if the array is not rectangular - * @throws NotPositiveException if {@code counts} has negative entries - */ - public double chiSquare(final long[][] counts) - throws NullArgumentException, NotPositiveException, - DimensionMismatchException { - - checkArray(counts); - int nRows = counts.length; - int nCols = counts[0].length; - - // compute row, column and total sums - double[] rowSum = new double[nRows]; - double[] colSum = new double[nCols]; - double total = 0.0d; - for (int row = 0; row < nRows; row++) { - for (int col = 0; col < nCols; col++) { - rowSum[row] += counts[row][col]; - colSum[col] += counts[row][col]; - total += counts[row][col]; - } - } - - // compute expected counts and chi-square - double sumSq = 0.0d; - double expected = 0.0d; - for (int row = 0; row < nRows; row++) { - for (int col = 0; col < nCols; col++) { - expected = (rowSum[row] * colSum[col]) / total; - sumSq += ((counts[row][col] - expected) * - (counts[row][col] - expected)) / expected; - } - } - return sumSq; - - } - - /** - * Returns the observed significance level, or - * p-value, associated with a - * - * chi-square test of independence based on the input counts - * array, viewed as a two-way table. - *

- * The rows of the 2-way table are - * count[0], ... , count[count.length - 1]

- *

- * Preconditions:

    - *
  • All counts must be ≥ 0. - *
  • - *
  • The count array must be rectangular (i.e. all count[i] subarrays must have - * the same length). - *
  • - *
  • The 2-way table represented by counts must have at least 2 - * columns and at least 2 rows. - *
  • - *

- * If any of the preconditions are not met, an - * IllegalArgumentException is thrown.

- * - * @param counts array representation of 2-way table - * @return p-value - * @throws NullArgumentException if the array is null - * @throws DimensionMismatchException if the array is not rectangular - * @throws NotPositiveException if {@code counts} has negative entries - * @throws MaxCountExceededException if an error occurs computing the p-value - */ - public double chiSquareTest(final long[][] counts) - throws NullArgumentException, DimensionMismatchException, - NotPositiveException, MaxCountExceededException { - - checkArray(counts); - double df = ((double) counts.length -1) * ((double) counts[0].length - 1); - // pass a null rng to avoid unneeded overhead as we will not sample from this distribution - final ChiSquaredDistribution distribution = new ChiSquaredDistribution(df); - return 1 - distribution.cumulativeProbability(chiSquare(counts)); - - } - - /** - * Performs a - * chi-square test of independence evaluating the null hypothesis that the - * classifications represented by the counts in the columns of the input 2-way table - * are independent of the rows, with significance level alpha. - * Returns true iff the null hypothesis can be rejected with 100 * (1 - alpha) percent - * confidence. - *

- * The rows of the 2-way table are - * count[0], ... , count[count.length - 1]

- *

- * Example:
- * To test the null hypothesis that the counts in - * count[0], ... , count[count.length - 1] - * all correspond to the same underlying probability distribution at the 99% level, use

- *

chiSquareTest(counts, 0.01)

- *

- * Preconditions:

    - *
  • All counts must be ≥ 0. - *
  • - *
  • The count array must be rectangular (i.e. all count[i] subarrays must have the - * same length).
  • - *
  • The 2-way table represented by counts must have at least 2 columns and - * at least 2 rows.
  • - *

- * If any of the preconditions are not met, an - * IllegalArgumentException is thrown.

- * - * @param counts array representation of 2-way table - * @param alpha significance level of the test - * @return true iff null hypothesis can be rejected with confidence - * 1 - alpha - * @throws NullArgumentException if the array is null - * @throws DimensionMismatchException if the array is not rectangular - * @throws NotPositiveException if {@code counts} has any negative entries - * @throws OutOfRangeException if alpha is not in the range (0, 0.5] - * @throws MaxCountExceededException if an error occurs computing the p-value - */ - public boolean chiSquareTest(final long[][] counts, final double alpha) - throws NullArgumentException, DimensionMismatchException, - NotPositiveException, OutOfRangeException, MaxCountExceededException { - - if ((alpha <= 0) || (alpha > 0.5)) { - throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, - alpha, 0, 0.5); - } - return chiSquareTest(counts) < alpha; - - } - - /** - *

Computes a - * - * Chi-Square two sample test statistic comparing bin frequency counts - * in observed1 and observed2. The - * sums of frequency counts in the two samples are not required to be the - * same. The formula used to compute the test statistic is

- * - * ∑[(K * observed1[i] - observed2[i]/K)2 / (observed1[i] + observed2[i])] - * where - *
K = √[∑(observed2 / ∑(observed1)] - * - *

This statistic can be used to perform a Chi-Square test evaluating the - * null hypothesis that both observed counts follow the same distribution.

- *

- * Preconditions:

    - *
  • Observed counts must be non-negative. - *
  • - *
  • Observed counts for a specific bin must not both be zero. - *
  • - *
  • Observed counts for a specific sample must not all be 0. - *
  • - *
  • The arrays observed1 and observed2 must have - * the same length and their common length must be at least 2. - *

- * If any of the preconditions are not met, an - * IllegalArgumentException is thrown.

- * - * @param observed1 array of observed frequency counts of the first data set - * @param observed2 array of observed frequency counts of the second data set - * @return chiSquare test statistic - * @throws DimensionMismatchException the length of the arrays does not match - * @throws NotPositiveException if any entries in observed1 or - * observed2 are negative - * @throws ZeroException if either all counts of observed1 or - * observed2 are zero, or if the count at some index is zero - * for both arrays - * @since 1.2 - */ - public double chiSquareDataSetsComparison(long[] observed1, long[] observed2) - throws DimensionMismatchException, NotPositiveException, ZeroException { - - // Make sure lengths are same - if (observed1.length < 2) { - throw new DimensionMismatchException(observed1.length, 2); - } - if (observed1.length != observed2.length) { - throw new DimensionMismatchException(observed1.length, observed2.length); - } - - // Ensure non-negative counts - MathArrays.checkNonNegative(observed1); - MathArrays.checkNonNegative(observed2); - - // Compute and compare count sums - long countSum1 = 0; - long countSum2 = 0; - boolean unequalCounts = false; - double weight = 0.0; - for (int i = 0; i < observed1.length; i++) { - countSum1 += observed1[i]; - countSum2 += observed2[i]; - } - // Ensure neither sample is uniformly 0 - if (countSum1 == 0 || countSum2 == 0) { - throw new ZeroException(); - } - // Compare and compute weight only if different - unequalCounts = countSum1 != countSum2; - if (unequalCounts) { - weight = FastMath.sqrt((double) countSum1 / (double) countSum2); - } - // Compute ChiSquare statistic - double sumSq = 0.0d; - double dev = 0.0d; - double obs1 = 0.0d; - double obs2 = 0.0d; - for (int i = 0; i < observed1.length; i++) { - if (observed1[i] == 0 && observed2[i] == 0) { - throw new ZeroException(LocalizedFormats.OBSERVED_COUNTS_BOTTH_ZERO_FOR_ENTRY, i); - } else { - obs1 = observed1[i]; - obs2 = observed2[i]; - if (unequalCounts) { // apply weights - dev = obs1/weight - obs2 * weight; - } else { - dev = obs1 - obs2; - } - sumSq += (dev * dev) / (obs1 + obs2); - } - } - return sumSq; - } - - /** - *

Returns the observed significance level, or - * p-value, associated with a Chi-Square two sample test comparing - * bin frequency counts in observed1 and - * observed2. - *

- *

The number returned is the smallest significance level at which one - * can reject the null hypothesis that the observed counts conform to the - * same distribution. - *

- *

See {@link #chiSquareDataSetsComparison(long[], long[])} for details - * on the formula used to compute the test statistic. The degrees of - * of freedom used to perform the test is one less than the common length - * of the input observed count arrays. - *

- * Preconditions:
    - *
  • Observed counts must be non-negative. - *
  • - *
  • Observed counts for a specific bin must not both be zero. - *
  • - *
  • Observed counts for a specific sample must not all be 0. - *
  • - *
  • The arrays observed1 and observed2 must - * have the same length and - * their common length must be at least 2. - *

- * If any of the preconditions are not met, an - * IllegalArgumentException is thrown.

- * - * @param observed1 array of observed frequency counts of the first data set - * @param observed2 array of observed frequency counts of the second data set - * @return p-value - * @throws DimensionMismatchException the length of the arrays does not match - * @throws NotPositiveException if any entries in observed1 or - * observed2 are negative - * @throws ZeroException if either all counts of observed1 or - * observed2 are zero, or if the count at the same index is zero - * for both arrays - * @throws MaxCountExceededException if an error occurs computing the p-value - * @since 1.2 - */ - public double chiSquareTestDataSetsComparison(long[] observed1, long[] observed2) - throws DimensionMismatchException, NotPositiveException, ZeroException, - MaxCountExceededException { - - // pass a null rng to avoid unneeded overhead as we will not sample from this distribution - final ChiSquaredDistribution distribution = - new ChiSquaredDistribution((double) observed1.length - 1); - return 1 - distribution.cumulativeProbability( - chiSquareDataSetsComparison(observed1, observed2)); - - } - - /** - *

Performs a Chi-Square two sample test comparing two binned data - * sets. The test evaluates the null hypothesis that the two lists of - * observed counts conform to the same frequency distribution, with - * significance level alpha. Returns true iff the null - * hypothesis can be rejected with 100 * (1 - alpha) percent confidence. - *

- *

See {@link #chiSquareDataSetsComparison(long[], long[])} for - * details on the formula used to compute the Chisquare statistic used - * in the test. The degrees of of freedom used to perform the test is - * one less than the common length of the input observed count arrays. - *

- * Preconditions:
    - *
  • Observed counts must be non-negative. - *
  • - *
  • Observed counts for a specific bin must not both be zero. - *
  • - *
  • Observed counts for a specific sample must not all be 0. - *
  • - *
  • The arrays observed1 and observed2 must - * have the same length and their common length must be at least 2. - *
  • - *
  • 0 < alpha < 0.5 - *

- * If any of the preconditions are not met, an - * IllegalArgumentException is thrown.

- * - * @param observed1 array of observed frequency counts of the first data set - * @param observed2 array of observed frequency counts of the second data set - * @param alpha significance level of the test - * @return true iff null hypothesis can be rejected with confidence - * 1 - alpha - * @throws DimensionMismatchException the length of the arrays does not match - * @throws NotPositiveException if any entries in observed1 or - * observed2 are negative - * @throws ZeroException if either all counts of observed1 or - * observed2 are zero, or if the count at the same index is zero - * for both arrays - * @throws OutOfRangeException if alpha is not in the range (0, 0.5] - * @throws MaxCountExceededException if an error occurs performing the test - * @since 1.2 - */ - public boolean chiSquareTestDataSetsComparison(final long[] observed1, - final long[] observed2, - final double alpha) - throws DimensionMismatchException, NotPositiveException, - ZeroException, OutOfRangeException, MaxCountExceededException { - - if (alpha <= 0 || - alpha > 0.5) { - throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, - alpha, 0, 0.5); - } - return chiSquareTestDataSetsComparison(observed1, observed2) < alpha; - - } - - /** - * Checks to make sure that the input long[][] array is rectangular, - * has at least 2 rows and 2 columns, and has all non-negative entries. - * - * @param in input 2-way table to check - * @throws NullArgumentException if the array is null - * @throws DimensionMismatchException if the array is not valid - * @throws NotPositiveException if the array contains any negative entries - */ - private void checkArray(final long[][] in) - throws NullArgumentException, DimensionMismatchException, - NotPositiveException { - - if (in.length < 2) { - throw new DimensionMismatchException(in.length, 2); - } - - if (in[0].length < 2) { - throw new DimensionMismatchException(in[0].length, 2); - } - - MathArrays.checkRectangular(in); - MathArrays.checkNonNegative(in); - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/GTest.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/GTest.java deleted file mode 100644 index 28d42ce4a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/GTest.java +++ /dev/null @@ -1,538 +0,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. - */ -package org.apache.commons.math4.stat.inference; - -import org.apache.commons.statistics.distribution.ChiSquaredDistribution; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.ZeroException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; - -/** - * Implements G Test - * statistics. - * - *

This is known in statistical genetics as the McDonald-Kreitman test. - * The implementation handles both known and unknown distributions.

- * - *

Two samples tests can be used when the distribution is unknown a priori - * but provided by one sample, or when the hypothesis under test is that the two - * samples come from the same underlying distribution.

- * - * @since 3.1 - */ -public class GTest { - - /** - * Computes the G statistic - * for Goodness of Fit comparing {@code observed} and {@code expected} - * frequency counts. - * - *

This statistic can be used to perform a G test (Log-Likelihood Ratio - * Test) evaluating the null hypothesis that the observed counts follow the - * expected distribution.

- * - *

Preconditions:

    - *
  • Expected counts must all be positive.
  • - *
  • Observed counts must all be ≥ 0.
  • - *
  • The observed and expected arrays must have the same length and their - * common length must be at least 2.
- * - *

If any of the preconditions are not met, a - * {@code MathIllegalArgumentException} is thrown.

- * - *

Note:This implementation rescales the - * {@code expected} array if necessary to ensure that the sum of the - * expected and observed counts are equal.

- * - * @param observed array of observed frequency counts - * @param expected array of expected frequency counts - * @return G-Test statistic - * @throws NotPositiveException if {@code observed} has negative entries - * @throws NotStrictlyPositiveException if {@code expected} has entries that - * are not strictly positive - * @throws DimensionMismatchException if the array lengths do not match or - * are less than 2. - */ - public double g(final double[] expected, final long[] observed) - throws NotPositiveException, NotStrictlyPositiveException, - DimensionMismatchException { - - if (expected.length < 2) { - throw new DimensionMismatchException(expected.length, 2); - } - if (expected.length != observed.length) { - throw new DimensionMismatchException(expected.length, observed.length); - } - MathArrays.checkPositive(expected); - MathArrays.checkNonNegative(observed); - - double sumExpected = 0d; - double sumObserved = 0d; - for (int i = 0; i < observed.length; i++) { - sumExpected += expected[i]; - sumObserved += observed[i]; - } - double ratio = 1d; - boolean rescale = false; - if (FastMath.abs(sumExpected - sumObserved) > 10E-6) { - ratio = sumObserved / sumExpected; - rescale = true; - } - double sum = 0d; - for (int i = 0; i < observed.length; i++) { - final double dev = rescale ? - FastMath.log((double) observed[i] / (ratio * expected[i])) : - FastMath.log((double) observed[i] / expected[i]); - sum += ((double) observed[i]) * dev; - } - return 2d * sum; - } - - /** - * Returns the observed significance level, or p-value, - * associated with a G-Test for goodness of fit comparing the - * {@code observed} frequency counts to those in the {@code expected} array. - * - *

The number returned is the smallest significance level at which one - * can reject the null hypothesis that the observed counts conform to the - * frequency distribution described by the expected counts.

- * - *

The probability returned is the tail probability beyond - * {@link #g(double[], long[]) g(expected, observed)} - * in the ChiSquare distribution with degrees of freedom one less than the - * common length of {@code expected} and {@code observed}.

- * - *

Preconditions:

    - *
  • Expected counts must all be positive.
  • - *
  • Observed counts must all be ≥ 0.
  • - *
  • The observed and expected arrays must have the - * same length and their common length must be at least 2.
  • - *
- * - *

If any of the preconditions are not met, a - * {@code MathIllegalArgumentException} is thrown.

- * - *

Note:This implementation rescales the - * {@code expected} array if necessary to ensure that the sum of the - * expected and observed counts are equal.

- * - * @param observed array of observed frequency counts - * @param expected array of expected frequency counts - * @return p-value - * @throws NotPositiveException if {@code observed} has negative entries - * @throws NotStrictlyPositiveException if {@code expected} has entries that - * are not strictly positive - * @throws DimensionMismatchException if the array lengths do not match or - * are less than 2. - * @throws MaxCountExceededException if an error occurs computing the - * p-value. - */ - public double gTest(final double[] expected, final long[] observed) - throws NotPositiveException, NotStrictlyPositiveException, - DimensionMismatchException, MaxCountExceededException { - - // pass a null rng to avoid unneeded overhead as we will not sample from this distribution - final ChiSquaredDistribution distribution = - new ChiSquaredDistribution(expected.length - 1.0); - return 1.0 - distribution.cumulativeProbability(g(expected, observed)); - } - - /** - * Returns the intrinsic (Hardy-Weinberg proportions) p-Value, as described - * in p64-69 of McDonald, J.H. 2009. Handbook of Biological Statistics - * (2nd ed.). Sparky House Publishing, Baltimore, Maryland. - * - *

The probability returned is the tail probability beyond - * {@link #g(double[], long[]) g(expected, observed)} - * in the ChiSquare distribution with degrees of freedom two less than the - * common length of {@code expected} and {@code observed}.

- * - * @param observed array of observed frequency counts - * @param expected array of expected frequency counts - * @return p-value - * @throws NotPositiveException if {@code observed} has negative entries - * @throws NotStrictlyPositiveException {@code expected} has entries that are - * not strictly positive - * @throws DimensionMismatchException if the array lengths do not match or - * are less than 2. - * @throws MaxCountExceededException if an error occurs computing the - * p-value. - */ - public double gTestIntrinsic(final double[] expected, final long[] observed) - throws NotPositiveException, NotStrictlyPositiveException, - DimensionMismatchException, MaxCountExceededException { - - // pass a null rng to avoid unneeded overhead as we will not sample from this distribution - final ChiSquaredDistribution distribution = - new ChiSquaredDistribution(expected.length - 2.0); - return 1.0 - distribution.cumulativeProbability(g(expected, observed)); - } - - /** - * Performs a G-Test (Log-Likelihood Ratio Test) for goodness of fit - * evaluating the null hypothesis that the observed counts conform to the - * frequency distribution described by the expected counts, with - * significance level {@code alpha}. Returns true iff the null - * hypothesis can be rejected with {@code 100 * (1 - alpha)} percent confidence. - * - *

Example:
To test the hypothesis that - * {@code observed} follows {@code expected} at the 99% level, - * use

- * {@code gTest(expected, observed, 0.01)}

- * - *

Returns true iff {@link #gTest(double[], long[]) - * gTestGoodnessOfFitPValue(expected, observed)} < alpha

- * - *

Preconditions:

    - *
  • Expected counts must all be positive.
  • - *
  • Observed counts must all be ≥ 0.
  • - *
  • The observed and expected arrays must have the same length and their - * common length must be at least 2. - *
  • {@code 0 < alpha < 0.5}
- * - *

If any of the preconditions are not met, a - * {@code MathIllegalArgumentException} is thrown.

- * - *

Note:This implementation rescales the - * {@code expected} array if necessary to ensure that the sum of the - * expected and observed counts are equal.

- * - * @param observed array of observed frequency counts - * @param expected array of expected frequency counts - * @param alpha significance level of the test - * @return true iff null hypothesis can be rejected with confidence 1 - - * alpha - * @throws NotPositiveException if {@code observed} has negative entries - * @throws NotStrictlyPositiveException if {@code expected} has entries that - * are not strictly positive - * @throws DimensionMismatchException if the array lengths do not match or - * are less than 2. - * @throws MaxCountExceededException if an error occurs computing the - * p-value. - * @throws OutOfRangeException if alpha is not strictly greater than zero - * and less than or equal to 0.5 - */ - public boolean gTest(final double[] expected, final long[] observed, - final double alpha) - throws NotPositiveException, NotStrictlyPositiveException, - DimensionMismatchException, OutOfRangeException, MaxCountExceededException { - - if ((alpha <= 0) || (alpha > 0.5)) { - throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, - alpha, 0, 0.5); - } - return gTest(expected, observed) < alpha; - } - - /** - * Calculates the Shannon - * entropy for 2 Dimensional Matrix. The value returned is the entropy - * of the vector formed by concatenating the rows (or columns) of {@code k} - * to form a vector. See {@link #entropy(long[])}. - * - * @param k 2 Dimensional Matrix of long values (for ex. the counts of a - * trials) - * @return Shannon Entropy of the given Matrix - * - */ - private double entropy(final long[][] k) { - double h = 0d; - double sum_k = 0d; - for (int i = 0; i < k.length; i++) { - for (int j = 0; j < k[i].length; j++) { - sum_k += (double) k[i][j]; - } - } - for (int i = 0; i < k.length; i++) { - for (int j = 0; j < k[i].length; j++) { - if (k[i][j] != 0) { - final double p_ij = (double) k[i][j] / sum_k; - h += p_ij * FastMath.log(p_ij); - } - } - } - return -h; - } - - /** - * Calculates the - * Shannon entropy for a vector. The values of {@code k} are taken to be - * incidence counts of the values of a random variable. What is returned is
- * ∑pilog(pi
- * where pi = k[i] / (sum of elements in k) - * - * @param k Vector (for ex. Row Sums of a trials) - * @return Shannon Entropy of the given Vector - * - */ - private double entropy(final long[] k) { - double h = 0d; - double sum_k = 0d; - for (int i = 0; i < k.length; i++) { - sum_k += (double) k[i]; - } - for (int i = 0; i < k.length; i++) { - if (k[i] != 0) { - final double p_i = (double) k[i] / sum_k; - h += p_i * FastMath.log(p_i); - } - } - return -h; - } - - /** - *

Computes a G (Log-Likelihood Ratio) two sample test statistic for - * independence comparing frequency counts in - * {@code observed1} and {@code observed2}. The sums of frequency - * counts in the two samples are not required to be the same. The formula - * used to compute the test statistic is

- * - *

{@code 2 * totalSum * [H(rowSums) + H(colSums) - H(k)]}

- * - *

where {@code H} is the - * - * Shannon Entropy of the random variable formed by viewing the elements - * of the argument array as incidence counts;
- * {@code k} is a matrix with rows {@code [observed1, observed2]};
- * {@code rowSums, colSums} are the row/col sums of {@code k};
- * and {@code totalSum} is the overall sum of all entries in {@code k}.

- * - *

This statistic can be used to perform a G test evaluating the null - * hypothesis that both observed counts are independent

- * - *

Preconditions:

    - *
  • Observed counts must be non-negative.
  • - *
  • Observed counts for a specific bin must not both be zero.
  • - *
  • Observed counts for a specific sample must not all be 0.
  • - *
  • The arrays {@code observed1} and {@code observed2} must have - * the same length and their common length must be at least 2.
- * - *

If any of the preconditions are not met, a - * {@code MathIllegalArgumentException} is thrown.

- * - * @param observed1 array of observed frequency counts of the first data set - * @param observed2 array of observed frequency counts of the second data - * set - * @return G-Test statistic - * @throws DimensionMismatchException the lengths of the arrays do not - * match or their common length is less than 2 - * @throws NotPositiveException if any entry in {@code observed1} or - * {@code observed2} is negative - * @throws ZeroException if either all counts of - * {@code observed1} or {@code observed2} are zero, or if the count - * at the same index is zero for both arrays. - */ - public double gDataSetsComparison(final long[] observed1, final long[] observed2) - throws DimensionMismatchException, NotPositiveException, ZeroException { - - // Make sure lengths are same - if (observed1.length < 2) { - throw new DimensionMismatchException(observed1.length, 2); - } - if (observed1.length != observed2.length) { - throw new DimensionMismatchException(observed1.length, observed2.length); - } - - // Ensure non-negative counts - MathArrays.checkNonNegative(observed1); - MathArrays.checkNonNegative(observed2); - - // Compute and compare count sums - long countSum1 = 0; - long countSum2 = 0; - - // Compute and compare count sums - final long[] collSums = new long[observed1.length]; - final long[][] k = new long[2][observed1.length]; - - for (int i = 0; i < observed1.length; i++) { - if (observed1[i] == 0 && observed2[i] == 0) { - throw new ZeroException(LocalizedFormats.OBSERVED_COUNTS_BOTTH_ZERO_FOR_ENTRY, i); - } else { - countSum1 += observed1[i]; - countSum2 += observed2[i]; - collSums[i] = observed1[i] + observed2[i]; - k[0][i] = observed1[i]; - k[1][i] = observed2[i]; - } - } - // Ensure neither sample is uniformly 0 - if (countSum1 == 0 || countSum2 == 0) { - throw new ZeroException(); - } - final long[] rowSums = {countSum1, countSum2}; - final double sum = (double) countSum1 + (double) countSum2; - return 2 * sum * (entropy(rowSums) + entropy(collSums) - entropy(k)); - } - - /** - * Calculates the root log-likelihood ratio for 2 state Datasets. See - * {@link #gDataSetsComparison(long[], long[] )}. - * - *

Given two events A and B, let k11 be the number of times both events - * occur, k12 the incidence of B without A, k21 the count of A without B, - * and k22 the number of times neither A nor B occurs. What is returned - * by this method is

- * - *

{@code (sgn) sqrt(gValueDataSetsComparison({k11, k12}, {k21, k22})}

- * - *

where {@code sgn} is -1 if {@code k11 / (k11 + k12) < k21 / (k21 + k22))};
- * 1 otherwise.

- * - *

Signed root LLR has two advantages over the basic LLR: a) it is positive - * where k11 is bigger than expected, negative where it is lower b) if there is - * no difference it is asymptotically normally distributed. This allows one - * to talk about "number of standard deviations" which is a more common frame - * of reference than the chi^2 distribution.

- * - * @param k11 number of times the two events occurred together (AB) - * @param k12 number of times the second event occurred WITHOUT the - * first event (notA,B) - * @param k21 number of times the first event occurred WITHOUT the - * second event (A, notB) - * @param k22 number of times something else occurred (i.e. was neither - * of these events (notA, notB) - * @return root log-likelihood ratio - * - */ - public double rootLogLikelihoodRatio(final long k11, long k12, - final long k21, final long k22) { - final double llr = gDataSetsComparison( - new long[]{k11, k12}, new long[]{k21, k22}); - double sqrt = FastMath.sqrt(llr); - if ((double) k11 / (k11 + k12) < (double) k21 / (k21 + k22)) { - sqrt = -sqrt; - } - return sqrt; - } - - /** - *

Returns the observed significance level, or - * p-value, associated with a G-Value (Log-Likelihood Ratio) for two - * sample test comparing bin frequency counts in {@code observed1} and - * {@code observed2}.

- * - *

The number returned is the smallest significance level at which one - * can reject the null hypothesis that the observed counts conform to the - * same distribution.

- * - *

See {@link #gTest(double[], long[])} for details - * on how the p-value is computed. The degrees of of freedom used to - * perform the test is one less than the common length of the input observed - * count arrays.

- * - *

Preconditions: - *

  • Observed counts must be non-negative.
  • - *
  • Observed counts for a specific bin must not both be zero.
  • - *
  • Observed counts for a specific sample must not all be 0.
  • - *
  • The arrays {@code observed1} and {@code observed2} must - * have the same length and their common length must be at least 2.
  • - *
- *

If any of the preconditions are not met, a - * {@code MathIllegalArgumentException} is thrown.

- * - * @param observed1 array of observed frequency counts of the first data set - * @param observed2 array of observed frequency counts of the second data - * set - * @return p-value - * @throws DimensionMismatchException the length of the arrays does not - * match or their common length is less than 2 - * @throws NotPositiveException if any of the entries in {@code observed1} or - * {@code observed2} are negative - * @throws ZeroException if either all counts of {@code observed1} or - * {@code observed2} are zero, or if the count at some index is - * zero for both arrays - * @throws MaxCountExceededException if an error occurs computing the - * p-value. - */ - public double gTestDataSetsComparison(final long[] observed1, - final long[] observed2) - throws DimensionMismatchException, NotPositiveException, ZeroException, - MaxCountExceededException { - - // pass a null rng to avoid unneeded overhead as we will not sample from this distribution - final ChiSquaredDistribution distribution = - new ChiSquaredDistribution((double) observed1.length - 1); - return 1 - distribution.cumulativeProbability( - gDataSetsComparison(observed1, observed2)); - } - - /** - *

Performs a G-Test (Log-Likelihood Ratio Test) comparing two binned - * data sets. The test evaluates the null hypothesis that the two lists - * of observed counts conform to the same frequency distribution, with - * significance level {@code alpha}. Returns true iff the null - * hypothesis can be rejected with 100 * (1 - alpha) percent confidence. - *

- *

See {@link #gDataSetsComparison(long[], long[])} for details - * on the formula used to compute the G (LLR) statistic used in the test and - * {@link #gTest(double[], long[])} for information on how - * the observed significance level is computed. The degrees of of freedom used - * to perform the test is one less than the common length of the input observed - * count arrays.

- * - * Preconditions:
    - *
  • Observed counts must be non-negative.
  • - *
  • Observed counts for a specific bin must not both be zero.
  • - *
  • Observed counts for a specific sample must not all be 0.
  • - *
  • The arrays {@code observed1} and {@code observed2} must - * have the same length and their common length must be at least 2.
  • - *
  • {@code 0 < alpha < 0.5}
- * - *

If any of the preconditions are not met, a - * {@code MathIllegalArgumentException} is thrown.

- * - * @param observed1 array of observed frequency counts of the first data set - * @param observed2 array of observed frequency counts of the second data - * set - * @param alpha significance level of the test - * @return true iff null hypothesis can be rejected with confidence 1 - - * alpha - * @throws DimensionMismatchException the length of the arrays does not - * match - * @throws NotPositiveException if any of the entries in {@code observed1} or - * {@code observed2} are negative - * @throws ZeroException if either all counts of {@code observed1} or - * {@code observed2} are zero, or if the count at some index is - * zero for both arrays - * @throws OutOfRangeException if {@code alpha} is not in the range - * (0, 0.5] - * @throws MaxCountExceededException if an error occurs performing the test - */ - public boolean gTestDataSetsComparison( - final long[] observed1, - final long[] observed2, - final double alpha) - throws DimensionMismatchException, NotPositiveException, - ZeroException, OutOfRangeException, MaxCountExceededException { - - if (alpha <= 0 || alpha > 0.5) { - throw new OutOfRangeException( - LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5); - } - return gTestDataSetsComparison(observed1, observed2) < alpha; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/InferenceTestUtils.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/InferenceTestUtils.java deleted file mode 100644 index 00c4615d5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/InferenceTestUtils.java +++ /dev/null @@ -1,745 +0,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. - */ -package org.apache.commons.math4.stat.inference; - -import java.util.Collection; - -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.statistics.distribution.ContinuousDistribution; -import org.apache.commons.math4.exception.ConvergenceException; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.InsufficientDataException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.ZeroException; -import org.apache.commons.math4.stat.descriptive.StatisticalSummary; - -/** - * A collection of static methods to create inference test instances or to - * perform inference tests. - * - * @since 1.1 - */ -public class InferenceTestUtils { - - /** Singleton TTest instance. */ - private static final TTest T_TEST = new TTest(); - - /** Singleton ChiSquareTest instance. */ - private static final ChiSquareTest CHI_SQUARE_TEST = new ChiSquareTest(); - - /** Singleton OneWayAnova instance. */ - private static final OneWayAnova ONE_WAY_ANANOVA = new OneWayAnova(); - - /** Singleton G-Test instance. */ - private static final GTest G_TEST = new GTest(); - - /** Singleton K-S test instance */ - private static final KolmogorovSmirnovTest KS_TEST = new KolmogorovSmirnovTest(); - - /** - * Prevent instantiation. - */ - private InferenceTestUtils() { - super(); - } - - // CHECKSTYLE: stop JavadocMethodCheck - - /** - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @return t statistic - * @see TTest#homoscedasticT(double[], double[]) - */ - public static double homoscedasticT(final double[] sample1, final double[] sample2) - throws NullArgumentException, NumberIsTooSmallException { - return T_TEST.homoscedasticT(sample1, sample2); - } - - /** - * @param sampleStats1 StatisticalSummary describing data from the first sample - * @param sampleStats2 StatisticalSummary describing data from the second sample - * @return t statistic - * @see TTest#homoscedasticT(org.apache.commons.math4.stat.descriptive.StatisticalSummary, org.apache.commons.math4.stat.descriptive.StatisticalSummary) - */ - public static double homoscedasticT(final StatisticalSummary sampleStats1, - final StatisticalSummary sampleStats2) - throws NullArgumentException, NumberIsTooSmallException { - return T_TEST.homoscedasticT(sampleStats1, sampleStats2); - } - - /** - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with - * confidence 1 - alpha - * @see TTest#homoscedasticTTest(double[], double[], double) - */ - public static boolean homoscedasticTTest(final double[] sample1, final double[] sample2, - final double alpha) - throws NullArgumentException, NumberIsTooSmallException, - OutOfRangeException, MaxCountExceededException { - return T_TEST.homoscedasticTTest(sample1, sample2, alpha); - } - - /** - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @return p-value for t-test - * @see TTest#homoscedasticTTest(double[], double[]) - */ - public static double homoscedasticTTest(final double[] sample1, final double[] sample2) - throws NullArgumentException, NumberIsTooSmallException, MaxCountExceededException { - return T_TEST.homoscedasticTTest(sample1, sample2); - } - - /** - * @param sampleStats1 StatisticalSummary describing data from the first sample - * @param sampleStats2 StatisticalSummary describing data from the second sample - * @return p-value for t-test - * @see TTest#homoscedasticTTest(org.apache.commons.math4.stat.descriptive.StatisticalSummary, org.apache.commons.math4.stat.descriptive.StatisticalSummary) - */ - public static double homoscedasticTTest(final StatisticalSummary sampleStats1, - final StatisticalSummary sampleStats2) - throws NullArgumentException, NumberIsTooSmallException, MaxCountExceededException { - return T_TEST.homoscedasticTTest(sampleStats1, sampleStats2); - } - - /** - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @return t statistic - * @see TTest#pairedT(double[], double[]) - */ - public static double pairedT(final double[] sample1, final double[] sample2) - throws NullArgumentException, NoDataException, - DimensionMismatchException, NumberIsTooSmallException { - return T_TEST.pairedT(sample1, sample2); - } - - /** - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with - * confidence 1 - alpha - * @see TTest#pairedTTest(double[], double[], double) - */ - public static boolean pairedTTest(final double[] sample1, final double[] sample2, - final double alpha) - throws NullArgumentException, NoDataException, DimensionMismatchException, - NumberIsTooSmallException, OutOfRangeException, MaxCountExceededException { - return T_TEST.pairedTTest(sample1, sample2, alpha); - } - - /** - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @return p-value for t-test - * @see TTest#pairedTTest(double[], double[]) - */ - public static double pairedTTest(final double[] sample1, final double[] sample2) - throws NullArgumentException, NoDataException, DimensionMismatchException, - NumberIsTooSmallException, MaxCountExceededException { - return T_TEST.pairedTTest(sample1, sample2); - } - - /** - * @param mu comparison constant - * @param observed array of values - * @return t statistic - * @see TTest#t(double, double[]) - */ - public static double t(final double mu, final double[] observed) - throws NullArgumentException, NumberIsTooSmallException { - return T_TEST.t(mu, observed); - } - - /** - * @param mu comparison constant - * @param sampleStats DescriptiveStatistics holding sample summary statitstics - * @return t statistic - * @see TTest#t(double, org.apache.commons.math4.stat.descriptive.StatisticalSummary) - */ - public static double t(final double mu, final StatisticalSummary sampleStats) - throws NullArgumentException, NumberIsTooSmallException { - return T_TEST.t(mu, sampleStats); - } - - /** - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @return t statistic - * @see TTest#t(double[], double[]) - */ - public static double t(final double[] sample1, final double[] sample2) - throws NullArgumentException, NumberIsTooSmallException { - return T_TEST.t(sample1, sample2); - } - - /** - * @param sampleStats1 StatisticalSummary describing data from the first sample - * @param sampleStats2 StatisticalSummary describing data from the second sample - * @return t statistic - * @see TTest#t(org.apache.commons.math4.stat.descriptive.StatisticalSummary, org.apache.commons.math4.stat.descriptive.StatisticalSummary) - */ - public static double t(final StatisticalSummary sampleStats1, - final StatisticalSummary sampleStats2) - throws NullArgumentException, NumberIsTooSmallException { - return T_TEST.t(sampleStats1, sampleStats2); - } - - /** - * @param mu constant value to compare sample mean against - * @param sample array of sample data values - * @param alpha significance level of the test - * @return p-value - * @see TTest#tTest(double, double[], double) - */ - public static boolean tTest(final double mu, final double[] sample, final double alpha) - throws NullArgumentException, NumberIsTooSmallException, - OutOfRangeException, MaxCountExceededException { - return T_TEST.tTest(mu, sample, alpha); - } - - /** - * @param mu constant value to compare sample mean against - * @param sample array of sample data values - * @return p-value - * @see TTest#tTest(double, double[]) - */ - public static double tTest(final double mu, final double[] sample) - throws NullArgumentException, NumberIsTooSmallException, - MaxCountExceededException { - return T_TEST.tTest(mu, sample); - } - - /** - * @param mu constant value to compare sample mean against - * @param sampleStats StatisticalSummary describing sample data values - * @param alpha significance level of the test - * @return p-value - * @see TTest#tTest(double, org.apache.commons.math4.stat.descriptive.StatisticalSummary, double) - */ - public static boolean tTest(final double mu, final StatisticalSummary sampleStats, - final double alpha) - throws NullArgumentException, NumberIsTooSmallException, - OutOfRangeException, MaxCountExceededException { - return T_TEST.tTest(mu, sampleStats, alpha); - } - - /** - * @param mu constant value to compare sample mean against - * @param sampleStats StatisticalSummary describing sample data - * @return p-value - * @see TTest#tTest(double, org.apache.commons.math4.stat.descriptive.StatisticalSummary) - */ - public static double tTest(final double mu, final StatisticalSummary sampleStats) - throws NullArgumentException, NumberIsTooSmallException, - MaxCountExceededException { - return T_TEST.tTest(mu, sampleStats); - } - - /** - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with - * confidence 1 - alpha - * @see TTest#tTest(double[], double[], double) - */ - public static boolean tTest(final double[] sample1, final double[] sample2, - final double alpha) - throws NullArgumentException, NumberIsTooSmallException, - OutOfRangeException, MaxCountExceededException { - return T_TEST.tTest(sample1, sample2, alpha); - } - - /** - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @return p-value for t-test - * @see TTest#tTest(double[], double[]) - */ - public static double tTest(final double[] sample1, final double[] sample2) - throws NullArgumentException, NumberIsTooSmallException, - MaxCountExceededException { - return T_TEST.tTest(sample1, sample2); - } - - /** - * @param sampleStats1 StatisticalSummary describing sample data values - * @param sampleStats2 StatisticalSummary describing sample data values - * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with - * confidence 1 - alpha - * @see TTest#tTest(org.apache.commons.math4.stat.descriptive.StatisticalSummary, org.apache.commons.math4.stat.descriptive.StatisticalSummary, double) - */ - public static boolean tTest(final StatisticalSummary sampleStats1, - final StatisticalSummary sampleStats2, - final double alpha) - throws NullArgumentException, NumberIsTooSmallException, - OutOfRangeException, MaxCountExceededException { - return T_TEST.tTest(sampleStats1, sampleStats2, alpha); - } - - /** - * @param sampleStats1 StatisticalSummary describing data from the first sample - * @param sampleStats2 StatisticalSummary describing data from the second sample - * @return p-value for t-test - * @see TTest#tTest(org.apache.commons.math4.stat.descriptive.StatisticalSummary, org.apache.commons.math4.stat.descriptive.StatisticalSummary) - */ - public static double tTest(final StatisticalSummary sampleStats1, - final StatisticalSummary sampleStats2) - throws NullArgumentException, NumberIsTooSmallException, - MaxCountExceededException { - return T_TEST.tTest(sampleStats1, sampleStats2); - } - - /** - * @param observed array of observed frequency counts - * @param expected array of expected frequency counts - * @return chiSquare test statistic -* @see ChiSquareTest#chiSquare(double[], long[]) - */ - public static double chiSquare(final double[] expected, final long[] observed) - throws NotPositiveException, NotStrictlyPositiveException, - DimensionMismatchException { - return CHI_SQUARE_TEST.chiSquare(expected, observed); - } - - /** - * @param counts array representation of 2-way table - * @return chiSquare test statistic - * @see ChiSquareTest#chiSquare(long[][]) - */ - public static double chiSquare(final long[][] counts) - throws NullArgumentException, NotPositiveException, - DimensionMismatchException { - return CHI_SQUARE_TEST.chiSquare(counts); - } - - /** - * @param observed array of observed frequency counts - * @param expected array of expected frequency counts - * @param alpha significance level of the test - * @return true iff null hypothesis can be rejected with confidence - * 1 - alpha - * @see ChiSquareTest#chiSquareTest(double[], long[], double) - */ - public static boolean chiSquareTest(final double[] expected, final long[] observed, - final double alpha) - throws NotPositiveException, NotStrictlyPositiveException, - DimensionMismatchException, OutOfRangeException, MaxCountExceededException { - return CHI_SQUARE_TEST.chiSquareTest(expected, observed, alpha); - } - - /** - * @param observed array of observed frequency counts - * @param expected array of expected frequency counts - * @return p-value - * @see ChiSquareTest#chiSquareTest(double[], long[]) - */ - public static double chiSquareTest(final double[] expected, final long[] observed) - throws NotPositiveException, NotStrictlyPositiveException, - DimensionMismatchException, MaxCountExceededException { - return CHI_SQUARE_TEST.chiSquareTest(expected, observed); - } - - /** - * @param counts array representation of 2-way table - * @param alpha significance level of the test - * @return true iff null hypothesis can be rejected with confidence - * 1 - alpha - * @see ChiSquareTest#chiSquareTest(long[][], double) - */ - public static boolean chiSquareTest(final long[][] counts, final double alpha) - throws NullArgumentException, DimensionMismatchException, - NotPositiveException, OutOfRangeException, MaxCountExceededException { - return CHI_SQUARE_TEST.chiSquareTest(counts, alpha); - } - - /** - * @param counts array representation of 2-way table - * @return p-value - * @see ChiSquareTest#chiSquareTest(long[][]) - */ - public static double chiSquareTest(final long[][] counts) - throws NullArgumentException, DimensionMismatchException, - NotPositiveException, MaxCountExceededException { - return CHI_SQUARE_TEST.chiSquareTest(counts); - } - - /** - * @param observed1 array of observed frequency counts of the first data set - * @param observed2 array of observed frequency counts of the second data set - * @return chiSquare test statistic - * @see ChiSquareTest#chiSquareDataSetsComparison(long[], long[]) - * - * @since 1.2 - */ - public static double chiSquareDataSetsComparison(final long[] observed1, - final long[] observed2) - throws DimensionMismatchException, NotPositiveException, ZeroException { - return CHI_SQUARE_TEST.chiSquareDataSetsComparison(observed1, observed2); - } - - /** - * @param observed1 array of observed frequency counts of the first data set - * @param observed2 array of observed frequency counts of the second data set - * @return p-value - * @see ChiSquareTest#chiSquareTestDataSetsComparison(long[], long[]) - * - * @since 1.2 - */ - public static double chiSquareTestDataSetsComparison(final long[] observed1, - final long[] observed2) - throws DimensionMismatchException, NotPositiveException, ZeroException, - MaxCountExceededException { - return CHI_SQUARE_TEST.chiSquareTestDataSetsComparison(observed1, observed2); - } - - /** - * @param observed1 array of observed frequency counts of the first data set - * @param observed2 array of observed frequency counts of the second data set - * @param alpha significance level of the test - * @return true iff null hypothesis can be rejected with confidence - * 1 - alpha - * @see ChiSquareTest#chiSquareTestDataSetsComparison(long[], long[], double) - * - * @since 1.2 - */ - public static boolean chiSquareTestDataSetsComparison(final long[] observed1, - final long[] observed2, - final double alpha) - throws DimensionMismatchException, NotPositiveException, - ZeroException, OutOfRangeException, MaxCountExceededException { - return CHI_SQUARE_TEST.chiSquareTestDataSetsComparison(observed1, observed2, alpha); - } - - /** - * @param categoryData Collection of double[] - * arrays each containing data for one category - * @return Fvalue - * @see OneWayAnova#anovaFValue(Collection) - * - * @since 1.2 - */ - public static double oneWayAnovaFValue(final Collection categoryData) - throws NullArgumentException, DimensionMismatchException { - return ONE_WAY_ANANOVA.anovaFValue(categoryData); - } - - /** - * @param categoryData Collection of double[] - * arrays each containing data for one category - * @return Pvalue - * @see OneWayAnova#anovaPValue(Collection) - * - * @since 1.2 - */ - public static double oneWayAnovaPValue(final Collection categoryData) - throws NullArgumentException, DimensionMismatchException, - ConvergenceException, MaxCountExceededException { - return ONE_WAY_ANANOVA.anovaPValue(categoryData); - } - - /** - * @param categoryData Collection of double[] - * arrays each containing data for one category - * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with - * confidence 1 - alpha - * @see OneWayAnova#anovaTest(Collection,double) - * - * @since 1.2 - */ - public static boolean oneWayAnovaTest(final Collection categoryData, - final double alpha) - throws NullArgumentException, DimensionMismatchException, - OutOfRangeException, ConvergenceException, MaxCountExceededException { - return ONE_WAY_ANANOVA.anovaTest(categoryData, alpha); - } - - /** - * @param observed array of observed frequency counts - * @param expected array of expected frequency counts - * @return G-Test statistic - * @see GTest#g(double[], long[]) - * @since 3.1 - */ - public static double g(final double[] expected, final long[] observed) - throws NotPositiveException, NotStrictlyPositiveException, - DimensionMismatchException { - return G_TEST.g(expected, observed); - } - - /** - * @param observed array of observed frequency counts - * @param expected array of expected frequency counts - * @return p-value - * @see GTest#gTest( double[], long[] ) - * @since 3.1 - */ - public static double gTest(final double[] expected, final long[] observed) - throws NotPositiveException, NotStrictlyPositiveException, - DimensionMismatchException, MaxCountExceededException { - return G_TEST.gTest(expected, observed); - } - - /** - * @param observed array of observed frequency counts - * @param expected array of expected frequency counts - * @return p-value - * @see GTest#gTestIntrinsic(double[], long[] ) - * @since 3.1 - */ - public static double gTestIntrinsic(final double[] expected, final long[] observed) - throws NotPositiveException, NotStrictlyPositiveException, - DimensionMismatchException, MaxCountExceededException { - return G_TEST.gTestIntrinsic(expected, observed); - } - - /** - * @param observed array of observed frequency counts - * @param expected array of expected frequency counts - * @param alpha significance level of the test - * @return true iff null hypothesis can be rejected with confidence 1 - - * alpha - * @see GTest#gTest( double[],long[],double) - * @since 3.1 - */ - public static boolean gTest(final double[] expected, final long[] observed, - final double alpha) - throws NotPositiveException, NotStrictlyPositiveException, - DimensionMismatchException, OutOfRangeException, MaxCountExceededException { - return G_TEST.gTest(expected, observed, alpha); - } - - /** - * @param observed1 array of observed frequency counts of the first data set - * @param observed2 array of observed frequency counts of the second data - * set - * @return G-Test statistic - * @see GTest#gDataSetsComparison(long[], long[]) - * @since 3.1 - */ - public static double gDataSetsComparison(final long[] observed1, - final long[] observed2) - throws DimensionMismatchException, NotPositiveException, ZeroException { - return G_TEST.gDataSetsComparison(observed1, observed2); - } - - /** - * @param k11 number of times the two events occurred together (AB) - * @param k12 number of times the second event occurred WITHOUT the - * first event (notA,B) - * @param k21 number of times the first event occurred WITHOUT the - * second event (A, notB) - * @param k22 number of times something else occurred (i.e. was neither - * of these events (notA, notB) - * @return root log-likelihood ratio - * @see GTest#rootLogLikelihoodRatio(long, long, long, long) - * @since 3.1 - */ - public static double rootLogLikelihoodRatio(final long k11, final long k12, final long k21, final long k22) - throws DimensionMismatchException, NotPositiveException, ZeroException { - return G_TEST.rootLogLikelihoodRatio(k11, k12, k21, k22); - } - - - /** - * @param observed1 array of observed frequency counts of the first data set - * @param observed2 array of observed frequency counts of the second data - * set - * @return p-value - * @see GTest#gTestDataSetsComparison(long[], long[]) - * @since 3.1 - */ - public static double gTestDataSetsComparison(final long[] observed1, - final long[] observed2) - throws DimensionMismatchException, NotPositiveException, ZeroException, - MaxCountExceededException { - return G_TEST.gTestDataSetsComparison(observed1, observed2); - } - - /** - * @param observed1 array of observed frequency counts of the first data set - * @param observed2 array of observed frequency counts of the second data - * set - * @param alpha significance level of the test - * @return true iff null hypothesis can be rejected with confidence 1 - - * alpha - * @see GTest#gTestDataSetsComparison(long[],long[],double) - * @since 3.1 - */ - public static boolean gTestDataSetsComparison(final long[] observed1, - final long[] observed2, - final double alpha) - throws DimensionMismatchException, NotPositiveException, - ZeroException, OutOfRangeException, MaxCountExceededException { - return G_TEST.gTestDataSetsComparison(observed1, observed2, alpha); - } - - /** - * @param dist reference distribution - * @param data sample being evaluated - * @return Kolmogorov-Smirnov statistic \(D_n\) - * @see org.apache.commons.math4.stat.inference.KolmogorovSmirnovTest#kolmogorovSmirnovStatistic(ContinuousDistribution, double[]) - * @since 3.3 - */ - public static double kolmogorovSmirnovStatistic(ContinuousDistribution dist, double[] data) - throws InsufficientDataException, NullArgumentException { - return KS_TEST.kolmogorovSmirnovStatistic(dist, data); - } - - /** - * @param dist reference distribution - * @param data sample being being evaluated - * @return the p-value associated with the null hypothesis that {@code data} is a sample from - * {@code distribution} - * @see org.apache.commons.math4.stat.inference.KolmogorovSmirnovTest#kolmogorovSmirnovTest(ContinuousDistribution, double[]) - * @since 3.3 - */ - public static double kolmogorovSmirnovTest(ContinuousDistribution dist, double[] data) - throws InsufficientDataException, NullArgumentException { - return KS_TEST.kolmogorovSmirnovTest(dist, data); - } - - /** - * @param dist reference distribution - * @param data sample being being evaluated - * @param strict whether or not to force exact computation of the p-value - * @return the p-value associated with the null hypothesis that {@code data} is a sample from - * {@code distribution} - * @see org.apache.commons.math4.stat.inference.KolmogorovSmirnovTest#kolmogorovSmirnovTest(ContinuousDistribution, double[], boolean) - * @since 3.3 - */ - public static double kolmogorovSmirnovTest(ContinuousDistribution dist, double[] data, boolean strict) - throws InsufficientDataException, NullArgumentException { - return KS_TEST.kolmogorovSmirnovTest(dist, data, strict); - } - - /** - * @param dist reference distribution - * @param data sample being being evaluated - * @param alpha significance level of the test - * @return true iff the null hypothesis that {@code data} is a sample from {@code distribution} - * can be rejected with confidence 1 - {@code alpha} - * @see org.apache.commons.math4.stat.inference.KolmogorovSmirnovTest#kolmogorovSmirnovTest(ContinuousDistribution, double[], double) - * @since 3.3 - */ - public static boolean kolmogorovSmirnovTest(ContinuousDistribution dist, double[] data, double alpha) - throws InsufficientDataException, NullArgumentException { - return KS_TEST.kolmogorovSmirnovTest(dist, data, alpha); - } - - /** - * @param x first sample - * @param y second sample - * @return test statistic \(D_{n,m}\) used to evaluate the null hypothesis that {@code x} and - * {@code y} represent samples from the same underlying distribution - * @see org.apache.commons.math4.stat.inference.KolmogorovSmirnovTest#kolmogorovSmirnovStatistic(double[], double[]) - * @since 3.3 - */ - public static double kolmogorovSmirnovStatistic(double[] x, double[] y) - throws InsufficientDataException, NullArgumentException { - return KS_TEST.kolmogorovSmirnovStatistic(x, y); - } - - /** - * @param x first sample dataset - * @param y second sample dataset - * @return p-value associated with the null hypothesis that {@code x} and {@code y} represent - * samples from the same distribution - * @see org.apache.commons.math4.stat.inference.KolmogorovSmirnovTest#kolmogorovSmirnovTest(double[], double[]) - * @since 3.3 - */ - public static double kolmogorovSmirnovTest(double[] x, double[] y) - throws InsufficientDataException, NullArgumentException { - return KS_TEST.kolmogorovSmirnovTest(x, y); - } - - /** - * @param x first sample dataset. - * @param y second sample dataset. - * @param strict whether or not the probability to compute is expressed as - * a strict inequality (ignored for large samples). - * @return p-value associated with the null hypothesis that {@code x} and - * {@code y} represent samples from the same distribution. - * @see org.apache.commons.math4.stat.inference.KolmogorovSmirnovTest#kolmogorovSmirnovTest(double[], double[], boolean) - * @since 3.3 - */ - public static double kolmogorovSmirnovTest(double[] x, double[] y, boolean strict) - throws InsufficientDataException, NullArgumentException { - return KS_TEST.kolmogorovSmirnovTest(x, y, strict); - } - - /** - * @param d D-statistic value - * @param n first sample size - * @param m second sample size - * @param strict whether or not the probability to compute is expressed as a strict inequality - * @return probability that a randomly selected m-n partition of m + n generates \(D_{n,m}\) - * greater than (resp. greater than or equal to) {@code d} - * @see org.apache.commons.math4.stat.inference.KolmogorovSmirnovTest#exactP(double, int, int, boolean) - * @since 3.3 - */ - public static double exactP(double d, int m, int n, boolean strict) { - return KS_TEST.exactP(d, n, m, strict); - } - - /** - * @param d D-statistic value - * @param n first sample size - * @param m second sample size - * @return approximate probability that a randomly selected m-n partition of m + n generates - * \(D_{n,m}\) greater than {@code d} - * @see org.apache.commons.math4.stat.inference.KolmogorovSmirnovTest#approximateP(double, int, int) - * @since 3.3 - */ - public static double approximateP(double d, int n, int m) { - return KS_TEST.approximateP(d, n, m); - } - - /** - * @param d D-statistic value - * @param n first sample size - * @param m second sample size - * @param iterations number of random partitions to generate - * @param strict whether or not the probability to compute is expressed as a strict inequality - * @param rng RNG used for generating the partitions. - * @return proportion of randomly generated m-n partitions of m + n that result in \(D_{n,m}\) - * greater than (resp. greater than or equal to) {@code d} - * @see org.apache.commons.math4.stat.inference.KolmogorovSmirnovTest#monteCarloP(double,int,int,boolean,int,UniformRandomProvider) - * @since 3.3 - */ - public static double monteCarloP(double d, int n, int m, boolean strict, int iterations, UniformRandomProvider rng) { - return KS_TEST.monteCarloP(d, n, m, strict, iterations, rng); - } - - - // CHECKSTYLE: resume JavadocMethodCheck - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/KolmogorovSmirnovTest.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/KolmogorovSmirnovTest.java deleted file mode 100644 index 153d1d6c6..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/KolmogorovSmirnovTest.java +++ /dev/null @@ -1,1206 +0,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. - */ - -package org.apache.commons.math4.stat.inference; - -import java.math.BigDecimal; -import java.util.Arrays; - -import org.apache.commons.rng.simple.RandomSource; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.statistics.distribution.ContinuousDistribution; -import org.apache.commons.numbers.combinatorics.BinomialCoefficientDouble; -import org.apache.commons.math4.distribution.EnumeratedRealDistribution; -import org.apache.commons.math4.distribution.AbstractRealDistribution; -import org.apache.commons.math4.exception.InsufficientDataException; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.MathInternalError; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.TooManyIterationsException; -import org.apache.commons.math4.exception.NotANumberException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.fraction.BigFraction; -import org.apache.commons.math4.fraction.BigFractionField; -import org.apache.commons.math4.fraction.FractionConversionException; -import org.apache.commons.math4.linear.Array2DRowFieldMatrix; -import org.apache.commons.math4.linear.FieldMatrix; -import org.apache.commons.math4.linear.MatrixUtils; -import org.apache.commons.math4.linear.RealMatrix; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.math4.util.MathUtils; - -/** - * Implementation of the - * Kolmogorov-Smirnov (K-S) test for equality of continuous distributions. - *

- * The K-S test uses a statistic based on the maximum deviation of the empirical distribution of - * sample data points from the distribution expected under the null hypothesis. For one-sample tests - * evaluating the null hypothesis that a set of sample data points follow a given distribution, the - * test statistic is \(D_n=\sup_x |F_n(x)-F(x)|\), where \(F\) is the expected distribution and - * \(F_n\) is the empirical distribution of the \(n\) sample data points. The distribution of - * \(D_n\) is estimated using a method based on [1] with certain quick decisions for extreme values - * given in [2]. - *

- *

- * Two-sample tests are also supported, evaluating the null hypothesis that the two samples - * {@code x} and {@code y} come from the same underlying distribution. In this case, the test - * statistic is \(D_{n,m}=\sup_t | F_n(t)-F_m(t)|\) where \(n\) is the length of {@code x}, \(m\) is - * the length of {@code y}, \(F_n\) is the empirical distribution that puts mass \(1/n\) at each of - * the values in {@code x} and \(F_m\) is the empirical distribution of the {@code y} values. The - * default 2-sample test method, {@link #kolmogorovSmirnovTest(double[], double[])} works as - * follows: - *

    - *
  • When the product of the sample sizes is less than 10000, the method presented in [4] - * is used to compute the exact p-value for the 2-sample test.
  • - *
  • When the product of the sample sizes is larger, the asymptotic - * distribution of \(D_{n,m}\) is used. See {@link #approximateP(double, int, int)} for details on - * the approximation.
  • - *

- * For small samples (former case), if the data contains ties, random jitter is added - * to the sample data to break ties before applying the algorithm above. Alternatively, - * the {@link #bootstrap(double[],double[],int,boolean,UniformRandomProvider)} - * method, modeled after ks.boot - * in the R Matching package [3], can be used if ties are known to be present in the data. - *

- *

- * In the two-sample case, \(D_{n,m}\) has a discrete distribution. This makes the p-value - * associated with the null hypothesis \(H_0 : D_{n,m} \ge d \) differ from \(H_0 : D_{n,m} \ge d \) - * by the mass of the observed value \(d\). To distinguish these, the two-sample tests use a boolean - * {@code strict} parameter. This parameter is ignored for large samples. - *

- *

- * The methods used by the 2-sample default implementation are also exposed directly: - *

    - *
  • {@link #exactP(double, int, int, boolean)} computes exact 2-sample p-values
  • - *
  • {@link #approximateP(double, int, int)} uses the asymptotic distribution The {@code boolean} - * arguments in the first two methods allow the probability used to estimate the p-value to be - * expressed using strict or non-strict inequality. See - * {@link #kolmogorovSmirnovTest(double[], double[], boolean)}.
  • - *
- *

- * References: - *

- *
- * Note that [1] contains an error in computing h, refer to MATH-437 for details. - * - * @since 3.3 - */ -public class KolmogorovSmirnovTest { - /** - * Bound on the number of partial sums in {@link #ksSum(double, double, int)} - */ - private static final int MAXIMUM_PARTIAL_SUM_COUNT = 100000; - /** Convergence criterion for {@link #ksSum(double, double, int)} */ - private static final double KS_SUM_CAUCHY_CRITERION = 1e-20; - /** Convergence criterion for the sums in {@link #pelzGood(double, int)} */ - private static final double PG_SUM_RELATIVE_ERROR = 1e-10; - - /** - * When product of sample sizes exceeds this value, 2-sample K-S test uses asymptotic - * distribution to compute the p-value. - */ - private static final int LARGE_SAMPLE_PRODUCT = 10000; - - /** - * Computes the p-value, or observed significance level, of a one-sample Kolmogorov-Smirnov test - * evaluating the null hypothesis that {@code data} conforms to {@code distribution}. If - * {@code exact} is true, the distribution used to compute the p-value is computed using - * extended precision. See {@link #cdfExact(double, int)}. - * - * @param distribution reference distribution - * @param data sample being being evaluated - * @param exact whether or not to force exact computation of the p-value - * @return the p-value associated with the null hypothesis that {@code data} is a sample from - * {@code distribution} - * @throws InsufficientDataException if {@code data} does not have length at least 2 - * @throws NullArgumentException if {@code data} is null - */ - public double kolmogorovSmirnovTest(ContinuousDistribution distribution, double[] data, boolean exact) { - return 1d - cdf(kolmogorovSmirnovStatistic(distribution, data), data.length, exact); - } - - /** - * Computes the one-sample Kolmogorov-Smirnov test statistic, \(D_n=\sup_x |F_n(x)-F(x)|\) where - * \(F\) is the distribution (cdf) function associated with {@code distribution}, \(n\) is the - * length of {@code data} and \(F_n\) is the empirical distribution that puts mass \(1/n\) at - * each of the values in {@code data}. - * - * @param distribution reference distribution - * @param data sample being evaluated - * @return Kolmogorov-Smirnov statistic \(D_n\) - * @throws InsufficientDataException if {@code data} does not have length at least 2 - * @throws NullArgumentException if {@code data} is null - */ - public double kolmogorovSmirnovStatistic(ContinuousDistribution distribution, double[] data) { - checkArray(data); - final int n = data.length; - final double nd = n; - final double[] dataCopy = new double[n]; - System.arraycopy(data, 0, dataCopy, 0, n); - Arrays.sort(dataCopy); - double d = 0d; - for (int i = 1; i <= n; i++) { - final double yi = distribution.cumulativeProbability(dataCopy[i - 1]); - final double currD = FastMath.max(yi - (i - 1) / nd, i / nd - yi); - if (currD > d) { - d = currD; - } - } - return d; - } - - /** - * Computes the p-value, or observed significance level, of a two-sample Kolmogorov-Smirnov test - * evaluating the null hypothesis that {@code x} and {@code y} are samples drawn from the same - * probability distribution. Specifically, what is returned is an estimate of the probability - * that the {@link #kolmogorovSmirnovStatistic(double[], double[])} associated with a randomly - * selected partition of the combined sample into subsamples of sizes {@code x.length} and - * {@code y.length} will strictly exceed (if {@code strict} is {@code true}) or be at least as - * large as (if {@code strict} is {@code false}) as {@code kolmogorovSmirnovStatistic(x, y)}. - * - * @param x first sample dataset. - * @param y second sample dataset. - * @param strict whether or not the probability to compute is expressed as - * a strict inequality (ignored for large samples). - * @return p-value associated with the null hypothesis that {@code x} and - * {@code y} represent samples from the same distribution. - * @throws InsufficientDataException if either {@code x} or {@code y} does - * not have length at least 2. - * @throws NullArgumentException if either {@code x} or {@code y} is null. - * @throws NotANumberException if the input arrays contain NaN values. - * - * @see #bootstrap(double[],double[],int,boolean,UniformRandomProvider) - */ - public double kolmogorovSmirnovTest(double[] x, double[] y, boolean strict) { - final long lengthProduct = (long) x.length * y.length; - double[] xa = null; - double[] ya = null; - if (lengthProduct < LARGE_SAMPLE_PRODUCT && hasTies(x,y)) { - xa = MathArrays.copyOf(x); - ya = MathArrays.copyOf(y); - fixTies(xa, ya); - } else { - xa = x; - ya = y; - } - if (lengthProduct < LARGE_SAMPLE_PRODUCT) { - return exactP(kolmogorovSmirnovStatistic(xa, ya), x.length, y.length, strict); - } - return approximateP(kolmogorovSmirnovStatistic(x, y), x.length, y.length); - } - - /** - * Computes the p-value, or observed significance level, of a two-sample Kolmogorov-Smirnov test - * evaluating the null hypothesis that {@code x} and {@code y} are samples drawn from the same - * probability distribution. Assumes the strict form of the inequality used to compute the - * p-value. See {@link #kolmogorovSmirnovTest(ContinuousDistribution, double[], boolean)}. - * - * @param x first sample dataset - * @param y second sample dataset - * @return p-value associated with the null hypothesis that {@code x} and {@code y} represent - * samples from the same distribution - * @throws InsufficientDataException if either {@code x} or {@code y} does not have length at - * least 2 - * @throws NullArgumentException if either {@code x} or {@code y} is null - */ - public double kolmogorovSmirnovTest(double[] x, double[] y) { - return kolmogorovSmirnovTest(x, y, true); - } - - /** - * Computes the two-sample Kolmogorov-Smirnov test statistic, \(D_{n,m}=\sup_x |F_n(x)-F_m(x)|\) - * where \(n\) is the length of {@code x}, \(m\) is the length of {@code y}, \(F_n\) is the - * empirical distribution that puts mass \(1/n\) at each of the values in {@code x} and \(F_m\) - * is the empirical distribution of the {@code y} values. - * - * @param x first sample - * @param y second sample - * @return test statistic \(D_{n,m}\) used to evaluate the null hypothesis that {@code x} and - * {@code y} represent samples from the same underlying distribution - * @throws InsufficientDataException if either {@code x} or {@code y} does not have length at - * least 2 - * @throws NullArgumentException if either {@code x} or {@code y} is null - */ - public double kolmogorovSmirnovStatistic(double[] x, double[] y) { - return integralKolmogorovSmirnovStatistic(x, y)/((double)(x.length * (long)y.length)); - } - - /** - * Computes the two-sample Kolmogorov-Smirnov test statistic, \(D_{n,m}=\sup_x |F_n(x)-F_m(x)|\) - * where \(n\) is the length of {@code x}, \(m\) is the length of {@code y}, \(F_n\) is the - * empirical distribution that puts mass \(1/n\) at each of the values in {@code x} and \(F_m\) - * is the empirical distribution of the {@code y} values. Finally \(n m D_{n,m}\) is returned - * as long value. - * - * @param x first sample - * @param y second sample - * @return test statistic \(n m D_{n,m}\) used to evaluate the null hypothesis that {@code x} and - * {@code y} represent samples from the same underlying distribution - * @throws InsufficientDataException if either {@code x} or {@code y} does not have length at - * least 2 - * @throws NullArgumentException if either {@code x} or {@code y} is null - */ - private long integralKolmogorovSmirnovStatistic(double[] x, double[] y) { - checkArray(x); - checkArray(y); - // Copy and sort the sample arrays - final double[] sx = MathArrays.copyOf(x); - final double[] sy = MathArrays.copyOf(y); - Arrays.sort(sx); - Arrays.sort(sy); - final int n = sx.length; - final int m = sy.length; - - int rankX = 0; - int rankY = 0; - long curD = 0l; - - // Find the max difference between cdf_x and cdf_y - long supD = 0l; - do { - double z = Double.compare(sx[rankX], sy[rankY]) <= 0 ? sx[rankX] : sy[rankY]; - while(rankX < n && Double.compare(sx[rankX], z) == 0) { - rankX += 1; - curD += m; - } - while(rankY < m && Double.compare(sy[rankY], z) == 0) { - rankY += 1; - curD -= n; - } - if (curD > supD) { - supD = curD; - } - else if (-curD > supD) { - supD = -curD; - } - } while(rankX < n && rankY < m); - return supD; - } - - /** - * Computes the p-value, or observed significance level, of a one-sample Kolmogorov-Smirnov test - * evaluating the null hypothesis that {@code data} conforms to {@code distribution}. - * - * @param distribution reference distribution - * @param data sample being being evaluated - * @return the p-value associated with the null hypothesis that {@code data} is a sample from - * {@code distribution} - * @throws InsufficientDataException if {@code data} does not have length at least 2 - * @throws NullArgumentException if {@code data} is null - */ - public double kolmogorovSmirnovTest(ContinuousDistribution distribution, double[] data) { - return kolmogorovSmirnovTest(distribution, data, false); - } - - /** - * Performs a Kolmogorov-Smirnov - * test evaluating the null hypothesis that {@code data} conforms to {@code distribution}. - * - * @param distribution reference distribution - * @param data sample being being evaluated - * @param alpha significance level of the test - * @return true iff the null hypothesis that {@code data} is a sample from {@code distribution} - * can be rejected with confidence 1 - {@code alpha} - * @throws InsufficientDataException if {@code data} does not have length at least 2 - * @throws NullArgumentException if {@code data} is null - */ - public boolean kolmogorovSmirnovTest(ContinuousDistribution distribution, double[] data, double alpha) { - if ((alpha <= 0) || (alpha > 0.5)) { - throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5); - } - return kolmogorovSmirnovTest(distribution, data) < alpha; - } - - /** - * Estimates the p-value of a two-sample - * Kolmogorov-Smirnov test - * evaluating the null hypothesis that {@code x} and {@code y} are samples - * drawn from the same probability distribution. - * This method estimates the p-value by repeatedly sampling sets of size - * {@code x.length} and {@code y.length} from the empirical distribution - * of the combined sample. - * When {@code strict} is true, this is equivalent to the algorithm implemented - * in the R function {@code ks.boot}, described in
-     * Jasjeet S. Sekhon. 2011. 'Multivariate and Propensity Score Matching
-     * Software with Automated Balance Optimization: The Matching package for R.'
-     * Journal of Statistical Software, 42(7): 1-52.
-     * 
- * - * @param x First sample. - * @param y Second sample. - * @param iterations Number of bootstrap resampling iterations. - * @param strict Whether or not the null hypothesis is expressed as a strict inequality. - * @param rng RNG for creating the sampling sets. - * @return the estimated p-value. - */ - public double bootstrap(double[] x, - double[] y, - int iterations, - boolean strict, - UniformRandomProvider rng) { - final int xLength = x.length; - final int yLength = y.length; - final double[] combined = new double[xLength + yLength]; - System.arraycopy(x, 0, combined, 0, xLength); - System.arraycopy(y, 0, combined, xLength, yLength); - final ContinuousDistribution.Sampler sampler = new EnumeratedRealDistribution(combined).createSampler(rng); - final long d = integralKolmogorovSmirnovStatistic(x, y); - int greaterCount = 0; - int equalCount = 0; - double[] curX; - double[] curY; - long curD; - for (int i = 0; i < iterations; i++) { - curX = AbstractRealDistribution.sample(xLength, sampler); - curY = AbstractRealDistribution.sample(yLength, sampler); - curD = integralKolmogorovSmirnovStatistic(curX, curY); - if (curD > d) { - greaterCount++; - } else if (curD == d) { - equalCount++; - } - } - return strict ? greaterCount / (double) iterations : - (greaterCount + equalCount) / (double) iterations; - } - - /** - * Calculates \(P(D_n < d)\) using the method described in [1] with quick decisions for extreme - * values given in [2] (see above). The result is not exact as with - * {@link #cdfExact(double, int)} because calculations are based on - * {@code double} rather than {@link org.apache.commons.math4.fraction.BigFraction}. - * - * @param d statistic - * @param n sample size - * @return \(P(D_n < d)\) - * @throws MathArithmeticException if algorithm fails to convert {@code h} to a - * {@link org.apache.commons.math4.fraction.BigFraction} in expressing {@code d} as \((k - * - h) / m\) for integer {@code k, m} and \(0 \le h < 1\) - */ - public double cdf(double d, int n) - throws MathArithmeticException { - return cdf(d, n, false); - } - - /** - * Calculates {@code P(D_n < d)}. The result is exact in the sense that BigFraction/BigReal is - * used everywhere at the expense of very slow execution time. Almost never choose this in real - * applications unless you are very sure; this is almost solely for verification purposes. - * Normally, you would choose {@link #cdf(double, int)}. See the class - * javadoc for definitions and algorithm description. - * - * @param d statistic - * @param n sample size - * @return \(P(D_n < d)\) - * @throws MathArithmeticException if the algorithm fails to convert {@code h} to a - * {@link org.apache.commons.math4.fraction.BigFraction} in expressing {@code d} as \((k - * - h) / m\) for integer {@code k, m} and \(0 \le h < 1\) - */ - public double cdfExact(double d, int n) - throws MathArithmeticException { - return cdf(d, n, true); - } - - /** - * Calculates {@code P(D_n < d)} using method described in [1] with quick decisions for extreme - * values given in [2] (see above). - * - * @param d statistic - * @param n sample size - * @param exact whether the probability should be calculated exact using - * {@link org.apache.commons.math4.fraction.BigFraction} everywhere at the expense of - * very slow execution time, or if {@code double} should be used convenient places to - * gain speed. Almost never choose {@code true} in real applications unless you are very - * sure; {@code true} is almost solely for verification purposes. - * @return \(P(D_n < d)\) - * @throws MathArithmeticException if algorithm fails to convert {@code h} to a - * {@link org.apache.commons.math4.fraction.BigFraction} in expressing {@code d} as \((k - * - h) / m\) for integer {@code k, m} and \(0 \le h < 1\). - */ - public double cdf(double d, int n, boolean exact) - throws MathArithmeticException { - - final double ninv = 1 / ((double) n); - final double ninvhalf = 0.5 * ninv; - - if (d <= ninvhalf) { - return 0; - } else if (ninvhalf < d && d <= ninv) { - double res = 1; - final double f = 2 * d - ninv; - // n! f^n = n*f * (n-1)*f * ... * 1*x - for (int i = 1; i <= n; ++i) { - res *= i * f; - } - return res; - } else if (1 - ninv <= d && d < 1) { - return 1 - 2 * Math.pow(1 - d, n); - } else if (1 <= d) { - return 1; - } - if (exact) { - return exactK(d, n); - } - if (n <= 140) { - return roundedK(d, n); - } - return pelzGood(d, n); - } - - /** - * Calculates the exact value of {@code P(D_n < d)} using the method described in [1] (reference - * in class javadoc above) and {@link org.apache.commons.math4.fraction.BigFraction} (see - * above). - * - * @param d statistic - * @param n sample size - * @return the two-sided probability of \(P(D_n < d)\) - * @throws MathArithmeticException if algorithm fails to convert {@code h} to a - * {@link org.apache.commons.math4.fraction.BigFraction} in expressing {@code d} as \((k - * - h) / m\) for integer {@code k, m} and \(0 \le h < 1\). - */ - private double exactK(double d, int n) - throws MathArithmeticException { - - final int k = (int) Math.ceil(n * d); - - final FieldMatrix H = this.createExactH(d, n); - final FieldMatrix Hpower = H.power(n); - - BigFraction pFrac = Hpower.getEntry(k - 1, k - 1); - - for (int i = 1; i <= n; ++i) { - pFrac = pFrac.multiply(i).divide(n); - } - - /* - * BigFraction.doubleValue converts numerator to double and the denominator to double and - * divides afterwards. That gives NaN quite easy. This does not (scale is the number of - * digits): - */ - return pFrac.bigDecimalValue(20, BigDecimal.ROUND_HALF_UP).doubleValue(); - } - - /** - * Calculates {@code P(D_n < d)} using method described in [1] and doubles (see above). - * - * @param d statistic - * @param n sample size - * @return \(P(D_n < d)\) - */ - private double roundedK(double d, int n) { - - final int k = (int) Math.ceil(n * d); - final RealMatrix H = this.createRoundedH(d, n); - final RealMatrix Hpower = H.power(n); - - double pFrac = Hpower.getEntry(k - 1, k - 1); - for (int i = 1; i <= n; ++i) { - pFrac *= (double) i / (double) n; - } - - return pFrac; - } - - /** - * Computes the Pelz-Good approximation for \(P(D_n < d)\) as described in [2] in the class javadoc. - * - * @param d value of d-statistic (x in [2]) - * @param n sample size - * @return \(P(D_n < d)\) - * @since 3.4 - */ - public double pelzGood(double d, int n) { - // Change the variable since approximation is for the distribution evaluated at d / sqrt(n) - final double sqrtN = FastMath.sqrt(n); - final double z = d * sqrtN; - final double z2 = d * d * n; - final double z4 = z2 * z2; - final double z6 = z4 * z2; - final double z8 = z4 * z4; - - // Eventual return value - double ret = 0; - - // Compute K_0(z) - double sum = 0; - double increment = 0; - double kTerm = 0; - double z2Term = MathUtils.PI_SQUARED / (8 * z2); - int k = 1; - for (; k < MAXIMUM_PARTIAL_SUM_COUNT; k++) { - kTerm = 2 * k - 1; - increment = FastMath.exp(-z2Term * kTerm * kTerm); - sum += increment; - if (increment <= PG_SUM_RELATIVE_ERROR * sum) { - break; - } - } - if (k == MAXIMUM_PARTIAL_SUM_COUNT) { - throw new TooManyIterationsException(MAXIMUM_PARTIAL_SUM_COUNT); - } - ret = sum * FastMath.sqrt(2 * FastMath.PI) / z; - - // K_1(z) - // Sum is -inf to inf, but k term is always (k + 1/2) ^ 2, so really have - // twice the sum from k = 0 to inf (k = -1 is same as 0, -2 same as 1, ...) - final double twoZ2 = 2 * z2; - sum = 0; - kTerm = 0; - double kTerm2 = 0; - for (k = 0; k < MAXIMUM_PARTIAL_SUM_COUNT; k++) { - kTerm = k + 0.5; - kTerm2 = kTerm * kTerm; - increment = (MathUtils.PI_SQUARED * kTerm2 - z2) * FastMath.exp(-MathUtils.PI_SQUARED * kTerm2 / twoZ2); - sum += increment; - if (FastMath.abs(increment) < PG_SUM_RELATIVE_ERROR * FastMath.abs(sum)) { - break; - } - } - if (k == MAXIMUM_PARTIAL_SUM_COUNT) { - throw new TooManyIterationsException(MAXIMUM_PARTIAL_SUM_COUNT); - } - final double sqrtHalfPi = FastMath.sqrt(FastMath.PI / 2); - // Instead of doubling sum, divide by 3 instead of 6 - ret += sum * sqrtHalfPi / (3 * z4 * sqrtN); - - // K_2(z) - // Same drill as K_1, but with two doubly infinite sums, all k terms are even powers. - final double z4Term = 2 * z4; - final double z6Term = 6 * z6; - z2Term = 5 * z2; - final double pi4 = MathUtils.PI_SQUARED * MathUtils.PI_SQUARED; - sum = 0; - kTerm = 0; - kTerm2 = 0; - for (k = 0; k < MAXIMUM_PARTIAL_SUM_COUNT; k++) { - kTerm = k + 0.5; - kTerm2 = kTerm * kTerm; - increment = (z6Term + z4Term + MathUtils.PI_SQUARED * (z4Term - z2Term) * kTerm2 + - pi4 * (1 - twoZ2) * kTerm2 * kTerm2) * FastMath.exp(-MathUtils.PI_SQUARED * kTerm2 / twoZ2); - sum += increment; - if (FastMath.abs(increment) < PG_SUM_RELATIVE_ERROR * FastMath.abs(sum)) { - break; - } - } - if (k == MAXIMUM_PARTIAL_SUM_COUNT) { - throw new TooManyIterationsException(MAXIMUM_PARTIAL_SUM_COUNT); - } - double sum2 = 0; - kTerm2 = 0; - for (k = 1; k < MAXIMUM_PARTIAL_SUM_COUNT; k++) { - kTerm2 = k * k; - increment = MathUtils.PI_SQUARED * kTerm2 * FastMath.exp(-MathUtils.PI_SQUARED * kTerm2 / twoZ2); - sum2 += increment; - if (FastMath.abs(increment) < PG_SUM_RELATIVE_ERROR * FastMath.abs(sum2)) { - break; - } - } - if (k == MAXIMUM_PARTIAL_SUM_COUNT) { - throw new TooManyIterationsException(MAXIMUM_PARTIAL_SUM_COUNT); - } - // Again, adjust coefficients instead of doubling sum, sum2 - ret += (sqrtHalfPi / n) * (sum / (36 * z2 * z2 * z2 * z) - sum2 / (18 * z2 * z)); - - // K_3(z) One more time with feeling - two doubly infinite sums, all k powers even. - // Multiply coefficient denominators by 2, so omit doubling sums. - final double pi6 = pi4 * MathUtils.PI_SQUARED; - sum = 0; - double kTerm4 = 0; - double kTerm6 = 0; - for (k = 0; k < MAXIMUM_PARTIAL_SUM_COUNT; k++) { - kTerm = k + 0.5; - kTerm2 = kTerm * kTerm; - kTerm4 = kTerm2 * kTerm2; - kTerm6 = kTerm4 * kTerm2; - increment = (pi6 * kTerm6 * (5 - 30 * z2) + pi4 * kTerm4 * (-60 * z2 + 212 * z4) + - MathUtils.PI_SQUARED * kTerm2 * (135 * z4 - 96 * z6) - 30 * z6 - 90 * z8) * - FastMath.exp(-MathUtils.PI_SQUARED * kTerm2 / twoZ2); - sum += increment; - if (FastMath.abs(increment) < PG_SUM_RELATIVE_ERROR * FastMath.abs(sum)) { - break; - } - } - if (k == MAXIMUM_PARTIAL_SUM_COUNT) { - throw new TooManyIterationsException(MAXIMUM_PARTIAL_SUM_COUNT); - } - sum2 = 0; - for (k = 1; k < MAXIMUM_PARTIAL_SUM_COUNT; k++) { - kTerm2 = k * k; - kTerm4 = kTerm2 * kTerm2; - increment = (-pi4 * kTerm4 + 3 * MathUtils.PI_SQUARED * kTerm2 * z2) * - FastMath.exp(-MathUtils.PI_SQUARED * kTerm2 / twoZ2); - sum2 += increment; - if (FastMath.abs(increment) < PG_SUM_RELATIVE_ERROR * FastMath.abs(sum2)) { - break; - } - } - if (k == MAXIMUM_PARTIAL_SUM_COUNT) { - throw new TooManyIterationsException(MAXIMUM_PARTIAL_SUM_COUNT); - } - return ret + (sqrtHalfPi / (sqrtN * n)) * (sum / (3240 * z6 * z4) + - + sum2 / (108 * z6)); - - } - - /*** - * Creates {@code H} of size {@code m x m} as described in [1] (see above). - * - * @param d statistic - * @param n sample size - * @return H matrix - * @throws NumberIsTooLargeException if fractional part is greater than 1 - * @throws FractionConversionException if algorithm fails to convert {@code h} to a - * {@link org.apache.commons.math4.fraction.BigFraction} in expressing {@code d} as \((k - * - h) / m\) for integer {@code k, m} and \(0 <= h < 1\). - */ - private FieldMatrix createExactH(double d, int n) - throws NumberIsTooLargeException, FractionConversionException { - - final int k = (int) Math.ceil(n * d); - final int m = 2 * k - 1; - final double hDouble = k - n * d; - if (hDouble >= 1) { - throw new NumberIsTooLargeException(hDouble, 1.0, false); - } - BigFraction h = null; - try { - h = new BigFraction(hDouble, 1.0e-20, 10000); - } catch (final FractionConversionException e1) { - try { - h = new BigFraction(hDouble, 1.0e-10, 10000); - } catch (final FractionConversionException e2) { - h = new BigFraction(hDouble, 1.0e-5, 10000); - } - } - final BigFraction[][] Hdata = new BigFraction[m][m]; - - /* - * Start by filling everything with either 0 or 1. - */ - for (int i = 0; i < m; ++i) { - for (int j = 0; j < m; ++j) { - if (i - j + 1 < 0) { - Hdata[i][j] = BigFraction.ZERO; - } else { - Hdata[i][j] = BigFraction.ONE; - } - } - } - - /* - * Setting up power-array to avoid calculating the same value twice: hPowers[0] = h^1 ... - * hPowers[m-1] = h^m - */ - final BigFraction[] hPowers = new BigFraction[m]; - hPowers[0] = h; - for (int i = 1; i < m; ++i) { - hPowers[i] = h.multiply(hPowers[i - 1]); - } - - /* - * First column and last row has special values (each other reversed). - */ - for (int i = 0; i < m; ++i) { - Hdata[i][0] = Hdata[i][0].subtract(hPowers[i]); - Hdata[m - 1][i] = Hdata[m - 1][i].subtract(hPowers[m - i - 1]); - } - - /* - * [1] states: "For 1/2 < h < 1 the bottom left element of the matrix should be (1 - 2*h^m + - * (2h - 1)^m )/m!" Since 0 <= h < 1, then if h > 1/2 is sufficient to check: - */ - if (h.compareTo(BigFraction.ONE_HALF) == 1) { - Hdata[m - 1][0] = Hdata[m - 1][0].add(h.multiply(2).subtract(1).pow(m)); - } - - /* - * Aside from the first column and last row, the (i, j)-th element is 1/(i - j + 1)! if i - - * j + 1 >= 0, else 0. 1's and 0's are already put, so only division with (i - j + 1)! is - * needed in the elements that have 1's. There is no need to calculate (i - j + 1)! and then - * divide - small steps avoid overflows. Note that i - j + 1 > 0 <=> i + 1 > j instead of - * j'ing all the way to m. Also note that it is started at g = 2 because dividing by 1 isn't - * really necessary. - */ - for (int i = 0; i < m; ++i) { - for (int j = 0; j < i + 1; ++j) { - if (i - j + 1 > 0) { - for (int g = 2; g <= i - j + 1; ++g) { - Hdata[i][j] = Hdata[i][j].divide(g); - } - } - } - } - return new Array2DRowFieldMatrix<>(BigFractionField.getInstance(), Hdata); - } - - /*** - * Creates {@code H} of size {@code m x m} as described in [1] (see above) - * using double-precision. - * - * @param d statistic - * @param n sample size - * @return H matrix - * @throws NumberIsTooLargeException if fractional part is greater than 1 - */ - private RealMatrix createRoundedH(double d, int n) - throws NumberIsTooLargeException { - - final int k = (int) Math.ceil(n * d); - final int m = 2 * k - 1; - final double h = k - n * d; - if (h >= 1) { - throw new NumberIsTooLargeException(h, 1.0, false); - } - final double[][] Hdata = new double[m][m]; - - /* - * Start by filling everything with either 0 or 1. - */ - for (int i = 0; i < m; ++i) { - for (int j = 0; j < m; ++j) { - if (i - j + 1 < 0) { - Hdata[i][j] = 0; - } else { - Hdata[i][j] = 1; - } - } - } - - /* - * Setting up power-array to avoid calculating the same value twice: hPowers[0] = h^1 ... - * hPowers[m-1] = h^m - */ - final double[] hPowers = new double[m]; - hPowers[0] = h; - for (int i = 1; i < m; ++i) { - hPowers[i] = h * hPowers[i - 1]; - } - - /* - * First column and last row has special values (each other reversed). - */ - for (int i = 0; i < m; ++i) { - Hdata[i][0] = Hdata[i][0] - hPowers[i]; - Hdata[m - 1][i] -= hPowers[m - i - 1]; - } - - /* - * [1] states: "For 1/2 < h < 1 the bottom left element of the matrix should be (1 - 2*h^m + - * (2h - 1)^m )/m!" Since 0 <= h < 1, then if h > 1/2 is sufficient to check: - */ - if (Double.compare(h, 0.5) > 0) { - Hdata[m - 1][0] += FastMath.pow(2 * h - 1, m); - } - - /* - * Aside from the first column and last row, the (i, j)-th element is 1/(i - j + 1)! if i - - * j + 1 >= 0, else 0. 1's and 0's are already put, so only division with (i - j + 1)! is - * needed in the elements that have 1's. There is no need to calculate (i - j + 1)! and then - * divide - small steps avoid overflows. Note that i - j + 1 > 0 <=> i + 1 > j instead of - * j'ing all the way to m. Also note that it is started at g = 2 because dividing by 1 isn't - * really necessary. - */ - for (int i = 0; i < m; ++i) { - for (int j = 0; j < i + 1; ++j) { - if (i - j + 1 > 0) { - for (int g = 2; g <= i - j + 1; ++g) { - Hdata[i][j] /= g; - } - } - } - } - return MatrixUtils.createRealMatrix(Hdata); - } - - /** - * Verifies that {@code array} has length at least 2. - * - * @param array array to test - * @throws NullArgumentException if array is null - * @throws InsufficientDataException if array is too short - */ - private void checkArray(double[] array) { - if (array == null) { - throw new NullArgumentException(LocalizedFormats.NULL_NOT_ALLOWED); - } - if (array.length < 2) { - throw new InsufficientDataException(LocalizedFormats.INSUFFICIENT_OBSERVED_POINTS_IN_SAMPLE, array.length, - 2); - } - } - - /** - * Computes \( 1 + 2 \sum_{i=1}^\infty (-1)^i e^{-2 i^2 t^2} \) stopping when successive partial - * sums are within {@code tolerance} of one another, or when {@code maxIterations} partial sums - * have been computed. If the sum does not converge before {@code maxIterations} iterations a - * {@link TooManyIterationsException} is thrown. - * - * @param t argument - * @param tolerance Cauchy criterion for partial sums - * @param maxIterations maximum number of partial sums to compute - * @return Kolmogorov sum evaluated at t - * @throws TooManyIterationsException if the series does not converge - */ - public double ksSum(double t, double tolerance, int maxIterations) { - if (t == 0.0) { - return 0.0; - } - - // TODO: for small t (say less than 1), the alternative expansion in part 3 of [1] - // from class javadoc should be used. - - final double x = -2 * t * t; - int sign = -1; - long i = 1; - double partialSum = 0.5d; - double delta = 1; - while (delta > tolerance && i < maxIterations) { - delta = FastMath.exp(x * i * i); - partialSum += sign * delta; - sign *= -1; - i++; - } - if (i == maxIterations) { - throw new TooManyIterationsException(maxIterations); - } - return partialSum * 2; - } - - /** - * Given a d-statistic in the range [0, 1] and the two sample sizes n and m, - * an integral d-statistic in the range [0, n*m] is calculated, that can be used for - * comparison with other integral d-statistics. Depending whether {@code strict} is - * {@code true} or not, the returned value divided by (n*m) is greater than - * (resp greater than or equal to) the given d value (allowing some tolerance). - * - * @param d a d-statistic in the range [0, 1] - * @param n first sample size - * @param m second sample size - * @param strict whether the returned value divided by (n*m) is allowed to be equal to d - * @return the integral d-statistic in the range [0, n*m] - */ - private static long calculateIntegralD(double d, int n, int m, boolean strict) { - final double tol = 1e-12; // d-values within tol of one another are considered equal - long nm = n * (long)m; - long upperBound = (long)FastMath.ceil((d - tol) * nm); - long lowerBound = (long)FastMath.floor((d + tol) * nm); - if (strict && lowerBound == upperBound) { - return upperBound + 1l; - } - else { - return upperBound; - } - } - - /** - * Computes \(P(D_{n,m} > d)\) if {@code strict} is {@code true}; otherwise \(P(D_{n,m} \ge - * d)\), where \(D_{n,m}\) is the 2-sample Kolmogorov-Smirnov statistic. See - * {@link #kolmogorovSmirnovStatistic(double[], double[])} for the definition of \(D_{n,m}\). - *

- * The returned probability is exact, implemented by unwinding the recursive function - * definitions presented in [4] (class javadoc). - *

- * - * @param d D-statistic value - * @param n first sample size - * @param m second sample size - * @param strict whether or not the probability to compute is expressed as a strict inequality - * @return probability that a randomly selected m-n partition of m + n generates \(D_{n,m}\) - * greater than (resp. greater than or equal to) {@code d} - */ - public double exactP(double d, int n, int m, boolean strict) { - return 1 - n(m, n, m, n, calculateIntegralD(d, m, n, strict), strict) / - BinomialCoefficientDouble.value(n + m, m); - } - - /** - * Uses the Kolmogorov-Smirnov distribution to approximate \(P(D_{n,m} > d)\) where \(D_{n,m}\) - * is the 2-sample Kolmogorov-Smirnov statistic. See - * {@link #kolmogorovSmirnovStatistic(double[], double[])} for the definition of \(D_{n,m}\). - *

- * Specifically, what is returned is \(1 - k(d \sqrt{mn / (m + n)})\) where \(k(t) = 1 + 2 - * \sum_{i=1}^\infty (-1)^i e^{-2 i^2 t^2}\). See {@link #ksSum(double, double, int)} for - * details on how convergence of the sum is determined. - *

- * - * @param d D-statistic value - * @param n first sample size - * @param m second sample size - * @return approximate probability that a randomly selected m-n partition of m + n generates - * \(D_{n,m}\) greater than {@code d} - */ - public double approximateP(double d, int n, int m) { - final double dm = m; - final double dn = n; - return 1 - ksSum(d * FastMath.sqrt((dm * dn) / (dm + dn)), - KS_SUM_CAUCHY_CRITERION, MAXIMUM_PARTIAL_SUM_COUNT); - } - - /** - * Fills a boolean array randomly with a fixed number of {@code true} values. - * The method uses a simplified version of the Fisher-Yates shuffle algorithm. - * By processing first the {@code true} values followed by the remaining {@code false} values - * less random numbers need to be generated. The method is optimized for the case - * that the number of {@code true} values is larger than or equal to the number of - * {@code false} values. - * - * @param b boolean array - * @param numberOfTrueValues number of {@code true} values the boolean array should finally have - * @param rng random data generator - */ - private static void fillBooleanArrayRandomlyWithFixedNumberTrueValues(final boolean[] b, final int numberOfTrueValues, final UniformRandomProvider rng) { - Arrays.fill(b, true); - for (int k = numberOfTrueValues; k < b.length; k++) { - final int r = rng.nextInt(k + 1); - b[(b[r]) ? r : k] = false; - } - } - - /** - * Uses Monte Carlo simulation to approximate \(P(D_{n,m} > d)\) where \(D_{n,m}\) is the - * 2-sample Kolmogorov-Smirnov statistic. See - * {@link #kolmogorovSmirnovStatistic(double[], double[])} for the definition of \(D_{n,m}\). - *

- * The simulation generates {@code iterations} random partitions of {@code m + n} into an - * {@code n} set and an {@code m} set, computing \(D_{n,m}\) for each partition and returning - * the proportion of values that are greater than {@code d}, or greater than or equal to - * {@code d} if {@code strict} is {@code false}. - *

- * - * @param d D-statistic value. - * @param n First sample size. - * @param m Second sample size. - * @param iterations Number of random partitions to generate. - * @param strict whether or not the probability to compute is expressed as a strict inequality - * @param rng RNG used for generating the partitions. - * @return proportion of randomly generated m-n partitions of m + n that result in \(D_{n,m}\) - * greater than (resp. greater than or equal to) {@code d}. - */ - public double monteCarloP(final double d, - final int n, - final int m, - final boolean strict, - final int iterations, - UniformRandomProvider rng) { - return integralMonteCarloP(calculateIntegralD(d, n, m, strict), n, m, iterations, rng); - } - - /** - * Uses Monte Carlo simulation to approximate \(P(D_{n,m} >= d / (n * m))\) - * where \(D_{n,m}\) is the 2-sample Kolmogorov-Smirnov statistic. - *

- * Here {@code d} is the D-statistic represented as long value. - * The real D-statistic is obtained by dividing {@code d} by {@code n * m}. - * See also {@link #monteCarloP(double,int,int,boolean,int,UniformRandomProvider)}. - * - * @param d Integral D-statistic. - * @param n First sample size. - * @param m Second sample size. - * @param iterations Number of random partitions to generate. - * @param rng RNG used for generating the partitions. - * @return proportion of randomly generated m-n partitions of m + n that result in \(D_{n,m}\) - * greater than or equal to {@code d / (n * m))}. - */ - private double integralMonteCarloP(final long d, - final int n, - final int m, - final int iterations, - UniformRandomProvider rng) { - // ensure that nn is always the max of (n, m) to require fewer random numbers - final int nn = FastMath.max(n, m); - final int mm = FastMath.min(n, m); - final int sum = nn + mm; - - int tail = 0; - final boolean b[] = new boolean[sum]; - for (int i = 0; i < iterations; i++) { - fillBooleanArrayRandomlyWithFixedNumberTrueValues(b, nn, rng); - long curD = 0l; - for(int j = 0; j < b.length; ++j) { - if (b[j]) { - curD += mm; - if (curD >= d) { - tail++; - break; - } - } else { - curD -= nn; - if (curD <= -d) { - tail++; - break; - } - } - } - } - return (double) tail / iterations; - } - - /** - * If there are no ties in the combined dataset formed from x and y, - * this method is a no-op. - * If there are ties, a uniform random deviate in - * is added to each value in x and y, and this method overwrites the - * data in x and y with the jittered values. - * - * @param x First sample. - * @param y Second sample. - * @throw NotANumberException if any of the input arrays contain - * a NaN value. - */ - private static void fixTies(double[] x, double[] y) { - if (hasTies(x, y)) { - // Add jitter using a fixed seed (so same arguments always give same results), - // low-initialization-overhead generator. - final UniformRandomProvider rng = RandomSource.create(RandomSource.TWO_CMRES, 7654321); - - // It is theoretically possible that jitter does not break ties, so repeat - // until all ties are gone. Bound the loop and throw MIE if bound is exceeded. - int ct = 0; - boolean ties = true; - do { - jitter(x, rng, 10); - jitter(y, rng, 10); - ties = hasTies(x, y); - ++ct; - } while (ties && ct < 10); - if (ties) { - throw new MathInternalError(); // Should never happen. - } - } - } - - /** - * Returns true iff there are ties in the combined sample formed from - * x and y. - * - * @param x First sample. - * @param y Second sample. - * @return true if x and y together contain ties. - * @throw NotANumberException if any of the input arrays contain - * a NaN value. - */ - private static boolean hasTies(double[] x, double[] y) { - final double[] values = MathArrays.unique(MathArrays.concatenate(x, y)); - - // "unique" moves NaN to the head of the output array. - if (Double.isNaN(values[0])) { - throw new NotANumberException(); - } - if (values.length == x.length + y.length) { - return false; // There are no ties. - } - - return true; - } - - /** - * Adds random jitter to {@code data} using deviates sampled from {@code dist}. - *

- * Note that jitter is applied in-place - i.e., the array - * values are overwritten with the result of applying jitter.

- * - * @param data input/output data array - entries overwritten by the method - * @param rng probability distribution to sample for jitter values - * @param ulp ulp used when generating random numbers - * @throws NullPointerException if either of the parameters is null - */ - private static void jitter(double[] data, - UniformRandomProvider rng, - int ulp) { - final int range = ulp * 2; - for (int i = 0; i < data.length; i++) { - final int rand = rng.nextInt(range) - ulp; - data[i] += rand * Math.ulp(data[i]); - } - } - - /** - * The function C(i, j) defined in [4] (class javadoc), formula (5.5). - * defined to return 1 if |i/n - j/m| <= c; 0 otherwise. Here c is scaled up - * and recoded as a long to avoid rounding errors in comparison tests, so what - * is actually tested is |im - jn| <= cmn. - * - * @param i first path parameter - * @param j second path paramter - * @param m first sample size - * @param n second sample size - * @param cmn integral D-statistic (see {@link #calculateIntegralD(double, int, int, boolean)}) - * @param strict whether or not the null hypothesis uses strict inequality - * @return C(i,j) for given m, n, c - */ - private static int c(int i, int j, int m, int n, long cmn, boolean strict) { - if (strict) { - return FastMath.abs(i*(long)n - j*(long)m) <= cmn ? 1 : 0; - } - return FastMath.abs(i*(long)n - j*(long)m) < cmn ? 1 : 0; - } - - /** - * The function N(i, j) defined in [4] (class javadoc). - * Returns the number of paths over the lattice {(i,j) : 0 <= i <= n, 0 <= j <= m} - * from (0,0) to (i,j) satisfying C(h,k, m, n, c) = 1 for each (h,k) on the path. - * The return value is integral, but subject to overflow, so it is maintained and - * returned as a double. - * - * @param i first path parameter - * @param j second path parameter - * @param m first sample size - * @param n second sample size - * @param cnm integral D-statistic (see {@link #calculateIntegralD(double, int, int, boolean)}) - * @param strict whether or not the null hypothesis uses strict inequality - * @return number or paths to (i, j) from (0,0) representing D-values as large as c for given m, n - */ - private static double n(int i, int j, int m, int n, long cnm, boolean strict) { - /* - * Unwind the recursive definition given in [4]. - * Compute n(1,1), n(1,2)...n(2,1), n(2,2)... up to n(i,j), one row at a time. - * When n(i,*) are being computed, lag[] holds the values of n(i - 1, *). - */ - final double[] lag = new double[n]; - double last = 0; - for (int k = 0; k < n; k++) { - lag[k] = c(0, k + 1, m, n, cnm, strict); - } - for (int k = 1; k <= i; k++) { - last = c(k, 0, m, n, cnm, strict); - for (int l = 1; l <= j; l++) { - lag[l - 1] = c(k, l, m, n, cnm, strict) * (last + lag[l - 1]); - last = lag[l - 1]; - } - } - return last; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/MannWhitneyUTest.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/MannWhitneyUTest.java deleted file mode 100644 index abe4183c4..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/MannWhitneyUTest.java +++ /dev/null @@ -1,236 +0,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. - */ -package org.apache.commons.math4.stat.inference; - -import org.apache.commons.statistics.distribution.NormalDistribution; -import org.apache.commons.math4.exception.ConvergenceException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.stat.ranking.NaNStrategy; -import org.apache.commons.math4.stat.ranking.NaturalRanking; -import org.apache.commons.math4.stat.ranking.TiesStrategy; -import org.apache.commons.math4.util.FastMath; - -/** - * An implementation of the Mann-Whitney U test (also called Wilcoxon rank-sum test). - * - */ -public class MannWhitneyUTest { - - /** Ranking algorithm. */ - private NaturalRanking naturalRanking; - - /** - * Create a test instance using where NaN's are left in place and ties get - * the average of applicable ranks. Use this unless you are very sure of - * what you are doing. - */ - public MannWhitneyUTest() { - naturalRanking = new NaturalRanking(NaNStrategy.FIXED, - TiesStrategy.AVERAGE); - } - - /** - * Create a test instance using the given strategies for NaN's and ties. - * Only use this if you are sure of what you are doing. - * - * @param nanStrategy - * specifies the strategy that should be used for Double.NaN's - * @param tiesStrategy - * specifies the strategy that should be used for ties - */ - public MannWhitneyUTest(final NaNStrategy nanStrategy, - final TiesStrategy tiesStrategy) { - naturalRanking = new NaturalRanking(nanStrategy, tiesStrategy); - } - - /** - * Ensures that the provided arrays fulfills the assumptions. - * - * @param x first sample - * @param y second sample - * @throws NullArgumentException if {@code x} or {@code y} are {@code null}. - * @throws NoDataException if {@code x} or {@code y} are zero-length. - */ - private void ensureDataConformance(final double[] x, final double[] y) - throws NullArgumentException, NoDataException { - - if (x == null || - y == null) { - throw new NullArgumentException(); - } - if (x.length == 0 || - y.length == 0) { - throw new NoDataException(); - } - } - - /** Concatenate the samples into one array. - * @param x first sample - * @param y second sample - * @return concatenated array - */ - private double[] concatenateSamples(final double[] x, final double[] y) { - final double[] z = new double[x.length + y.length]; - - System.arraycopy(x, 0, z, 0, x.length); - System.arraycopy(y, 0, z, x.length, y.length); - - return z; - } - - /** - * Computes the Mann-Whitney - * U statistic comparing mean for two independent samples possibly of - * different length. - *

- * This statistic can be used to perform a Mann-Whitney U test evaluating - * the null hypothesis that the two independent samples has equal mean. - *

- *

- * Let Xi denote the i'th individual of the first sample and - * Yj the j'th individual in the second sample. Note that the - * samples would often have different length. - *

- *

- * Preconditions: - *

    - *
  • All observations in the two samples are independent.
  • - *
  • The observations are at least ordinal (continuous are also ordinal).
  • - *
- * - * @param x the first sample - * @param y the second sample - * @return Mann-Whitney U statistic (maximum of Ux and Uy) - * @throws NullArgumentException if {@code x} or {@code y} are {@code null}. - * @throws NoDataException if {@code x} or {@code y} are zero-length. - */ - public double mannWhitneyU(final double[] x, final double[] y) - throws NullArgumentException, NoDataException { - - ensureDataConformance(x, y); - - final double[] z = concatenateSamples(x, y); - final double[] ranks = naturalRanking.rank(z); - - double sumRankX = 0; - - /* - * The ranks for x is in the first x.length entries in ranks because x - * is in the first x.length entries in z - */ - for (int i = 0; i < x.length; ++i) { - sumRankX += ranks[i]; - } - - /* - * U1 = R1 - (n1 * (n1 + 1)) / 2 where R1 is sum of ranks for sample 1, - * e.g. x, n1 is the number of observations in sample 1. - */ - final double U1 = sumRankX - ((long) x.length * (x.length + 1)) / 2; - - /* - * It can be shown that U1 + U2 = n1 * n2 - */ - final double U2 = (long) x.length * y.length - U1; - - return FastMath.max(U1, U2); - } - - /** - * @param Umin smallest Mann-Whitney U value - * @param n1 number of subjects in first sample - * @param n2 number of subjects in second sample - * @return two-sided asymptotic p-value - * @throws ConvergenceException if the p-value can not be computed - * due to a convergence error - * @throws MaxCountExceededException if the maximum number of - * iterations is exceeded - */ - private double calculateAsymptoticPValue(final double Umin, - final int n1, - final int n2) - throws ConvergenceException, MaxCountExceededException { - - /* long multiplication to avoid overflow (double not used due to efficiency - * and to avoid precision loss) - */ - final long n1n2prod = (long) n1 * n2; - - // http://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U#Normal_approximation - final double EU = n1n2prod / 2.0; - final double VarU = n1n2prod * (n1 + n2 + 1) / 12.0; - - final double z = (Umin - EU) / FastMath.sqrt(VarU); - - // No try-catch or advertised exception because args are valid - // pass a null rng to avoid unneeded overhead as we will not sample from this distribution - final NormalDistribution standardNormal = new NormalDistribution(0, 1); - - return 2 * standardNormal.cumulativeProbability(z); - } - - /** - * Returns the asymptotic observed significance level, or - * p-value, associated with a Mann-Whitney - * U statistic comparing mean for two independent samples. - *

- * Let Xi denote the i'th individual of the first sample and - * Yj the j'th individual in the second sample. Note that the - * samples would often have different length. - *

- *

- * Preconditions: - *

    - *
  • All observations in the two samples are independent.
  • - *
  • The observations are at least ordinal (continuous are also ordinal).
  • - *

- * Ties give rise to biased variance at the moment. See e.g. http://mlsc.lboro.ac.uk/resources/statistics/Mannwhitney.pdf.

- * - * @param x the first sample - * @param y the second sample - * @return asymptotic p-value - * @throws NullArgumentException if {@code x} or {@code y} are {@code null}. - * @throws NoDataException if {@code x} or {@code y} are zero-length. - * @throws ConvergenceException if the p-value can not be computed due to a - * convergence error - * @throws MaxCountExceededException if the maximum number of iterations - * is exceeded - */ - public double mannWhitneyUTest(final double[] x, final double[] y) - throws NullArgumentException, NoDataException, - ConvergenceException, MaxCountExceededException { - - ensureDataConformance(x, y); - - final double Umax = mannWhitneyU(x, y); - - /* - * It can be shown that U1 + U2 = n1 * n2 - */ - final double Umin = (long) x.length * y.length - Umax; - - return calculateAsymptoticPValue(Umin, x.length, y.length); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/OneWayAnova.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/OneWayAnova.java deleted file mode 100644 index f41e56a61..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/OneWayAnova.java +++ /dev/null @@ -1,355 +0,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. - */ -package org.apache.commons.math4.stat.inference; - -import java.util.ArrayList; -import java.util.Collection; - -import org.apache.commons.statistics.distribution.FDistribution; -import org.apache.commons.math4.exception.ConvergenceException; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.stat.descriptive.SummaryStatistics; -import org.apache.commons.math4.util.MathUtils; - -/** - * Implements one-way ANOVA (analysis of variance) statistics. - * - *

Tests for differences between two or more categories of univariate data - * (for example, the body mass index of accountants, lawyers, doctors and - * computer programmers). When two categories are given, this is equivalent to - * the {@link TTest}. - *

- * Uses the {@link FDistribution - * commons-math F Distribution implementation} to estimate exact p-values.

- *

This implementation is based on a description at - * http://faculty.vassar.edu/lowry/ch13pt1.html

- *
- * Abbreviations: bg = between groups,
- *                wg = within groups,
- *                ss = sum squared deviations
- * 
- * - * @since 1.2 - */ -public class OneWayAnova { - - /** - * Default constructor. - */ - public OneWayAnova() { - } - - /** - * Computes the ANOVA F-value for a collection of double[] - * arrays. - * - *

Preconditions:

    - *
  • The categoryData Collection must contain - * double[] arrays.
  • - *
  • There must be at least two double[] arrays in the - * categoryData collection and each of these arrays must - * contain at least two values.

- * This implementation computes the F statistic using the definitional - * formula

-     *   F = msbg/mswg
- * where
-     *  msbg = between group mean square
-     *  mswg = within group mean square
- * are as defined - * here - * - * @param categoryData Collection of double[] - * arrays each containing data for one category - * @return Fvalue - * @throws NullArgumentException if categoryData is null - * @throws DimensionMismatchException if the length of the categoryData - * array is less than 2 or a contained double[] array does not have - * at least two values - */ - public double anovaFValue(final Collection categoryData) - throws NullArgumentException, DimensionMismatchException { - - AnovaStats a = anovaStats(categoryData); - return a.F; - - } - - /** - * Computes the ANOVA P-value for a collection of double[] - * arrays. - * - *

Preconditions:

    - *
  • The categoryData Collection must contain - * double[] arrays.
  • - *
  • There must be at least two double[] arrays in the - * categoryData collection and each of these arrays must - * contain at least two values.

- * This implementation uses the - * {@link FDistribution - * commons-math F Distribution implementation} to estimate the exact - * p-value, using the formula

-     *   p = 1 - cumulativeProbability(F)
- * where F is the F value and cumulativeProbability - * is the commons-math implementation of the F distribution. - * - * @param categoryData Collection of double[] - * arrays each containing data for one category - * @return Pvalue - * @throws NullArgumentException if categoryData is null - * @throws DimensionMismatchException if the length of the categoryData - * array is less than 2 or a contained double[] array does not have - * at least two values - * @throws ConvergenceException if the p-value can not be computed due to a convergence error - * @throws MaxCountExceededException if the maximum number of iterations is exceeded - */ - public double anovaPValue(final Collection categoryData) - throws NullArgumentException, DimensionMismatchException, - ConvergenceException, MaxCountExceededException { - - final AnovaStats a = anovaStats(categoryData); - // No try-catch or advertised exception because args are valid - // pass a null rng to avoid unneeded overhead as we will not sample from this distribution - final FDistribution fdist = new FDistribution(a.dfbg, a.dfwg); - return 1.0 - fdist.cumulativeProbability(a.F); - - } - - /** - * Computes the ANOVA P-value for a collection of {@link SummaryStatistics}. - * - *

Preconditions:

    - *
  • The categoryData Collection must contain - * {@link SummaryStatistics}.
  • - *
  • There must be at least two {@link SummaryStatistics} in the - * categoryData collection and each of these statistics must - * contain at least two values.

- * This implementation uses the - * {@link FDistribution - * commons-math F Distribution implementation} to estimate the exact - * p-value, using the formula

-     *   p = 1 - cumulativeProbability(F)
- * where F is the F value and cumulativeProbability - * is the commons-math implementation of the F distribution. - * - * @param categoryData Collection of {@link SummaryStatistics} - * each containing data for one category - * @param allowOneElementData if true, allow computation for one catagory - * only or for one data element per category - * @return Pvalue - * @throws NullArgumentException if categoryData is null - * @throws DimensionMismatchException if the length of the categoryData - * array is less than 2 or a contained {@link SummaryStatistics} does not have - * at least two values - * @throws ConvergenceException if the p-value can not be computed due to a convergence error - * @throws MaxCountExceededException if the maximum number of iterations is exceeded - * @since 3.2 - */ - public double anovaPValue(final Collection categoryData, - final boolean allowOneElementData) - throws NullArgumentException, DimensionMismatchException, - ConvergenceException, MaxCountExceededException { - - final AnovaStats a = anovaStats(categoryData, allowOneElementData); - // pass a null rng to avoid unneeded overhead as we will not sample from this distribution - final FDistribution fdist = new FDistribution(a.dfbg, a.dfwg); - return 1.0 - fdist.cumulativeProbability(a.F); - - } - - /** - * This method calls the method that actually does the calculations (except - * P-value). - * - * @param categoryData - * Collection of double[] arrays each - * containing data for one category - * @return computed AnovaStats - * @throws NullArgumentException - * if categoryData is null - * @throws DimensionMismatchException - * if the length of the categoryData array is less - * than 2 or a contained double[] array does not - * contain at least two values - */ - private AnovaStats anovaStats(final Collection categoryData) - throws NullArgumentException, DimensionMismatchException { - - MathUtils.checkNotNull(categoryData); - - final Collection categoryDataSummaryStatistics = - new ArrayList<>(categoryData.size()); - - // convert arrays to SummaryStatistics - for (final double[] data : categoryData) { - final SummaryStatistics dataSummaryStatistics = new SummaryStatistics(); - categoryDataSummaryStatistics.add(dataSummaryStatistics); - for (final double val : data) { - dataSummaryStatistics.addValue(val); - } - } - - return anovaStats(categoryDataSummaryStatistics, false); - - } - - /** - * Performs an ANOVA test, evaluating the null hypothesis that there - * is no difference among the means of the data categories. - * - *

Preconditions:

    - *
  • The categoryData Collection must contain - * double[] arrays.
  • - *
  • There must be at least two double[] arrays in the - * categoryData collection and each of these arrays must - * contain at least two values.
  • - *
  • alpha must be strictly greater than 0 and less than or equal to 0.5. - *

- * This implementation uses the - * {@link FDistribution - * commons-math F Distribution implementation} to estimate the exact - * p-value, using the formula

-     *   p = 1 - cumulativeProbability(F)
- * where F is the F value and cumulativeProbability - * is the commons-math implementation of the F distribution. - *

True is returned iff the estimated p-value is less than alpha.

- * - * @param categoryData Collection of double[] - * arrays each containing data for one category - * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with - * confidence 1 - alpha - * @throws NullArgumentException if categoryData is null - * @throws DimensionMismatchException if the length of the categoryData - * array is less than 2 or a contained double[] array does not have - * at least two values - * @throws OutOfRangeException if alpha is not in the range (0, 0.5] - * @throws ConvergenceException if the p-value can not be computed due to a convergence error - * @throws MaxCountExceededException if the maximum number of iterations is exceeded - */ - public boolean anovaTest(final Collection categoryData, - final double alpha) - throws NullArgumentException, DimensionMismatchException, - OutOfRangeException, ConvergenceException, MaxCountExceededException { - - if ((alpha <= 0) || (alpha > 0.5)) { - throw new OutOfRangeException( - LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, - alpha, 0, 0.5); - } - return anovaPValue(categoryData) < alpha; - - } - - /** - * This method actually does the calculations (except P-value). - * - * @param categoryData Collection of double[] - * arrays each containing data for one category - * @param allowOneElementData if true, allow computation for one catagory - * only or for one data element per category - * @return computed AnovaStats - * @throws NullArgumentException if categoryData is null - * @throws DimensionMismatchException if allowOneElementData is false and the number of - * categories is less than 2 or a contained SummaryStatistics does not contain - * at least two values - */ - private AnovaStats anovaStats(final Collection categoryData, - final boolean allowOneElementData) - throws NullArgumentException, DimensionMismatchException { - - MathUtils.checkNotNull(categoryData); - - if (!allowOneElementData) { - // check if we have enough categories - if (categoryData.size() < 2) { - throw new DimensionMismatchException(LocalizedFormats.TWO_OR_MORE_CATEGORIES_REQUIRED, - categoryData.size(), 2); - } - - // check if each category has enough data - for (final SummaryStatistics array : categoryData) { - if (array.getN() <= 1) { - throw new DimensionMismatchException(LocalizedFormats.TWO_OR_MORE_VALUES_IN_CATEGORY_REQUIRED, - (int) array.getN(), 2); - } - } - } - - int dfwg = 0; - double sswg = 0; - double totsum = 0; - double totsumsq = 0; - int totnum = 0; - - for (final SummaryStatistics data : categoryData) { - - final double sum = data.getSum(); - final double sumsq = data.getSumsq(); - final int num = (int) data.getN(); - totnum += num; - totsum += sum; - totsumsq += sumsq; - - dfwg += num - 1; - final double ss = sumsq - ((sum * sum) / num); - sswg += ss; - } - - final double sst = totsumsq - ((totsum * totsum) / totnum); - final double ssbg = sst - sswg; - final int dfbg = categoryData.size() - 1; - final double msbg = ssbg / dfbg; - final double mswg = sswg / dfwg; - final double F = msbg / mswg; - - return new AnovaStats(dfbg, dfwg, F); - - } - - /** - Convenience class to pass dfbg,dfwg,F values around within OneWayAnova. - No get/set methods provided. - */ - private static class AnovaStats { - - /** Degrees of freedom in numerator (between groups). */ - private final int dfbg; - - /** Degrees of freedom in denominator (within groups). */ - private final int dfwg; - - /** Statistic. */ - private final double F; - - /** - * Constructor - * @param dfbg degrees of freedom in numerator (between groups) - * @param dfwg degrees of freedom in denominator (within groups) - * @param F statistic - */ - private AnovaStats(int dfbg, int dfwg, double F) { - this.dfbg = dfbg; - this.dfwg = dfwg; - this.F = F; - } - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/TTest.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/TTest.java deleted file mode 100644 index 89842f9e7..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/TTest.java +++ /dev/null @@ -1,1183 +0,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. - */ -package org.apache.commons.math4.stat.inference; - -import org.apache.commons.statistics.distribution.TDistribution; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.stat.StatUtils; -import org.apache.commons.math4.stat.descriptive.StatisticalSummary; -import org.apache.commons.math4.util.FastMath; - -/** - * An implementation for Student's t-tests. - *

- * Tests can be:

    - *
  • One-sample or two-sample
  • - *
  • One-sided or two-sided
  • - *
  • Paired or unpaired (for two-sample tests)
  • - *
  • Homoscedastic (equal variance assumption) or heteroscedastic - * (for two sample tests)
  • - *
  • Fixed significance level (boolean-valued) or returning p-values. - *
- *

- * Test statistics are available for all tests. Methods including "Test" in - * in their names perform tests, all other methods return t-statistics. Among - * the "Test" methods, double-valued methods return p-values; - * boolean-valued methods perform fixed significance level tests. - * Significance levels are always specified as numbers between 0 and 0.5 - * (e.g. tests at the 95% level use alpha=0.05).

- *

- * Input to tests can be either double[] arrays or - * {@link StatisticalSummary} instances.

- * Uses commons-math {@link TDistribution} - * implementation to estimate exact p-values.

- * - */ -public class TTest { - /** - * Computes a paired, 2-sample t-statistic based on the data in the input - * arrays. The t-statistic returned is equivalent to what would be returned by - * computing the one-sample t-statistic {@link #t(double, double[])}, with - * mu = 0 and the sample array consisting of the (signed) - * differences between corresponding entries in sample1 and - * sample2. - *

- * Preconditions:

    - *
  • The input arrays must have the same length and their common length - * must be at least 2. - *
- * - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @return t statistic - * @throws NullArgumentException if the arrays are null - * @throws NoDataException if the arrays are empty - * @throws DimensionMismatchException if the length of the arrays is not equal - * @throws NumberIsTooSmallException if the length of the arrays is < 2 - */ - public double pairedT(final double[] sample1, final double[] sample2) - throws NullArgumentException, NoDataException, - DimensionMismatchException, NumberIsTooSmallException { - - checkSampleData(sample1); - checkSampleData(sample2); - double meanDifference = StatUtils.meanDifference(sample1, sample2); - return t(meanDifference, 0, - StatUtils.varianceDifference(sample1, sample2, meanDifference), - sample1.length); - - } - - /** - * Returns the observed significance level, or - * p-value, associated with a paired, two-sample, two-tailed t-test - * based on the data in the input arrays. - *

- * The number returned is the smallest significance level - * at which one can reject the null hypothesis that the mean of the paired - * differences is 0 in favor of the two-sided alternative that the mean paired - * difference is not equal to 0. For a one-sided test, divide the returned - * value by 2.

- *

- * This test is equivalent to a one-sample t-test computed using - * {@link #tTest(double, double[])} with mu = 0 and the sample - * array consisting of the signed differences between corresponding elements of - * sample1 and sample2.

- *

- * Usage Note:
- * The validity of the p-value depends on the assumptions of the parametric - * t-test procedure, as discussed - * - * here

- *

- * Preconditions:

    - *
  • The input array lengths must be the same and their common length must - * be at least 2. - *
- * - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @return p-value for t-test - * @throws NullArgumentException if the arrays are null - * @throws NoDataException if the arrays are empty - * @throws DimensionMismatchException if the length of the arrays is not equal - * @throws NumberIsTooSmallException if the length of the arrays is < 2 - * @throws MaxCountExceededException if an error occurs computing the p-value - */ - public double pairedTTest(final double[] sample1, final double[] sample2) - throws NullArgumentException, NoDataException, DimensionMismatchException, - NumberIsTooSmallException, MaxCountExceededException { - - double meanDifference = StatUtils.meanDifference(sample1, sample2); - return tTest(meanDifference, 0, - StatUtils.varianceDifference(sample1, sample2, meanDifference), - sample1.length); - - } - - /** - * Performs a paired t-test evaluating the null hypothesis that the - * mean of the paired differences between sample1 and - * sample2 is 0 in favor of the two-sided alternative that the - * mean paired difference is not equal to 0, with significance level - * alpha. - *

- * Returns true iff the null hypothesis can be rejected with - * confidence 1 - alpha. To perform a 1-sided test, use - * alpha * 2

- *

- * Usage Note:
- * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed - * - * here

- *

- * Preconditions:

    - *
  • The input array lengths must be the same and their common length - * must be at least 2. - *
  • - *
  • 0 < alpha < 0.5 - *
- * - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with - * confidence 1 - alpha - * @throws NullArgumentException if the arrays are null - * @throws NoDataException if the arrays are empty - * @throws DimensionMismatchException if the length of the arrays is not equal - * @throws NumberIsTooSmallException if the length of the arrays is < 2 - * @throws OutOfRangeException if alpha is not in the range (0, 0.5] - * @throws MaxCountExceededException if an error occurs computing the p-value - */ - public boolean pairedTTest(final double[] sample1, final double[] sample2, - final double alpha) - throws NullArgumentException, NoDataException, DimensionMismatchException, - NumberIsTooSmallException, OutOfRangeException, MaxCountExceededException { - - checkSignificanceLevel(alpha); - return pairedTTest(sample1, sample2) < alpha; - - } - - /** - * Computes a - * t statistic given observed values and a comparison constant. - *

- * This statistic can be used to perform a one sample t-test for the mean. - *

- * Preconditions:

    - *
  • The observed array length must be at least 2. - *
- * - * @param mu comparison constant - * @param observed array of values - * @return t statistic - * @throws NullArgumentException if observed is null - * @throws NumberIsTooSmallException if the length of observed is < 2 - */ - public double t(final double mu, final double[] observed) - throws NullArgumentException, NumberIsTooSmallException { - - checkSampleData(observed); - // No try-catch or advertised exception because args have just been checked - return t(StatUtils.mean(observed), mu, StatUtils.variance(observed), - observed.length); - - } - - /** - * Computes a - * t statistic to use in comparing the mean of the dataset described by - * sampleStats to mu. - *

- * This statistic can be used to perform a one sample t-test for the mean. - *

- * Preconditions:

    - *
  • observed.getN() ≥ 2. - *
- * - * @param mu comparison constant - * @param sampleStats DescriptiveStatistics holding sample summary statitstics - * @return t statistic - * @throws NullArgumentException if sampleStats is null - * @throws NumberIsTooSmallException if the number of samples is < 2 - */ - public double t(final double mu, final StatisticalSummary sampleStats) - throws NullArgumentException, NumberIsTooSmallException { - - checkSampleData(sampleStats); - return t(sampleStats.getMean(), mu, sampleStats.getVariance(), - sampleStats.getN()); - - } - - /** - * Computes a 2-sample t statistic, under the hypothesis of equal - * subpopulation variances. To compute a t-statistic without the - * equal variances hypothesis, use {@link #t(double[], double[])}. - *

- * This statistic can be used to perform a (homoscedastic) two-sample - * t-test to compare sample means.

- *

- * The t-statistic is

- *

- *    t = (m1 - m2) / (sqrt(1/n1 +1/n2) sqrt(var)) - *

- * where n1 is the size of first sample; - * n2 is the size of second sample; - * m1 is the mean of first sample; - * m2 is the mean of second sample - * and var is the pooled variance estimate: - *

- * var = sqrt(((n1 - 1)var1 + (n2 - 1)var2) / ((n1-1) + (n2-1))) - *

- * with var1 the variance of the first sample and - * var2 the variance of the second sample. - *

- * Preconditions:

    - *
  • The observed array lengths must both be at least 2. - *
- * - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @return t statistic - * @throws NullArgumentException if the arrays are null - * @throws NumberIsTooSmallException if the length of the arrays is < 2 - */ - public double homoscedasticT(final double[] sample1, final double[] sample2) - throws NullArgumentException, NumberIsTooSmallException { - - checkSampleData(sample1); - checkSampleData(sample2); - // No try-catch or advertised exception because args have just been checked - return homoscedasticT(StatUtils.mean(sample1), StatUtils.mean(sample2), - StatUtils.variance(sample1), StatUtils.variance(sample2), - sample1.length, sample2.length); - - } - - /** - * Computes a 2-sample t statistic, without the hypothesis of equal - * subpopulation variances. To compute a t-statistic assuming equal - * variances, use {@link #homoscedasticT(double[], double[])}. - *

- * This statistic can be used to perform a two-sample t-test to compare - * sample means.

- *

- * The t-statistic is

- *

- *    t = (m1 - m2) / sqrt(var1/n1 + var2/n2) - *

- * where n1 is the size of the first sample - * n2 is the size of the second sample; - * m1 is the mean of the first sample; - * m2 is the mean of the second sample; - * var1 is the variance of the first sample; - * var2 is the variance of the second sample; - *

- * Preconditions:

    - *
  • The observed array lengths must both be at least 2. - *
- * - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @return t statistic - * @throws NullArgumentException if the arrays are null - * @throws NumberIsTooSmallException if the length of the arrays is < 2 - */ - public double t(final double[] sample1, final double[] sample2) - throws NullArgumentException, NumberIsTooSmallException { - - checkSampleData(sample1); - checkSampleData(sample2); - // No try-catch or advertised exception because args have just been checked - return t(StatUtils.mean(sample1), StatUtils.mean(sample2), - StatUtils.variance(sample1), StatUtils.variance(sample2), - sample1.length, sample2.length); - - } - - /** - * Computes a 2-sample t statistic, comparing the means of the datasets - * described by two {@link StatisticalSummary} instances, without the - * assumption of equal subpopulation variances. Use - * {@link #homoscedasticT(StatisticalSummary, StatisticalSummary)} to - * compute a t-statistic under the equal variances assumption. - *

- * This statistic can be used to perform a two-sample t-test to compare - * sample means.

- *

- * The returned t-statistic is

- *

- *    t = (m1 - m2) / sqrt(var1/n1 + var2/n2) - *

- * where n1 is the size of the first sample; - * n2 is the size of the second sample; - * m1 is the mean of the first sample; - * m2 is the mean of the second sample - * var1 is the variance of the first sample; - * var2 is the variance of the second sample - *

- * Preconditions:

    - *
  • The datasets described by the two Univariates must each contain - * at least 2 observations. - *
- * - * @param sampleStats1 StatisticalSummary describing data from the first sample - * @param sampleStats2 StatisticalSummary describing data from the second sample - * @return t statistic - * @throws NullArgumentException if the sample statistics are null - * @throws NumberIsTooSmallException if the number of samples is < 2 - */ - public double t(final StatisticalSummary sampleStats1, - final StatisticalSummary sampleStats2) - throws NullArgumentException, NumberIsTooSmallException { - - checkSampleData(sampleStats1); - checkSampleData(sampleStats2); - return t(sampleStats1.getMean(), sampleStats2.getMean(), - sampleStats1.getVariance(), sampleStats2.getVariance(), - sampleStats1.getN(), sampleStats2.getN()); - - } - - /** - * Computes a 2-sample t statistic, comparing the means of the datasets - * described by two {@link StatisticalSummary} instances, under the - * assumption of equal subpopulation variances. To compute a t-statistic - * without the equal variances assumption, use - * {@link #t(StatisticalSummary, StatisticalSummary)}. - *

- * This statistic can be used to perform a (homoscedastic) two-sample - * t-test to compare sample means.

- *

- * The t-statistic returned is

- *

- *    t = (m1 - m2) / (sqrt(1/n1 +1/n2) sqrt(var)) - *

- * where n1 is the size of first sample; - * n2 is the size of second sample; - * m1 is the mean of first sample; - * m2 is the mean of second sample - * and var is the pooled variance estimate: - *

- * var = sqrt(((n1 - 1)var1 + (n2 - 1)var2) / ((n1-1) + (n2-1))) - *

- * with var1 the variance of the first sample and - * var2 the variance of the second sample. - *

- * Preconditions:

    - *
  • The datasets described by the two Univariates must each contain - * at least 2 observations. - *
- * - * @param sampleStats1 StatisticalSummary describing data from the first sample - * @param sampleStats2 StatisticalSummary describing data from the second sample - * @return t statistic - * @throws NullArgumentException if the sample statistics are null - * @throws NumberIsTooSmallException if the number of samples is < 2 - */ - public double homoscedasticT(final StatisticalSummary sampleStats1, - final StatisticalSummary sampleStats2) - throws NullArgumentException, NumberIsTooSmallException { - - checkSampleData(sampleStats1); - checkSampleData(sampleStats2); - return homoscedasticT(sampleStats1.getMean(), sampleStats2.getMean(), - sampleStats1.getVariance(), sampleStats2.getVariance(), - sampleStats1.getN(), sampleStats2.getN()); - - } - - /** - * Returns the observed significance level, or - * p-value, associated with a one-sample, two-tailed t-test - * comparing the mean of the input array with the constant mu. - *

- * The number returned is the smallest significance level - * at which one can reject the null hypothesis that the mean equals - * mu in favor of the two-sided alternative that the mean - * is different from mu. For a one-sided test, divide the - * returned value by 2.

- *

- * Usage Note:
- * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed - * here - *

- * Preconditions:

    - *
  • The observed array length must be at least 2. - *
- * - * @param mu constant value to compare sample mean against - * @param sample array of sample data values - * @return p-value - * @throws NullArgumentException if the sample array is null - * @throws NumberIsTooSmallException if the length of the array is < 2 - * @throws MaxCountExceededException if an error occurs computing the p-value - */ - public double tTest(final double mu, final double[] sample) - throws NullArgumentException, NumberIsTooSmallException, - MaxCountExceededException { - - checkSampleData(sample); - // No try-catch or advertised exception because args have just been checked - return tTest(StatUtils.mean(sample), mu, StatUtils.variance(sample), - sample.length); - - } - - /** - * Performs a - * two-sided t-test evaluating the null hypothesis that the mean of the population from - * which sample is drawn equals mu. - *

- * Returns true iff the null hypothesis can be - * rejected with confidence 1 - alpha. To - * perform a 1-sided test, use alpha * 2

- *

- * Examples:

    - *
  1. To test the (2-sided) hypothesis sample mean = mu at - * the 95% level, use
    tTest(mu, sample, 0.05) - *
  2. - *
  3. To test the (one-sided) hypothesis sample mean < mu - * at the 99% level, first verify that the measured sample mean is less - * than mu and then use - *
    tTest(mu, sample, 0.02) - *
- *

- * Usage Note:
- * The validity of the test depends on the assumptions of the one-sample - * parametric t-test procedure, as discussed - * here - *

- * Preconditions:

    - *
  • The observed array length must be at least 2. - *
- * - * @param mu constant value to compare sample mean against - * @param sample array of sample data values - * @param alpha significance level of the test - * @return p-value - * @throws NullArgumentException if the sample array is null - * @throws NumberIsTooSmallException if the length of the array is < 2 - * @throws OutOfRangeException if alpha is not in the range (0, 0.5] - * @throws MaxCountExceededException if an error computing the p-value - */ - public boolean tTest(final double mu, final double[] sample, final double alpha) - throws NullArgumentException, NumberIsTooSmallException, - OutOfRangeException, MaxCountExceededException { - - checkSignificanceLevel(alpha); - return tTest(mu, sample) < alpha; - - } - - /** - * Returns the observed significance level, or - * p-value, associated with a one-sample, two-tailed t-test - * comparing the mean of the dataset described by sampleStats - * with the constant mu. - *

- * The number returned is the smallest significance level - * at which one can reject the null hypothesis that the mean equals - * mu in favor of the two-sided alternative that the mean - * is different from mu. For a one-sided test, divide the - * returned value by 2.

- *

- * Usage Note:
- * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed - * - * here

- *

- * Preconditions:

    - *
  • The sample must contain at least 2 observations. - *
- * - * @param mu constant value to compare sample mean against - * @param sampleStats StatisticalSummary describing sample data - * @return p-value - * @throws NullArgumentException if sampleStats is null - * @throws NumberIsTooSmallException if the number of samples is < 2 - * @throws MaxCountExceededException if an error occurs computing the p-value - */ - public double tTest(final double mu, final StatisticalSummary sampleStats) - throws NullArgumentException, NumberIsTooSmallException, - MaxCountExceededException { - - checkSampleData(sampleStats); - return tTest(sampleStats.getMean(), mu, sampleStats.getVariance(), - sampleStats.getN()); - - } - - /** - * Performs a - * two-sided t-test evaluating the null hypothesis that the mean of the - * population from which the dataset described by stats is - * drawn equals mu. - *

- * Returns true iff the null hypothesis can be rejected with - * confidence 1 - alpha. To perform a 1-sided test, use - * alpha * 2.

- *

- * Examples:

    - *
  1. To test the (2-sided) hypothesis sample mean = mu at - * the 95% level, use
    tTest(mu, sampleStats, 0.05) - *
  2. - *
  3. To test the (one-sided) hypothesis sample mean < mu - * at the 99% level, first verify that the measured sample mean is less - * than mu and then use - *
    tTest(mu, sampleStats, 0.02) - *
- *

- * Usage Note:
- * The validity of the test depends on the assumptions of the one-sample - * parametric t-test procedure, as discussed - * here - *

- * Preconditions:

    - *
  • The sample must include at least 2 observations. - *
- * - * @param mu constant value to compare sample mean against - * @param sampleStats StatisticalSummary describing sample data values - * @param alpha significance level of the test - * @return p-value - * @throws NullArgumentException if sampleStats is null - * @throws NumberIsTooSmallException if the number of samples is < 2 - * @throws OutOfRangeException if alpha is not in the range (0, 0.5] - * @throws MaxCountExceededException if an error occurs computing the p-value - */ - public boolean tTest(final double mu, final StatisticalSummary sampleStats, - final double alpha) - throws NullArgumentException, NumberIsTooSmallException, - OutOfRangeException, MaxCountExceededException { - - checkSignificanceLevel(alpha); - return tTest(mu, sampleStats) < alpha; - - } - - /** - * Returns the observed significance level, or - * p-value, associated with a two-sample, two-tailed t-test - * comparing the means of the input arrays. - *

- * The number returned is the smallest significance level - * at which one can reject the null hypothesis that the two means are - * equal in favor of the two-sided alternative that they are different. - * For a one-sided test, divide the returned value by 2.

- *

- * The test does not assume that the underlying popuation variances are - * equal and it uses approximated degrees of freedom computed from the - * sample data to compute the p-value. The t-statistic used is as defined in - * {@link #t(double[], double[])} and the Welch-Satterthwaite approximation - * to the degrees of freedom is used, - * as described - * - * here. To perform the test under the assumption of equal subpopulation - * variances, use {@link #homoscedasticTTest(double[], double[])}.

- *

- * Usage Note:
- * The validity of the p-value depends on the assumptions of the parametric - * t-test procedure, as discussed - * - * here

- *

- * Preconditions:

    - *
  • The observed array lengths must both be at least 2. - *
- * - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @return p-value for t-test - * @throws NullArgumentException if the arrays are null - * @throws NumberIsTooSmallException if the length of the arrays is < 2 - * @throws MaxCountExceededException if an error occurs computing the p-value - */ - public double tTest(final double[] sample1, final double[] sample2) - throws NullArgumentException, NumberIsTooSmallException, - MaxCountExceededException { - - checkSampleData(sample1); - checkSampleData(sample2); - // No try-catch or advertised exception because args have just been checked - return tTest(StatUtils.mean(sample1), StatUtils.mean(sample2), - StatUtils.variance(sample1), StatUtils.variance(sample2), - sample1.length, sample2.length); - - } - - /** - * Returns the observed significance level, or - * p-value, associated with a two-sample, two-tailed t-test - * comparing the means of the input arrays, under the assumption that - * the two samples are drawn from subpopulations with equal variances. - * To perform the test without the equal variances assumption, use - * {@link #tTest(double[], double[])}. - *

- * The number returned is the smallest significance level - * at which one can reject the null hypothesis that the two means are - * equal in favor of the two-sided alternative that they are different. - * For a one-sided test, divide the returned value by 2.

- *

- * A pooled variance estimate is used to compute the t-statistic. See - * {@link #homoscedasticT(double[], double[])}. The sum of the sample sizes - * minus 2 is used as the degrees of freedom.

- *

- * Usage Note:
- * The validity of the p-value depends on the assumptions of the parametric - * t-test procedure, as discussed - * - * here

- *

- * Preconditions:

    - *
  • The observed array lengths must both be at least 2. - *
- * - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @return p-value for t-test - * @throws NullArgumentException if the arrays are null - * @throws NumberIsTooSmallException if the length of the arrays is < 2 - * @throws MaxCountExceededException if an error occurs computing the p-value - */ - public double homoscedasticTTest(final double[] sample1, final double[] sample2) - throws NullArgumentException, NumberIsTooSmallException, - MaxCountExceededException { - - checkSampleData(sample1); - checkSampleData(sample2); - // No try-catch or advertised exception because args have just been checked - return homoscedasticTTest(StatUtils.mean(sample1), - StatUtils.mean(sample2), - StatUtils.variance(sample1), - StatUtils.variance(sample2), - sample1.length, sample2.length); - - } - - /** - * Performs a - * - * two-sided t-test evaluating the null hypothesis that sample1 - * and sample2 are drawn from populations with the same mean, - * with significance level alpha. This test does not assume - * that the subpopulation variances are equal. To perform the test assuming - * equal variances, use - * {@link #homoscedasticTTest(double[], double[], double)}. - *

- * Returns true iff the null hypothesis that the means are - * equal can be rejected with confidence 1 - alpha. To - * perform a 1-sided test, use alpha * 2

- *

- * See {@link #t(double[], double[])} for the formula used to compute the - * t-statistic. Degrees of freedom are approximated using the - * - * Welch-Satterthwaite approximation.

- *

- * Examples:

    - *
  1. To test the (2-sided) hypothesis mean 1 = mean 2 at - * the 95% level, use - *
    tTest(sample1, sample2, 0.05). - *
  2. - *
  3. To test the (one-sided) hypothesis mean 1 < mean 2 , - * at the 99% level, first verify that the measured mean of sample 1 - * is less than the mean of sample 2 and then use - *
    tTest(sample1, sample2, 0.02) - *
- *

- * Usage Note:
- * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed - * - * here

- *

- * Preconditions:

    - *
  • The observed array lengths must both be at least 2. - *
  • - *
  • 0 < alpha < 0.5 - *
- * - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with - * confidence 1 - alpha - * @throws NullArgumentException if the arrays are null - * @throws NumberIsTooSmallException if the length of the arrays is < 2 - * @throws OutOfRangeException if alpha is not in the range (0, 0.5] - * @throws MaxCountExceededException if an error occurs computing the p-value - */ - public boolean tTest(final double[] sample1, final double[] sample2, - final double alpha) - throws NullArgumentException, NumberIsTooSmallException, - OutOfRangeException, MaxCountExceededException { - - checkSignificanceLevel(alpha); - return tTest(sample1, sample2) < alpha; - - } - - /** - * Performs a - * - * two-sided t-test evaluating the null hypothesis that sample1 - * and sample2 are drawn from populations with the same mean, - * with significance level alpha, assuming that the - * subpopulation variances are equal. Use - * {@link #tTest(double[], double[], double)} to perform the test without - * the assumption of equal variances. - *

- * Returns true iff the null hypothesis that the means are - * equal can be rejected with confidence 1 - alpha. To - * perform a 1-sided test, use alpha * 2. To perform the test - * without the assumption of equal subpopulation variances, use - * {@link #tTest(double[], double[], double)}.

- *

- * A pooled variance estimate is used to compute the t-statistic. See - * {@link #t(double[], double[])} for the formula. The sum of the sample - * sizes minus 2 is used as the degrees of freedom.

- *

- * Examples:

    - *
  1. To test the (2-sided) hypothesis mean 1 = mean 2 at - * the 95% level, use
    tTest(sample1, sample2, 0.05). - *
  2. - *
  3. To test the (one-sided) hypothesis mean 1 < mean 2, - * at the 99% level, first verify that the measured mean of - * sample 1 is less than the mean of sample 2 - * and then use - *
    tTest(sample1, sample2, 0.02) - *
- *

- * Usage Note:
- * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed - * - * here

- *

- * Preconditions:

    - *
  • The observed array lengths must both be at least 2. - *
  • - *
  • 0 < alpha < 0.5 - *
- * - * @param sample1 array of sample data values - * @param sample2 array of sample data values - * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with - * confidence 1 - alpha - * @throws NullArgumentException if the arrays are null - * @throws NumberIsTooSmallException if the length of the arrays is < 2 - * @throws OutOfRangeException if alpha is not in the range (0, 0.5] - * @throws MaxCountExceededException if an error occurs computing the p-value - */ - public boolean homoscedasticTTest(final double[] sample1, final double[] sample2, - final double alpha) - throws NullArgumentException, NumberIsTooSmallException, - OutOfRangeException, MaxCountExceededException { - - checkSignificanceLevel(alpha); - return homoscedasticTTest(sample1, sample2) < alpha; - - } - - /** - * Returns the observed significance level, or - * p-value, associated with a two-sample, two-tailed t-test - * comparing the means of the datasets described by two StatisticalSummary - * instances. - *

- * The number returned is the smallest significance level - * at which one can reject the null hypothesis that the two means are - * equal in favor of the two-sided alternative that they are different. - * For a one-sided test, divide the returned value by 2.

- *

- * The test does not assume that the underlying population variances are - * equal and it uses approximated degrees of freedom computed from the - * sample data to compute the p-value. To perform the test assuming - * equal variances, use - * {@link #homoscedasticTTest(StatisticalSummary, StatisticalSummary)}.

- *

- * Usage Note:
- * The validity of the p-value depends on the assumptions of the parametric - * t-test procedure, as discussed - * - * here

- *

- * Preconditions:

    - *
  • The datasets described by the two Univariates must each contain - * at least 2 observations. - *
- * - * @param sampleStats1 StatisticalSummary describing data from the first sample - * @param sampleStats2 StatisticalSummary describing data from the second sample - * @return p-value for t-test - * @throws NullArgumentException if the sample statistics are null - * @throws NumberIsTooSmallException if the number of samples is < 2 - * @throws MaxCountExceededException if an error occurs computing the p-value - */ - public double tTest(final StatisticalSummary sampleStats1, - final StatisticalSummary sampleStats2) - throws NullArgumentException, NumberIsTooSmallException, - MaxCountExceededException { - - checkSampleData(sampleStats1); - checkSampleData(sampleStats2); - return tTest(sampleStats1.getMean(), sampleStats2.getMean(), - sampleStats1.getVariance(), sampleStats2.getVariance(), - sampleStats1.getN(), sampleStats2.getN()); - - } - - /** - * Returns the observed significance level, or - * p-value, associated with a two-sample, two-tailed t-test - * comparing the means of the datasets described by two StatisticalSummary - * instances, under the hypothesis of equal subpopulation variances. To - * perform a test without the equal variances assumption, use - * {@link #tTest(StatisticalSummary, StatisticalSummary)}. - *

- * The number returned is the smallest significance level - * at which one can reject the null hypothesis that the two means are - * equal in favor of the two-sided alternative that they are different. - * For a one-sided test, divide the returned value by 2.

- *

- * See {@link #homoscedasticT(double[], double[])} for the formula used to - * compute the t-statistic. The sum of the sample sizes minus 2 is used as - * the degrees of freedom.

- *

- * Usage Note:
- * The validity of the p-value depends on the assumptions of the parametric - * t-test procedure, as discussed - * here - *

- * Preconditions:

    - *
  • The datasets described by the two Univariates must each contain - * at least 2 observations. - *
- * - * @param sampleStats1 StatisticalSummary describing data from the first sample - * @param sampleStats2 StatisticalSummary describing data from the second sample - * @return p-value for t-test - * @throws NullArgumentException if the sample statistics are null - * @throws NumberIsTooSmallException if the number of samples is < 2 - * @throws MaxCountExceededException if an error occurs computing the p-value - */ - public double homoscedasticTTest(final StatisticalSummary sampleStats1, - final StatisticalSummary sampleStats2) - throws NullArgumentException, NumberIsTooSmallException, - MaxCountExceededException { - - checkSampleData(sampleStats1); - checkSampleData(sampleStats2); - return homoscedasticTTest(sampleStats1.getMean(), - sampleStats2.getMean(), - sampleStats1.getVariance(), - sampleStats2.getVariance(), - sampleStats1.getN(), sampleStats2.getN()); - - } - - /** - * Performs a - * - * two-sided t-test evaluating the null hypothesis that - * sampleStats1 and sampleStats2 describe - * datasets drawn from populations with the same mean, with significance - * level alpha. This test does not assume that the - * subpopulation variances are equal. To perform the test under the equal - * variances assumption, use - * {@link #homoscedasticTTest(StatisticalSummary, StatisticalSummary)}. - *

- * Returns true iff the null hypothesis that the means are - * equal can be rejected with confidence 1 - alpha. To - * perform a 1-sided test, use alpha * 2

- *

- * See {@link #t(double[], double[])} for the formula used to compute the - * t-statistic. Degrees of freedom are approximated using the - * - * Welch-Satterthwaite approximation.

- *

- * Examples:

    - *
  1. To test the (2-sided) hypothesis mean 1 = mean 2 at - * the 95%, use - *
    tTest(sampleStats1, sampleStats2, 0.05) - *
  2. - *
  3. To test the (one-sided) hypothesis mean 1 < mean 2 - * at the 99% level, first verify that the measured mean of - * sample 1 is less than the mean of sample 2 - * and then use - *
    tTest(sampleStats1, sampleStats2, 0.02) - *
- *

- * Usage Note:
- * The validity of the test depends on the assumptions of the parametric - * t-test procedure, as discussed - * - * here

- *

- * Preconditions:

    - *
  • The datasets described by the two Univariates must each contain - * at least 2 observations. - *
  • - *
  • 0 < alpha < 0.5 - *
- * - * @param sampleStats1 StatisticalSummary describing sample data values - * @param sampleStats2 StatisticalSummary describing sample data values - * @param alpha significance level of the test - * @return true if the null hypothesis can be rejected with - * confidence 1 - alpha - * @throws NullArgumentException if the sample statistics are null - * @throws NumberIsTooSmallException if the number of samples is < 2 - * @throws OutOfRangeException if alpha is not in the range (0, 0.5] - * @throws MaxCountExceededException if an error occurs computing the p-value - */ - public boolean tTest(final StatisticalSummary sampleStats1, - final StatisticalSummary sampleStats2, - final double alpha) - throws NullArgumentException, NumberIsTooSmallException, - OutOfRangeException, MaxCountExceededException { - - checkSignificanceLevel(alpha); - return tTest(sampleStats1, sampleStats2) < alpha; - - } - - //----------------------------------------------- Protected methods - - /** - * Computes approximate degrees of freedom for 2-sample t-test. - * - * @param v1 first sample variance - * @param v2 second sample variance - * @param n1 first sample n - * @param n2 second sample n - * @return approximate degrees of freedom - */ - protected double df(double v1, double v2, double n1, double n2) { - return (((v1 / n1) + (v2 / n2)) * ((v1 / n1) + (v2 / n2))) / - ((v1 * v1) / (n1 * n1 * (n1 - 1d)) + (v2 * v2) / - (n2 * n2 * (n2 - 1d))); - } - - /** - * Computes t test statistic for 1-sample t-test. - * - * @param m sample mean - * @param mu constant to test against - * @param v sample variance - * @param n sample n - * @return t test statistic - */ - protected double t(final double m, final double mu, - final double v, final double n) { - return (m - mu) / FastMath.sqrt(v / n); - } - - /** - * Computes t test statistic for 2-sample t-test. - *

- * Does not assume that subpopulation variances are equal.

- * - * @param m1 first sample mean - * @param m2 second sample mean - * @param v1 first sample variance - * @param v2 second sample variance - * @param n1 first sample n - * @param n2 second sample n - * @return t test statistic - */ - protected double t(final double m1, final double m2, - final double v1, final double v2, - final double n1, final double n2) { - return (m1 - m2) / FastMath.sqrt((v1 / n1) + (v2 / n2)); - } - - /** - * Computes t test statistic for 2-sample t-test under the hypothesis - * of equal subpopulation variances. - * - * @param m1 first sample mean - * @param m2 second sample mean - * @param v1 first sample variance - * @param v2 second sample variance - * @param n1 first sample n - * @param n2 second sample n - * @return t test statistic - */ - protected double homoscedasticT(final double m1, final double m2, - final double v1, final double v2, - final double n1, final double n2) { - final double pooledVariance = ((n1 - 1) * v1 + (n2 -1) * v2 ) / (n1 + n2 - 2); - return (m1 - m2) / FastMath.sqrt(pooledVariance * (1d / n1 + 1d / n2)); - } - - /** - * Computes p-value for 2-sided, 1-sample t-test. - * - * @param m sample mean - * @param mu constant to test against - * @param v sample variance - * @param n sample n - * @return p-value - * @throws MaxCountExceededException if an error occurs computing the p-value - * @throws MathIllegalArgumentException if n is not greater than 1 - */ - protected double tTest(final double m, final double mu, - final double v, final double n) - throws MaxCountExceededException, MathIllegalArgumentException { - - final double t = FastMath.abs(t(m, mu, v, n)); - // pass a null rng to avoid unneeded overhead as we will not sample from this distribution - final TDistribution distribution = new TDistribution(n - 1); - return 2.0 * distribution.cumulativeProbability(-t); - - } - - /** - * Computes p-value for 2-sided, 2-sample t-test. - *

- * Does not assume subpopulation variances are equal. Degrees of freedom - * are estimated from the data.

- * - * @param m1 first sample mean - * @param m2 second sample mean - * @param v1 first sample variance - * @param v2 second sample variance - * @param n1 first sample n - * @param n2 second sample n - * @return p-value - * @throws MaxCountExceededException if an error occurs computing the p-value - * @throws NotStrictlyPositiveException if the estimated degrees of freedom is not - * strictly positive - */ - protected double tTest(final double m1, final double m2, - final double v1, final double v2, - final double n1, final double n2) - throws MaxCountExceededException, NotStrictlyPositiveException { - - final double t = FastMath.abs(t(m1, m2, v1, v2, n1, n2)); - final double degreesOfFreedom = df(v1, v2, n1, n2); - // pass a null rng to avoid unneeded overhead as we will not sample from this distribution - final TDistribution distribution = new TDistribution(degreesOfFreedom); - return 2.0 * distribution.cumulativeProbability(-t); - - } - - /** - * Computes p-value for 2-sided, 2-sample t-test, under the assumption - * of equal subpopulation variances. - *

- * The sum of the sample sizes minus 2 is used as degrees of freedom.

- * - * @param m1 first sample mean - * @param m2 second sample mean - * @param v1 first sample variance - * @param v2 second sample variance - * @param n1 first sample n - * @param n2 second sample n - * @return p-value - * @throws MaxCountExceededException if an error occurs computing the p-value - * @throws NotStrictlyPositiveException if the estimated degrees of freedom is not - * strictly positive - */ - protected double homoscedasticTTest(double m1, double m2, - double v1, double v2, - double n1, double n2) - throws MaxCountExceededException, NotStrictlyPositiveException { - - final double t = FastMath.abs(homoscedasticT(m1, m2, v1, v2, n1, n2)); - final double degreesOfFreedom = n1 + n2 - 2; - // pass a null rng to avoid unneeded overhead as we will not sample from this distribution - final TDistribution distribution = new TDistribution(degreesOfFreedom); - return 2.0 * distribution.cumulativeProbability(-t); - - } - - /** - * Check significance level. - * - * @param alpha significance level - * @throws OutOfRangeException if the significance level is out of bounds. - */ - private void checkSignificanceLevel(final double alpha) - throws OutOfRangeException { - - if (alpha <= 0 || alpha > 0.5) { - throw new OutOfRangeException(LocalizedFormats.SIGNIFICANCE_LEVEL, - alpha, 0.0, 0.5); - } - - } - - /** - * Check sample data. - * - * @param data Sample data. - * @throws NullArgumentException if {@code data} is {@code null}. - * @throws NumberIsTooSmallException if there is not enough sample data. - */ - private void checkSampleData(final double[] data) - throws NullArgumentException, NumberIsTooSmallException { - - if (data == null) { - throw new NullArgumentException(); - } - if (data.length < 2) { - throw new NumberIsTooSmallException( - LocalizedFormats.INSUFFICIENT_DATA_FOR_T_STATISTIC, - data.length, 2, true); - } - - } - - /** - * Check sample data. - * - * @param stat Statistical summary. - * @throws NullArgumentException if {@code data} is {@code null}. - * @throws NumberIsTooSmallException if there is not enough sample data. - */ - private void checkSampleData(final StatisticalSummary stat) - throws NullArgumentException, NumberIsTooSmallException { - - if (stat == null) { - throw new NullArgumentException(); - } - if (stat.getN() < 2) { - throw new NumberIsTooSmallException( - LocalizedFormats.INSUFFICIENT_DATA_FOR_T_STATISTIC, - stat.getN(), 2, true); - } - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/WilcoxonSignedRankTest.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/WilcoxonSignedRankTest.java deleted file mode 100644 index efa9ca57b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/WilcoxonSignedRankTest.java +++ /dev/null @@ -1,323 +0,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. - */ -package org.apache.commons.math4.stat.inference; - -import org.apache.commons.statistics.distribution.NormalDistribution; -import org.apache.commons.math4.exception.ConvergenceException; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.stat.ranking.NaNStrategy; -import org.apache.commons.math4.stat.ranking.NaturalRanking; -import org.apache.commons.math4.stat.ranking.TiesStrategy; -import org.apache.commons.math4.util.FastMath; - -/** - * An implementation of the Wilcoxon signed-rank test. - * - */ -public class WilcoxonSignedRankTest { - - /** Ranking algorithm. */ - private NaturalRanking naturalRanking; - - /** - * Create a test instance where NaN's are left in place and ties get - * the average of applicable ranks. Use this unless you are very sure - * of what you are doing. - */ - public WilcoxonSignedRankTest() { - naturalRanking = new NaturalRanking(NaNStrategy.FIXED, - TiesStrategy.AVERAGE); - } - - /** - * Create a test instance using the given strategies for NaN's and ties. - * Only use this if you are sure of what you are doing. - * - * @param nanStrategy - * specifies the strategy that should be used for Double.NaN's - * @param tiesStrategy - * specifies the strategy that should be used for ties - */ - public WilcoxonSignedRankTest(final NaNStrategy nanStrategy, - final TiesStrategy tiesStrategy) { - naturalRanking = new NaturalRanking(nanStrategy, tiesStrategy); - } - - /** - * Ensures that the provided arrays fulfills the assumptions. - * - * @param x first sample - * @param y second sample - * @throws NullArgumentException if {@code x} or {@code y} are {@code null}. - * @throws NoDataException if {@code x} or {@code y} are zero-length. - * @throws DimensionMismatchException if {@code x} and {@code y} do not - * have the same length. - */ - private void ensureDataConformance(final double[] x, final double[] y) - throws NullArgumentException, NoDataException, DimensionMismatchException { - - if (x == null || - y == null) { - throw new NullArgumentException(); - } - if (x.length == 0 || - y.length == 0) { - throw new NoDataException(); - } - if (y.length != x.length) { - throw new DimensionMismatchException(y.length, x.length); - } - } - - /** - * Calculates y[i] - x[i] for all i - * - * @param x first sample - * @param y second sample - * @return z = y - x - */ - private double[] calculateDifferences(final double[] x, final double[] y) { - - final double[] z = new double[x.length]; - - for (int i = 0; i < x.length; ++i) { - z[i] = y[i] - x[i]; - } - - return z; - } - - /** - * Calculates |z[i]| for all i - * - * @param z sample - * @return |z| - * @throws NullArgumentException if {@code z} is {@code null} - * @throws NoDataException if {@code z} is zero-length. - */ - private double[] calculateAbsoluteDifferences(final double[] z) - throws NullArgumentException, NoDataException { - - if (z == null) { - throw new NullArgumentException(); - } - - if (z.length == 0) { - throw new NoDataException(); - } - - final double[] zAbs = new double[z.length]; - - for (int i = 0; i < z.length; ++i) { - zAbs[i] = FastMath.abs(z[i]); - } - - return zAbs; - } - - /** - * Computes the - * Wilcoxon signed ranked statistic comparing mean for two related - * samples or repeated measurements on a single sample. - *

- * This statistic can be used to perform a Wilcoxon signed ranked test - * evaluating the null hypothesis that the two related samples or repeated - * measurements on a single sample has equal mean. - *

- *

- * Let Xi denote the i'th individual of the first sample and - * Yi the related i'th individual in the second sample. Let - * Zi = Yi - Xi. - *

- *

- * Preconditions: - *

    - *
  • The differences Zi must be independent.
  • - *
  • Each Zi comes from a continuous population (they must be - * identical) and is symmetric about a common median.
  • - *
  • The values that Xi and Yi represent are - * ordered, so the comparisons greater than, less than, and equal to are - * meaningful.
  • - *
- * - * @param x the first sample - * @param y the second sample - * @return wilcoxonSignedRank statistic (the larger of W+ and W-) - * @throws NullArgumentException if {@code x} or {@code y} are {@code null}. - * @throws NoDataException if {@code x} or {@code y} are zero-length. - * @throws DimensionMismatchException if {@code x} and {@code y} do not - * have the same length. - */ - public double wilcoxonSignedRank(final double[] x, final double[] y) - throws NullArgumentException, NoDataException, DimensionMismatchException { - - ensureDataConformance(x, y); - - // throws IllegalArgumentException if x and y are not correctly - // specified - final double[] z = calculateDifferences(x, y); - final double[] zAbs = calculateAbsoluteDifferences(z); - - final double[] ranks = naturalRanking.rank(zAbs); - - double Wplus = 0; - - for (int i = 0; i < z.length; ++i) { - if (z[i] > 0) { - Wplus += ranks[i]; - } - } - - final int N = x.length; - final double Wminus = (((double) (N * (N + 1))) / 2.0) - Wplus; - - return FastMath.max(Wplus, Wminus); - } - - /** - * Algorithm inspired by - * http://www.fon.hum.uva.nl/Service/Statistics/Signed_Rank_Algorihms.html#C - * by Rob van Son, Institute of Phonetic Sciences & IFOTT, - * University of Amsterdam - * - * @param Wmax largest Wilcoxon signed rank value - * @param N number of subjects (corresponding to x.length) - * @return two-sided exact p-value - */ - private double calculateExactPValue(final double Wmax, final int N) { - - // Total number of outcomes (equal to 2^N but a lot faster) - final int m = 1 << N; - - int largerRankSums = 0; - - for (int i = 0; i < m; ++i) { - int rankSum = 0; - - // Generate all possible rank sums - for (int j = 0; j < N; ++j) { - - // (i >> j) & 1 extract i's j-th bit from the right - if (((i >> j) & 1) == 1) { - rankSum += j + 1; - } - } - - if (rankSum >= Wmax) { - ++largerRankSums; - } - } - - /* - * largerRankSums / m gives the one-sided p-value, so it's multiplied - * with 2 to get the two-sided p-value - */ - return 2 * ((double) largerRankSums) / ((double) m); - } - - /** - * @param Wmin smallest Wilcoxon signed rank value - * @param N number of subjects (corresponding to x.length) - * @return two-sided asymptotic p-value - */ - private double calculateAsymptoticPValue(final double Wmin, final int N) { - - final double ES = (double) (N * (N + 1)) / 4.0; - - /* Same as (but saves computations): - * final double VarW = ((double) (N * (N + 1) * (2*N + 1))) / 24; - */ - final double VarS = ES * ((double) (2 * N + 1) / 6.0); - - // - 0.5 is a continuity correction - final double z = (Wmin - ES - 0.5) / FastMath.sqrt(VarS); - - // No try-catch or advertised exception because args are valid - // pass a null rng to avoid unneeded overhead as we will not sample from this distribution - final NormalDistribution standardNormal = new NormalDistribution(0, 1); - - return 2*standardNormal.cumulativeProbability(z); - } - - /** - * Returns the observed significance level, or - * p-value, associated with a - * Wilcoxon signed ranked statistic comparing mean for two related - * samples or repeated measurements on a single sample. - *

- * Let Xi denote the i'th individual of the first sample and - * Yi the related i'th individual in the second sample. Let - * Zi = Yi - Xi. - *

- *

- * Preconditions: - *

    - *
  • The differences Zi must be independent.
  • - *
  • Each Zi comes from a continuous population (they must be - * identical) and is symmetric about a common median.
  • - *
  • The values that Xi and Yi represent are - * ordered, so the comparisons greater than, less than, and equal to are - * meaningful.
  • - *
- * - * @param x the first sample - * @param y the second sample - * @param exactPValue - * if the exact p-value is wanted (only works for x.length >= 30, - * if true and x.length < 30, this is ignored because - * calculations may take too long) - * @return p-value - * @throws NullArgumentException if {@code x} or {@code y} are {@code null}. - * @throws NoDataException if {@code x} or {@code y} are zero-length. - * @throws DimensionMismatchException if {@code x} and {@code y} do not - * have the same length. - * @throws NumberIsTooLargeException if {@code exactPValue} is {@code true} - * and {@code x.length} > 30 - * @throws ConvergenceException if the p-value can not be computed due to - * a convergence error - * @throws MaxCountExceededException if the maximum number of iterations - * is exceeded - */ - public double wilcoxonSignedRankTest(final double[] x, final double[] y, - final boolean exactPValue) - throws NullArgumentException, NoDataException, DimensionMismatchException, - NumberIsTooLargeException, ConvergenceException, MaxCountExceededException { - - ensureDataConformance(x, y); - - final int N = x.length; - final double Wmax = wilcoxonSignedRank(x, y); - - if (exactPValue && N > 30) { - throw new NumberIsTooLargeException(N, 30, true); - } - - if (exactPValue) { - return calculateExactPValue(Wmax, N); - } else { - final double Wmin = ( (double)(N*(N+1)) / 2.0 ) - Wmax; - return calculateAsymptoticPValue(Wmin, N); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/package-info.java deleted file mode 100644 index ed7b486ee..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/inference/package-info.java +++ /dev/null @@ -1,22 +0,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. - */ -/** - * - * Classes providing hypothesis testing. - * - */ -package org.apache.commons.math4.stat.inference; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/AgrestiCoullInterval.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/AgrestiCoullInterval.java deleted file mode 100644 index 9b9dded5f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/AgrestiCoullInterval.java +++ /dev/null @@ -1,49 +0,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. - */ -package org.apache.commons.math4.stat.interval; - -import org.apache.commons.statistics.distribution.NormalDistribution; -import org.apache.commons.math4.util.FastMath; - -/** - * Implements the Agresti-Coull method for creating a binomial proportion confidence interval. - * - * @see - * Agresti-Coull interval (Wikipedia) - * @since 3.3 - */ -public class AgrestiCoullInterval implements BinomialConfidenceInterval { - - /** {@inheritDoc} */ - @Override - public ConfidenceInterval createInterval(int numberOfTrials, int numberOfSuccesses, double confidenceLevel) { - IntervalUtils.checkParameters(numberOfTrials, numberOfSuccesses, confidenceLevel); - final double alpha = (1.0 - confidenceLevel) / 2; - final NormalDistribution normalDistribution = new NormalDistribution(0, 1); - final double z = normalDistribution.inverseCumulativeProbability(1 - alpha); - final double zSquared = FastMath.pow(z, 2); - final double modifiedNumberOfTrials = numberOfTrials + zSquared; - final double modifiedSuccessesRatio = (1.0 / modifiedNumberOfTrials) * (numberOfSuccesses + 0.5 * zSquared); - final double difference = z * - FastMath.sqrt(1.0 / modifiedNumberOfTrials * modifiedSuccessesRatio * - (1 - modifiedSuccessesRatio)); - return new ConfidenceInterval(modifiedSuccessesRatio - difference, modifiedSuccessesRatio + difference, - confidenceLevel); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/BinomialConfidenceInterval.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/BinomialConfidenceInterval.java deleted file mode 100644 index 9bf9e230f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/BinomialConfidenceInterval.java +++ /dev/null @@ -1,61 +0,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. - */ -package org.apache.commons.math4.stat.interval; - -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.OutOfRangeException; - -/** - * Interface to generate confidence intervals for a binomial proportion. - * - * @see Binomial - * proportion confidence interval (Wikipedia) - * @since 3.3 - */ -public interface BinomialConfidenceInterval { - - /** - * Create a confidence interval for the true probability of success - * of an unknown binomial distribution with the given observed number - * of trials, successes and confidence level. - *

- * Preconditions: - *

    - *
  • {@code numberOfTrials} must be positive
  • - *
  • {@code numberOfSuccesses} may not exceed {@code numberOfTrials}
  • - *
  • {@code confidenceLevel} must be strictly between 0 and 1 (exclusive)
  • - *
- * - * @param numberOfTrials number of trials - * @param numberOfSuccesses number of successes - * @param confidenceLevel desired probability that the true probability of - * success falls within the returned interval - * @return Confidence interval containing the probability of success with - * probability {@code confidenceLevel} - * @throws NotStrictlyPositiveException if {@code numberOfTrials <= 0}. - * @throws NotPositiveException if {@code numberOfSuccesses < 0}. - * @throws NumberIsTooLargeException if {@code numberOfSuccesses > numberOfTrials}. - * @throws OutOfRangeException if {@code confidenceLevel} is not in the interval {@code (0, 1)}. - */ - ConfidenceInterval createInterval(int numberOfTrials, int numberOfSuccesses, double confidenceLevel) - throws NotStrictlyPositiveException, NotPositiveException, - NumberIsTooLargeException, OutOfRangeException; - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/ClopperPearsonInterval.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/ClopperPearsonInterval.java deleted file mode 100644 index 5bf642c5c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/ClopperPearsonInterval.java +++ /dev/null @@ -1,62 +0,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. - */ -package org.apache.commons.math4.stat.interval; - -import org.apache.commons.statistics.distribution.FDistribution; - -/** - * Implements the Clopper-Pearson method for creating a binomial proportion confidence interval. - * - * @see - * Clopper-Pearson interval (Wikipedia) - * @since 3.3 - */ -public class ClopperPearsonInterval implements BinomialConfidenceInterval { - - /** {@inheritDoc} */ - @Override - public ConfidenceInterval createInterval(int numberOfTrials, - int numberOfSuccesses, - double confidenceLevel) { - IntervalUtils.checkParameters(numberOfTrials, numberOfSuccesses, confidenceLevel); - double lowerBound = 0; - double upperBound = 0; - - if (numberOfSuccesses > 0) { - final double alpha = 0.5 * (1 - confidenceLevel); - - final FDistribution distributionLowerBound = new FDistribution(2 * (numberOfTrials - numberOfSuccesses + 1), - 2 * numberOfSuccesses); - final double fValueLowerBound = distributionLowerBound.inverseCumulativeProbability(1 - alpha); - lowerBound = numberOfSuccesses / - (numberOfSuccesses + (numberOfTrials - numberOfSuccesses + 1) * fValueLowerBound); - - if (numberOfSuccesses != numberOfTrials) { - final FDistribution distributionUpperBound = new FDistribution(2 * (numberOfSuccesses + 1), - 2 * (numberOfTrials - numberOfSuccesses)); - final double fValueUpperBound = distributionUpperBound.inverseCumulativeProbability(1 - alpha); - upperBound = (numberOfSuccesses + 1) * fValueUpperBound / - (numberOfTrials - numberOfSuccesses + (numberOfSuccesses + 1) * fValueUpperBound); - } else { - upperBound = 1; - } - } - - return new ConfidenceInterval(lowerBound, upperBound, confidenceLevel); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/ConfidenceInterval.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/ConfidenceInterval.java deleted file mode 100644 index e41ebf175..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/ConfidenceInterval.java +++ /dev/null @@ -1,108 +0,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. - */ -package org.apache.commons.math4.stat.interval; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Represents an interval estimate of a population parameter. - * - * @since 3.3 - */ -public class ConfidenceInterval { - - /** Lower endpoint of the interval */ - private double lowerBound; - - /** Upper endpoint of the interval */ - private double upperBound; - - /** - * The asserted probability that the interval contains the population - * parameter - */ - private double confidenceLevel; - - /** - * Create a confidence interval with the given bounds and confidence level. - *

- * Preconditions: - *

    - *
  • {@code lower} must be strictly less than {@code upper}
  • - *
  • {@code confidenceLevel} must be strictly between 0 and 1 (exclusive)
  • - *
- * - * @param lowerBound lower endpoint of the interval - * @param upperBound upper endpoint of the interval - * @param confidenceLevel coverage probability - * @throws MathIllegalArgumentException if the preconditions are not met - */ - public ConfidenceInterval(double lowerBound, double upperBound, double confidenceLevel) { - checkParameters(lowerBound, upperBound, confidenceLevel); - this.lowerBound = lowerBound; - this.upperBound = upperBound; - this.confidenceLevel = confidenceLevel; - } - - /** - * @return the lower endpoint of the interval - */ - public double getLowerBound() { - return lowerBound; - } - - /** - * @return the upper endpoint of the interval - */ - public double getUpperBound() { - return upperBound; - } - - /** - * @return the asserted probability that the interval contains the - * population parameter - */ - public double getConfidenceLevel() { - return confidenceLevel; - } - - /** - * @return String representation of the confidence interval - */ - @Override - public String toString() { - return "[" + lowerBound + ";" + upperBound + "] (confidence level:" + confidenceLevel + ")"; - } - - /** - * Verifies that (lower, upper) is a valid non-empty interval and confidence - * is strictly between 0 and 1. - * - * @param lower lower endpoint - * @param upper upper endpoint - * @param confidence confidence level - */ - private void checkParameters(double lower, double upper, double confidence) { - if (lower >= upper) { - throw new MathIllegalArgumentException(LocalizedFormats.LOWER_BOUND_NOT_BELOW_UPPER_BOUND, lower, upper); - } - if (confidence <= 0 || confidence >= 1) { - throw new MathIllegalArgumentException(LocalizedFormats.OUT_OF_BOUNDS_CONFIDENCE_LEVEL, confidence, 0, 1); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/IntervalUtils.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/IntervalUtils.java deleted file mode 100644 index 11ead0cc6..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/IntervalUtils.java +++ /dev/null @@ -1,173 +0,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. - */ -package org.apache.commons.math4.stat.interval; - -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Factory methods to generate confidence intervals for a binomial proportion. - * The supported methods are: - *
    - *
  • Agresti-Coull interval
  • - *
  • Clopper-Pearson method (exact method)
  • - *
  • Normal approximation (based on central limit theorem)
  • - *
  • Wilson score interval
  • - *
- * - * @since 3.3 - */ -public final class IntervalUtils { - - /** Singleton Agresti-Coull instance. */ - private static final BinomialConfidenceInterval AGRESTI_COULL = new AgrestiCoullInterval(); - - /** Singleton Clopper-Pearson instance. */ - private static final BinomialConfidenceInterval CLOPPER_PEARSON = new ClopperPearsonInterval(); - - /** Singleton NormalApproximation instance. */ - private static final BinomialConfidenceInterval NORMAL_APPROXIMATION = new NormalApproximationInterval(); - - /** Singleton Wilson score instance. */ - private static final BinomialConfidenceInterval WILSON_SCORE = new WilsonScoreInterval(); - - /** - * Prevent instantiation. - */ - private IntervalUtils() { - } - - /** - * Create an Agresti-Coull binomial confidence interval for the true - * probability of success of an unknown binomial distribution with the given - * observed number of trials, successes and confidence level. - * - * @param numberOfTrials number of trials - * @param numberOfSuccesses number of successes - * @param confidenceLevel desired probability that the true probability of - * success falls within the returned interval - * @return Confidence interval containing the probability of success with - * probability {@code confidenceLevel} - * @throws NotStrictlyPositiveException if {@code numberOfTrials <= 0}. - * @throws NotPositiveException if {@code numberOfSuccesses < 0}. - * @throws NumberIsTooLargeException if {@code numberOfSuccesses > numberOfTrials}. - * @throws OutOfRangeException if {@code confidenceLevel} is not in the interval {@code (0, 1)}. - */ - public static ConfidenceInterval getAgrestiCoullInterval(int numberOfTrials, int numberOfSuccesses, - double confidenceLevel) { - return AGRESTI_COULL.createInterval(numberOfTrials, numberOfSuccesses, confidenceLevel); - } - - /** - * Create a Clopper-Pearson binomial confidence interval for the true - * probability of success of an unknown binomial distribution with the given - * observed number of trials, successes and confidence level. - *

- * Preconditions: - *

    - *
  • {@code numberOfTrials} must be positive
  • - *
  • {@code numberOfSuccesses} may not exceed {@code numberOfTrials}
  • - *
  • {@code confidenceLevel} must be strictly between 0 and 1 (exclusive)
  • - *
- * - * @param numberOfTrials number of trials - * @param numberOfSuccesses number of successes - * @param confidenceLevel desired probability that the true probability of - * success falls within the returned interval - * @return Confidence interval containing the probability of success with - * probability {@code confidenceLevel} - * @throws NotStrictlyPositiveException if {@code numberOfTrials <= 0}. - * @throws NotPositiveException if {@code numberOfSuccesses < 0}. - * @throws NumberIsTooLargeException if {@code numberOfSuccesses > numberOfTrials}. - * @throws OutOfRangeException if {@code confidenceLevel} is not in the interval {@code (0, 1)}. - */ - public static ConfidenceInterval getClopperPearsonInterval(int numberOfTrials, int numberOfSuccesses, - double confidenceLevel) { - return CLOPPER_PEARSON.createInterval(numberOfTrials, numberOfSuccesses, confidenceLevel); - } - - /** - * Create a binomial confidence interval for the true probability of success - * of an unknown binomial distribution with the given observed number of - * trials, successes and confidence level using the Normal approximation to - * the binomial distribution. - * - * @param numberOfTrials number of trials - * @param numberOfSuccesses number of successes - * @param confidenceLevel desired probability that the true probability of - * success falls within the interval - * @return Confidence interval containing the probability of success with - * probability {@code confidenceLevel} - */ - public static ConfidenceInterval getNormalApproximationInterval(int numberOfTrials, int numberOfSuccesses, - double confidenceLevel) { - return NORMAL_APPROXIMATION.createInterval(numberOfTrials, numberOfSuccesses, confidenceLevel); - } - - /** - * Create a Wilson score binomial confidence interval for the true - * probability of success of an unknown binomial distribution with the given - * observed number of trials, successes and confidence level. - * - * @param numberOfTrials number of trials - * @param numberOfSuccesses number of successes - * @param confidenceLevel desired probability that the true probability of - * success falls within the returned interval - * @return Confidence interval containing the probability of success with - * probability {@code confidenceLevel} - * @throws NotStrictlyPositiveException if {@code numberOfTrials <= 0}. - * @throws NotPositiveException if {@code numberOfSuccesses < 0}. - * @throws NumberIsTooLargeException if {@code numberOfSuccesses > numberOfTrials}. - * @throws OutOfRangeException if {@code confidenceLevel} is not in the interval {@code (0, 1)}. - */ - public static ConfidenceInterval getWilsonScoreInterval(int numberOfTrials, int numberOfSuccesses, - double confidenceLevel) { - return WILSON_SCORE.createInterval(numberOfTrials, numberOfSuccesses, confidenceLevel); - } - - /** - * Verifies that parameters satisfy preconditions. - * - * @param numberOfTrials number of trials (must be positive) - * @param numberOfSuccesses number of successes (must not exceed numberOfTrials) - * @param confidenceLevel confidence level (must be strictly between 0 and 1) - * @throws NotStrictlyPositiveException if {@code numberOfTrials <= 0}. - * @throws NotPositiveException if {@code numberOfSuccesses < 0}. - * @throws NumberIsTooLargeException if {@code numberOfSuccesses > numberOfTrials}. - * @throws OutOfRangeException if {@code confidenceLevel} is not in the interval {@code (0, 1)}. - */ - static void checkParameters(int numberOfTrials, int numberOfSuccesses, double confidenceLevel) { - if (numberOfTrials <= 0) { - throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_TRIALS, numberOfTrials); - } - if (numberOfSuccesses < 0) { - throw new NotPositiveException(LocalizedFormats.NEGATIVE_NUMBER_OF_SUCCESSES, numberOfSuccesses); - } - if (numberOfSuccesses > numberOfTrials) { - throw new NumberIsTooLargeException(LocalizedFormats.NUMBER_OF_SUCCESS_LARGER_THAN_POPULATION_SIZE, - numberOfSuccesses, numberOfTrials, true); - } - if (confidenceLevel <= 0 || confidenceLevel >= 1) { - throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUNDS_CONFIDENCE_LEVEL, - confidenceLevel, 0, 1); - } - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/NormalApproximationInterval.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/NormalApproximationInterval.java deleted file mode 100644 index 9c63d3308..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/NormalApproximationInterval.java +++ /dev/null @@ -1,45 +0,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. - */ -package org.apache.commons.math4.stat.interval; - -import org.apache.commons.statistics.distribution.NormalDistribution; -import org.apache.commons.math4.util.FastMath; - -/** - * Implements the normal approximation method for creating a binomial proportion confidence interval. - * - * @see - * Normal approximation interval (Wikipedia) - * @since 3.3 - */ -public class NormalApproximationInterval implements BinomialConfidenceInterval { - - /** {@inheritDoc} */ - @Override - public ConfidenceInterval createInterval(int numberOfTrials, int numberOfSuccesses, - double confidenceLevel) { - IntervalUtils.checkParameters(numberOfTrials, numberOfSuccesses, confidenceLevel); - final double mean = (double) numberOfSuccesses / (double) numberOfTrials; - final double alpha = (1.0 - confidenceLevel) / 2; - final NormalDistribution normalDistribution = new NormalDistribution(0, 1); - final double difference = normalDistribution.inverseCumulativeProbability(1 - alpha) * - FastMath.sqrt(1.0 / numberOfTrials * mean * (1 - mean)); - return new ConfidenceInterval(mean - difference, mean + difference, confidenceLevel); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/WilsonScoreInterval.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/WilsonScoreInterval.java deleted file mode 100644 index 7881ec9b6..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/WilsonScoreInterval.java +++ /dev/null @@ -1,51 +0,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. - */ -package org.apache.commons.math4.stat.interval; - -import org.apache.commons.statistics.distribution.NormalDistribution; -import org.apache.commons.math4.util.FastMath; - -/** - * Implements the - * Wilson score method for creating a binomial proportion confidence interval. - * - * @since 3.3 - */ -public class WilsonScoreInterval implements BinomialConfidenceInterval { - - /** {@inheritDoc} */ - @Override - public ConfidenceInterval createInterval(int numberOfTrials, int numberOfSuccesses, double confidenceLevel) { - IntervalUtils.checkParameters(numberOfTrials, numberOfSuccesses, confidenceLevel); - final double alpha = (1 - confidenceLevel) / 2; - final NormalDistribution normalDistribution = new NormalDistribution(0, 1); - final double z = normalDistribution.inverseCumulativeProbability(1 - alpha); - final double zSquared = z * z; - final double oneOverNumTrials = 1d / numberOfTrials; - final double zSquaredOverNumTrials = zSquared * oneOverNumTrials; - final double mean = oneOverNumTrials * numberOfSuccesses; - - final double factor = 1 / (1 + zSquaredOverNumTrials); - final double modifiedSuccessRatio = mean + zSquaredOverNumTrials / 2; - final double difference = z * FastMath.sqrt(oneOverNumTrials * mean * (1 - mean) + - (oneOverNumTrials * zSquaredOverNumTrials / 4)); - - final double lowerBound = factor * (modifiedSuccessRatio - difference); - final double upperBound = factor * (modifiedSuccessRatio + difference); - return new ConfidenceInterval(lowerBound, upperBound, confidenceLevel); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/package-info.java deleted file mode 100644 index 0e1fa28a2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/interval/package-info.java +++ /dev/null @@ -1,22 +0,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. - */ -/** - * - * Classes providing binomial proportion confidence interval construction. - * - */ -package org.apache.commons.math4.stat.interval; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/package-info.java deleted file mode 100644 index 4919e19c2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/package-info.java +++ /dev/null @@ -1,20 +0,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. - */ -/** - * Data storage, manipulation and summary routines. - */ -package org.apache.commons.math4.stat; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/ranking/NaNStrategy.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/ranking/NaNStrategy.java deleted file mode 100644 index 77521034c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/ranking/NaNStrategy.java +++ /dev/null @@ -1,55 +0,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. - */ - -package org.apache.commons.math4.stat.ranking; - -/** - * Strategies for handling NaN values in rank transformations. - *
    - *
  • MINIMAL - NaNs are treated as minimal in the ordering, equivalent to - * (that is, tied with) Double.NEGATIVE_INFINITY.
  • - *
  • MAXIMAL - NaNs are treated as maximal in the ordering, equivalent to - * Double.POSITIVE_INFINITY
  • - *
  • REMOVED - NaNs are removed before the rank transform is applied
  • - *
  • FIXED - NaNs are left "in place," that is the rank transformation is - * applied to the other elements in the input array, but the NaN elements - * are returned unchanged.
  • - *
  • FAILED - If any NaN is encountered in the input array, an appropriate - * exception is thrown
  • - *
- * - * @since 2.0 - */ -public enum NaNStrategy { - - /** NaNs are considered minimal in the ordering */ - MINIMAL, - - /** NaNs are considered maximal in the ordering */ - MAXIMAL, - - /** NaNs are removed before computing ranks */ - REMOVED, - - /** NaNs are left in place */ - FIXED, - - /** NaNs result in an exception - * @since 3.1 - */ - FAILED -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/ranking/NaturalRanking.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/ranking/NaturalRanking.java deleted file mode 100644 index 013a8fa56..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/ranking/NaturalRanking.java +++ /dev/null @@ -1,480 +0,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. - */ - -package org.apache.commons.math4.stat.ranking; - -import org.apache.commons.math4.exception.MathInternalError; -import org.apache.commons.math4.exception.NotANumberException; -import org.apache.commons.math4.random.RandomUtils; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.simple.RandomSource; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - - -/** - * Ranking based on the natural ordering on doubles. - * - *

NaNs are treated according to the configured {@link NaNStrategy} and ties - * are handled using the selected {@link TiesStrategy}. - * Configuration settings are supplied in optional constructor arguments. - * Defaults are {@link NaNStrategy#FAILED} and {@link TiesStrategy#AVERAGE}, - * respectively. When using {@link TiesStrategy#RANDOM}, a - * {@link UniformRandomProvider random generator} may be supplied as a - * constructor argument.

- *

Examples: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
rankings
- * Input data: (20, 17, 30, 42.3, 17, 50, Double.NaN, Double.NEGATIVE_INFINITY, 17) - *
NaNStrategyTiesStrategyrank(data)
default (NaNs maximal)default (ties averaged)(5, 3, 6, 7, 3, 8, 9, 1, 3)
default (NaNs maximal)MINIMUM(5, 2, 6, 7, 2, 8, 9, 1, 2)
MINIMALdefault (ties averaged)(6, 4, 7, 8, 4, 9, 1.5, 1.5, 4)
REMOVEDSEQUENTIAL(5, 2, 6, 7, 3, 8, 1, 4)
MINIMALMAXIMUM(6, 5, 7, 8, 5, 9, 2, 2, 5)
- * - * @since 2.0 - */ -public class NaturalRanking implements RankingAlgorithm { - - /** default NaN strategy */ - public static final NaNStrategy DEFAULT_NAN_STRATEGY = NaNStrategy.FAILED; - - /** default ties strategy */ - public static final TiesStrategy DEFAULT_TIES_STRATEGY = TiesStrategy.AVERAGE; - - /** NaN strategy - defaults to NaNs maximal */ - private final NaNStrategy nanStrategy; - - /** Ties strategy - defaults to ties averaged */ - private final TiesStrategy tiesStrategy; - - /** Source of random data - used only when ties strategy is RANDOM */ - private final RandomUtils.DataGenerator randomData; - - /** - * Create a NaturalRanking with default strategies for handling ties and NaNs. - */ - public NaturalRanking() { - this(DEFAULT_NAN_STRATEGY, DEFAULT_TIES_STRATEGY, null); - } - - /** - * Create a NaturalRanking with the given TiesStrategy. - * - * @param tiesStrategy the TiesStrategy to use - */ - public NaturalRanking(TiesStrategy tiesStrategy) { - this(DEFAULT_NAN_STRATEGY, - tiesStrategy, - RandomSource.create(RandomSource.WELL_19937_C)); - } - - /** - * Create a NaturalRanking with the given NaNStrategy. - * - * @param nanStrategy the NaNStrategy to use - */ - public NaturalRanking(NaNStrategy nanStrategy) { - this(nanStrategy, DEFAULT_TIES_STRATEGY, null); - } - - /** - * Create a NaturalRanking with the given NaNStrategy and TiesStrategy. - * - * @param nanStrategy NaNStrategy to use - * @param tiesStrategy TiesStrategy to use - */ - public NaturalRanking(NaNStrategy nanStrategy, - TiesStrategy tiesStrategy) { - this(nanStrategy, - tiesStrategy, - RandomSource.create(RandomSource.WELL_19937_C)); - } - - /** - * Create a NaturalRanking with TiesStrategy.RANDOM and the given - * random generator as the source of random data. - * - * @param randomGenerator source of random data - */ - public NaturalRanking(UniformRandomProvider randomGenerator) { - this(DEFAULT_NAN_STRATEGY, TiesStrategy.RANDOM, randomGenerator); - } - - /** - * Create a NaturalRanking with the given NaNStrategy, TiesStrategy.RANDOM - * and the given source of random data. - * - * @param nanStrategy NaNStrategy to use - * @param randomGenerator source of random data - */ - public NaturalRanking(NaNStrategy nanStrategy, - UniformRandomProvider randomGenerator) { - this(nanStrategy, TiesStrategy.RANDOM, randomGenerator); - } - - /** - * @param nanStrategy NaN strategy. - * @param tiesStrategy Tie strategy. - * @param randomGenerator RNG. - */ - private NaturalRanking(NaNStrategy nanStrategy, - TiesStrategy tiesStrategy, - UniformRandomProvider randomGenerator) { - this.nanStrategy = nanStrategy; - this.tiesStrategy = tiesStrategy; - randomData = RandomUtils.createDataGenerator(randomGenerator); - } - - /** - * Return the NaNStrategy - * - * @return returns the NaNStrategy - */ - public NaNStrategy getNanStrategy() { - return nanStrategy; - } - - /** - * Return the TiesStrategy - * - * @return the TiesStrategy - */ - public TiesStrategy getTiesStrategy() { - return tiesStrategy; - } - - /** - * Rank data using the natural ordering on Doubles, with - * NaN values handled according to nanStrategy and ties - * resolved using tiesStrategy. - * - * @param data array to be ranked - * @return array of ranks - * @throws NotANumberException if the selected {@link NaNStrategy} is {@code FAILED} - * and a {@link Double#NaN} is encountered in the input data - */ - @Override - public double[] rank(double[] data) { - - // Array recording initial positions of data to be ranked - IntDoublePair[] ranks = new IntDoublePair[data.length]; - for (int i = 0; i < data.length; i++) { - ranks[i] = new IntDoublePair(data[i], i); - } - - // Recode, remove or record positions of NaNs - List nanPositions = null; - switch (nanStrategy) { - case MAXIMAL: // Replace NaNs with +INFs - recodeNaNs(ranks, Double.POSITIVE_INFINITY); - break; - case MINIMAL: // Replace NaNs with -INFs - recodeNaNs(ranks, Double.NEGATIVE_INFINITY); - break; - case REMOVED: // Drop NaNs from data - ranks = removeNaNs(ranks); - break; - case FIXED: // Record positions of NaNs - nanPositions = getNanPositions(ranks); - break; - case FAILED: - nanPositions = getNanPositions(ranks); - if (nanPositions.size() > 0) { - throw new NotANumberException(); - } - break; - default: // this should not happen unless NaNStrategy enum is changed - throw new MathInternalError(); - } - - // Sort the IntDoublePairs - Arrays.sort(ranks); - - // Walk the sorted array, filling output array using sorted positions, - // resolving ties as we go - double[] out = new double[ranks.length]; - int pos = 1; // position in sorted array - out[ranks[0].getPosition()] = pos; - List tiesTrace = new ArrayList<>(); - tiesTrace.add(ranks[0].getPosition()); - for (int i = 1; i < ranks.length; i++) { - if (Double.compare(ranks[i].getValue(), ranks[i - 1].getValue()) > 0) { - // tie sequence has ended (or had length 1) - pos = i + 1; - if (tiesTrace.size() > 1) { // if seq is nontrivial, resolve - resolveTie(out, tiesTrace); - } - tiesTrace = new ArrayList<>(); - tiesTrace.add(ranks[i].getPosition()); - } else { - // tie sequence continues - tiesTrace.add(ranks[i].getPosition()); - } - out[ranks[i].getPosition()] = pos; - } - if (tiesTrace.size() > 1) { // handle tie sequence at end - resolveTie(out, tiesTrace); - } - if (nanStrategy == NaNStrategy.FIXED) { - restoreNaNs(out, nanPositions); - } - return out; - } - - /** - * Returns an array that is a copy of the input array with IntDoublePairs - * having NaN values removed. - * - * @param ranks input array - * @return array with NaN-valued entries removed - */ - private IntDoublePair[] removeNaNs(IntDoublePair[] ranks) { - if (!containsNaNs(ranks)) { - return ranks; - } - IntDoublePair[] outRanks = new IntDoublePair[ranks.length]; - int j = 0; - for (int i = 0; i < ranks.length; i++) { - if (Double.isNaN(ranks[i].getValue())) { - // drop, but adjust original ranks of later elements - for (int k = i + 1; k < ranks.length; k++) { - ranks[k] = new IntDoublePair( - ranks[k].getValue(), ranks[k].getPosition() - 1); - } - } else { - outRanks[j] = new IntDoublePair( - ranks[i].getValue(), ranks[i].getPosition()); - j++; - } - } - IntDoublePair[] returnRanks = new IntDoublePair[j]; - System.arraycopy(outRanks, 0, returnRanks, 0, j); - return returnRanks; - } - - /** - * Recodes NaN values to the given value. - * - * @param ranks array to recode - * @param value the value to replace NaNs with - */ - private void recodeNaNs(IntDoublePair[] ranks, double value) { - for (int i = 0; i < ranks.length; i++) { - if (Double.isNaN(ranks[i].getValue())) { - ranks[i] = new IntDoublePair( - value, ranks[i].getPosition()); - } - } - } - - /** - * Checks for presence of NaNs in ranks. - * - * @param ranks array to be searched for NaNs - * @return true iff ranks contains one or more NaNs - */ - private boolean containsNaNs(IntDoublePair[] ranks) { - for (int i = 0; i < ranks.length; i++) { - if (Double.isNaN(ranks[i].getValue())) { - return true; - } - } - return false; - } - - /** - * Resolve a sequence of ties, using the configured {@link TiesStrategy}. - * The input ranks array is expected to take the same value - * for all indices in tiesTrace. The common value is recoded - * according to the tiesStrategy. For example, if ranks = <5,8,2,6,2,7,1,2>, - * tiesTrace = <2,4,7> and tiesStrategy is MINIMUM, ranks will be unchanged. - * The same array and trace with tiesStrategy AVERAGE will come out - * <5,8,3,6,3,7,1,3>. - * - * @param ranks array of ranks - * @param tiesTrace list of indices where ranks is constant - * -- that is, for any i and j in TiesTrace, ranks[i] == ranks[j] - * - */ - private void resolveTie(double[] ranks, List tiesTrace) { - - // constant value of ranks over tiesTrace - final double c = ranks[tiesTrace.get(0)]; - - // length of sequence of tied ranks - final int length = tiesTrace.size(); - - switch (tiesStrategy) { - case AVERAGE: // Replace ranks with average - fill(ranks, tiesTrace, (2 * c + length - 1) / 2d); - break; - case MAXIMUM: // Replace ranks with maximum values - fill(ranks, tiesTrace, c + length - 1); - break; - case MINIMUM: // Replace ties with minimum - fill(ranks, tiesTrace, c); - break; - case RANDOM: // Fill with random integral values in [c, c + length - 1] - Iterator iterator = tiesTrace.iterator(); - long f = FastMath.round(c); - while (iterator.hasNext()) { - // No advertised exception because args are guaranteed valid - ranks[iterator.next()] = - randomData.nextLong(f, f + length - 1); - } - break; - case SEQUENTIAL: // Fill sequentially from c to c + length - 1 - // walk and fill - iterator = tiesTrace.iterator(); - f = FastMath.round(c); - int i = 0; - while (iterator.hasNext()) { - ranks[iterator.next()] = f + i++; - } - break; - default: // this should not happen unless TiesStrategy enum is changed - throw new MathInternalError(); - } - } - - /** - * Setsdata[i] = value for each i in tiesTrace. - * - * @param data array to modify - * @param tiesTrace list of index values to set - * @param value value to set - */ - private void fill(double[] data, List tiesTrace, double value) { - Iterator iterator = tiesTrace.iterator(); - while (iterator.hasNext()) { - data[iterator.next()] = value; - } - } - - /** - * Set ranks[i] = Double.NaN for each i in nanPositions. - * - * @param ranks array to modify - * @param nanPositions list of index values to set to Double.NaN - */ - private void restoreNaNs(double[] ranks, List nanPositions) { - if (nanPositions.size() == 0) { - return; - } - Iterator iterator = nanPositions.iterator(); - while (iterator.hasNext()) { - ranks[iterator.next().intValue()] = Double.NaN; - } - - } - - /** - * Returns a list of indexes where ranks is NaN. - * - * @param ranks array to search for NaNs - * @return list of indexes i such that ranks[i] = NaN - */ - private List getNanPositions(IntDoublePair[] ranks) { - ArrayList out = new ArrayList<>(); - for (int i = 0; i < ranks.length; i++) { - if (Double.isNaN(ranks[i].getValue())) { - out.add(Integer.valueOf(i)); - } - } - return out; - } - - /** - * Represents the position of a double value in an ordering. - * Comparable interface is implemented so Arrays.sort can be used - * to sort an array of IntDoublePairs by value. Note that the - * implicitly defined natural ordering is NOT consistent with equals. - */ - private static class IntDoublePair implements Comparable { - - /** Value of the pair */ - private final double value; - - /** Original position of the pair */ - private final int position; - - /** - * Construct an IntDoublePair with the given value and position. - * @param value the value of the pair - * @param position the original position - */ - IntDoublePair(double value, int position) { - this.value = value; - this.position = position; - } - - /** - * Compare this IntDoublePair to another pair. - * Only the values are compared. - * - * @param other the other pair to compare this to - * @return result of Double.compare(value, other.value) - */ - @Override - public int compareTo(IntDoublePair other) { - return Double.compare(value, other.value); - } - - // N.B. equals() and hashCode() are not implemented; see MATH-610 for discussion. - - /** - * Returns the value of the pair. - * @return value - */ - public double getValue() { - return value; - } - - /** - * Returns the original position of the pair. - * @return position - */ - public int getPosition() { - return position; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/ranking/RankingAlgorithm.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/ranking/RankingAlgorithm.java deleted file mode 100644 index f3c02da3f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/ranking/RankingAlgorithm.java +++ /dev/null @@ -1,40 +0,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. - */ - -package org.apache.commons.math4.stat.ranking; - -/** - * Interface representing a rank transformation. - * - * @since 2.0 - */ -public interface RankingAlgorithm { - /** - *

Performs a rank transformation on the input data, returning an array - * of ranks.

- * - *

Ranks should be 1-based - that is, the smallest value - * returned in an array of ranks should be greater than or equal to one, - * rather than 0. Ranks should in general take integer values, though - * implementations may return averages or other floating point values - * to resolve ties in the input data.

- * - * @param data array of data to be ranked - * @return an array of ranks corresponding to the elements of the input array - */ - double[] rank(double[] data); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/ranking/TiesStrategy.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/ranking/TiesStrategy.java deleted file mode 100644 index 2ae33522d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/ranking/TiesStrategy.java +++ /dev/null @@ -1,54 +0,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. - */ - -package org.apache.commons.math4.stat.ranking; - -/** - * Strategies for handling tied values in rank transformations. - *
    - *
  • SEQUENTIAL - Ties are assigned ranks in order of occurrence in the original array, - * for example (1,3,4,3) is ranked as (1,2,4,3)
  • - *
  • MINIMUM - Tied values are assigned the minimum applicable rank, or the rank - * of the first occurrence. For example, (1,3,4,3) is ranked as (1,2,4,2)
  • - *
  • MAXIMUM - Tied values are assigned the maximum applicable rank, or the rank - * of the last occurrence. For example, (1,3,4,3) is ranked as (1,3,4,3)
  • - *
  • AVERAGE - Tied values are assigned the average of the applicable ranks. - * For example, (1,3,4,3) is ranked as (1,2.5,4,2.5)
  • - *
  • RANDOM - Tied values are assigned a random integer rank from among the - * applicable values. The assigned rank will always be an integer, (inclusively) - * between the values returned by the MINIMUM and MAXIMUM strategies.
  • - *
- * - * @since 2.0 - */ -public enum TiesStrategy { - - /** Ties assigned sequential ranks in order of occurrence */ - SEQUENTIAL, - - /** Ties get the minimum applicable rank */ - MINIMUM, - - /** Ties get the maximum applicable rank */ - MAXIMUM, - - /** Ties get the average of applicable ranks */ - AVERAGE, - - /** Ties get a random integral value from among applicable ranks */ - RANDOM -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/ranking/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/ranking/package-info.java deleted file mode 100644 index e37d851f5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/ranking/package-info.java +++ /dev/null @@ -1,22 +0,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. - */ -/** - * - * Classes providing rank transformations. - * - */ -package org.apache.commons.math4.stat.ranking; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/AbstractMultipleLinearRegression.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/AbstractMultipleLinearRegression.java deleted file mode 100644 index f7563cac9..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/AbstractMultipleLinearRegression.java +++ /dev/null @@ -1,386 +0,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. - */ -package org.apache.commons.math4.stat.regression; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.InsufficientDataException; -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.linear.Array2DRowRealMatrix; -import org.apache.commons.math4.linear.ArrayRealVector; -import org.apache.commons.math4.linear.NonSquareMatrixException; -import org.apache.commons.math4.linear.RealMatrix; -import org.apache.commons.math4.linear.RealVector; -import org.apache.commons.math4.stat.descriptive.moment.Variance; -import org.apache.commons.math4.util.FastMath; - -/** - * Abstract base class for implementations of MultipleLinearRegression. - * @since 2.0 - */ -public abstract class AbstractMultipleLinearRegression implements - MultipleLinearRegression { - - /** X sample data. */ - private RealMatrix xMatrix; - - /** Y sample data. */ - private RealVector yVector; - - /** Whether or not the regression model includes an intercept. True means no intercept. */ - private boolean noIntercept = false; - - /** - * @return the X sample data. - */ - protected RealMatrix getX() { - return xMatrix; - } - - /** - * @return the Y sample data. - */ - protected RealVector getY() { - return yVector; - } - - /** - * @return true if the model has no intercept term; false otherwise - * @since 2.2 - */ - public boolean isNoIntercept() { - return noIntercept; - } - - /** - * @param noIntercept true means the model is to be estimated without an intercept term - * @since 2.2 - */ - public void setNoIntercept(boolean noIntercept) { - this.noIntercept = noIntercept; - } - - /** - *

Loads model x and y sample data from a flat input array, overriding any previous sample. - *

- *

Assumes that rows are concatenated with y values first in each row. For example, an input - * data array containing the sequence of values (1, 2, 3, 4, 5, 6, 7, 8, 9) with - * nobs = 3 and nvars = 2 creates a regression dataset with two - * independent variables, as below: - *

-     *   y   x[0]  x[1]
-     *   --------------
-     *   1     2     3
-     *   4     5     6
-     *   7     8     9
-     * 
- * - *

Note that there is no need to add an initial unitary column (column of 1's) when - * specifying a model including an intercept term. If {@link #isNoIntercept()} is true, - * the X matrix will be created without an initial column of "1"s; otherwise this column will - * be added. - *

- *

Throws IllegalArgumentException if any of the following preconditions fail: - *

  • data cannot be null
  • - *
  • data.length = nobs * (nvars + 1)
  • - *
  • {@code nobs > nvars}
- * - * @param data input data array - * @param nobs number of observations (rows) - * @param nvars number of independent variables (columns, not counting y) - * @throws NullArgumentException if the data array is null - * @throws DimensionMismatchException if the length of the data array is not equal - * to nobs * (nvars + 1) - * @throws InsufficientDataException if nobs is less than - * nvars + 1 - */ - public void newSampleData(double[] data, int nobs, int nvars) { - if (data == null) { - throw new NullArgumentException(); - } - if (data.length != nobs * (nvars + 1)) { - throw new DimensionMismatchException(data.length, nobs * (nvars + 1)); - } - if (nobs <= nvars) { - throw new InsufficientDataException(LocalizedFormats.INSUFFICIENT_OBSERVED_POINTS_IN_SAMPLE, nobs, nvars + 1); - } - double[] y = new double[nobs]; - final int cols = noIntercept ? nvars: nvars + 1; - double[][] x = new double[nobs][cols]; - int pointer = 0; - for (int i = 0; i < nobs; i++) { - y[i] = data[pointer++]; - if (!noIntercept) { - x[i][0] = 1.0d; - } - for (int j = noIntercept ? 0 : 1; j < cols; j++) { - x[i][j] = data[pointer++]; - } - } - this.xMatrix = new Array2DRowRealMatrix(x); - this.yVector = new ArrayRealVector(y); - } - - /** - * Loads new y sample data, overriding any previous data. - * - * @param y the array representing the y sample - * @throws NullArgumentException if y is null - * @throws NoDataException if y is empty - */ - protected void newYSampleData(double[] y) { - if (y == null) { - throw new NullArgumentException(); - } - if (y.length == 0) { - throw new NoDataException(); - } - this.yVector = new ArrayRealVector(y); - } - - /** - *

Loads new x sample data, overriding any previous data. - *

- * The input x array should have one row for each sample - * observation, with columns corresponding to independent variables. - * For example, if
-     *  x = new double[][] {{1, 2}, {3, 4}, {5, 6}} 
- * then setXSampleData(x) results in a model with two independent - * variables and 3 observations: - *
-     *   x[0]  x[1]
-     *   ----------
-     *     1    2
-     *     3    4
-     *     5    6
-     * 
- *

Note that there is no need to add an initial unitary column (column of 1's) when - * specifying a model including an intercept term. - *

- * @param x the rectangular array representing the x sample - * @throws NullArgumentException if x is null - * @throws NoDataException if x is empty - * @throws DimensionMismatchException if x is not rectangular - */ - protected void newXSampleData(double[][] x) { - if (x == null) { - throw new NullArgumentException(); - } - if (x.length == 0) { - throw new NoDataException(); - } - if (noIntercept) { - this.xMatrix = new Array2DRowRealMatrix(x, true); - } else { // Augment design matrix with initial unitary column - final int nVars = x[0].length; - final double[][] xAug = new double[x.length][nVars + 1]; - for (int i = 0; i < x.length; i++) { - if (x[i].length != nVars) { - throw new DimensionMismatchException(x[i].length, nVars); - } - xAug[i][0] = 1.0d; - System.arraycopy(x[i], 0, xAug[i], 1, nVars); - } - this.xMatrix = new Array2DRowRealMatrix(xAug, false); - } - } - - /** - * Validates sample data. Checks that - *
  • Neither x nor y is null or empty;
  • - *
  • The length (i.e. number of rows) of x equals the length of y
  • - *
  • x has at least one more row than it has columns (i.e. there is - * sufficient data to estimate regression coefficients for each of the - * columns in x plus an intercept.
  • - *
- * - * @param x the [n,k] array representing the x data - * @param y the [n,1] array representing the y data - * @throws NullArgumentException if {@code x} or {@code y} is null - * @throws DimensionMismatchException if {@code x} and {@code y} do not - * have the same length - * @throws NoDataException if {@code x} or {@code y} are zero-length - * @throws MathIllegalArgumentException if the number of rows of {@code x} - * is not larger than the number of columns + 1 - */ - protected void validateSampleData(double[][] x, double[] y) throws MathIllegalArgumentException { - if ((x == null) || (y == null)) { - throw new NullArgumentException(); - } - if (x.length != y.length) { - throw new DimensionMismatchException(y.length, x.length); - } - if (x.length == 0) { // Must be no y data either - throw new NoDataException(); - } - if (x[0].length + 1 > x.length) { - throw new MathIllegalArgumentException( - LocalizedFormats.NOT_ENOUGH_DATA_FOR_NUMBER_OF_PREDICTORS, - x.length, x[0].length); - } - } - - /** - * Validates that the x data and covariance matrix have the same - * number of rows and that the covariance matrix is square. - * - * @param x the [n,k] array representing the x sample - * @param covariance the [n,n] array representing the covariance matrix - * @throws DimensionMismatchException if the number of rows in x is not equal - * to the number of rows in covariance - * @throws NonSquareMatrixException if the covariance matrix is not square - */ - protected void validateCovarianceData(double[][] x, double[][] covariance) { - if (x.length != covariance.length) { - throw new DimensionMismatchException(x.length, covariance.length); - } - if (covariance.length > 0 && covariance.length != covariance[0].length) { - throw new NonSquareMatrixException(covariance.length, covariance[0].length); - } - } - - /** - * {@inheritDoc} - */ - @Override - public double[] estimateRegressionParameters() { - RealVector b = calculateBeta(); - return b.toArray(); - } - - /** - * {@inheritDoc} - */ - @Override - public double[] estimateResiduals() { - RealVector b = calculateBeta(); - RealVector e = yVector.subtract(xMatrix.operate(b)); - return e.toArray(); - } - - /** - * {@inheritDoc} - */ - @Override - public double[][] estimateRegressionParametersVariance() { - return calculateBetaVariance().getData(); - } - - /** - * {@inheritDoc} - */ - @Override - public double[] estimateRegressionParametersStandardErrors() { - double[][] betaVariance = estimateRegressionParametersVariance(); - double sigma = calculateErrorVariance(); - int length = betaVariance[0].length; - double[] result = new double[length]; - for (int i = 0; i < length; i++) { - result[i] = FastMath.sqrt(sigma * betaVariance[i][i]); - } - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public double estimateRegressandVariance() { - return calculateYVariance(); - } - - /** - * Estimates the variance of the error. - * - * @return estimate of the error variance - * @since 2.2 - */ - public double estimateErrorVariance() { - return calculateErrorVariance(); - - } - - /** - * Estimates the standard error of the regression. - * - * @return regression standard error - * @since 2.2 - */ - public double estimateRegressionStandardError() { - return FastMath.sqrt(estimateErrorVariance()); - } - - /** - * Calculates the beta of multiple linear regression in matrix notation. - * - * @return beta - */ - protected abstract RealVector calculateBeta(); - - /** - * Calculates the beta variance of multiple linear regression in matrix - * notation. - * - * @return beta variance - */ - protected abstract RealMatrix calculateBetaVariance(); - - - /** - * Calculates the variance of the y values. - * - * @return Y variance - */ - protected double calculateYVariance() { - return new Variance().evaluate(yVector.toArray()); - } - - /** - *

Calculates the variance of the error term.

- * Uses the formula
-     * var(u) = u · u / (n - k)
-     * 
- * where n and k are the row and column dimensions of the design - * matrix X. - * - * @return error variance estimate - * @since 2.2 - */ - protected double calculateErrorVariance() { - RealVector residuals = calculateResiduals(); - return residuals.dotProduct(residuals) / - (xMatrix.getRowDimension() - xMatrix.getColumnDimension()); - } - - /** - * Calculates the residuals of multiple linear regression in matrix - * notation. - * - *
-     * u = y - X * b
-     * 
- * - * @return The residuals [n,1] matrix - */ - protected RealVector calculateResiduals() { - RealVector b = calculateBeta(); - return yVector.subtract(xMatrix.operate(b)); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/GLSMultipleLinearRegression.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/GLSMultipleLinearRegression.java deleted file mode 100644 index f5981d440..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/GLSMultipleLinearRegression.java +++ /dev/null @@ -1,135 +0,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. - */ -package org.apache.commons.math4.stat.regression; - -import org.apache.commons.math4.linear.Array2DRowRealMatrix; -import org.apache.commons.math4.linear.LUDecomposition; -import org.apache.commons.math4.linear.RealMatrix; -import org.apache.commons.math4.linear.RealVector; - -/** - * The GLS implementation of multiple linear regression. - * - * GLS assumes a general covariance matrix Omega of the error - *
- * u ~ N(0, Omega)
- * 
- * - * Estimated by GLS, - *
- * b=(X' Omega^-1 X)^-1X'Omega^-1 y
- * 
- * whose variance is - *
- * Var(b)=(X' Omega^-1 X)^-1
- * 
- * @since 2.0 - */ -public class GLSMultipleLinearRegression extends AbstractMultipleLinearRegression { - - /** Covariance matrix. */ - private RealMatrix Omega; - - /** Inverse of covariance matrix. */ - private RealMatrix OmegaInverse; - - /** Replace sample data, overriding any previous sample. - * @param y y values of the sample - * @param x x values of the sample - * @param covariance array representing the covariance matrix - */ - public void newSampleData(double[] y, double[][] x, double[][] covariance) { - validateSampleData(x, y); - newYSampleData(y); - newXSampleData(x); - validateCovarianceData(x, covariance); - newCovarianceData(covariance); - } - - /** - * Add the covariance data. - * - * @param omega the [n,n] array representing the covariance - */ - protected void newCovarianceData(double[][] omega){ - this.Omega = new Array2DRowRealMatrix(omega); - this.OmegaInverse = null; - } - - /** - * Get the inverse of the covariance. - *

The inverse of the covariance matrix is lazily evaluated and cached.

- * @return inverse of the covariance - */ - protected RealMatrix getOmegaInverse() { - if (OmegaInverse == null) { - OmegaInverse = new LUDecomposition(Omega).getSolver().getInverse(); - } - return OmegaInverse; - } - - /** - * Calculates beta by GLS. - *
-     *  b=(X' Omega^-1 X)^-1X'Omega^-1 y
-     * 
- * @return beta - */ - @Override - protected RealVector calculateBeta() { - RealMatrix OI = getOmegaInverse(); - RealMatrix XT = getX().transpose(); - RealMatrix XTOIX = XT.multiply(OI).multiply(getX()); - RealMatrix inverse = new LUDecomposition(XTOIX).getSolver().getInverse(); - return inverse.multiply(XT).multiply(OI).operate(getY()); - } - - /** - * Calculates the variance on the beta. - *
-     *  Var(b)=(X' Omega^-1 X)^-1
-     * 
- * @return The beta variance matrix - */ - @Override - protected RealMatrix calculateBetaVariance() { - RealMatrix OI = getOmegaInverse(); - RealMatrix XTOIX = getX().transpose().multiply(OI).multiply(getX()); - return new LUDecomposition(XTOIX).getSolver().getInverse(); - } - - - /** - * Calculates the estimated variance of the error term using the formula - *
-     *  Var(u) = Tr(u' Omega^-1 u)/(n-k)
-     * 
- * where n and k are the row and column dimensions of the design - * matrix X. - * - * @return error variance - * @since 2.2 - */ - @Override - protected double calculateErrorVariance() { - RealVector residuals = calculateResiduals(); - double t = residuals.dotProduct(getOmegaInverse().operate(residuals)); - return t / (getX().getRowDimension() - getX().getColumnDimension()); - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/MillerUpdatingRegression.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/MillerUpdatingRegression.java deleted file mode 100644 index e3b563be5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/MillerUpdatingRegression.java +++ /dev/null @@ -1,1109 +0,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. - */ -package org.apache.commons.math4.stat.regression; - -import java.util.Arrays; - -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; -import org.apache.commons.numbers.core.Precision; - -/** - * This class is a concrete implementation of the {@link UpdatingMultipleLinearRegression} interface. - * - *

The algorithm is described in:

- * Algorithm AS 274: Least Squares Routines to Supplement Those of Gentleman
- * Author(s): Alan J. Miller
- * Source: Journal of the Royal Statistical Society.
- * Series C (Applied Statistics), Vol. 41, No. 2
- * (1992), pp. 458-478
- * Published by: Blackwell Publishing for the Royal Statistical Society
- * Stable URL: http://www.jstor.org/stable/2347583 
- * - *

This method for multiple regression forms the solution to the OLS problem - * by updating the QR decomposition as described by Gentleman.

- * - * @since 3.0 - */ -public class MillerUpdatingRegression implements UpdatingMultipleLinearRegression { - - /** number of variables in regression */ - private final int nvars; - /** diagonals of cross products matrix */ - private final double[] d; - /** the elements of the R`Y */ - private final double[] rhs; - /** the off diagonal portion of the R matrix */ - private final double[] r; - /** the tolerance for each of the variables */ - private final double[] tol; - /** residual sum of squares for all nested regressions */ - private final double[] rss; - /** order of the regressors */ - private final int[] vorder; - /** scratch space for tolerance calc */ - private final double[] work_tolset; - /** number of observations entered */ - private long nobs = 0; - /** sum of squared errors of largest regression */ - private double sserr = 0.0; - /** has rss been called? */ - private boolean rss_set = false; - /** has the tolerance setting method been called */ - private boolean tol_set = false; - /** flags for variables with linear dependency problems */ - private final boolean[] lindep; - /** singular x values */ - private final double[] x_sing; - /** workspace for singularity method */ - private final double[] work_sing; - /** summation of Y variable */ - private double sumy = 0.0; - /** summation of squared Y values */ - private double sumsqy = 0.0; - /** boolean flag whether a regression constant is added */ - private final boolean hasIntercept; - /** zero tolerance */ - private final double epsilon; - /** - * Set the default constructor to private access - * to prevent inadvertent instantiation - */ - @SuppressWarnings("unused") - private MillerUpdatingRegression() { - this(-1, false, Double.NaN); - } - - /** - * This is the augmented constructor for the MillerUpdatingRegression class. - * - * @param numberOfVariables number of regressors to expect, not including constant - * @param includeConstant include a constant automatically - * @param errorTolerance zero tolerance, how machine zero is determined - * @throws ModelSpecificationException if {@code numberOfVariables is less than 1} - */ - public MillerUpdatingRegression(int numberOfVariables, boolean includeConstant, double errorTolerance) - throws ModelSpecificationException { - if (numberOfVariables < 1) { - throw new ModelSpecificationException(LocalizedFormats.NO_REGRESSORS); - } - if (includeConstant) { - this.nvars = numberOfVariables + 1; - } else { - this.nvars = numberOfVariables; - } - this.hasIntercept = includeConstant; - this.nobs = 0; - this.d = new double[this.nvars]; - this.rhs = new double[this.nvars]; - this.r = new double[this.nvars * (this.nvars - 1) / 2]; - this.tol = new double[this.nvars]; - this.rss = new double[this.nvars]; - this.vorder = new int[this.nvars]; - this.x_sing = new double[this.nvars]; - this.work_sing = new double[this.nvars]; - this.work_tolset = new double[this.nvars]; - this.lindep = new boolean[this.nvars]; - for (int i = 0; i < this.nvars; i++) { - vorder[i] = i; - } - if (errorTolerance > 0) { - this.epsilon = errorTolerance; - } else { - this.epsilon = -errorTolerance; - } - } - - /** - * Primary constructor for the MillerUpdatingRegression. - * - * @param numberOfVariables maximum number of potential regressors - * @param includeConstant include a constant automatically - * @throws ModelSpecificationException if {@code numberOfVariables is less than 1} - */ - public MillerUpdatingRegression(int numberOfVariables, boolean includeConstant) - throws ModelSpecificationException { - this(numberOfVariables, includeConstant, Precision.EPSILON); - } - - /** - * A getter method which determines whether a constant is included. - * @return true regression has an intercept, false no intercept - */ - @Override - public boolean hasIntercept() { - return this.hasIntercept; - } - - /** - * Gets the number of observations added to the regression model. - * @return number of observations - */ - @Override - public long getN() { - return this.nobs; - } - - /** - * Adds an observation to the regression model. - * @param x the array with regressor values - * @param y the value of dependent variable given these regressors - * @exception ModelSpecificationException if the length of {@code x} does not equal - * the number of independent variables in the model - */ - @Override - public void addObservation(final double[] x, final double y) - throws ModelSpecificationException { - - if ((!this.hasIntercept && x.length != nvars) || - (this.hasIntercept && x.length + 1 != nvars)) { - throw new ModelSpecificationException(LocalizedFormats.INVALID_REGRESSION_OBSERVATION, - x.length, nvars); - } - if (!this.hasIntercept) { - include(MathArrays.copyOf(x, x.length), 1.0, y); - } else { - final double[] tmp = new double[x.length + 1]; - System.arraycopy(x, 0, tmp, 1, x.length); - tmp[0] = 1.0; - include(tmp, 1.0, y); - } - ++nobs; - - } - - /** - * Adds multiple observations to the model. - * @param x observations on the regressors - * @param y observations on the regressand - * @throws ModelSpecificationException if {@code x} is not rectangular, does not match - * the length of {@code y} or does not contain sufficient data to estimate the model - */ - @Override - public void addObservations(double[][] x, double[] y) throws ModelSpecificationException { - if ((x == null) || (y == null) || (x.length != y.length)) { - throw new ModelSpecificationException( - LocalizedFormats.DIMENSIONS_MISMATCH_SIMPLE, - (x == null) ? 0 : x.length, - (y == null) ? 0 : y.length); - } - if (x.length == 0) { // Must be no y data either - throw new ModelSpecificationException( - LocalizedFormats.NO_DATA); - } - if (x[0].length + 1 > x.length) { - throw new ModelSpecificationException( - LocalizedFormats.NOT_ENOUGH_DATA_FOR_NUMBER_OF_PREDICTORS, - x.length, x[0].length); - } - for (int i = 0; i < x.length; i++) { - addObservation(x[i], y[i]); - } - } - - /** - * The include method is where the QR decomposition occurs. This statement forms all - * intermediate data which will be used for all derivative measures. - * According to the miller paper, note that in the original implementation the x vector - * is overwritten. In this implementation, the include method is passed a copy of the - * original data vector so that there is no contamination of the data. Additionally, - * this method differs slightly from Gentleman's method, in that the assumption is - * of dense design matrices, there is some advantage in using the original gentleman algorithm - * on sparse matrices. - * - * @param x observations on the regressors - * @param wi weight of the this observation (-1,1) - * @param yi observation on the regressand - */ - private void include(final double[] x, final double wi, final double yi) { - int nextr = 0; - double w = wi; - double y = yi; - double xi; - double di; - double wxi; - double dpi; - double xk; - double _w; - this.rss_set = false; - sumy = smartAdd(yi, sumy); - sumsqy = smartAdd(sumsqy, yi * yi); - for (int i = 0; i < x.length; i++) { - if (w == 0.0) { - return; - } - xi = x[i]; - - if (xi == 0.0) { - nextr += nvars - i - 1; - continue; - } - di = d[i]; - wxi = w * xi; - _w = w; - if (di != 0.0) { - dpi = smartAdd(di, wxi * xi); - final double tmp = wxi * xi / di; - if (FastMath.abs(tmp) > Precision.EPSILON) { - w = (di * w) / dpi; - } - } else { - dpi = wxi * xi; - w = 0.0; - } - d[i] = dpi; - for (int k = i + 1; k < nvars; k++) { - xk = x[k]; - x[k] = smartAdd(xk, -xi * r[nextr]); - if (di != 0.0) { - r[nextr] = smartAdd(di * r[nextr], (_w * xi) * xk) / dpi; - } else { - r[nextr] = xk / xi; - } - ++nextr; - } - xk = y; - y = smartAdd(xk, -xi * rhs[i]); - if (di != 0.0) { - rhs[i] = smartAdd(di * rhs[i], wxi * xk) / dpi; - } else { - rhs[i] = xk / xi; - } - } - sserr = smartAdd(sserr, w * y * y); - } - - /** - * Adds to number a and b such that the contamination due to - * numerical smallness of one addend does not corrupt the sum. - * @param a - an addend - * @param b - an addend - * @return the sum of the a and b - */ - private double smartAdd(double a, double b) { - final double _a = FastMath.abs(a); - final double _b = FastMath.abs(b); - if (_a > _b) { - final double eps = _a * Precision.EPSILON; - if (_b > eps) { - return a + b; - } - return a; - } else { - final double eps = _b * Precision.EPSILON; - if (_a > eps) { - return a + b; - } - return b; - } - } - - /** - * As the name suggests, clear wipes the internals and reorders everything in the - * canonical order. - */ - @Override - public void clear() { - Arrays.fill(this.d, 0.0); - Arrays.fill(this.rhs, 0.0); - Arrays.fill(this.r, 0.0); - Arrays.fill(this.tol, 0.0); - Arrays.fill(this.rss, 0.0); - Arrays.fill(this.work_tolset, 0.0); - Arrays.fill(this.work_sing, 0.0); - Arrays.fill(this.x_sing, 0.0); - Arrays.fill(this.lindep, false); - for (int i = 0; i < nvars; i++) { - this.vorder[i] = i; - } - this.nobs = 0; - this.sserr = 0.0; - this.sumy = 0.0; - this.sumsqy = 0.0; - this.rss_set = false; - this.tol_set = false; - } - - /** - * This sets up tolerances for singularity testing. - */ - private void tolset() { - int pos; - double total; - final double eps = this.epsilon; - for (int i = 0; i < nvars; i++) { - this.work_tolset[i] = FastMath.sqrt(d[i]); - } - tol[0] = eps * this.work_tolset[0]; - for (int col = 1; col < nvars; col++) { - pos = col - 1; - total = work_tolset[col]; - for (int row = 0; row < col; row++) { - total += FastMath.abs(r[pos]) * work_tolset[row]; - pos += nvars - row - 2; - } - tol[col] = eps * total; - } - tol_set = true; - } - - /** - * The regcf method conducts the linear regression and extracts the - * parameter vector. Notice that the algorithm can do subset regression - * with no alteration. - * - * @param nreq how many of the regressors to include (either in canonical - * order, or in the current reordered state) - * @return an array with the estimated slope coefficients - * @throws ModelSpecificationException if {@code nreq} is less than 1 - * or greater than the number of independent variables - */ - private double[] regcf(int nreq) throws ModelSpecificationException { - int nextr; - if (nreq < 1) { - throw new ModelSpecificationException(LocalizedFormats.NO_REGRESSORS); - } - if (nreq > this.nvars) { - throw new ModelSpecificationException( - LocalizedFormats.TOO_MANY_REGRESSORS, nreq, this.nvars); - } - if (!this.tol_set) { - tolset(); - } - final double[] ret = new double[nreq]; - boolean rankProblem = false; - for (int i = nreq - 1; i > -1; i--) { - if (FastMath.sqrt(d[i]) < tol[i]) { - ret[i] = 0.0; - d[i] = 0.0; - rankProblem = true; - } else { - ret[i] = rhs[i]; - nextr = i * (nvars + nvars - i - 1) / 2; - for (int j = i + 1; j < nreq; j++) { - ret[i] = smartAdd(ret[i], -r[nextr] * ret[j]); - ++nextr; - } - } - } - if (rankProblem) { - for (int i = 0; i < nreq; i++) { - if (this.lindep[i]) { - ret[i] = Double.NaN; - } - } - } - return ret; - } - - /** - * The method which checks for singularities and then eliminates the offending - * columns. - */ - private void singcheck() { - int pos; - for (int i = 0; i < nvars; i++) { - work_sing[i] = FastMath.sqrt(d[i]); - } - for (int col = 0; col < nvars; col++) { - // Set elements within R to zero if they are less than tol(col) in - // absolute value after being scaled by the square root of their row - // multiplier - final double temp = tol[col]; - pos = col - 1; - for (int row = 0; row < col - 1; row++) { - if (FastMath.abs(r[pos]) * work_sing[row] < temp) { - r[pos] = 0.0; - } - pos += nvars - row - 2; - } - // If diagonal element is near zero, set it to zero, set appropriate - // element of LINDEP, and use INCLUD to augment the projections in - // the lower rows of the orthogonalization. - lindep[col] = false; - if (work_sing[col] < temp) { - lindep[col] = true; - if (col < nvars - 1) { - Arrays.fill(x_sing, 0.0); - int _pi = col * (nvars + nvars - col - 1) / 2; - for (int _xi = col + 1; _xi < nvars; _xi++, _pi++) { - x_sing[_xi] = r[_pi]; - r[_pi] = 0.0; - } - final double y = rhs[col]; - final double weight = d[col]; - d[col] = 0.0; - rhs[col] = 0.0; - this.include(x_sing, weight, y); - } else { - sserr += d[col] * rhs[col] * rhs[col]; - } - } - } - } - - /** - * Calculates the sum of squared errors for the full regression - * and all subsets in the following manner:
-     * rss[] ={
-     * ResidualSumOfSquares_allNvars,
-     * ResidualSumOfSquares_FirstNvars-1,
-     * ResidualSumOfSquares_FirstNvars-2,
-     * ..., ResidualSumOfSquares_FirstVariable} 
- */ - private void ss() { - double total = sserr; - rss[nvars - 1] = sserr; - for (int i = nvars - 1; i > 0; i--) { - total += d[i] * rhs[i] * rhs[i]; - rss[i - 1] = total; - } - rss_set = true; - } - - /** - * Calculates the cov matrix assuming only the first nreq variables are - * included in the calculation. The returned array contains a symmetric - * matrix stored in lower triangular form. The matrix will have - * ( nreq + 1 ) * nreq / 2 elements. For illustration
-     * cov =
-     * {
-     *  cov_00,
-     *  cov_10, cov_11,
-     *  cov_20, cov_21, cov22,
-     *  ...
-     * } 
- * - * @param nreq how many of the regressors to include (either in canonical - * order, or in the current reordered state) - * @return an array with the variance covariance of the included - * regressors in lower triangular form - */ - private double[] cov(int nreq) { - if (this.nobs <= nreq) { - return null; - } - double rnk = 0.0; - for (int i = 0; i < nreq; i++) { - if (!this.lindep[i]) { - rnk += 1.0; - } - } - final double var = rss[nreq - 1] / (nobs - rnk); - final double[] rinv = new double[nreq * (nreq - 1) / 2]; - inverse(rinv, nreq); - final double[] covmat = new double[nreq * (nreq + 1) / 2]; - Arrays.fill(covmat, Double.NaN); - int pos2; - int pos1; - int start = 0; - double total = 0; - for (int row = 0; row < nreq; row++) { - pos2 = start; - if (!this.lindep[row]) { - for (int col = row; col < nreq; col++) { - if (!this.lindep[col]) { - pos1 = start + col - row; - if (row == col) { - total = 1.0 / d[col]; - } else { - total = rinv[pos1 - 1] / d[col]; - } - for (int k = col + 1; k < nreq; k++) { - if (!this.lindep[k]) { - total += rinv[pos1] * rinv[pos2] / d[k]; - } - ++pos1; - ++pos2; - } - covmat[ (col + 1) * col / 2 + row] = total * var; - } else { - pos2 += nreq - col - 1; - } - } - } - start += nreq - row - 1; - } - return covmat; - } - - /** - * This internal method calculates the inverse of the upper-triangular portion - * of the R matrix. - * @param rinv the storage for the inverse of r - * @param nreq how many of the regressors to include (either in canonical - * order, or in the current reordered state) - */ - private void inverse(double[] rinv, int nreq) { - int pos = nreq * (nreq - 1) / 2 - 1; - int pos1 = -1; - int pos2 = -1; - double total = 0.0; - Arrays.fill(rinv, Double.NaN); - for (int row = nreq - 1; row > 0; --row) { - if (!this.lindep[row]) { - final int start = (row - 1) * (nvars + nvars - row) / 2; - for (int col = nreq; col > row; --col) { - pos1 = start; - pos2 = pos; - total = 0.0; - for (int k = row; k < col - 1; k++) { - pos2 += nreq - k - 1; - if (!this.lindep[k]) { - total += -r[pos1] * rinv[pos2]; - } - ++pos1; - } - rinv[pos] = total - r[pos1]; - --pos; - } - } else { - pos -= nreq - row; - } - } - } - - /** - * In the original algorithm only the partial correlations of the regressors - * is returned to the user. In this implementation, we have
-     * corr =
-     * {
-     *   corrxx - lower triangular
-     *   corrxy - bottom row of the matrix
-     * }
-     * Replaces subroutines PCORR and COR of:
-     * ALGORITHM AS274  APPL. STATIST. (1992) VOL.41, NO. 2 
- * - *

Calculate partial correlations after the variables in rows - * 1, 2, ..., IN have been forced into the regression. - * If IN = 1, and the first row of R represents a constant in the - * model, then the usual simple correlations are returned.

- * - *

If IN = 0, the value returned in array CORMAT for the correlation - * of variables Xi & Xj is:

-     * sum ( Xi.Xj ) / Sqrt ( sum (Xi^2) . sum (Xj^2) )
- * - *

On return, array CORMAT contains the upper triangle of the matrix of - * partial correlations stored by rows, excluding the 1's on the diagonal. - * e.g. if IN = 2, the consecutive elements returned are: - * (3,4) (3,5) ... (3,ncol), (4,5) (4,6) ... (4,ncol), etc. - * Array YCORR stores the partial correlations with the Y-variable - * starting with YCORR(IN+1) = partial correlation with the variable in - * position (IN+1).

- * - * @param in how many of the regressors to include (either in canonical - * order, or in the current reordered state) - * @return an array with the partial correlations of the remainder of - * regressors with each other and the regressand, in lower triangular form - */ - public double[] getPartialCorrelations(int in) { - final double[] output = new double[(nvars - in + 1) * (nvars - in) / 2]; - int pos; - int pos1; - int pos2; - final int rms_off = -in; - final int wrk_off = -(in + 1); - final double[] rms = new double[nvars - in]; - final double[] work = new double[nvars - in - 1]; - double sumxx; - double sumxy; - double sumyy; - final int offXX = (nvars - in) * (nvars - in - 1) / 2; - if (in < -1 || in >= nvars) { - return null; - } - final int nvm = nvars - 1; - final int base_pos = r.length - (nvm - in) * (nvm - in + 1) / 2; - if (d[in] > 0.0) { - rms[in + rms_off] = 1.0 / FastMath.sqrt(d[in]); - } - for (int col = in + 1; col < nvars; col++) { - pos = base_pos + col - 1 - in; - sumxx = d[col]; - for (int row = in; row < col; row++) { - sumxx += d[row] * r[pos] * r[pos]; - pos += nvars - row - 2; - } - if (sumxx > 0.0) { - rms[col + rms_off] = 1.0 / FastMath.sqrt(sumxx); - } else { - rms[col + rms_off] = 0.0; - } - } - sumyy = sserr; - for (int row = in; row < nvars; row++) { - sumyy += d[row] * rhs[row] * rhs[row]; - } - if (sumyy > 0.0) { - sumyy = 1.0 / FastMath.sqrt(sumyy); - } - pos = 0; - for (int col1 = in; col1 < nvars; col1++) { - sumxy = 0.0; - Arrays.fill(work, 0.0); - pos1 = base_pos + col1 - in - 1; - for (int row = in; row < col1; row++) { - pos2 = pos1 + 1; - for (int col2 = col1 + 1; col2 < nvars; col2++) { - work[col2 + wrk_off] += d[row] * r[pos1] * r[pos2]; - pos2++; - } - sumxy += d[row] * r[pos1] * rhs[row]; - pos1 += nvars - row - 2; - } - pos2 = pos1 + 1; - for (int col2 = col1 + 1; col2 < nvars; col2++) { - work[col2 + wrk_off] += d[col1] * r[pos2]; - ++pos2; - output[ (col2 - 1 - in) * (col2 - in) / 2 + col1 - in] = - work[col2 + wrk_off] * rms[col1 + rms_off] * rms[col2 + rms_off]; - ++pos; - } - sumxy += d[col1] * rhs[col1]; - output[col1 + rms_off + offXX] = sumxy * rms[col1 + rms_off] * sumyy; - } - - return output; - } - - /** - * ALGORITHM AS274 APPL. STATIST. (1992) VOL.41, NO. 2. - * Move variable from position FROM to position TO in an - * orthogonal reduction produced by AS75.1. - * - * @param from initial position - * @param to destination - */ - private void vmove(int from, int to) { - double d1; - double d2; - double X; - double d1new; - double d2new; - double cbar; - double sbar; - double Y; - int first; - int inc; - int m1; - int m2; - int mp1; - int pos; - boolean bSkipTo40 = false; - if (from == to) { - return; - } - if (!this.rss_set) { - ss(); - } - int count = 0; - if (from < to) { - first = from; - inc = 1; - count = to - from; - } else { - first = from - 1; - inc = -1; - count = from - to; - } - - int m = first; - int idx = 0; - while (idx < count) { - m1 = m * (nvars + nvars - m - 1) / 2; - m2 = m1 + nvars - m - 1; - mp1 = m + 1; - - d1 = d[m]; - d2 = d[mp1]; - // Special cases. - if (d1 > this.epsilon || d2 > this.epsilon) { - X = r[m1]; - if (FastMath.abs(X) * FastMath.sqrt(d1) < tol[mp1]) { - X = 0.0; - } - if (d1 < this.epsilon || FastMath.abs(X) < this.epsilon) { - d[m] = d2; - d[mp1] = d1; - r[m1] = 0.0; - for (int col = m + 2; col < nvars; col++) { - ++m1; - X = r[m1]; - r[m1] = r[m2]; - r[m2] = X; - ++m2; - } - X = rhs[m]; - rhs[m] = rhs[mp1]; - rhs[mp1] = X; - bSkipTo40 = true; - //break; - } else if (d2 < this.epsilon) { - d[m] = d1 * X * X; - r[m1] = 1.0 / X; - for (int _i = m1 + 1; _i < m1 + nvars - m - 1; _i++) { - r[_i] /= X; - } - rhs[m] /= X; - bSkipTo40 = true; - //break; - } - if (!bSkipTo40) { - d1new = d2 + d1 * X * X; - cbar = d2 / d1new; - sbar = X * d1 / d1new; - d2new = d1 * cbar; - d[m] = d1new; - d[mp1] = d2new; - r[m1] = sbar; - for (int col = m + 2; col < nvars; col++) { - ++m1; - Y = r[m1]; - r[m1] = cbar * r[m2] + sbar * Y; - r[m2] = Y - X * r[m2]; - ++m2; - } - Y = rhs[m]; - rhs[m] = cbar * rhs[mp1] + sbar * Y; - rhs[mp1] = Y - X * rhs[mp1]; - } - } - if (m > 0) { - pos = m; - for (int row = 0; row < m; row++) { - X = r[pos]; - r[pos] = r[pos - 1]; - r[pos - 1] = X; - pos += nvars - row - 2; - } - } - // Adjust variable order (VORDER), the tolerances (TOL) and - // the vector of residual sums of squares (RSS). - m1 = vorder[m]; - vorder[m] = vorder[mp1]; - vorder[mp1] = m1; - X = tol[m]; - tol[m] = tol[mp1]; - tol[mp1] = X; - rss[m] = rss[mp1] + d[mp1] * rhs[mp1] * rhs[mp1]; - - m += inc; - ++idx; - } - } - - /** - * ALGORITHM AS274 APPL. STATIST. (1992) VOL.41, NO. 2 - * - *

Re-order the variables in an orthogonal reduction produced by - * AS75.1 so that the N variables in LIST start at position POS1, - * though will not necessarily be in the same order as in LIST. - * Any variables in VORDER before position POS1 are not moved. - * Auxiliary routine called: VMOVE.

- * - *

This internal method reorders the regressors.

- * - * @param list the regressors to move - * @param pos1 where the list will be placed - * @return -1 error, 0 everything ok - */ - private int reorderRegressors(int[] list, int pos1) { - int next; - int i; - int l; - if (list.length < 1 || list.length > nvars + 1 - pos1) { - return -1; - } - next = pos1; - i = pos1; - while (i < nvars) { - l = vorder[i]; - for (int j = 0; j < list.length; j++) { - if (l == list[j] && i > next) { - this.vmove(i, next); - ++next; - if (next >= list.length + pos1) { - return 0; - } else { - break; - } - } - } - ++i; - } - return 0; - } - - /** - * Gets the diagonal of the Hat matrix also known as the leverage matrix. - * - * @param row_data returns the diagonal of the hat matrix for this observation - * @return the diagonal element of the hatmatrix - */ - public double getDiagonalOfHatMatrix(double[] row_data) { - double[] wk = new double[this.nvars]; - int pos; - double total; - - if (row_data.length > nvars) { - return Double.NaN; - } - double[] xrow; - if (this.hasIntercept) { - xrow = new double[row_data.length + 1]; - xrow[0] = 1.0; - System.arraycopy(row_data, 0, xrow, 1, row_data.length); - } else { - xrow = row_data; - } - double hii = 0.0; - for (int col = 0; col < xrow.length; col++) { - if (FastMath.sqrt(d[col]) < tol[col]) { - wk[col] = 0.0; - } else { - pos = col - 1; - total = xrow[col]; - for (int row = 0; row < col; row++) { - total = smartAdd(total, -wk[row] * r[pos]); - pos += nvars - row - 2; - } - wk[col] = total; - hii = smartAdd(hii, (total * total) / d[col]); - } - } - return hii; - } - - /** - * Gets the order of the regressors, useful if some type of reordering - * has been called. Calling regress with int[]{} args will trigger - * a reordering. - * - * @return int[] with the current order of the regressors - */ - public int[] getOrderOfRegressors(){ - return MathArrays.copyOf(vorder); - } - - /** - * Conducts a regression on the data in the model, using all regressors. - * - * @return RegressionResults the structure holding all regression results - * @exception ModelSpecificationException - thrown if number of observations is - * less than the number of variables - */ - @Override - public RegressionResults regress() throws ModelSpecificationException { - return regress(this.nvars); - } - - /** - * Conducts a regression on the data in the model, using a subset of regressors. - * - * @param numberOfRegressors many of the regressors to include (either in canonical - * order, or in the current reordered state) - * @return RegressionResults the structure holding all regression results - * @exception ModelSpecificationException - thrown if number of observations is - * less than the number of variables or number of regressors requested - * is greater than the regressors in the model - */ - public RegressionResults regress(int numberOfRegressors) throws ModelSpecificationException { - if (this.nobs <= numberOfRegressors) { - throw new ModelSpecificationException( - LocalizedFormats.NOT_ENOUGH_DATA_FOR_NUMBER_OF_PREDICTORS, - this.nobs, numberOfRegressors); - } - if( numberOfRegressors > this.nvars ){ - throw new ModelSpecificationException( - LocalizedFormats.TOO_MANY_REGRESSORS, numberOfRegressors, this.nvars); - } - - tolset(); - singcheck(); - - double[] beta = this.regcf(numberOfRegressors); - - ss(); - - double[] cov = this.cov(numberOfRegressors); - - int rnk = 0; - for (int i = 0; i < this.lindep.length; i++) { - if (!this.lindep[i]) { - ++rnk; - } - } - - boolean needsReorder = false; - for (int i = 0; i < numberOfRegressors; i++) { - if (this.vorder[i] != i) { - needsReorder = true; - break; - } - } - if (!needsReorder) { - return new RegressionResults( - beta, new double[][]{cov}, true, this.nobs, rnk, - this.sumy, this.sumsqy, this.sserr, this.hasIntercept, false); - } else { - double[] betaNew = new double[beta.length]; - double[] covNew = new double[cov.length]; - - int[] newIndices = new int[beta.length]; - for (int i = 0; i < nvars; i++) { - for (int j = 0; j < numberOfRegressors; j++) { - if (this.vorder[j] == i) { - betaNew[i] = beta[ j]; - newIndices[i] = j; - } - } - } - - int idx1 = 0; - int idx2; - int _i; - int _j; - for (int i = 0; i < beta.length; i++) { - _i = newIndices[i]; - for (int j = 0; j <= i; j++, idx1++) { - _j = newIndices[j]; - if (_i > _j) { - idx2 = _i * (_i + 1) / 2 + _j; - } else { - idx2 = _j * (_j + 1) / 2 + _i; - } - covNew[idx1] = cov[idx2]; - } - } - return new RegressionResults( - betaNew, new double[][]{covNew}, true, this.nobs, rnk, - this.sumy, this.sumsqy, this.sserr, this.hasIntercept, false); - } - } - - /** - * Conducts a regression on the data in the model, using regressors in array - * Calling this method will change the internal order of the regressors - * and care is required in interpreting the hatmatrix. - * - * @param variablesToInclude array of variables to include in regression - * @return RegressionResults the structure holding all regression results - * @exception ModelSpecificationException - thrown if number of observations is - * less than the number of variables, the number of regressors requested - * is greater than the regressors in the model or a regressor index in - * regressor array does not exist - */ - @Override - public RegressionResults regress(int[] variablesToInclude) throws ModelSpecificationException { - if (variablesToInclude.length > this.nvars) { - throw new ModelSpecificationException( - LocalizedFormats.TOO_MANY_REGRESSORS, variablesToInclude.length, this.nvars); - } - if (this.nobs <= this.nvars) { - throw new ModelSpecificationException( - LocalizedFormats.NOT_ENOUGH_DATA_FOR_NUMBER_OF_PREDICTORS, - this.nobs, this.nvars); - } - Arrays.sort(variablesToInclude); - int iExclude = 0; - for (int i = 0; i < variablesToInclude.length; i++) { - if (i >= this.nvars) { - throw new ModelSpecificationException( - LocalizedFormats.INDEX_LARGER_THAN_MAX, i, this.nvars); - } - if (i > 0 && variablesToInclude[i] == variablesToInclude[i - 1]) { - variablesToInclude[i] = -1; - ++iExclude; - } - } - int[] series; - if (iExclude > 0) { - int j = 0; - series = new int[variablesToInclude.length - iExclude]; - for (int i = 0; i < variablesToInclude.length; i++) { - if (variablesToInclude[i] > -1) { - series[j] = variablesToInclude[i]; - ++j; - } - } - } else { - series = variablesToInclude; - } - - reorderRegressors(series, 0); - tolset(); - singcheck(); - - double[] beta = this.regcf(series.length); - - ss(); - - double[] cov = this.cov(series.length); - - int rnk = 0; - for (int i = 0; i < this.lindep.length; i++) { - if (!this.lindep[i]) { - ++rnk; - } - } - - boolean needsReorder = false; - for (int i = 0; i < series.length; i++) { - if (this.vorder[i] != series[i]) { - needsReorder = true; - break; - } - } - if (!needsReorder) { - return new RegressionResults( - beta, new double[][]{cov}, true, this.nobs, rnk, - this.sumy, this.sumsqy, this.sserr, this.hasIntercept, false); - } else { - double[] betaNew = new double[beta.length]; - int[] newIndices = new int[beta.length]; - for (int i = 0; i < series.length; i++) { - for (int j = 0; j < this.vorder.length; j++) { - if (this.vorder[j] == series[i]) { - betaNew[i] = beta[ j]; - newIndices[i] = j; - } - } - } - double[] covNew = new double[cov.length]; - int idx1 = 0; - int idx2; - int _i; - int _j; - for (int i = 0; i < beta.length; i++) { - _i = newIndices[i]; - for (int j = 0; j <= i; j++, idx1++) { - _j = newIndices[j]; - if (_i > _j) { - idx2 = _i * (_i + 1) / 2 + _j; - } else { - idx2 = _j * (_j + 1) / 2 + _i; - } - covNew[idx1] = cov[idx2]; - } - } - return new RegressionResults( - betaNew, new double[][]{covNew}, true, this.nobs, rnk, - this.sumy, this.sumsqy, this.sserr, this.hasIntercept, false); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/ModelSpecificationException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/ModelSpecificationException.java deleted file mode 100644 index 2607a5f96..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/ModelSpecificationException.java +++ /dev/null @@ -1,39 +0,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. - */ -package org.apache.commons.math4.stat.regression; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.util.Localizable; - -/** - * Exception thrown when a regression model is not correctly specified. - * - * @since 3.0 - */ -public class ModelSpecificationException extends MathIllegalArgumentException { - /** Serializable version Id. */ - private static final long serialVersionUID = 4206514456095401070L; - - /** - * @param pattern message pattern describing the specification error. - * - * @param args arguments. - */ - public ModelSpecificationException(Localizable pattern, Object ... args) { - super(pattern, args); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/MultipleLinearRegression.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/MultipleLinearRegression.java deleted file mode 100644 index 7a0c09ed9..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/MultipleLinearRegression.java +++ /dev/null @@ -1,69 +0,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. - */ -package org.apache.commons.math4.stat.regression; - -/** - * The multiple linear regression can be represented in matrix-notation. - *
- *  y=X*b+u
- * 
- * where y is an n-vector regressand, X is a [n,k] matrix whose k columns are called - * regressors, b is k-vector of regression parameters and u is an n-vector - * of error terms or residuals. - * - * The notation is quite standard in literature, - * cf eg Davidson and MacKinnon, Econometrics Theory and Methods, 2004. - * @since 2.0 - */ -public interface MultipleLinearRegression { - - /** - * Estimates the regression parameters b. - * - * @return The [k,1] array representing b - */ - double[] estimateRegressionParameters(); - - /** - * Estimates the variance of the regression parameters, ie Var(b). - * - * @return The [k,k] array representing the variance of b - */ - double[][] estimateRegressionParametersVariance(); - - /** - * Estimates the residuals, ie u = y - X*b. - * - * @return The [n,1] array representing the residuals - */ - double[] estimateResiduals(); - - /** - * Returns the variance of the regressand, ie Var(y). - * - * @return The double representing the variance of y - */ - double estimateRegressandVariance(); - - /** - * Returns the standard errors of the regression parameters. - * - * @return standard errors of estimated regression parameters - */ - double[] estimateRegressionParametersStandardErrors(); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/OLSMultipleLinearRegression.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/OLSMultipleLinearRegression.java deleted file mode 100644 index 637e4fecc..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/OLSMultipleLinearRegression.java +++ /dev/null @@ -1,285 +0,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. - */ -package org.apache.commons.math4.stat.regression; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.linear.Array2DRowRealMatrix; -import org.apache.commons.math4.linear.LUDecomposition; -import org.apache.commons.math4.linear.QRDecomposition; -import org.apache.commons.math4.linear.RealMatrix; -import org.apache.commons.math4.linear.RealVector; -import org.apache.commons.math4.stat.StatUtils; -import org.apache.commons.math4.stat.descriptive.moment.SecondMoment; - -/** - *

Implements ordinary least squares (OLS) to estimate the parameters of a - * multiple linear regression model.

- * - *

The regression coefficients, b, satisfy the normal equations: - *

 XT X b = XT y 
- * - *

To solve the normal equations, this implementation uses QR decomposition - * of the X matrix. (See {@link QRDecomposition} for details on the - * decomposition algorithm.) The X matrix, also known as the design matrix, - * has rows corresponding to sample observations and columns corresponding to independent - * variables. When the model is estimated using an intercept term (i.e. when - * {@link #isNoIntercept() isNoIntercept} is false as it is by default), the X - * matrix includes an initial column identically equal to 1. We solve the normal equations - * as follows: - *

 XTX b = XT y
- * (QR)T (QR) b = (QR)Ty
- * RT (QTQ) R b = RT QT y
- * RT R b = RT QT y
- * (RT)-1 RT R b = (RT)-1 RT QT y
- * R b = QT y 
- * - *

Given Q and R, the last equation is solved by back-substitution.

- * - * @since 2.0 - */ -public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegression { - - /** Cached QR decomposition of X matrix */ - private QRDecomposition qr = null; - - /** Singularity threshold for QR decomposition */ - private final double threshold; - - /** - * Create an empty OLSMultipleLinearRegression instance. - */ - public OLSMultipleLinearRegression() { - this(0d); - } - - /** - * Create an empty OLSMultipleLinearRegression instance, using the given - * singularity threshold for the QR decomposition. - * - * @param threshold the singularity threshold - * @since 3.3 - */ - public OLSMultipleLinearRegression(final double threshold) { - this.threshold = threshold; - } - - /** - * Loads model x and y sample data, overriding any previous sample. - * - * Computes and caches QR decomposition of the X matrix. - * @param y the [n,1] array representing the y sample - * @param x the [n,k] array representing the x sample - * @throws MathIllegalArgumentException if the x and y array data are not - * compatible for the regression - */ - public void newSampleData(double[] y, double[][] x) throws MathIllegalArgumentException { - validateSampleData(x, y); - newYSampleData(y); - newXSampleData(x); - } - - /** - * {@inheritDoc} - *

This implementation computes and caches the QR decomposition of the X matrix.

- */ - @Override - public void newSampleData(double[] data, int nobs, int nvars) { - super.newSampleData(data, nobs, nvars); - qr = new QRDecomposition(getX(), threshold); - } - - /** - *

Compute the "hat" matrix. - *

- *

The hat matrix is defined in terms of the design matrix X - * by X(XTX)-1XT - *

- *

The implementation here uses the QR decomposition to compute the - * hat matrix as Q IpQT where Ip is the - * p-dimensional identity matrix augmented by 0's. This computational - * formula is from "The Hat Matrix in Regression and ANOVA", - * David C. Hoaglin and Roy E. Welsch, - * The American Statistician, Vol. 32, No. 1 (Feb., 1978), pp. 17-22. - *

- *

Data for the model must have been successfully loaded using one of - * the {@code newSampleData} methods before invoking this method; otherwise - * a {@code NullPointerException} will be thrown.

- * - * @return the hat matrix - * @throws NullPointerException unless method {@code newSampleData} has been - * called beforehand. - */ - public RealMatrix calculateHat() { - // Create augmented identity matrix - RealMatrix Q = qr.getQ(); - final int p = qr.getR().getColumnDimension(); - final int n = Q.getColumnDimension(); - // No try-catch or advertised NotStrictlyPositiveException - NPE above if n < 3 - Array2DRowRealMatrix augI = new Array2DRowRealMatrix(n, n); - double[][] augIData = augI.getDataRef(); - for (int i = 0; i < n; i++) { - for (int j =0; j < n; j++) { - if (i == j && i < p) { - augIData[i][j] = 1d; - } else { - augIData[i][j] = 0d; - } - } - } - - // Compute and return Hat matrix - // No DME advertised - args valid if we get here - return Q.multiply(augI).multiply(Q.transpose()); - } - - /** - *

Returns the sum of squared deviations of Y from its mean.

- * - *

If the model has no intercept term, 0 is used for the - * mean of Y - i.e., what is returned is the sum of the squared Y values.

- * - *

The value returned by this method is the SSTO value used in - * the {@link #calculateRSquared() R-squared} computation.

- * - * @return SSTO - the total sum of squares - * @throws NullPointerException if the sample has not been set - * @see #isNoIntercept() - * @since 2.2 - */ - public double calculateTotalSumOfSquares() { - if (isNoIntercept()) { - return StatUtils.sumSq(getY().toArray()); - } else { - return new SecondMoment().evaluate(getY().toArray()); - } - } - - /** - * Returns the sum of squared residuals. - * - * @return residual sum of squares - * @since 2.2 - * @throws org.apache.commons.math4.linear.SingularMatrixException if the design matrix is singular - * @throws NullPointerException if the data for the model have not been loaded - */ - public double calculateResidualSumOfSquares() { - final RealVector residuals = calculateResiduals(); - // No advertised DME, args are valid - return residuals.dotProduct(residuals); - } - - /** - * Returns the R-Squared statistic, defined by the formula
- * R2 = 1 - SSR / SSTO - *
- * where SSR is the {@link #calculateResidualSumOfSquares() sum of squared residuals} - * and SSTO is the {@link #calculateTotalSumOfSquares() total sum of squares} - * - *

If there is no variance in y, i.e., SSTO = 0, NaN is returned.

- * - * @return R-square statistic - * @throws NullPointerException if the sample has not been set - * @throws org.apache.commons.math4.linear.SingularMatrixException if the design matrix is singular - * @since 2.2 - */ - public double calculateRSquared() { - return 1 - calculateResidualSumOfSquares() / calculateTotalSumOfSquares(); - } - - /** - *

Returns the adjusted R-squared statistic, defined by the formula

- * R2adj = 1 - [SSR (n - 1)] / [SSTO (n - p)] - *
- * where SSR is the {@link #calculateResidualSumOfSquares() sum of squared residuals}, - * SSTO is the {@link #calculateTotalSumOfSquares() total sum of squares}, n is the number - * of observations and p is the number of parameters estimated (including the intercept). - * - *

If the regression is estimated without an intercept term, what is returned is

-     *  1 - (1 - {@link #calculateRSquared()}) * (n / (n - p)) 
-     * 
- * - *

If there is no variance in y, i.e., SSTO = 0, NaN is returned.

- * - * @return adjusted R-Squared statistic - * @throws NullPointerException if the sample has not been set - * @throws org.apache.commons.math4.linear.SingularMatrixException if the design matrix is singular - * @see #isNoIntercept() - * @since 2.2 - */ - public double calculateAdjustedRSquared() { - final double n = getX().getRowDimension(); - if (isNoIntercept()) { - return 1 - (1 - calculateRSquared()) * (n / (n - getX().getColumnDimension())); - } else { - return 1 - (calculateResidualSumOfSquares() * (n - 1)) / - (calculateTotalSumOfSquares() * (n - getX().getColumnDimension())); - } - } - - /** - * {@inheritDoc} - *

This implementation computes and caches the QR decomposition of the X matrix - * once it is successfully loaded.

- */ - @Override - protected void newXSampleData(double[][] x) { - super.newXSampleData(x); - qr = new QRDecomposition(getX(), threshold); - } - - /** - * Calculates the regression coefficients using OLS. - * - *

Data for the model must have been successfully loaded using one of - * the {@code newSampleData} methods before invoking this method; otherwise - * a {@code NullPointerException} will be thrown.

- * - * @return beta - * @throws org.apache.commons.math4.linear.SingularMatrixException if the design matrix is singular - * @throws NullPointerException if the data for the model have not been loaded - */ - @Override - protected RealVector calculateBeta() { - return qr.getSolver().solve(getY()); - } - - /** - *

Calculates the variance-covariance matrix of the regression parameters. - *

- *

Var(b) = (XTX)-1 - *

- *

Uses QR decomposition to reduce (XTX)-1 - * to (RTR)-1, with only the top p rows of - * R included, where p = the length of the beta vector.

- * - *

Data for the model must have been successfully loaded using one of - * the {@code newSampleData} methods before invoking this method; otherwise - * a {@code NullPointerException} will be thrown.

- * - * @return The beta variance-covariance matrix - * @throws org.apache.commons.math4.linear.SingularMatrixException if the design matrix is singular - * @throws NullPointerException if the data for the model have not been loaded - */ - @Override - protected RealMatrix calculateBetaVariance() { - int p = getX().getColumnDimension(); - RealMatrix Raug = qr.getR().getSubMatrix(0, p - 1 , 0, p - 1); - RealMatrix Rinv = new LUDecomposition(Raug).getSolver().getInverse(); - return Rinv.multiply(Rinv.transpose()); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/RegressionResults.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/RegressionResults.java deleted file mode 100644 index 8a2a7fa62..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/RegressionResults.java +++ /dev/null @@ -1,422 +0,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. - */ -package org.apache.commons.math4.stat.regression; - -import java.io.Serializable; -import java.util.Arrays; - -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.math4.util.MathArrays; - -/** - * Results of a Multiple Linear Regression model fit. - * - * @since 3.0 - */ -public class RegressionResults implements Serializable { - - /** INDEX of Sum of Squared Errors */ - private static final int SSE_IDX = 0; - /** INDEX of Sum of Squares of Model */ - private static final int SST_IDX = 1; - /** INDEX of R-Squared of regression */ - private static final int RSQ_IDX = 2; - /** INDEX of Mean Squared Error */ - private static final int MSE_IDX = 3; - /** INDEX of Adjusted R Squared */ - private static final int ADJRSQ_IDX = 4; - /** UID */ - private static final long serialVersionUID = 1l; - /** regression slope parameters */ - private final double[] parameters; - /** variance covariance matrix of parameters */ - private final double[][] varCovData; - /** boolean flag for variance covariance matrix in symm compressed storage */ - private final boolean isSymmetricVCD; - /** rank of the solution */ - @SuppressWarnings("unused") - private final int rank; - /** number of observations on which results are based */ - private final long nobs; - /** boolean flag indicator of whether a constant was included*/ - private final boolean containsConstant; - /** array storing global results, SSE, MSE, RSQ, adjRSQ */ - private final double[] globalFitInfo; - - /** - * Set the default constructor to private access - * to prevent inadvertent instantiation - */ - @SuppressWarnings("unused") - private RegressionResults() { - this.parameters = null; - this.varCovData = null; - this.rank = -1; - this.nobs = -1; - this.containsConstant = false; - this.isSymmetricVCD = false; - this.globalFitInfo = null; - } - - /** - * Constructor for Regression Results. - * - * @param parameters a double array with the regression slope estimates - * @param varcov the variance covariance matrix, stored either in a square matrix - * or as a compressed - * @param isSymmetricCompressed a flag which denotes that the variance covariance - * matrix is in symmetric compressed format - * @param nobs the number of observations of the regression estimation - * @param rank the number of independent variables in the regression - * @param sumy the sum of the independent variable - * @param sumysq the sum of the squared independent variable - * @param sse sum of squared errors - * @param containsConstant true model has constant, false model does not have constant - * @param copyData if true a deep copy of all input data is made, if false only references - * are copied and the RegressionResults become mutable - */ - public RegressionResults( - final double[] parameters, final double[][] varcov, - final boolean isSymmetricCompressed, - final long nobs, final int rank, - final double sumy, final double sumysq, final double sse, - final boolean containsConstant, - final boolean copyData) { - if (copyData) { - this.parameters = MathArrays.copyOf(parameters); - this.varCovData = new double[varcov.length][]; - for (int i = 0; i < varcov.length; i++) { - this.varCovData[i] = MathArrays.copyOf(varcov[i]); - } - } else { - this.parameters = parameters; - this.varCovData = varcov; - } - this.isSymmetricVCD = isSymmetricCompressed; - this.nobs = nobs; - this.rank = rank; - this.containsConstant = containsConstant; - this.globalFitInfo = new double[5]; - Arrays.fill(this.globalFitInfo, Double.NaN); - - if (rank > 0) { - this.globalFitInfo[SST_IDX] = containsConstant ? - (sumysq - sumy * sumy / nobs) : sumysq; - } - - this.globalFitInfo[SSE_IDX] = sse; - this.globalFitInfo[MSE_IDX] = this.globalFitInfo[SSE_IDX] / - (nobs - rank); - this.globalFitInfo[RSQ_IDX] = 1.0 - - this.globalFitInfo[SSE_IDX] / - this.globalFitInfo[SST_IDX]; - - if (!containsConstant) { - this.globalFitInfo[ADJRSQ_IDX] = 1.0- - (1.0 - this.globalFitInfo[RSQ_IDX]) * - ( (double) nobs / ( (double) (nobs - rank))); - } else { - this.globalFitInfo[ADJRSQ_IDX] = 1.0 - (sse * (nobs - 1.0)) / - (globalFitInfo[SST_IDX] * (nobs - rank)); - } - } - - /** - *

Returns the parameter estimate for the regressor at the given index.

- * - *

A redundant regressor will have its redundancy flag set, as well as - * a parameters estimated equal to {@code Double.NaN}

- * - * @param index Index. - * @return the parameters estimated for regressor at index. - * @throws OutOfRangeException if {@code index} is not in the interval - * {@code [0, number of parameters)}. - */ - public double getParameterEstimate(int index) throws OutOfRangeException { - if (parameters == null) { - return Double.NaN; - } - if (index < 0 || index >= this.parameters.length) { - throw new OutOfRangeException(index, 0, this.parameters.length - 1); - } - return this.parameters[index]; - } - - /** - *

Returns a copy of the regression parameters estimates.

- * - *

The parameter estimates are returned in the natural order of the data.

- * - *

A redundant regressor will have its redundancy flag set, as will - * a parameter estimate equal to {@code Double.NaN}.

- * - * @return array of parameter estimates, null if no estimation occurred - */ - public double[] getParameterEstimates() { - if (this.parameters == null) { - return null; - } - return MathArrays.copyOf(parameters); - } - - /** - * Returns the standard - * error of the parameter estimate at index, - * usually denoted s(bindex). - * - * @param index Index. - * @return the standard errors associated with parameters estimated at index. - * @throws OutOfRangeException if {@code index} is not in the interval - * {@code [0, number of parameters)}. - */ - public double getStdErrorOfEstimate(int index) throws OutOfRangeException { - if (parameters == null) { - return Double.NaN; - } - if (index < 0 || index >= this.parameters.length) { - throw new OutOfRangeException(index, 0, this.parameters.length - 1); - } - double var = this.getVcvElement(index, index); - if (!Double.isNaN(var) && var > Double.MIN_VALUE) { - return FastMath.sqrt(var); - } - return Double.NaN; - } - - /** - *

Returns the standard - * error of the parameter estimates, - * usually denoted s(bi).

- * - *

If there are problems with an ill conditioned design matrix then the regressor - * which is redundant will be assigned Double.NaN.

- * - * @return an array standard errors associated with parameters estimates, - * null if no estimation occurred - */ - public double[] getStdErrorOfEstimates() { - if (parameters == null) { - return null; - } - double[] se = new double[this.parameters.length]; - for (int i = 0; i < this.parameters.length; i++) { - double var = this.getVcvElement(i, i); - if (!Double.isNaN(var) && var > Double.MIN_VALUE) { - se[i] = FastMath.sqrt(var); - continue; - } - se[i] = Double.NaN; - } - return se; - } - - /** - *

Returns the covariance between regression parameters i and j.

- * - *

If there are problems with an ill conditioned design matrix then the covariance - * which involves redundant columns will be assigned {@code Double.NaN}.

- * - * @param i {@code i}th regression parameter. - * @param j {@code j}th regression parameter. - * @return the covariance of the parameter estimates. - * @throws OutOfRangeException if {@code i} or {@code j} is not in the - * interval {@code [0, number of parameters)}. - */ - public double getCovarianceOfParameters(int i, int j) throws OutOfRangeException { - if (parameters == null) { - return Double.NaN; - } - if (i < 0 || i >= this.parameters.length) { - throw new OutOfRangeException(i, 0, this.parameters.length - 1); - } - if (j < 0 || j >= this.parameters.length) { - throw new OutOfRangeException(j, 0, this.parameters.length - 1); - } - return this.getVcvElement(i, j); - } - - /** - *

Returns the number of parameters estimated in the model.

- * - *

This is the maximum number of regressors, some techniques may drop - * redundant parameters

- * - * @return number of regressors, -1 if not estimated - */ - public int getNumberOfParameters() { - if (this.parameters == null) { - return -1; - } - return this.parameters.length; - } - - /** - * Returns the number of observations added to the regression model. - * - * @return Number of observations, -1 if an error condition prevents estimation - */ - public long getN() { - return this.nobs; - } - - /** - *

Returns the sum of squared deviations of the y values about their mean.

- * - *

This is defined as SSTO - * here.

- * - *

If {@code n < 2}, this returns {@code Double.NaN}.

- * - * @return sum of squared deviations of y values - */ - public double getTotalSumSquares() { - return this.globalFitInfo[SST_IDX]; - } - - /** - *

Returns the sum of squared deviations of the predicted y values about - * their mean (which equals the mean of y).

- * - *

This is usually abbreviated SSR or SSM. It is defined as SSM - * here

- * - *

Preconditions:

    - *
  • At least two observations (with at least two different x values) - * must have been added before invoking this method. If this method is - * invoked before a model can be estimated, Double.NaN is - * returned. - *
- * - * @return sum of squared deviations of predicted y values - */ - public double getRegressionSumSquares() { - return this.globalFitInfo[SST_IDX] - this.globalFitInfo[SSE_IDX]; - } - - /** - *

Returns the - * sum of squared errors (SSE) associated with the regression - * model.

- * - *

The return value is constrained to be non-negative - i.e., if due to - * rounding errors the computational formula returns a negative result, - * 0 is returned.

- * - *

Preconditions:

    - *
  • numberOfParameters data pairs - * must have been added before invoking this method. If this method is - * invoked before a model can be estimated, Double,NaN is - * returned. - *
- * - * @return sum of squared errors associated with the regression model - */ - public double getErrorSumSquares() { - return this.globalFitInfo[ SSE_IDX]; - } - - /** - *

Returns the sum of squared errors divided by the degrees of freedom, - * usually abbreviated MSE.

- * - *

If there are fewer than numberOfParameters + 1 data pairs in the model, - * or if there is no variation in x, this returns - * Double.NaN.

- * - * @return sum of squared deviations of y values - */ - public double getMeanSquareError() { - return this.globalFitInfo[ MSE_IDX]; - } - - /** - *

Returns the - * coefficient of multiple determination, - * usually denoted r-square.

- * - *

Preconditions:

    - *
  • At least numberOfParameters observations (with at least numberOfParameters different x values) - * must have been added before invoking this method. If this method is - * invoked before a model can be estimated, {@code Double,NaN} is - * returned. - *
- * - * @return r-square, a double in the interval [0, 1] - */ - public double getRSquared() { - return this.globalFitInfo[ RSQ_IDX]; - } - - /** - *

Returns the adjusted R-squared statistic, defined by the formula

- * R2adj = 1 - [SSR (n - 1)] / [SSTO (n - p)] - *
- * where SSR is the sum of squared residuals}, - * SSTO is the total sum of squares}, n is the number - * of observations and p is the number of parameters estimated (including the intercept). - * - *

If the regression is estimated without an intercept term, what is returned is

-     *  1 - (1 - {@link #getRSquared()} ) * (n / (n - p)) 
-     * 
- * - * @return adjusted R-Squared statistic - */ - public double getAdjustedRSquared() { - return this.globalFitInfo[ ADJRSQ_IDX]; - } - - /** - * Returns true if the regression model has been computed including an intercept. - * In this case, the coefficient of the intercept is the first element of the - * {@link #getParameterEstimates() parameter estimates}. - * @return true if the model has an intercept term - */ - public boolean hasIntercept() { - return this.containsConstant; - } - - /** - * Gets the i-jth element of the variance-covariance matrix. - * - * @param i first variable index - * @param j second variable index - * @return the requested variance-covariance matrix entry - */ - private double getVcvElement(int i, int j) { - if (this.isSymmetricVCD) { - if (this.varCovData.length > 1) { - //could be stored in upper or lower triangular - if (i == j) { - return varCovData[i][i]; - } else if (i >= varCovData[j].length) { - return varCovData[i][j]; - } else { - return varCovData[j][i]; - } - } else {//could be in single array - if (i > j) { - return varCovData[0][(i + 1) * i / 2 + j]; - } else { - return varCovData[0][(j + 1) * j / 2 + i]; - } - } - } else { - return this.varCovData[i][j]; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/SimpleRegression.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/SimpleRegression.java deleted file mode 100644 index 7fc823d3c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/SimpleRegression.java +++ /dev/null @@ -1,888 +0,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. - */ - -package org.apache.commons.math4.stat.regression; -import java.io.Serializable; - -import org.apache.commons.statistics.distribution.TDistribution; -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.OutOfRangeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.math4.util.FastMath; -import org.apache.commons.numbers.core.Precision; - -/** - * Estimates an ordinary least squares regression model - * with one independent variable. - *

- * y = intercept + slope * x

- *

- * Standard errors for intercept and slope are - * available as well as ANOVA, r-square and Pearson's r statistics.

- *

- * Observations (x,y pairs) can be added to the model one at a time or they - * can be provided in a 2-dimensional array. The observations are not stored - * in memory, so there is no limit to the number of observations that can be - * added to the model.

- *

- * Usage Notes:

    - *
  • When there are fewer than two observations in the model, or when - * there is no variation in the x values (i.e. all x values are the same) - * all statistics return NaN. At least two observations with - * different x coordinates are required to estimate a bivariate regression - * model. - *
  • - *
  • Getters for the statistics always compute values based on the current - * set of observations -- i.e., you can get statistics, then add more data - * and get updated statistics without using a new instance. There is no - * "compute" method that updates all statistics. Each of the getters performs - * the necessary computations to return the requested statistic. - *
  • - *
  • The intercept term may be suppressed by passing {@code false} to - * the {@link #SimpleRegression(boolean)} constructor. When the - * {@code hasIntercept} property is false, the model is estimated without a - * constant term and {@link #getIntercept()} returns {@code 0}.
  • - *
- * - */ -public class SimpleRegression implements Serializable, UpdatingMultipleLinearRegression { - - /** Serializable version identifier */ - private static final long serialVersionUID = -3004689053607543335L; - - /** sum of x values */ - private double sumX = 0d; - - /** total variation in x (sum of squared deviations from xbar) */ - private double sumXX = 0d; - - /** sum of y values */ - private double sumY = 0d; - - /** total variation in y (sum of squared deviations from ybar) */ - private double sumYY = 0d; - - /** sum of products */ - private double sumXY = 0d; - - /** number of observations */ - private long n = 0; - - /** mean of accumulated x values, used in updating formulas */ - private double xbar = 0; - - /** mean of accumulated y values, used in updating formulas */ - private double ybar = 0; - - /** include an intercept or not */ - private final boolean hasIntercept; - // ---------------------Public methods-------------------------------------- - - /** - * Create an empty SimpleRegression instance - */ - public SimpleRegression() { - this(true); - } - /** - * Create a SimpleRegression instance, specifying whether or not to estimate - * an intercept. - * - *

Use {@code false} to estimate a model with no intercept. When the - * {@code hasIntercept} property is false, the model is estimated without a - * constant term and {@link #getIntercept()} returns {@code 0}.

- * - * @param includeIntercept whether or not to include an intercept term in - * the regression model - */ - public SimpleRegression(boolean includeIntercept) { - super(); - hasIntercept = includeIntercept; - } - - /** - * Adds the observation (x,y) to the regression data set. - *

- * Uses updating formulas for means and sums of squares defined in - * "Algorithms for Computing the Sample Variance: Analysis and - * Recommendations", Chan, T.F., Golub, G.H., and LeVeque, R.J. - * 1983, American Statistician, vol. 37, pp. 242-247, referenced in - * Weisberg, S. "Applied Linear Regression". 2nd Ed. 1985.

- * - * - * @param x independent variable value - * @param y dependent variable value - */ - public void addData(final double x,final double y) { - if (n == 0) { - xbar = x; - ybar = y; - } else { - if( hasIntercept ){ - final double fact1 = 1.0 + n; - final double fact2 = n / (1.0 + n); - final double dx = x - xbar; - final double dy = y - ybar; - sumXX += dx * dx * fact2; - sumYY += dy * dy * fact2; - sumXY += dx * dy * fact2; - xbar += dx / fact1; - ybar += dy / fact1; - } - } - if( !hasIntercept ){ - sumXX += x * x ; - sumYY += y * y ; - sumXY += x * y ; - } - sumX += x; - sumY += y; - n++; - } - - /** - * Appends data from another regression calculation to this one. - * - *

The mean update formulae are based on a paper written by Philippe - * Pébay: - * - * Formulas for Robust, One-Pass Parallel Computation of Covariances and - * Arbitrary-Order Statistical Moments, 2008, Technical Report - * SAND2008-6212, Sandia National Laboratories.

- * - * @param reg model to append data from - * @since 3.3 - */ - public void append(SimpleRegression reg) { - if (n == 0) { - xbar = reg.xbar; - ybar = reg.ybar; - sumXX = reg.sumXX; - sumYY = reg.sumYY; - sumXY = reg.sumXY; - } else { - if (hasIntercept) { - final double fact1 = reg.n / (double) (reg.n + n); - final double fact2 = n * reg.n / (double) (reg.n + n); - final double dx = reg.xbar - xbar; - final double dy = reg.ybar - ybar; - sumXX += reg.sumXX + dx * dx * fact2; - sumYY += reg.sumYY + dy * dy * fact2; - sumXY += reg.sumXY + dx * dy * fact2; - xbar += dx * fact1; - ybar += dy * fact1; - }else{ - sumXX += reg.sumXX; - sumYY += reg.sumYY; - sumXY += reg.sumXY; - } - } - sumX += reg.sumX; - sumY += reg.sumY; - n += reg.n; - } - - /** - * Removes the observation (x,y) from the regression data set. - *

- * Mirrors the addData method. This method permits the use of - * SimpleRegression instances in streaming mode where the regression - * is applied to a sliding "window" of observations, however the caller is - * responsible for maintaining the set of observations in the window.

- * - * The method has no effect if there are no points of data (i.e. n=0) - * - * @param x independent variable value - * @param y dependent variable value - */ - public void removeData(final double x,final double y) { - if (n > 0) { - if (hasIntercept) { - final double fact1 = n - 1.0; - final double fact2 = n / (n - 1.0); - final double dx = x - xbar; - final double dy = y - ybar; - sumXX -= dx * dx * fact2; - sumYY -= dy * dy * fact2; - sumXY -= dx * dy * fact2; - xbar -= dx / fact1; - ybar -= dy / fact1; - } else { - final double fact1 = n - 1.0; - sumXX -= x * x; - sumYY -= y * y; - sumXY -= x * y; - xbar -= x / fact1; - ybar -= y / fact1; - } - sumX -= x; - sumY -= y; - n--; - } - } - - /** - * Adds the observations represented by the elements in - * data. - *

- * (data[0][0],data[0][1]) will be the first observation, then - * (data[1][0],data[1][1]), etc.

- *

- * This method does not replace data that has already been added. The - * observations represented by data are added to the existing - * dataset.

- *

- * To replace all data, use clear() before adding the new - * data.

- * - * @param data array of observations to be added - * @throws ModelSpecificationException if the length of {@code data[i]} is not - * greater than or equal to 2 - */ - public void addData(final double[][] data) throws ModelSpecificationException { - for (int i = 0; i < data.length; i++) { - if( data[i].length < 2 ){ - throw new ModelSpecificationException(LocalizedFormats.INVALID_REGRESSION_OBSERVATION, - data[i].length, 2); - } - addData(data[i][0], data[i][1]); - } - } - - /** - * Adds one observation to the regression model. - * - * @param x the independent variables which form the design matrix - * @param y the dependent or response variable - * @throws ModelSpecificationException if the length of {@code x} does not equal - * the number of independent variables in the model - */ - @Override - public void addObservation(final double[] x,final double y) - throws ModelSpecificationException { - if( x == null || x.length == 0 ){ - throw new ModelSpecificationException(LocalizedFormats.INVALID_REGRESSION_OBSERVATION,x!=null?x.length:0, 1); - } - addData( x[0], y ); - } - - /** - * Adds a series of observations to the regression model. The lengths of - * x and y must be the same and x must be rectangular. - * - * @param x a series of observations on the independent variables - * @param y a series of observations on the dependent variable - * The length of x and y must be the same - * @throws ModelSpecificationException if {@code x} is not rectangular, does not match - * the length of {@code y} or does not contain sufficient data to estimate the model - */ - @Override - public void addObservations(final double[][] x,final double[] y) throws ModelSpecificationException { - if ((x == null) || (y == null) || (x.length != y.length)) { - throw new ModelSpecificationException( - LocalizedFormats.DIMENSIONS_MISMATCH_SIMPLE, - (x == null) ? 0 : x.length, - (y == null) ? 0 : y.length); - } - boolean obsOk=true; - for( int i = 0 ; i < x.length; i++){ - if( x[i] == null || x[i].length == 0 ){ - obsOk = false; - } - } - if( !obsOk ){ - throw new ModelSpecificationException( - LocalizedFormats.NOT_ENOUGH_DATA_FOR_NUMBER_OF_PREDICTORS, - 0, 1); - } - for( int i = 0 ; i < x.length ; i++){ - addData( x[i][0], y[i] ); - } - } - - /** - * Removes observations represented by the elements in data. - *

- * If the array is larger than the current n, only the first n elements are - * processed. This method permits the use of SimpleRegression instances in - * streaming mode where the regression is applied to a sliding "window" of - * observations, however the caller is responsible for maintaining the set - * of observations in the window.

- *

- * To remove all data, use clear().

- * - * @param data array of observations to be removed - */ - public void removeData(double[][] data) { - for (int i = 0; i < data.length && n > 0; i++) { - removeData(data[i][0], data[i][1]); - } - } - - /** - * Clears all data from the model. - */ - @Override - public void clear() { - sumX = 0d; - sumXX = 0d; - sumY = 0d; - sumYY = 0d; - sumXY = 0d; - n = 0; - } - - /** - * Returns the number of observations that have been added to the model. - * - * @return n number of observations that have been added. - */ - @Override - public long getN() { - return n; - } - - /** - * Returns the "predicted" y value associated with the - * supplied x value, based on the data that has been - * added to the model when this method is activated. - *

- * predict(x) = intercept + slope * x

- *

- * Preconditions:

    - *
  • At least two observations (with at least two different x values) - * must have been added before invoking this method. If this method is - * invoked before a model can be estimated, Double,NaN is - * returned. - *
- * - * @param x input x value - * @return predicted y value - */ - public double predict(final double x) { - final double b1 = getSlope(); - if (hasIntercept) { - return getIntercept(b1) + b1 * x; - } - return b1 * x; - } - - /** - * Returns the intercept of the estimated regression line, if - * {@link #hasIntercept()} is true; otherwise 0. - *

- * The least squares estimate of the intercept is computed using the - * normal equations. - * The intercept is sometimes denoted b0.

- *

- * Preconditions:

    - *
  • At least two observations (with at least two different x values) - * must have been added before invoking this method. If this method is - * invoked before a model can be estimated, Double,NaN is - * returned. - *
- * - * @return the intercept of the regression line if the model includes an - * intercept; 0 otherwise - * @see #SimpleRegression(boolean) - */ - public double getIntercept() { - return hasIntercept ? getIntercept(getSlope()) : 0.0; - } - - /** - * Returns true if the model includes an intercept term. - * - * @return true if the regression includes an intercept; false otherwise - * @see #SimpleRegression(boolean) - */ - @Override - public boolean hasIntercept() { - return hasIntercept; - } - - /** - * Returns the slope of the estimated regression line. - *

- * The least squares estimate of the slope is computed using the - * normal equations. - * The slope is sometimes denoted b1.

- *

- * Preconditions:

    - *
  • At least two observations (with at least two different x values) - * must have been added before invoking this method. If this method is - * invoked before a model can be estimated, Double.NaN is - * returned. - *
- * - * @return the slope of the regression line - */ - public double getSlope() { - if (n < 2) { - return Double.NaN; //not enough data - } - if (FastMath.abs(sumXX) < 10 * Double.MIN_VALUE) { - return Double.NaN; //not enough variation in x - } - return sumXY / sumXX; - } - - /** - * Returns the - * sum of squared errors (SSE) associated with the regression - * model. - *

- * The sum is computed using the computational formula

- *

- * SSE = SYY - (SXY * SXY / SXX)

- *

- * where SYY is the sum of the squared deviations of the y - * values about their mean, SXX is similarly defined and - * SXY is the sum of the products of x and y mean deviations. - *

- * The sums are accumulated using the updating algorithm referenced in - * {@link #addData}.

- *

- * The return value is constrained to be non-negative - i.e., if due to - * rounding errors the computational formula returns a negative result, - * 0 is returned.

- *

- * Preconditions:

    - *
  • At least two observations (with at least two different x values) - * must have been added before invoking this method. If this method is - * invoked before a model can be estimated, Double,NaN is - * returned. - *
- * - * @return sum of squared errors associated with the regression model - */ - public double getSumSquaredErrors() { - return FastMath.max(0d, sumYY - sumXY * sumXY / sumXX); - } - - /** - * Returns the sum of squared deviations of the y values about their mean. - *

- * This is defined as SSTO - * here.

- *

- * If {@code n < 2}, this returns Double.NaN.

- * - * @return sum of squared deviations of y values - */ - public double getTotalSumSquares() { - if (n < 2) { - return Double.NaN; - } - return sumYY; - } - - /** - * Returns the sum of squared deviations of the x values about their mean. - * - * If n < 2, this returns Double.NaN. - * - * @return sum of squared deviations of x values - */ - public double getXSumSquares() { - if (n < 2) { - return Double.NaN; - } - return sumXX; - } - - /** - * Returns the sum of crossproducts, xi*yi. - * - * @return sum of cross products - */ - public double getSumOfCrossProducts() { - return sumXY; - } - - /** - * Returns the sum of squared deviations of the predicted y values about - * their mean (which equals the mean of y). - *

- * This is usually abbreviated SSR or SSM. It is defined as SSM - * here

- *

- * Preconditions:

    - *
  • At least two observations (with at least two different x values) - * must have been added before invoking this method. If this method is - * invoked before a model can be estimated, Double.NaN is - * returned. - *
- * - * @return sum of squared deviations of predicted y values - */ - public double getRegressionSumSquares() { - return getRegressionSumSquares(getSlope()); - } - - /** - * Returns the sum of squared errors divided by the degrees of freedom, - * usually abbreviated MSE. - *

- * If there are fewer than three data pairs in the model, - * or if there is no variation in x, this returns - * Double.NaN.

- * - * @return sum of squared deviations of y values - */ - public double getMeanSquareError() { - if (n < 3) { - return Double.NaN; - } - return hasIntercept ? (getSumSquaredErrors() / (n - 2)) : (getSumSquaredErrors() / (n - 1)); - } - - /** - * Returns - * Pearson's product moment correlation coefficient, - * usually denoted r. - *

- * Preconditions:

    - *
  • At least two observations (with at least two different x values) - * must have been added before invoking this method. If this method is - * invoked before a model can be estimated, Double,NaN is - * returned. - *
- * - * @return Pearson's r - */ - public double getR() { - double b1 = getSlope(); - double result = FastMath.sqrt(getRSquare()); - if (b1 < 0) { - result = -result; - } - return result; - } - - /** - * Returns the - * coefficient of determination, - * usually denoted r-square. - *

- * Preconditions:

    - *
  • At least two observations (with at least two different x values) - * must have been added before invoking this method. If this method is - * invoked before a model can be estimated, Double,NaN is - * returned. - *
- * - * @return r-square - */ - public double getRSquare() { - double ssto = getTotalSumSquares(); - return (ssto - getSumSquaredErrors()) / ssto; - } - - /** - * Returns the - * standard error of the intercept estimate, - * usually denoted s(b0). - *

- * If there are fewer that three observations in the - * model, or if there is no variation in x, this returns - * Double.NaN.

Additionally, a Double.NaN is - * returned when the intercept is constrained to be zero - * - * @return standard error associated with intercept estimate - */ - public double getInterceptStdErr() { - if( !hasIntercept ){ - return Double.NaN; - } - return FastMath.sqrt( - getMeanSquareError() * ((1d / n) + (xbar * xbar) / sumXX)); - } - - /** - * Returns the standard - * error of the slope estimate, - * usually denoted s(b1). - *

- * If there are fewer that three data pairs in the model, - * or if there is no variation in x, this returns Double.NaN. - *

- * - * @return standard error associated with slope estimate - */ - public double getSlopeStdErr() { - return FastMath.sqrt(getMeanSquareError() / sumXX); - } - - /** - * Returns the half-width of a 95% confidence interval for the slope - * estimate. - *

- * The 95% confidence interval is

- *

- * (getSlope() - getSlopeConfidenceInterval(), - * getSlope() + getSlopeConfidenceInterval())

- *

- * If there are fewer that three observations in the - * model, or if there is no variation in x, this returns - * Double.NaN.

- *

- * Usage Note:
- * The validity of this statistic depends on the assumption that the - * observations included in the model are drawn from a - * - * Bivariate Normal Distribution.

- * - * @return half-width of 95% confidence interval for the slope estimate - * @throws OutOfRangeException if the confidence interval can not be computed. - */ - public double getSlopeConfidenceInterval() throws OutOfRangeException { - return getSlopeConfidenceInterval(0.05d); - } - - /** - * Returns the half-width of a (100-100*alpha)% confidence interval for - * the slope estimate. - *

- * The (100-100*alpha)% confidence interval is

- *

- * (getSlope() - getSlopeConfidenceInterval(), - * getSlope() + getSlopeConfidenceInterval())

- *

- * To request, for example, a 99% confidence interval, use - * alpha = .01

- *

- * Usage Note:
- * The validity of this statistic depends on the assumption that the - * observations included in the model are drawn from a - * - * Bivariate Normal Distribution.

- *

- * Preconditions:

    - *
  • If there are fewer that three observations in the - * model, or if there is no variation in x, this returns - * Double.NaN. - *
  • - *
  • {@code (0 < alpha < 1)}; otherwise an - * OutOfRangeException is thrown. - *
- * - * @param alpha the desired significance level - * @return half-width of 95% confidence interval for the slope estimate - * @throws OutOfRangeException if the confidence interval can not be computed. - */ - public double getSlopeConfidenceInterval(final double alpha) - throws OutOfRangeException { - if (n < 3) { - return Double.NaN; - } - if (alpha >= 1 || alpha <= 0) { - throw new OutOfRangeException(LocalizedFormats.SIGNIFICANCE_LEVEL, - alpha, 0, 1); - } - // No advertised NotStrictlyPositiveException here - will return NaN above - TDistribution distribution = new TDistribution(n - 2); - return getSlopeStdErr() * - distribution.inverseCumulativeProbability(1d - alpha / 2d); - } - - /** - * Returns the significance level of the slope (equiv) correlation. - *

- * Specifically, the returned value is the smallest alpha - * such that the slope confidence interval with significance level - * equal to alpha does not include 0. - * On regression output, this is often denoted {@code Prob(|t| > 0)} - *

- * Usage Note:
- * The validity of this statistic depends on the assumption that the - * observations included in the model are drawn from a - * - * Bivariate Normal Distribution.

- *

- * If there are fewer that three observations in the - * model, or if there is no variation in x, this returns - * Double.NaN.

- * - * @return significance level for slope/correlation - * @throws org.apache.commons.math4.exception.MaxCountExceededException - * if the significance level can not be computed. - */ - public double getSignificance() { - if (n < 3) { - return Double.NaN; - } - // No advertised NotStrictlyPositiveException here - will return NaN above - TDistribution distribution = new TDistribution(n - 2); - return 2d * (1.0 - distribution.cumulativeProbability( - FastMath.abs(getSlope()) / getSlopeStdErr())); - } - - // ---------------------Private methods----------------------------------- - - /** - * Returns the intercept of the estimated regression line, given the slope. - *

- * Will return NaN if slope is NaN.

- * - * @param slope current slope - * @return the intercept of the regression line - */ - private double getIntercept(final double slope) { - if( hasIntercept){ - return (sumY - slope * sumX) / n; - } - return 0.0; - } - - /** - * Computes SSR from b1. - * - * @param slope regression slope estimate - * @return sum of squared deviations of predicted y values - */ - private double getRegressionSumSquares(final double slope) { - return slope * slope * sumXX; - } - - /** - * Performs a regression on data present in buffers and outputs a RegressionResults object. - * - *

If there are fewer than 3 observations in the model and {@code hasIntercept} is true - * a {@code NoDataException} is thrown. If there is no intercept term, the model must - * contain at least 2 observations.

- * - * @return RegressionResults acts as a container of regression output - * @throws ModelSpecificationException if the model is not correctly specified - * @throws NoDataException if there is not sufficient data in the model to - * estimate the regression parameters - */ - @Override - public RegressionResults regress() throws ModelSpecificationException, NoDataException { - if (hasIntercept) { - if (n < 3) { - throw new NoDataException(LocalizedFormats.NOT_ENOUGH_DATA_REGRESSION); - } - if (FastMath.abs(sumXX) > Precision.SAFE_MIN) { - final double[] params = new double[] { getIntercept(), getSlope() }; - final double mse = getMeanSquareError(); - final double _syy = sumYY + sumY * sumY / n; - final double[] vcv = new double[] { mse * (xbar * xbar / sumXX + 1.0 / n), -xbar * mse / sumXX, mse / sumXX }; - return new RegressionResults(params, new double[][] { vcv }, true, n, 2, sumY, _syy, getSumSquaredErrors(), true, - false); - } else { - final double[] params = new double[] { sumY / n, Double.NaN }; - // final double mse = getMeanSquareError(); - final double[] vcv = new double[] { ybar / (n - 1.0), Double.NaN, Double.NaN }; - return new RegressionResults(params, new double[][] { vcv }, true, n, 1, sumY, sumYY, getSumSquaredErrors(), true, - false); - } - } else { - if (n < 2) { - throw new NoDataException(LocalizedFormats.NOT_ENOUGH_DATA_REGRESSION); - } - if (!Double.isNaN(sumXX)) { - final double[] vcv = new double[] { getMeanSquareError() / sumXX }; - final double[] params = new double[] { sumXY / sumXX }; - return new RegressionResults(params, new double[][] { vcv }, true, n, 1, sumY, sumYY, getSumSquaredErrors(), false, - false); - } else { - final double[] vcv = new double[] { Double.NaN }; - final double[] params = new double[] { Double.NaN }; - return new RegressionResults(params, new double[][] { vcv }, true, n, 1, Double.NaN, Double.NaN, Double.NaN, false, - false); - } - } - } - - /** - * Performs a regression on data present in buffers including only regressors - * indexed in variablesToInclude and outputs a RegressionResults object - * @param variablesToInclude an array of indices of regressors to include - * @return RegressionResults acts as a container of regression output - * @throws MathIllegalArgumentException if the variablesToInclude array is null or zero length - * @throws OutOfRangeException if a requested variable is not present in model - */ - @Override - public RegressionResults regress(int[] variablesToInclude) throws MathIllegalArgumentException{ - if( variablesToInclude == null || variablesToInclude.length == 0){ - throw new MathIllegalArgumentException(LocalizedFormats.ARRAY_ZERO_LENGTH_OR_NULL_NOT_ALLOWED); - } - if( variablesToInclude.length > 2 || (variablesToInclude.length > 1 && !hasIntercept) ){ - throw new ModelSpecificationException( - LocalizedFormats.ARRAY_SIZE_EXCEEDS_MAX_VARIABLES, - (variablesToInclude.length > 1 && !hasIntercept) ? 1 : 2); - } - - if( hasIntercept ){ - if( variablesToInclude.length == 2 ){ - if( variablesToInclude[0] == 1 ){ - throw new ModelSpecificationException(LocalizedFormats.NOT_INCREASING_SEQUENCE); - }else if( variablesToInclude[0] != 0 ){ - throw new OutOfRangeException( variablesToInclude[0], 0,1 ); - } - if( variablesToInclude[1] != 1){ - throw new OutOfRangeException( variablesToInclude[0], 0,1 ); - } - return regress(); - }else{ - if( variablesToInclude[0] != 1 && variablesToInclude[0] != 0 ){ - throw new OutOfRangeException( variablesToInclude[0],0,1 ); - } - final double _mean = sumY * sumY / n; - final double _syy = sumYY + _mean; - if( variablesToInclude[0] == 0 ){ - //just the mean - final double[] vcv = new double[]{ sumYY/(((n-1)*n)) }; - final double[] params = new double[]{ ybar }; - return new RegressionResults( - params, new double[][]{vcv}, true, n, 1, - sumY, _syy+_mean, sumYY,true,false); - - }else if( variablesToInclude[0] == 1){ - //final double _syy = sumYY + sumY * sumY / ((double) n); - final double _sxx = sumXX + sumX * sumX / n; - final double _sxy = sumXY + sumX * sumY / n; - final double _sse = FastMath.max(0d, _syy - _sxy * _sxy / _sxx); - final double _mse = _sse/((n-1)); - if( !Double.isNaN(_sxx) ){ - final double[] vcv = new double[]{ _mse / _sxx }; - final double[] params = new double[]{ _sxy/_sxx }; - return new RegressionResults( - params, new double[][]{vcv}, true, n, 1, - sumY, _syy, _sse,false,false); - }else{ - final double[] vcv = new double[]{Double.NaN }; - final double[] params = new double[]{ Double.NaN }; - return new RegressionResults( - params, new double[][]{vcv}, true, n, 1, - Double.NaN, Double.NaN, Double.NaN,false,false); - } - } - } - }else{ - if( variablesToInclude[0] != 0 ){ - throw new OutOfRangeException(variablesToInclude[0],0,0); - } - return regress(); - } - - return null; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/UpdatingMultipleLinearRegression.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/UpdatingMultipleLinearRegression.java deleted file mode 100644 index 60a0534b0..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/UpdatingMultipleLinearRegression.java +++ /dev/null @@ -1,93 +0,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. - */ -package org.apache.commons.math4.stat.regression; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NoDataException; - -/** - * An interface for regression models allowing for dynamic updating of the data. - * That is, the entire data set need not be loaded into memory. As observations - * become available, they can be added to the regression model and an updated - * estimate regression statistics can be calculated. - * - * @since 3.0 - */ -public interface UpdatingMultipleLinearRegression { - - /** - * Returns true if a constant has been included false otherwise. - * - * @return true if constant exists, false otherwise - */ - boolean hasIntercept(); - - /** - * Returns the number of observations added to the regression model. - * - * @return Number of observations - */ - long getN(); - - /** - * Adds one observation to the regression model. - * - * @param x the independent variables which form the design matrix - * @param y the dependent or response variable - * @throws ModelSpecificationException if the length of {@code x} does not equal - * the number of independent variables in the model - */ - void addObservation(double[] x, double y) throws ModelSpecificationException; - - /** - * Adds a series of observations to the regression model. The lengths of - * x and y must be the same and x must be rectangular. - * - * @param x a series of observations on the independent variables - * @param y a series of observations on the dependent variable - * The length of x and y must be the same - * @throws ModelSpecificationException if {@code x} is not rectangular, does not match - * the length of {@code y} or does not contain sufficient data to estimate the model - */ - void addObservations(double[][] x, double[] y) throws ModelSpecificationException; - - /** - * Clears internal buffers and resets the regression model. This means all - * data and derived values are initialized - */ - void clear(); - - - /** - * Performs a regression on data present in buffers and outputs a RegressionResults object - * @return RegressionResults acts as a container of regression output - * @throws ModelSpecificationException if the model is not correctly specified - * @throws NoDataException if there is not sufficient data in the model to - * estimate the regression parameters - */ - RegressionResults regress() throws ModelSpecificationException, NoDataException; - - /** - * Performs a regression on data present in buffers including only regressors - * indexed in variablesToInclude and outputs a RegressionResults object - * @param variablesToInclude an array of indices of regressors to include - * @return RegressionResults acts as a container of regression output - * @throws ModelSpecificationException if the model is not correctly specified - * @throws MathIllegalArgumentException if the variablesToInclude array is null or zero length - */ - RegressionResults regress(int[] variablesToInclude) throws ModelSpecificationException, MathIllegalArgumentException; -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/package-info.java deleted file mode 100644 index ad05581b5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/stat/regression/package-info.java +++ /dev/null @@ -1,22 +0,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. - */ -/** - * - * Statistical routines involving multivariate data. - * - */ -package org.apache.commons.math4.stat.regression; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/BigReal.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/BigReal.java deleted file mode 100644 index a69ed5d08..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/BigReal.java +++ /dev/null @@ -1,334 +0,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. - */ -package org.apache.commons.math4.util; - - -import java.io.Serializable; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.math.MathContext; -import java.math.RoundingMode; - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Arbitrary precision decimal number. - *

- * This class is a simple wrapper around the standard BigDecimal - * in order to implement the {@link FieldElement} interface. - *

- * @since 2.0 - */ -public class BigReal implements FieldElement, Comparable, Serializable { - - /** A big real representing 0. */ - public static final BigReal ZERO = new BigReal(BigDecimal.ZERO); - - /** A big real representing 1. */ - public static final BigReal ONE = new BigReal(BigDecimal.ONE); - - /** Serializable version identifier. */ - private static final long serialVersionUID = 4984534880991310382L; - - /** Underlying BigDecimal. */ - private final BigDecimal d; - - /** Rounding mode for divisions. **/ - private RoundingMode roundingMode = RoundingMode.HALF_UP; - - /*** BigDecimal scale ***/ - private int scale = 64; - - /** Build an instance from a BigDecimal. - * @param val value of the instance - */ - public BigReal(BigDecimal val) { - d = val; - } - - /** Build an instance from a BigInteger. - * @param val value of the instance - */ - public BigReal(BigInteger val) { - d = new BigDecimal(val); - } - - /** Build an instance from an unscaled BigInteger. - * @param unscaledVal unscaled value - * @param scale scale to use - */ - public BigReal(BigInteger unscaledVal, int scale) { - d = new BigDecimal(unscaledVal, scale); - } - - /** Build an instance from an unscaled BigInteger. - * @param unscaledVal unscaled value - * @param scale scale to use - * @param mc to used - */ - public BigReal(BigInteger unscaledVal, int scale, MathContext mc) { - d = new BigDecimal(unscaledVal, scale, mc); - } - - /** Build an instance from a BigInteger. - * @param val value of the instance - * @param mc context to use - */ - public BigReal(BigInteger val, MathContext mc) { - d = new BigDecimal(val, mc); - } - - /** Build an instance from a characters representation. - * @param in character representation of the value - */ - public BigReal(char[] in) { - d = new BigDecimal(in); - } - - /** Build an instance from a characters representation. - * @param in character representation of the value - * @param offset offset of the first character to analyze - * @param len length of the array slice to analyze - */ - public BigReal(char[] in, int offset, int len) { - d = new BigDecimal(in, offset, len); - } - - /** Build an instance from a characters representation. - * @param in character representation of the value - * @param offset offset of the first character to analyze - * @param len length of the array slice to analyze - * @param mc context to use - */ - public BigReal(char[] in, int offset, int len, MathContext mc) { - d = new BigDecimal(in, offset, len, mc); - } - - /** Build an instance from a characters representation. - * @param in character representation of the value - * @param mc context to use - */ - public BigReal(char[] in, MathContext mc) { - d = new BigDecimal(in, mc); - } - - /** Build an instance from a double. - * @param val value of the instance - */ - public BigReal(double val) { - d = new BigDecimal(val); - } - - /** Build an instance from a double. - * @param val value of the instance - * @param mc context to use - */ - public BigReal(double val, MathContext mc) { - d = new BigDecimal(val, mc); - } - - /** Build an instance from an int. - * @param val value of the instance - */ - public BigReal(int val) { - d = new BigDecimal(val); - } - - /** Build an instance from an int. - * @param val value of the instance - * @param mc context to use - */ - public BigReal(int val, MathContext mc) { - d = new BigDecimal(val, mc); - } - - /** Build an instance from a long. - * @param val value of the instance - */ - public BigReal(long val) { - d = new BigDecimal(val); - } - - /** Build an instance from a long. - * @param val value of the instance - * @param mc context to use - */ - public BigReal(long val, MathContext mc) { - d = new BigDecimal(val, mc); - } - - /** Build an instance from a String representation. - * @param val character representation of the value - */ - public BigReal(String val) { - d = new BigDecimal(val); - } - - /** Build an instance from a String representation. - * @param val character representation of the value - * @param mc context to use - */ - public BigReal(String val, MathContext mc) { - d = new BigDecimal(val, mc); - } - - /*** - * Gets the rounding mode for division operations - * The default is {@code RoundingMode.HALF_UP} - * @return the rounding mode. - * @since 2.1 - */ - public RoundingMode getRoundingMode() { - return roundingMode; - } - - /*** - * Sets the rounding mode for decimal divisions. - * @param roundingMode rounding mode for decimal divisions - * @since 2.1 - */ - public void setRoundingMode(RoundingMode roundingMode) { - this.roundingMode = roundingMode; - } - - /*** - * Sets the scale for division operations. - * The default is 64 - * @return the scale - * @since 2.1 - */ - public int getScale() { - return scale; - } - - /*** - * Sets the scale for division operations. - * @param scale scale for division operations - * @since 2.1 - */ - public void setScale(int scale) { - this.scale = scale; - } - - /** {@inheritDoc} */ - @Override - public BigReal add(BigReal a) { - return new BigReal(d.add(a.d)); - } - - /** {@inheritDoc} */ - @Override - public BigReal subtract(BigReal a) { - return new BigReal(d.subtract(a.d)); - } - - /** {@inheritDoc} */ - @Override - public BigReal negate() { - return new BigReal(d.negate()); - } - - /** - * {@inheritDoc} - * - * @throws MathArithmeticException if {@code a} is zero - */ - @Override - public BigReal divide(BigReal a) throws MathArithmeticException { - try { - return new BigReal(d.divide(a.d, scale, roundingMode)); - } catch (ArithmeticException e) { - // Division by zero has occurred - throw new MathArithmeticException(LocalizedFormats.ZERO_NOT_ALLOWED); - } - } - - /** - * {@inheritDoc} - * - * @throws MathArithmeticException if {@code this} is zero - */ - @Override - public BigReal reciprocal() throws MathArithmeticException { - try { - return new BigReal(BigDecimal.ONE.divide(d, scale, roundingMode)); - } catch (ArithmeticException e) { - // Division by zero has occurred - throw new MathArithmeticException(LocalizedFormats.ZERO_NOT_ALLOWED); - } - } - - /** {@inheritDoc} */ - @Override - public BigReal multiply(BigReal a) { - return new BigReal(d.multiply(a.d)); - } - - /** {@inheritDoc} */ - @Override - public BigReal multiply(final int n) { - return new BigReal(d.multiply(new BigDecimal(n))); - } - - /** {@inheritDoc} */ - @Override - public int compareTo(BigReal a) { - return d.compareTo(a.d); - } - - /** Get the double value corresponding to the instance. - * @return double value corresponding to the instance - */ - public double doubleValue() { - return d.doubleValue(); - } - - /** Get the BigDecimal value corresponding to the instance. - * @return BigDecimal value corresponding to the instance - */ - public BigDecimal bigDecimalValue() { - return d; - } - - /** {@inheritDoc} */ - @Override - public boolean equals(Object other) { - if (this == other){ - return true; - } - - if (other instanceof BigReal){ - return d.equals(((BigReal) other).d); - } - return false; - } - - /** {@inheritDoc} */ - @Override - public int hashCode() { - return d.hashCode(); - } - - /** {@inheritDoc} */ - @Override - public Field getField() { - return BigRealField.getInstance(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/BigRealField.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/BigRealField.java deleted file mode 100644 index d6e9bca7e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/BigRealField.java +++ /dev/null @@ -1,86 +0,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. - */ - -package org.apache.commons.math4.util; - -import java.io.Serializable; - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; - -/** - * Representation of real numbers with arbitrary precision field. - *

- * This class is a singleton. - *

- * @see BigReal - * @since 2.0 - */ -public class BigRealField implements Field, Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 4756431066541037559L; - - /** Private constructor for the singleton. - */ - private BigRealField() { - } - - /** Get the unique instance. - * @return the unique instance - */ - public static BigRealField getInstance() { - return LazyHolder.INSTANCE; - } - - /** {@inheritDoc} */ - @Override - public BigReal getOne() { - return BigReal.ONE; - } - - /** {@inheritDoc} */ - @Override - public BigReal getZero() { - return BigReal.ZERO; - } - - /** {@inheritDoc} */ - @Override - public Class> getRuntimeClass() { - return BigReal.class; - } - - // CHECKSTYLE: stop HideUtilityClassConstructor - /** Holder for the instance. - *

We use here the Initialization On Demand Holder Idiom.

- */ - private static class LazyHolder { - /** Cached field instance. */ - private static final BigRealField INSTANCE = new BigRealField(); - } - // CHECKSTYLE: resume HideUtilityClassConstructor - - /** Handle deserialization of the singleton. - * @return the singleton instance - */ - private Object readResolve() { - // return the singleton instance - return LazyHolder.INSTANCE; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/CentralPivotingStrategy.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/CentralPivotingStrategy.java deleted file mode 100644 index 9581a37ba..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/CentralPivotingStrategy.java +++ /dev/null @@ -1,47 +0,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. - */ -package org.apache.commons.math4.util; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; - - -/** - * A mid point strategy based on the average of begin and end indices. - * @since 3.4 - */ -public class CentralPivotingStrategy implements PivotingStrategyInterface, Serializable { - - /** Serializable UID. */ - private static final long serialVersionUID = 20140713L; - - /** - * {@inheritDoc} - * This in particular picks a average of begin and end indices - * @return The index corresponding to a simple average of - * the first and the last element indices of the array slice - * @throws MathIllegalArgumentException when indices exceeds range - */ - @Override - public int pivotIndex(final double[] work, final int begin, final int end) - throws MathIllegalArgumentException { - MathArrays.verifyValues(work, begin, end-begin); - return begin + (end - begin)/2; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/CombinatoricsUtils.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/CombinatoricsUtils.java deleted file mode 100644 index 26a96834b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/CombinatoricsUtils.java +++ /dev/null @@ -1,125 +0,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. - */ -package org.apache.commons.math4.util; - -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; -import org.apache.commons.numbers.combinatorics.BinomialCoefficient; -import org.apache.commons.numbers.combinatorics.Factorial; -import org.apache.commons.numbers.core.ArithmeticUtils; - -import java.util.concurrent.atomic.AtomicReference; - -/** - * Combinatorial utilities. - * - * @since 3.3 - */ -public final class CombinatoricsUtils { - /** Stirling numbers of the second kind. */ - static final AtomicReference STIRLING_S2 = new AtomicReference<> (null); - - /** Private constructor (class contains only static methods). */ - private CombinatoricsUtils() {} - - /** - * Returns the - * Stirling number of the second kind, "{@code S(n,k)}", the number of - * ways of partitioning an {@code n}-element set into {@code k} non-empty - * subsets. - *

- * The preconditions are {@code 0 <= k <= n } (otherwise - * {@code NotPositiveException} is thrown) - *

- * @param n the size of the set - * @param k the number of non-empty subsets - * @return {@code S(n,k)} - * @throws NotPositiveException if {@code k < 0}. - * @throws NumberIsTooLargeException if {@code k > n}. - * @throws MathArithmeticException if some overflow happens, typically for n exceeding 25 and - * k between 20 and n-2 (S(n,n-1) is handled specifically and does not overflow) - * @since 3.1 - */ - public static long stirlingS2(final int n, final int k) - throws NotPositiveException, NumberIsTooLargeException, MathArithmeticException { - if (k < 0) { - throw new NotPositiveException(k); - } - if (k > n) { - throw new NumberIsTooLargeException(k, n, true); - } - - long[][] stirlingS2 = STIRLING_S2.get(); - - if (stirlingS2 == null) { - // the cache has never been initialized, compute the first numbers - // by direct recurrence relation - - // as S(26,9) = 11201516780955125625 is larger than Long.MAX_VALUE - // we must stop computation at row 26 - final int maxIndex = 26; - stirlingS2 = new long[maxIndex][]; - stirlingS2[0] = new long[] { 1l }; - for (int i = 1; i < stirlingS2.length; ++i) { - stirlingS2[i] = new long[i + 1]; - stirlingS2[i][0] = 0; - stirlingS2[i][1] = 1; - stirlingS2[i][i] = 1; - for (int j = 2; j < i; ++j) { - stirlingS2[i][j] = j * stirlingS2[i - 1][j] + stirlingS2[i - 1][j - 1]; - } - } - - // atomically save the cache - STIRLING_S2.compareAndSet(null, stirlingS2); - - } - - if (n < stirlingS2.length) { - // the number is in the small cache - return stirlingS2[n][k]; - } else { - // use explicit formula to compute the number without caching it - if (k == 0) { - return 0; - } else if (k == 1 || k == n) { - return 1; - } else if (k == 2) { - return (1l << (n - 1)) - 1l; - } else if (k == n - 1) { - return BinomialCoefficient.value(n, 2); - } else { - // definition formula: note that this may trigger some overflow - long sum = 0; - long sign = ((k & 0x1) == 0) ? 1 : -1; - for (int j = 1; j <= k; ++j) { - sign = -sign; - sum += sign * BinomialCoefficient.value(k, j) * ArithmeticUtils.pow(j, n); - if (sum < 0) { - // there was an overflow somewhere - throw new MathArithmeticException(LocalizedFormats.ARGUMENT_OUTSIDE_DOMAIN, - n, 0, stirlingS2.length - 1); - } - } - return sum / Factorial.value(k); - } - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/CompositeFormat.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/CompositeFormat.java deleted file mode 100644 index 230ca26a9..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/CompositeFormat.java +++ /dev/null @@ -1,218 +0,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. - */ -package org.apache.commons.math4.util; - -import java.text.FieldPosition; -import java.text.NumberFormat; -import java.text.ParsePosition; -import java.util.Locale; - -/** - * Base class for formatters of composite objects (complex numbers, vectors ...). - * - */ -public class CompositeFormat { - - /** - * Class contains only static methods. - */ - private CompositeFormat() {} - - /** - * Create a default number format. The default number format is based on - * {@link NumberFormat#getInstance()} with the only customizing that the - * maximum number of fraction digits is set to 10. - * @return the default number format. - */ - public static NumberFormat getDefaultNumberFormat() { - return getDefaultNumberFormat(Locale.getDefault()); - } - - /** - * Create a default number format. The default number format is based on - * {@link NumberFormat#getInstance(Locale)} with the only - * customizing that the maximum number of fraction digits is set to 10. - * @param locale the specific locale used by the format. - * @return the default number format specific to the given locale. - */ - public static NumberFormat getDefaultNumberFormat(final Locale locale) { - final NumberFormat nf = NumberFormat.getInstance(locale); - nf.setMaximumFractionDigits(10); - return nf; - } - - /** - * Parses source until a non-whitespace character is found. - * - * @param source the string to parse - * @param pos input/output parsing parameter. On output, pos - * holds the index of the next non-whitespace character. - */ - public static void parseAndIgnoreWhitespace(final String source, - final ParsePosition pos) { - parseNextCharacter(source, pos); - pos.setIndex(pos.getIndex() - 1); - } - - /** - * Parses source until a non-whitespace character is found. - * - * @param source the string to parse - * @param pos input/output parsing parameter. - * @return the first non-whitespace character. - */ - public static char parseNextCharacter(final String source, - final ParsePosition pos) { - int index = pos.getIndex(); - final int n = source.length(); - char ret = 0; - - if (index < n) { - char c; - do { - c = source.charAt(index++); - } while (Character.isWhitespace(c) && index < n); - pos.setIndex(index); - - if (index < n) { - ret = c; - } - } - - return ret; - } - - /** - * Parses source for special double values. These values - * include Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY. - * - * @param source the string to parse - * @param value the special value to parse. - * @param pos input/output parsing parameter. - * @return the special number. - */ - private static Number parseNumber(final String source, final double value, - final ParsePosition pos) { - Number ret = null; - - StringBuilder sb = new StringBuilder(); - sb.append('('); - sb.append(value); - sb.append(')'); - - final int n = sb.length(); - final int startIndex = pos.getIndex(); - final int endIndex = startIndex + n; - if (endIndex < source.length() && - source.substring(startIndex, endIndex).compareTo(sb.toString()) == 0) { - ret = Double.valueOf(value); - pos.setIndex(endIndex); - } - - return ret; - } - - /** - * Parses source for a number. This method can parse normal, - * numeric values as well as special values. These special values include - * Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY. - * - * @param source the string to parse - * @param format the number format used to parse normal, numeric values. - * @param pos input/output parsing parameter. - * @return the parsed number. - */ - public static Number parseNumber(final String source, final NumberFormat format, - final ParsePosition pos) { - final int startIndex = pos.getIndex(); - Number number = format.parse(source, pos); - final int endIndex = pos.getIndex(); - - // check for error parsing number - if (startIndex == endIndex) { - // try parsing special numbers - final double[] special = { - Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY - }; - for (int i = 0; i < special.length; ++i) { - number = parseNumber(source, special[i], pos); - if (number != null) { - break; - } - } - } - - return number; - } - - /** - * Parse source for an expected fixed string. - * @param source the string to parse - * @param expected expected string - * @param pos input/output parsing parameter. - * @return true if the expected string was there - */ - public static boolean parseFixedstring(final String source, - final String expected, - final ParsePosition pos) { - - final int startIndex = pos.getIndex(); - final int endIndex = startIndex + expected.length(); - if ((startIndex >= source.length()) || - (endIndex > source.length()) || - (source.substring(startIndex, endIndex).compareTo(expected) != 0)) { - // set index back to start, error index should be the start index - pos.setIndex(startIndex); - pos.setErrorIndex(startIndex); - return false; - } - - // the string was here - pos.setIndex(endIndex); - return true; - } - - /** - * Formats a double value to produce a string. In general, the value is - * formatted using the formatting rules of format. There are - * three exceptions to this: - *
    - *
  1. NaN is formatted as '(NaN)'
  2. - *
  3. Positive infinity is formatted as '(Infinity)'
  4. - *
  5. Negative infinity is formatted as '(-Infinity)'
  6. - *
- * - * @param value the double to format. - * @param format the format used. - * @param toAppendTo where the text is to be appended - * @param pos On input: an alignment field, if desired. On output: the - * offsets of the alignment field - * @return the value passed in as toAppendTo. - */ - public static StringBuffer formatDouble(final double value, final NumberFormat format, - final StringBuffer toAppendTo, - final FieldPosition pos) { - if( Double.isNaN(value) || Double.isInfinite(value) ) { - toAppendTo.append('('); - toAppendTo.append(value); - toAppendTo.append(')'); - } else { - format.format(value, toAppendTo, pos); - } - return toAppendTo; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/Decimal64.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/Decimal64.java deleted file mode 100644 index bbd1107ce..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/Decimal64.java +++ /dev/null @@ -1,754 +0,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. - */ -package org.apache.commons.math4.util; - -import org.apache.commons.numbers.arrays.LinearCombination; -import org.apache.commons.math4.Field; -import org.apache.commons.math4.RealFieldElement; -import org.apache.commons.math4.exception.DimensionMismatchException; - -/** - * This class wraps a {@code double} value in an object. It is similar to the - * standard class {@link Double}, while also implementing the - * {@link RealFieldElement} interface. - * - * @since 3.1 - */ -public class Decimal64 extends Number - implements RealFieldElement, Comparable { - - /** The constant value of {@code 0d} as a {@code Decimal64}. */ - public static final Decimal64 ZERO; - - /** The constant value of {@code 1d} as a {@code Decimal64}. */ - public static final Decimal64 ONE; - - /** - * The constant value of {@link Double#NEGATIVE_INFINITY} as a - * {@code Decimal64}. - */ - public static final Decimal64 NEGATIVE_INFINITY; - - /** - * The constant value of {@link Double#POSITIVE_INFINITY} as a - * {@code Decimal64}. - */ - public static final Decimal64 POSITIVE_INFINITY; - - /** The constant value of {@link Double#NaN} as a {@code Decimal64}. */ - public static final Decimal64 NAN; - - /** */ - private static final long serialVersionUID = 20120227L; - - static { - ZERO = new Decimal64(0d); - ONE = new Decimal64(1d); - NEGATIVE_INFINITY = new Decimal64(Double.NEGATIVE_INFINITY); - POSITIVE_INFINITY = new Decimal64(Double.POSITIVE_INFINITY); - NAN = new Decimal64(Double.NaN); - } - - /** The primitive {@code double} value of this object. */ - private final double value; - - /** - * Creates a new instance of this class. - * - * @param x the primitive {@code double} value of the object to be created - */ - public Decimal64(final double x) { - this.value = x; - } - - /* - * Methods from the FieldElement interface. - */ - - /** {@inheritDoc} */ - @Override - public Field getField() { - return Decimal64Field.getInstance(); - } - - /** - * {@inheritDoc} - * - * The current implementation strictly enforces - * {@code this.add(a).equals(new Decimal64(this.doubleValue() - * + a.doubleValue()))}. - */ - @Override - public Decimal64 add(final Decimal64 a) { - return new Decimal64(this.value + a.value); - } - - /** - * {@inheritDoc} - * - * The current implementation strictly enforces - * {@code this.subtract(a).equals(new Decimal64(this.doubleValue() - * - a.doubleValue()))}. - */ - @Override - public Decimal64 subtract(final Decimal64 a) { - return new Decimal64(this.value - a.value); - } - - /** - * {@inheritDoc} - * - * The current implementation strictly enforces - * {@code this.negate().equals(new Decimal64(-this.doubleValue()))}. - */ - @Override - public Decimal64 negate() { - return new Decimal64(-this.value); - } - - /** - * {@inheritDoc} - * - * The current implementation strictly enforces - * {@code this.multiply(a).equals(new Decimal64(this.doubleValue() - * * a.doubleValue()))}. - */ - @Override - public Decimal64 multiply(final Decimal64 a) { - return new Decimal64(this.value * a.value); - } - - /** - * {@inheritDoc} - * - * The current implementation strictly enforces - * {@code this.multiply(n).equals(new Decimal64(n * this.doubleValue()))}. - */ - @Override - public Decimal64 multiply(final int n) { - return new Decimal64(n * this.value); - } - - /** - * {@inheritDoc} - * - * The current implementation strictly enforces - * {@code this.divide(a).equals(new Decimal64(this.doubleValue() - * / a.doubleValue()))}. - * - */ - @Override - public Decimal64 divide(final Decimal64 a) { - return new Decimal64(this.value / a.value); - } - - /** - * {@inheritDoc} - * - * The current implementation strictly enforces - * {@code this.reciprocal().equals(new Decimal64(1.0 - * / this.doubleValue()))}. - */ - @Override - public Decimal64 reciprocal() { - return new Decimal64(1.0 / this.value); - } - - /* - * Methods from the Number abstract class - */ - - /** - * {@inheritDoc} - * - * The current implementation performs casting to a {@code byte}. - */ - @Override - public byte byteValue() { - return (byte) value; - } - - /** - * {@inheritDoc} - * - * The current implementation performs casting to a {@code short}. - */ - @Override - public short shortValue() { - return (short) value; - } - - /** - * {@inheritDoc} - * - * The current implementation performs casting to a {@code int}. - */ - @Override - public int intValue() { - return (int) value; - } - - /** - * {@inheritDoc} - * - * The current implementation performs casting to a {@code long}. - */ - @Override - public long longValue() { - return (long) value; - } - - /** - * {@inheritDoc} - * - * The current implementation performs casting to a {@code float}. - */ - @Override - public float floatValue() { - return (float) value; - } - - /** {@inheritDoc} */ - @Override - public double doubleValue() { - return value; - } - - /* - * Methods from the Comparable interface. - */ - - /** - * {@inheritDoc} - * - * The current implementation returns the same value as - * {@code new Double(this.doubleValue()).compareTo(new - * Double(o.doubleValue()))} - * - * @see Double#compareTo(Double) - */ - @Override - public int compareTo(final Decimal64 o) { - return Double.compare(this.value, o.value); - } - - /* - * Methods from the Object abstract class. - */ - - /** {@inheritDoc} */ - @Override - public boolean equals(final Object obj) { - if (obj instanceof Decimal64) { - final Decimal64 that = (Decimal64) obj; - return Double.doubleToLongBits(this.value) == Double - .doubleToLongBits(that.value); - } - return false; - } - - /** - * {@inheritDoc} - * - * The current implementation returns the same value as - * {@code new Double(this.doubleValue()).hashCode()} - * - * @see Double#hashCode() - */ - @Override - public int hashCode() { - long v = Double.doubleToLongBits(value); - return (int) (v ^ (v >>> 32)); - } - - /** - * {@inheritDoc} - * - * The returned {@code String} is equal to - * {@code Double.toString(this.doubleValue())} - * - * @see Double#toString(double) - */ - @Override - public String toString() { - return Double.toString(value); - } - - /* - * Methods inspired by the Double class. - */ - - /** - * Returns {@code true} if {@code this} double precision number is infinite - * ({@link Double#POSITIVE_INFINITY} or {@link Double#NEGATIVE_INFINITY}). - * - * @return {@code true} if {@code this} number is infinite - */ - public boolean isInfinite() { - return Double.isInfinite(value); - } - - /** - * Returns {@code true} if {@code this} double precision number is - * Not-a-Number ({@code NaN}), false otherwise. - * - * @return {@code true} if {@code this} is {@code NaN} - */ - public boolean isNaN() { - return Double.isNaN(value); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public double getReal() { - return value; - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 add(final double a) { - return new Decimal64(value + a); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 subtract(final double a) { - return new Decimal64(value - a); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 multiply(final double a) { - return new Decimal64(value * a); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 divide(final double a) { - return new Decimal64(value / a); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 remainder(final double a) { - return new Decimal64(FastMath.IEEEremainder(value, a)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 remainder(final Decimal64 a) { - return new Decimal64(FastMath.IEEEremainder(value, a.value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 abs() { - return new Decimal64(FastMath.abs(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 ceil() { - return new Decimal64(FastMath.ceil(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 floor() { - return new Decimal64(FastMath.floor(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 rint() { - return new Decimal64(FastMath.rint(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public long round() { - return FastMath.round(value); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 signum() { - return new Decimal64(FastMath.signum(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 copySign(final Decimal64 sign) { - return new Decimal64(FastMath.copySign(value, sign.value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 copySign(final double sign) { - return new Decimal64(FastMath.copySign(value, sign)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 scalb(final int n) { - return new Decimal64(FastMath.scalb(value, n)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 hypot(final Decimal64 y) { - return new Decimal64(FastMath.hypot(value, y.value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 sqrt() { - return new Decimal64(FastMath.sqrt(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 cbrt() { - return new Decimal64(FastMath.cbrt(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 rootN(final int n) { - if (value < 0) { - return new Decimal64(-FastMath.pow(-value, 1.0 / n)); - } else { - return new Decimal64(FastMath.pow(value, 1.0 / n)); - } - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 pow(final double p) { - return new Decimal64(FastMath.pow(value, p)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 pow(final int n) { - return new Decimal64(FastMath.pow(value, n)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 pow(final Decimal64 e) { - return new Decimal64(FastMath.pow(value, e.value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 exp() { - return new Decimal64(FastMath.exp(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 expm1() { - return new Decimal64(FastMath.expm1(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 log() { - return new Decimal64(FastMath.log(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 log1p() { - return new Decimal64(FastMath.log1p(value)); - } - - /** Base 10 logarithm. - * @return base 10 logarithm of the instance - * @since 3.2 - */ - @Override - public Decimal64 log10() { - return new Decimal64(FastMath.log10(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 cos() { - return new Decimal64(FastMath.cos(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 sin() { - return new Decimal64(FastMath.sin(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 tan() { - return new Decimal64(FastMath.tan(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 acos() { - return new Decimal64(FastMath.acos(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 asin() { - return new Decimal64(FastMath.asin(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 atan() { - return new Decimal64(FastMath.atan(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 atan2(final Decimal64 x) { - return new Decimal64(FastMath.atan2(value, x.value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 cosh() { - return new Decimal64(FastMath.cosh(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 sinh() { - return new Decimal64(FastMath.sinh(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 tanh() { - return new Decimal64(FastMath.tanh(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 acosh() { - return new Decimal64(FastMath.acosh(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 asinh() { - return new Decimal64(FastMath.asinh(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 atanh() { - return new Decimal64(FastMath.atanh(value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 linearCombination(final Decimal64[] a, final Decimal64[] b) - throws DimensionMismatchException { - if (a.length != b.length) { - throw new DimensionMismatchException(a.length, b.length); - } - final double[] aDouble = new double[a.length]; - final double[] bDouble = new double[b.length]; - for (int i = 0; i < a.length; ++i) { - aDouble[i] = a[i].value; - bDouble[i] = b[i].value; - } - return new Decimal64(LinearCombination.value(aDouble, bDouble)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 linearCombination(final double[] a, final Decimal64[] b) - throws DimensionMismatchException { - if (a.length != b.length) { - throw new DimensionMismatchException(a.length, b.length); - } - final double[] bDouble = new double[b.length]; - for (int i = 0; i < a.length; ++i) { - bDouble[i] = b[i].value; - } - return new Decimal64(LinearCombination.value(a, bDouble)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 linearCombination(final Decimal64 a1, final Decimal64 b1, - final Decimal64 a2, final Decimal64 b2) { - return new Decimal64(LinearCombination.value(a1.value, b1.value, - a2.value, b2.value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 linearCombination(final double a1, final Decimal64 b1, - final double a2, final Decimal64 b2) { - return new Decimal64(LinearCombination.value(a1, b1.value, - a2, b2.value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 linearCombination(final Decimal64 a1, final Decimal64 b1, - final Decimal64 a2, final Decimal64 b2, - final Decimal64 a3, final Decimal64 b3) { - return new Decimal64(LinearCombination.value(a1.value, b1.value, - a2.value, b2.value, - a3.value, b3.value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 linearCombination(final double a1, final Decimal64 b1, - final double a2, final Decimal64 b2, - final double a3, final Decimal64 b3) { - return new Decimal64(LinearCombination.value(a1, b1.value, - a2, b2.value, - a3, b3.value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 linearCombination(final Decimal64 a1, final Decimal64 b1, - final Decimal64 a2, final Decimal64 b2, - final Decimal64 a3, final Decimal64 b3, - final Decimal64 a4, final Decimal64 b4) { - return new Decimal64(LinearCombination.value(a1.value, b1.value, - a2.value, b2.value, - a3.value, b3.value, - a4.value, b4.value)); - } - - /** {@inheritDoc} - * @since 3.2 - */ - @Override - public Decimal64 linearCombination(final double a1, final Decimal64 b1, - final double a2, final Decimal64 b2, - final double a3, final Decimal64 b3, - final double a4, final Decimal64 b4) { - return new Decimal64(LinearCombination.value(a1, b1.value, - a2, b2.value, - a3, b3.value, - a4, b4.value)); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/Decimal64Field.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/Decimal64Field.java deleted file mode 100644 index c0a401da4..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/Decimal64Field.java +++ /dev/null @@ -1,64 +0,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. - */ -package org.apache.commons.math4.util; - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; - -/** - * The field of double precision floating-point numbers. - * - * @since 3.1 - * @see Decimal64 - */ -public class Decimal64Field implements Field { - - /** The unique instance of this class. */ - private static final Decimal64Field INSTANCE = new Decimal64Field(); - - /** Default constructor. */ - private Decimal64Field() { - // Do nothing - } - - /** - * Returns the unique instance of this class. - * - * @return the unique instance of this class - */ - public static final Decimal64Field getInstance() { - return INSTANCE; - } - - /** {@inheritDoc} */ - @Override - public Decimal64 getZero() { - return Decimal64.ZERO; - } - - /** {@inheritDoc} */ - @Override - public Decimal64 getOne() { - return Decimal64.ONE; - } - - /** {@inheritDoc} */ - @Override - public Class> getRuntimeClass() { - return Decimal64.class; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/DefaultTransformer.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/DefaultTransformer.java deleted file mode 100644 index b0d8d04c4..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/DefaultTransformer.java +++ /dev/null @@ -1,81 +0,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. - */ - -package org.apache.commons.math4.util; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * A Default NumberTransformer for java.lang.Numbers and Numeric Strings. This - * provides some simple conversion capabilities to turn any java.lang.Number - * into a primitive double or to turn a String representation of a Number into - * a double. - */ -public class DefaultTransformer implements NumberTransformer, Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 4019938025047800455L; - - /** - * @param o the object that gets transformed. - * @return a double primitive representation of the Object o. - * @throws NullArgumentException if Object o is {@code null}. - * @throws MathIllegalArgumentException if Object o - * cannot successfully be transformed - * @see Commons Collections Transformer - */ - @Override - public double transform(Object o) - throws NullArgumentException, MathIllegalArgumentException { - - if (o == null) { - throw new NullArgumentException(LocalizedFormats.OBJECT_TRANSFORMATION); - } - - if (o instanceof Number) { - return ((Number)o).doubleValue(); - } - - try { - return Double.parseDouble(o.toString()); - } catch (NumberFormatException e) { - throw new MathIllegalArgumentException(LocalizedFormats.CANNOT_TRANSFORM_TO_DOUBLE, - o.toString()); - } - } - - /** {@inheritDoc} */ - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - return other instanceof DefaultTransformer; - } - - /** {@inheritDoc} */ - @Override - public int hashCode() { - // some arbitrary number ... - return 401993047; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/DoubleArray.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/DoubleArray.java deleted file mode 100644 index 371bd84a4..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/DoubleArray.java +++ /dev/null @@ -1,110 +0,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. - */ -package org.apache.commons.math4.util; - - -/** - * Provides a standard interface for double arrays. Allows different - * array implementations to support various storage mechanisms - * such as automatic expansion, contraction, and array "rolling". - * - */ -public interface DoubleArray { - - /** - * Returns the number of elements currently in the array. Please note - * that this may be different from the length of the internal storage array. - * - * @return number of elements - */ - int getNumElements(); - - /** - * Returns the element at the specified index. Note that if an - * out of bounds index is supplied a ArrayIndexOutOfBoundsException - * will be thrown. - * - * @param index index to fetch a value from - * @return value stored at the specified index - * @throws ArrayIndexOutOfBoundsException if index is less than - * zero or is greater than getNumElements() - 1. - */ - double getElement(int index); - - /** - * Sets the element at the specified index. If the specified index is greater than - * getNumElements() - 1, the numElements property - * is increased to index +1 and additional storage is allocated - * (if necessary) for the new element and all (uninitialized) elements - * between the new element and the previous end of the array). - * - * @param index index to store a value in - * @param value value to store at the specified index - * @throws ArrayIndexOutOfBoundsException if index is less than - * zero. - */ - void setElement(int index, double value); - - /** - * Adds an element to the end of this expandable array - * - * @param value to be added to end of array - */ - void addElement(double value); - - /** - * Adds elements to the end of this expandable array - * - * @param values to be added to end of array - */ - void addElements(double[] values); - - /** - *

- * Adds an element to the end of the array and removes the first - * element in the array. Returns the discarded first element. - * The effect is similar to a push operation in a FIFO queue. - *

- *

- * Example: If the array contains the elements 1, 2, 3, 4 (in that order) - * and addElementRolling(5) is invoked, the result is an array containing - * the entries 2, 3, 4, 5 and the value returned is 1. - *

- * - * @param value the value to be added to the array - * @return the value which has been discarded or "pushed" out of the array - * by this rolling insert - */ - double addElementRolling(double value); - - /** - * Returns a double[] array containing the elements of this - * DoubleArray. If the underlying implementation is - * array-based, this method should always return a copy, rather than a - * reference to the underlying array so that changes made to the returned - * array have no effect on the DoubleArray. - * - * @return all elements added to the array - */ - double[] getElements(); - - /** - * Clear the double array - */ - void clear(); - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/FastMath.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/FastMath.java deleted file mode 100644 index 4d0568a32..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/FastMath.java +++ /dev/null @@ -1,4345 +0,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. - */ -package org.apache.commons.math4.util; - -import java.io.PrintStream; - -import org.apache.commons.numbers.core.Precision; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Faster, more accurate, portable alternative to {@link Math} and - * {@link StrictMath} for large scale computation. - *

- * FastMath is a drop-in replacement for both Math and StrictMath. This - * means that for any method in Math (say {@code Math.sin(x)} or - * {@code Math.cbrt(y)}), user can directly change the class and use the - * methods as is (using {@code FastMath.sin(x)} or {@code FastMath.cbrt(y)} - * in the previous example). - *

- *

- * FastMath speed is achieved by relying heavily on optimizing compilers - * to native code present in many JVMs today and use of large tables. - * The larger tables are lazily initialized on first use, so that the setup - * time does not penalize methods that don't need them. - *

- *

- * Note that FastMath is - * extensively used inside Apache Commons Math, so by calling some algorithms, - * the overhead when the tables need to be initialized will occur - * regardless of the end-user calling FastMath methods directly or not. - * Performance figures for a specific JVM and hardware can be evaluated by - * running the FastMathTestPerformance tests in the test directory of the source - * distribution. - *

- *

- * FastMath accuracy should be mostly independent of the JVM as it relies only - * on IEEE-754 basic operations and on embedded tables. Almost all operations - * are accurate to about 0.5 ulp throughout the domain range. This statement, - * of course is only a rough global observed behavior, it is not a - * guarantee for every double numbers input (see William Kahan's Table - * Maker's Dilemma). - *

- *

- * FastMath additionally implements the following methods not found in Math/StrictMath: - *

    - *
  • {@link #asinh(double)}
  • - *
  • {@link #acosh(double)}
  • - *
  • {@link #atanh(double)}
  • - *
- * The following methods are found in Math/StrictMath since 1.6 only, they are provided - * by FastMath even in 1.5 Java virtual machines - *
    - *
  • {@link #copySign(double, double)}
  • - *
  • {@link #getExponent(double)}
  • - *
  • {@link #nextAfter(double,double)}
  • - *
  • {@link #nextUp(double)}
  • - *
  • {@link #scalb(double, int)}
  • - *
  • {@link #copySign(float, float)}
  • - *
  • {@link #getExponent(float)}
  • - *
  • {@link #nextAfter(float,double)}
  • - *
  • {@link #nextUp(float)}
  • - *
  • {@link #scalb(float, int)}
  • - *
- * @since 2.2 - */ -public class FastMath { - /** Archimede's constant PI, ratio of circle circumference to diameter. */ - public static final double PI = 105414357.0 / 33554432.0 + 1.984187159361080883e-9; - - /** Napier's constant e, base of the natural logarithm. */ - public static final double E = 2850325.0 / 1048576.0 + 8.254840070411028747e-8; - - /** Index of exp(0) in the array of integer exponentials. */ - static final int EXP_INT_TABLE_MAX_INDEX = 750; - /** Length of the array of integer exponentials. */ - static final int EXP_INT_TABLE_LEN = EXP_INT_TABLE_MAX_INDEX * 2; - /** Logarithm table length. */ - static final int LN_MANT_LEN = 1024; - /** Exponential fractions table length. */ - static final int EXP_FRAC_TABLE_LEN = 1025; // 0, 1/1024, ... 1024/1024 - - /** StrictMath.log(Double.MAX_VALUE): {@value} */ - private static final double LOG_MAX_VALUE = StrictMath.log(Double.MAX_VALUE); - - /** Indicator for tables initialization. - *

- * This compile-time constant should be set to true only if one explicitly - * wants to compute the tables at class loading time instead of using the - * already computed ones provided as literal arrays below. - *

- */ - private static final boolean RECOMPUTE_TABLES_AT_RUNTIME = false; - - /** log(2) (high bits). */ - private static final double LN_2_A = 0.693147063255310059; - - /** log(2) (low bits). */ - private static final double LN_2_B = 1.17304635250823482e-7; - - /** Coefficients for log, when input 0.99 < x < 1.01. */ - private static final double LN_QUICK_COEF[][] = { - {1.0, 5.669184079525E-24}, - {-0.25, -0.25}, - {0.3333333134651184, 1.986821492305628E-8}, - {-0.25, -6.663542893624021E-14}, - {0.19999998807907104, 1.1921056801463227E-8}, - {-0.1666666567325592, -7.800414592973399E-9}, - {0.1428571343421936, 5.650007086920087E-9}, - {-0.12502530217170715, -7.44321345601866E-11}, - {0.11113807559013367, 9.219544613762692E-9}, - }; - - /** Coefficients for log in the range of 1.0 < x < 1.0 + 2^-10. */ - private static final double LN_HI_PREC_COEF[][] = { - {1.0, -6.032174644509064E-23}, - {-0.25, -0.25}, - {0.3333333134651184, 1.9868161777724352E-8}, - {-0.2499999701976776, -2.957007209750105E-8}, - {0.19999954104423523, 1.5830993332061267E-10}, - {-0.16624879837036133, -2.6033824355191673E-8} - }; - - /** Sine, Cosine, Tangent tables are for 0, 1/8, 2/8, ... 13/8 = PI/2 approx. */ - private static final int SINE_TABLE_LEN = 14; - - /** Sine table (high bits). */ - private static final double SINE_TABLE_A[] = - { - +0.0d, - +0.1246747374534607d, - +0.24740394949913025d, - +0.366272509098053d, - +0.4794255495071411d, - +0.5850973129272461d, - +0.6816387176513672d, - +0.7675435543060303d, - +0.8414709568023682d, - +0.902267575263977d, - +0.9489846229553223d, - +0.9808930158615112d, - +0.9974949359893799d, - +0.9985313415527344d, - }; - - /** Sine table (low bits). */ - private static final double SINE_TABLE_B[] = - { - +0.0d, - -4.068233003401932E-9d, - +9.755392680573412E-9d, - +1.9987994582857286E-8d, - -1.0902938113007961E-8d, - -3.9986783938944604E-8d, - +4.23719669792332E-8d, - -5.207000323380292E-8d, - +2.800552834259E-8d, - +1.883511811213715E-8d, - -3.5997360512765566E-9d, - +4.116164446561962E-8d, - +5.0614674548127384E-8d, - -1.0129027912496858E-9d, - }; - - /** Cosine table (high bits). */ - private static final double COSINE_TABLE_A[] = - { - +1.0d, - +0.9921976327896118d, - +0.9689123630523682d, - +0.9305076599121094d, - +0.8775825500488281d, - +0.8109631538391113d, - +0.7316888570785522d, - +0.6409968137741089d, - +0.5403022766113281d, - +0.4311765432357788d, - +0.3153223395347595d, - +0.19454771280288696d, - +0.07073719799518585d, - -0.05417713522911072d, - }; - - /** Cosine table (low bits). */ - private static final double COSINE_TABLE_B[] = - { - +0.0d, - +3.4439717236742845E-8d, - +5.865827662008209E-8d, - -3.7999795083850525E-8d, - +1.184154459111628E-8d, - -3.43338934259355E-8d, - +1.1795268640216787E-8d, - +4.438921624363781E-8d, - +2.925681159240093E-8d, - -2.6437112632041807E-8d, - +2.2860509143963117E-8d, - -4.813899778443457E-9d, - +3.6725170580355583E-9d, - +2.0217439756338078E-10d, - }; - - - /** Tangent table, used by atan() (high bits). */ - private static final double TANGENT_TABLE_A[] = - { - +0.0d, - +0.1256551444530487d, - +0.25534194707870483d, - +0.3936265707015991d, - +0.5463024377822876d, - +0.7214844226837158d, - +0.9315965175628662d, - +1.1974215507507324d, - +1.5574076175689697d, - +2.092571258544922d, - +3.0095696449279785d, - +5.041914939880371d, - +14.101419448852539d, - -18.430862426757812d, - }; - - /** Tangent table, used by atan() (low bits). */ - private static final double TANGENT_TABLE_B[] = - { - +0.0d, - -7.877917738262007E-9d, - -2.5857668567479893E-8d, - +5.2240336371356666E-9d, - +5.206150291559893E-8d, - +1.8307188599677033E-8d, - -5.7618793749770706E-8d, - +7.848361555046424E-8d, - +1.0708593250394448E-7d, - +1.7827257129423813E-8d, - +2.893485277253286E-8d, - +3.1660099222737955E-7d, - +4.983191803254889E-7d, - -3.356118100840571E-7d, - }; - - /** Bits of 1/(2*pi), need for reducePayneHanek(). */ - private static final long RECIP_2PI[] = new long[] { - (0x28be60dbL << 32) | 0x9391054aL, - (0x7f09d5f4L << 32) | 0x7d4d3770L, - (0x36d8a566L << 32) | 0x4f10e410L, - (0x7f9458eaL << 32) | 0xf7aef158L, - (0x6dc91b8eL << 32) | 0x909374b8L, - (0x01924bbaL << 32) | 0x82746487L, - (0x3f877ac7L << 32) | 0x2c4a69cfL, - (0xba208d7dL << 32) | 0x4baed121L, - (0x3a671c09L << 32) | 0xad17df90L, - (0x4e64758eL << 32) | 0x60d4ce7dL, - (0x272117e2L << 32) | 0xef7e4a0eL, - (0xc7fe25ffL << 32) | 0xf7816603L, - (0xfbcbc462L << 32) | 0xd6829b47L, - (0xdb4d9fb3L << 32) | 0xc9f2c26dL, - (0xd3d18fd9L << 32) | 0xa797fa8bL, - (0x5d49eeb1L << 32) | 0xfaf97c5eL, - (0xcf41ce7dL << 32) | 0xe294a4baL, - 0x9afed7ecL << 32 }; - - /** Bits of pi/4, need for reducePayneHanek(). */ - private static final long PI_O_4_BITS[] = new long[] { - (0xc90fdaa2L << 32) | 0x2168c234L, - (0xc4c6628bL << 32) | 0x80dc1cd1L }; - - /** Eighths. - * This is used by sinQ, because its faster to do a table lookup than - * a multiply in this time-critical routine - */ - private static final double EIGHTHS[] = {0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0, 1.125, 1.25, 1.375, 1.5, 1.625}; - - /** Table of 2^((n+2)/3) */ - private static final double CBRTTWO[] = { 0.6299605249474366, - 0.7937005259840998, - 1.0, - 1.2599210498948732, - 1.5874010519681994 }; - - /* - * There are 52 bits in the mantissa of a double. - * For additional precision, the code splits double numbers into two parts, - * by clearing the low order 30 bits if possible, and then performs the arithmetic - * on each half separately. - */ - - /** - * 0x40000000 - used to split a double into two parts, both with the low order bits cleared. - * Equivalent to 2^30. - */ - private static final long HEX_40000000 = 0x40000000L; // 1073741824L - - /** Mask used to clear low order 30 bits */ - private static final long MASK_30BITS = -1L - (HEX_40000000 -1); // 0xFFFFFFFFC0000000L; - - /** Mask used to clear the non-sign part of an int. */ - private static final int MASK_NON_SIGN_INT = 0x7fffffff; - - /** Mask used to clear the non-sign part of a long. */ - private static final long MASK_NON_SIGN_LONG = 0x7fffffffffffffffl; - - /** Mask used to extract exponent from double bits. */ - private static final long MASK_DOUBLE_EXPONENT = 0x7ff0000000000000L; - - /** Mask used to extract mantissa from double bits. */ - private static final long MASK_DOUBLE_MANTISSA = 0x000fffffffffffffL; - - /** Mask used to add implicit high order bit for normalized double. */ - private static final long IMPLICIT_HIGH_BIT = 0x0010000000000000L; - - /** 2^52 - double numbers this large must be integral (no fraction) or NaN or Infinite */ - private static final double TWO_POWER_52 = 4503599627370496.0; - - /** Constant: {@value}. */ - private static final double F_1_3 = 1d / 3d; - /** Constant: {@value}. */ - private static final double F_1_5 = 1d / 5d; - /** Constant: {@value}. */ - private static final double F_1_7 = 1d / 7d; - /** Constant: {@value}. */ - private static final double F_1_9 = 1d / 9d; - /** Constant: {@value}. */ - private static final double F_1_11 = 1d / 11d; - /** Constant: {@value}. */ - private static final double F_1_13 = 1d / 13d; - /** Constant: {@value}. */ - private static final double F_1_15 = 1d / 15d; - /** Constant: {@value}. */ - private static final double F_1_17 = 1d / 17d; - /** Constant: {@value}. */ - private static final double F_3_4 = 3d / 4d; - /** Constant: {@value}. */ - private static final double F_15_16 = 15d / 16d; - /** Constant: {@value}. */ - private static final double F_13_14 = 13d / 14d; - /** Constant: {@value}. */ - private static final double F_11_12 = 11d / 12d; - /** Constant: {@value}. */ - private static final double F_9_10 = 9d / 10d; - /** Constant: {@value}. */ - private static final double F_7_8 = 7d / 8d; - /** Constant: {@value}. */ - private static final double F_5_6 = 5d / 6d; - /** Constant: {@value}. */ - private static final double F_1_2 = 1d / 2d; - /** Constant: {@value}. */ - private static final double F_1_4 = 1d / 4d; - - /** - * Private Constructor - */ - private FastMath() {} - - // Generic helper methods - - /** - * Get the high order bits from the mantissa. - * Equivalent to adding and subtracting HEX_40000 but also works for very large numbers - * - * @param d the value to split - * @return the high order part of the mantissa - */ - private static double doubleHighPart(double d) { - if (d > -Precision.SAFE_MIN && d < Precision.SAFE_MIN){ - return d; // These are un-normalised - don't try to convert - } - long xl = Double.doubleToRawLongBits(d); // can take raw bits because just gonna convert it back - xl &= MASK_30BITS; // Drop low order bits - return Double.longBitsToDouble(xl); - } - - /** Compute the square root of a number. - *

Note: this implementation currently delegates to {@link Math#sqrt} - * @param a number on which evaluation is done - * @return square root of a - */ - public static double sqrt(final double a) { - return Math.sqrt(a); - } - - /** Compute the hyperbolic cosine of a number. - * @param x number on which evaluation is done - * @return hyperbolic cosine of x - */ - public static double cosh(double x) { - if (Double.isNaN(x)) { - return x; - } - - // cosh[z] = (exp(z) + exp(-z))/2 - - // for numbers with magnitude 20 or so, - // exp(-z) can be ignored in comparison with exp(z) - - if (x > 20) { - if (x >= LOG_MAX_VALUE) { - // Avoid overflow (MATH-905). - final double t = exp(0.5 * x); - return (0.5 * t) * t; - } else { - return 0.5 * exp(x); - } - } else if (x < -20) { - if (x <= -LOG_MAX_VALUE) { - // Avoid overflow (MATH-905). - final double t = exp(-0.5 * x); - return (0.5 * t) * t; - } else { - return 0.5 * exp(-x); - } - } - - final double hiPrec[] = new double[2]; - if (x < 0.0) { - x = -x; - } - exp(x, 0.0, hiPrec); - - double ya = hiPrec[0] + hiPrec[1]; - double yb = -(ya - hiPrec[0] - hiPrec[1]); - - double temp = ya * HEX_40000000; - double yaa = ya + temp - temp; - double yab = ya - yaa; - - // recip = 1/y - double recip = 1.0/ya; - temp = recip * HEX_40000000; - double recipa = recip + temp - temp; - double recipb = recip - recipa; - - // Correct for rounding in division - recipb += (1.0 - yaa*recipa - yaa*recipb - yab*recipa - yab*recipb) * recip; - // Account for yb - recipb += -yb * recip * recip; - - // y = y + 1/y - temp = ya + recipa; - yb += -(temp - ya - recipa); - ya = temp; - temp = ya + recipb; - yb += -(temp - ya - recipb); - ya = temp; - - double result = ya + yb; - result *= 0.5; - return result; - } - - /** Compute the hyperbolic sine of a number. - * @param x number on which evaluation is done - * @return hyperbolic sine of x - */ - public static double sinh(double x) { - boolean negate = false; - if (Double.isNaN(x)) { - return x; - } - - // sinh[z] = (exp(z) - exp(-z) / 2 - - // for values of z larger than about 20, - // exp(-z) can be ignored in comparison with exp(z) - - if (x > 20) { - if (x >= LOG_MAX_VALUE) { - // Avoid overflow (MATH-905). - final double t = exp(0.5 * x); - return (0.5 * t) * t; - } else { - return 0.5 * exp(x); - } - } else if (x < -20) { - if (x <= -LOG_MAX_VALUE) { - // Avoid overflow (MATH-905). - final double t = exp(-0.5 * x); - return (-0.5 * t) * t; - } else { - return -0.5 * exp(-x); - } - } - - if (x == 0) { - return x; - } - - if (x < 0.0) { - x = -x; - negate = true; - } - - double result; - - if (x > 0.25) { - double hiPrec[] = new double[2]; - exp(x, 0.0, hiPrec); - - double ya = hiPrec[0] + hiPrec[1]; - double yb = -(ya - hiPrec[0] - hiPrec[1]); - - double temp = ya * HEX_40000000; - double yaa = ya + temp - temp; - double yab = ya - yaa; - - // recip = 1/y - double recip = 1.0/ya; - temp = recip * HEX_40000000; - double recipa = recip + temp - temp; - double recipb = recip - recipa; - - // Correct for rounding in division - recipb += (1.0 - yaa*recipa - yaa*recipb - yab*recipa - yab*recipb) * recip; - // Account for yb - recipb += -yb * recip * recip; - - recipa = -recipa; - recipb = -recipb; - - // y = y + 1/y - temp = ya + recipa; - yb += -(temp - ya - recipa); - ya = temp; - temp = ya + recipb; - yb += -(temp - ya - recipb); - ya = temp; - - result = ya + yb; - result *= 0.5; - } - else { - double hiPrec[] = new double[2]; - expm1(x, hiPrec); - - double ya = hiPrec[0] + hiPrec[1]; - double yb = -(ya - hiPrec[0] - hiPrec[1]); - - /* Compute expm1(-x) = -expm1(x) / (expm1(x) + 1) */ - double denom = 1.0 + ya; - double denomr = 1.0 / denom; - double denomb = -(denom - 1.0 - ya) + yb; - double ratio = ya * denomr; - double temp = ratio * HEX_40000000; - double ra = ratio + temp - temp; - double rb = ratio - ra; - - temp = denom * HEX_40000000; - double za = denom + temp - temp; - double zb = denom - za; - - rb += (ya - za*ra - za*rb - zb*ra - zb*rb) * denomr; - - // Adjust for yb - rb += yb*denomr; // numerator - rb += -ya * denomb * denomr * denomr; // denominator - - // y = y - 1/y - temp = ya + ra; - yb += -(temp - ya - ra); - ya = temp; - temp = ya + rb; - yb += -(temp - ya - rb); - ya = temp; - - result = ya + yb; - result *= 0.5; - } - - if (negate) { - result = -result; - } - - return result; - } - - /** Compute the hyperbolic tangent of a number. - * @param x number on which evaluation is done - * @return hyperbolic tangent of x - */ - public static double tanh(double x) { - boolean negate = false; - - if (Double.isNaN(x)) { - return x; - } - - // tanh[z] = sinh[z] / cosh[z] - // = (exp(z) - exp(-z)) / (exp(z) + exp(-z)) - // = (exp(2x) - 1) / (exp(2x) + 1) - - // for magnitude > 20, sinh[z] == cosh[z] in double precision - - if (x > 20.0) { - return 1.0; - } - - if (x < -20) { - return -1.0; - } - - if (x == 0) { - return x; - } - - if (x < 0.0) { - x = -x; - negate = true; - } - - double result; - if (x >= 0.5) { - double hiPrec[] = new double[2]; - // tanh(x) = (exp(2x) - 1) / (exp(2x) + 1) - exp(x*2.0, 0.0, hiPrec); - - double ya = hiPrec[0] + hiPrec[1]; - double yb = -(ya - hiPrec[0] - hiPrec[1]); - - /* Numerator */ - double na = -1.0 + ya; - double nb = -(na + 1.0 - ya); - double temp = na + yb; - nb += -(temp - na - yb); - na = temp; - - /* Denominator */ - double da = 1.0 + ya; - double db = -(da - 1.0 - ya); - temp = da + yb; - db += -(temp - da - yb); - da = temp; - - temp = da * HEX_40000000; - double daa = da + temp - temp; - double dab = da - daa; - - // ratio = na/da - double ratio = na/da; - temp = ratio * HEX_40000000; - double ratioa = ratio + temp - temp; - double ratiob = ratio - ratioa; - - // Correct for rounding in division - ratiob += (na - daa*ratioa - daa*ratiob - dab*ratioa - dab*ratiob) / da; - - // Account for nb - ratiob += nb / da; - // Account for db - ratiob += -db * na / da / da; - - result = ratioa + ratiob; - } - else { - double hiPrec[] = new double[2]; - // tanh(x) = expm1(2x) / (expm1(2x) + 2) - expm1(x*2.0, hiPrec); - - double ya = hiPrec[0] + hiPrec[1]; - double yb = -(ya - hiPrec[0] - hiPrec[1]); - - /* Numerator */ - double na = ya; - double nb = yb; - - /* Denominator */ - double da = 2.0 + ya; - double db = -(da - 2.0 - ya); - double temp = da + yb; - db += -(temp - da - yb); - da = temp; - - temp = da * HEX_40000000; - double daa = da + temp - temp; - double dab = da - daa; - - // ratio = na/da - double ratio = na/da; - temp = ratio * HEX_40000000; - double ratioa = ratio + temp - temp; - double ratiob = ratio - ratioa; - - // Correct for rounding in division - ratiob += (na - daa*ratioa - daa*ratiob - dab*ratioa - dab*ratiob) / da; - - // Account for nb - ratiob += nb / da; - // Account for db - ratiob += -db * na / da / da; - - result = ratioa + ratiob; - } - - if (negate) { - result = -result; - } - - return result; - } - - /** Compute the inverse hyperbolic cosine of a number. - * @param a number on which evaluation is done - * @return inverse hyperbolic cosine of a - */ - public static double acosh(final double a) { - return FastMath.log(a + FastMath.sqrt(a * a - 1)); - } - - /** Compute the inverse hyperbolic sine of a number. - * @param a number on which evaluation is done - * @return inverse hyperbolic sine of a - */ - public static double asinh(double a) { - boolean negative = false; - if (a < 0) { - negative = true; - a = -a; - } - - double absAsinh; - if (a > 0.167) { - absAsinh = FastMath.log(FastMath.sqrt(a * a + 1) + a); - } else { - final double a2 = a * a; - if (a > 0.097) { - absAsinh = a * (1 - a2 * (F_1_3 - a2 * (F_1_5 - a2 * (F_1_7 - a2 * (F_1_9 - a2 * (F_1_11 - a2 * (F_1_13 - a2 * (F_1_15 - a2 * F_1_17 * F_15_16) * F_13_14) * F_11_12) * F_9_10) * F_7_8) * F_5_6) * F_3_4) * F_1_2); - } else if (a > 0.036) { - absAsinh = a * (1 - a2 * (F_1_3 - a2 * (F_1_5 - a2 * (F_1_7 - a2 * (F_1_9 - a2 * (F_1_11 - a2 * F_1_13 * F_11_12) * F_9_10) * F_7_8) * F_5_6) * F_3_4) * F_1_2); - } else if (a > 0.0036) { - absAsinh = a * (1 - a2 * (F_1_3 - a2 * (F_1_5 - a2 * (F_1_7 - a2 * F_1_9 * F_7_8) * F_5_6) * F_3_4) * F_1_2); - } else { - absAsinh = a * (1 - a2 * (F_1_3 - a2 * F_1_5 * F_3_4) * F_1_2); - } - } - - return negative ? -absAsinh : absAsinh; - } - - /** Compute the inverse hyperbolic tangent of a number. - * @param a number on which evaluation is done - * @return inverse hyperbolic tangent of a - */ - public static double atanh(double a) { - boolean negative = false; - if (a < 0) { - negative = true; - a = -a; - } - - double absAtanh; - if (a > 0.15) { - absAtanh = 0.5 * FastMath.log((1 + a) / (1 - a)); - } else { - final double a2 = a * a; - if (a > 0.087) { - absAtanh = a * (1 + a2 * (F_1_3 + a2 * (F_1_5 + a2 * (F_1_7 + a2 * (F_1_9 + a2 * (F_1_11 + a2 * (F_1_13 + a2 * (F_1_15 + a2 * F_1_17)))))))); - } else if (a > 0.031) { - absAtanh = a * (1 + a2 * (F_1_3 + a2 * (F_1_5 + a2 * (F_1_7 + a2 * (F_1_9 + a2 * (F_1_11 + a2 * F_1_13)))))); - } else if (a > 0.003) { - absAtanh = a * (1 + a2 * (F_1_3 + a2 * (F_1_5 + a2 * (F_1_7 + a2 * F_1_9)))); - } else { - absAtanh = a * (1 + a2 * (F_1_3 + a2 * F_1_5)); - } - } - - return negative ? -absAtanh : absAtanh; - } - - /** Compute the signum of a number. - * The signum is -1 for negative numbers, +1 for positive numbers and 0 otherwise - * @param a number on which evaluation is done - * @return -1.0, -0.0, +0.0, +1.0 or NaN depending on sign of a - */ - public static double signum(final double a) { - return (a < 0.0) ? -1.0 : ((a > 0.0) ? 1.0 : a); // return +0.0/-0.0/NaN depending on a - } - - /** Compute the signum of a number. - * The signum is -1 for negative numbers, +1 for positive numbers and 0 otherwise - * @param a number on which evaluation is done - * @return -1.0, -0.0, +0.0, +1.0 or NaN depending on sign of a - */ - public static float signum(final float a) { - return (a < 0.0f) ? -1.0f : ((a > 0.0f) ? 1.0f : a); // return +0.0/-0.0/NaN depending on a - } - - /** Compute next number towards positive infinity. - * @param a number to which neighbor should be computed - * @return neighbor of a towards positive infinity - */ - public static double nextUp(final double a) { - return nextAfter(a, Double.POSITIVE_INFINITY); - } - - /** Compute next number towards positive infinity. - * @param a number to which neighbor should be computed - * @return neighbor of a towards positive infinity - */ - public static float nextUp(final float a) { - return nextAfter(a, Float.POSITIVE_INFINITY); - } - - /** Compute next number towards negative infinity. - * @param a number to which neighbor should be computed - * @return neighbor of a towards negative infinity - * @since 3.4 - */ - public static double nextDown(final double a) { - return nextAfter(a, Double.NEGATIVE_INFINITY); - } - - /** Compute next number towards negative infinity. - * @param a number to which neighbor should be computed - * @return neighbor of a towards negative infinity - * @since 3.4 - */ - public static float nextDown(final float a) { - return nextAfter(a, Float.NEGATIVE_INFINITY); - } - - /** Returns a pseudo-random number between 0.0 and 1.0. - *

Note: this implementation currently delegates to {@link Math#random} - * @return a random number between 0.0 and 1.0 - */ - public static double random() { - return Math.random(); - } - - /** - * Exponential function. - * - * Computes exp(x), function result is nearly rounded. It will be correctly - * rounded to the theoretical value for 99.9% of input values, otherwise it will - * have a 1 ULP error. - * - * Method: - * Lookup intVal = exp(int(x)) - * Lookup fracVal = exp(int(x-int(x) / 1024.0) * 1024.0 ); - * Compute z as the exponential of the remaining bits by a polynomial minus one - * exp(x) = intVal * fracVal * (1 + z) - * - * Accuracy: - * Calculation is done with 63 bits of precision, so result should be correctly - * rounded for 99.9% of input values, with less than 1 ULP error otherwise. - * - * @param x a double - * @return double ex - */ - public static double exp(double x) { - return exp(x, 0.0, null); - } - - /** - * Internal helper method for exponential function. - * @param x original argument of the exponential function - * @param extra extra bits of precision on input (To Be Confirmed) - * @param hiPrec extra bits of precision on output (To Be Confirmed) - * @return exp(x) - */ - private static double exp(double x, double extra, double[] hiPrec) { - double intPartA; - double intPartB; - int intVal = (int) x; - - /* Lookup exp(floor(x)). - * intPartA will have the upper 22 bits, intPartB will have the lower - * 52 bits. - */ - if (x < 0.0) { - - // We don't check against intVal here as conversion of large negative double values - // may be affected by a JIT bug. Subsequent comparisons can safely use intVal - if (x < -746d) { - if (hiPrec != null) { - hiPrec[0] = 0.0; - hiPrec[1] = 0.0; - } - return 0.0; - } - - if (intVal < -709) { - /* This will produce a subnormal output */ - final double result = exp(x+40.19140625, extra, hiPrec) / 285040095144011776.0; - if (hiPrec != null) { - hiPrec[0] /= 285040095144011776.0; - hiPrec[1] /= 285040095144011776.0; - } - return result; - } - - if (intVal == -709) { - /* exp(1.494140625) is nearly a machine number... */ - final double result = exp(x+1.494140625, extra, hiPrec) / 4.455505956692756620; - if (hiPrec != null) { - hiPrec[0] /= 4.455505956692756620; - hiPrec[1] /= 4.455505956692756620; - } - return result; - } - - intVal--; - - } else { - if (intVal > 709) { - if (hiPrec != null) { - hiPrec[0] = Double.POSITIVE_INFINITY; - hiPrec[1] = 0.0; - } - return Double.POSITIVE_INFINITY; - } - - } - - intPartA = ExpIntTable.EXP_INT_TABLE_A[EXP_INT_TABLE_MAX_INDEX+intVal]; - intPartB = ExpIntTable.EXP_INT_TABLE_B[EXP_INT_TABLE_MAX_INDEX+intVal]; - - /* Get the fractional part of x, find the greatest multiple of 2^-10 less than - * x and look up the exp function of it. - * fracPartA will have the upper 22 bits, fracPartB the lower 52 bits. - */ - final int intFrac = (int) ((x - intVal) * 1024.0); - final double fracPartA = ExpFracTable.EXP_FRAC_TABLE_A[intFrac]; - final double fracPartB = ExpFracTable.EXP_FRAC_TABLE_B[intFrac]; - - /* epsilon is the difference in x from the nearest multiple of 2^-10. It - * has a value in the range 0 <= epsilon < 2^-10. - * Do the subtraction from x as the last step to avoid possible loss of precision. - */ - final double epsilon = x - (intVal + intFrac / 1024.0); - - /* Compute z = exp(epsilon) - 1.0 via a minimax polynomial. z has - full double precision (52 bits). Since z < 2^-10, we will have - 62 bits of precision when combined with the constant 1. This will be - used in the last addition below to get proper rounding. */ - - /* Remez generated polynomial. Converges on the interval [0, 2^-10], error - is less than 0.5 ULP */ - double z = 0.04168701738764507; - z = z * epsilon + 0.1666666505023083; - z = z * epsilon + 0.5000000000042687; - z = z * epsilon + 1.0; - z = z * epsilon + -3.940510424527919E-20; - - /* Compute (intPartA+intPartB) * (fracPartA+fracPartB) by binomial - expansion. - tempA is exact since intPartA and intPartB only have 22 bits each. - tempB will have 52 bits of precision. - */ - double tempA = intPartA * fracPartA; - double tempB = intPartA * fracPartB + intPartB * fracPartA + intPartB * fracPartB; - - /* Compute the result. (1+z)(tempA+tempB). Order of operations is - important. For accuracy add by increasing size. tempA is exact and - much larger than the others. If there are extra bits specified from the - pow() function, use them. */ - final double tempC = tempB + tempA; - - // If tempC is positive infinite, the evaluation below could result in NaN, - // because z could be negative at the same time. - if (tempC == Double.POSITIVE_INFINITY) { - return Double.POSITIVE_INFINITY; - } - - final double result; - if (extra != 0.0) { - result = tempC*extra*z + tempC*extra + tempC*z + tempB + tempA; - } else { - result = tempC*z + tempB + tempA; - } - - if (hiPrec != null) { - // If requesting high precision - hiPrec[0] = tempA; - hiPrec[1] = tempC*extra*z + tempC*extra + tempC*z + tempB; - } - - return result; - } - - /** Compute exp(x) - 1 - * @param x number to compute shifted exponential - * @return exp(x) - 1 - */ - public static double expm1(double x) { - return expm1(x, null); - } - - /** Internal helper method for expm1 - * @param x number to compute shifted exponential - * @param hiPrecOut receive high precision result for -1.0 < x < 1.0 - * @return exp(x) - 1 - */ - private static double expm1(double x, double hiPrecOut[]) { - if (Double.isNaN(x) || x == 0.0) { // NaN or zero - return x; - } - - if (x <= -1.0 || x >= 1.0) { - // If not between +/- 1.0 - //return exp(x) - 1.0; - double hiPrec[] = new double[2]; - exp(x, 0.0, hiPrec); - if (x > 0.0) { - return -1.0 + hiPrec[0] + hiPrec[1]; - } else { - final double ra = -1.0 + hiPrec[0]; - double rb = -(ra + 1.0 - hiPrec[0]); - rb += hiPrec[1]; - return ra + rb; - } - } - - double baseA; - double baseB; - double epsilon; - boolean negative = false; - - if (x < 0.0) { - x = -x; - negative = true; - } - - { - int intFrac = (int) (x * 1024.0); - double tempA = ExpFracTable.EXP_FRAC_TABLE_A[intFrac] - 1.0; - double tempB = ExpFracTable.EXP_FRAC_TABLE_B[intFrac]; - - double temp = tempA + tempB; - tempB = -(temp - tempA - tempB); - tempA = temp; - - temp = tempA * HEX_40000000; - baseA = tempA + temp - temp; - baseB = tempB + (tempA - baseA); - - epsilon = x - intFrac/1024.0; - } - - - /* Compute expm1(epsilon) */ - double zb = 0.008336750013465571; - zb = zb * epsilon + 0.041666663879186654; - zb = zb * epsilon + 0.16666666666745392; - zb = zb * epsilon + 0.49999999999999994; - zb *= epsilon; - zb *= epsilon; - - double za = epsilon; - double temp = za + zb; - zb = -(temp - za - zb); - za = temp; - - temp = za * HEX_40000000; - temp = za + temp - temp; - zb += za - temp; - za = temp; - - /* Combine the parts. expm1(a+b) = expm1(a) + expm1(b) + expm1(a)*expm1(b) */ - double ya = za * baseA; - //double yb = za*baseB + zb*baseA + zb*baseB; - temp = ya + za * baseB; - double yb = -(temp - ya - za * baseB); - ya = temp; - - temp = ya + zb * baseA; - yb += -(temp - ya - zb * baseA); - ya = temp; - - temp = ya + zb * baseB; - yb += -(temp - ya - zb*baseB); - ya = temp; - - //ya = ya + za + baseA; - //yb = yb + zb + baseB; - temp = ya + baseA; - yb += -(temp - baseA - ya); - ya = temp; - - temp = ya + za; - //yb += (ya > za) ? -(temp - ya - za) : -(temp - za - ya); - yb += -(temp - ya - za); - ya = temp; - - temp = ya + baseB; - //yb += (ya > baseB) ? -(temp - ya - baseB) : -(temp - baseB - ya); - yb += -(temp - ya - baseB); - ya = temp; - - temp = ya + zb; - //yb += (ya > zb) ? -(temp - ya - zb) : -(temp - zb - ya); - yb += -(temp - ya - zb); - ya = temp; - - if (negative) { - /* Compute expm1(-x) = -expm1(x) / (expm1(x) + 1) */ - double denom = 1.0 + ya; - double denomr = 1.0 / denom; - double denomb = -(denom - 1.0 - ya) + yb; - double ratio = ya * denomr; - temp = ratio * HEX_40000000; - final double ra = ratio + temp - temp; - double rb = ratio - ra; - - temp = denom * HEX_40000000; - za = denom + temp - temp; - zb = denom - za; - - rb += (ya - za * ra - za * rb - zb * ra - zb * rb) * denomr; - - // f(x) = x/1+x - // Compute f'(x) - // Product rule: d(uv) = du*v + u*dv - // Chain rule: d(f(g(x)) = f'(g(x))*f(g'(x)) - // d(1/x) = -1/(x*x) - // d(1/1+x) = -1/( (1+x)^2) * 1 = -1/((1+x)*(1+x)) - // d(x/1+x) = -x/((1+x)(1+x)) + 1/1+x = 1 / ((1+x)(1+x)) - - // Adjust for yb - rb += yb * denomr; // numerator - rb += -ya * denomb * denomr * denomr; // denominator - - // negate - ya = -ra; - yb = -rb; - } - - if (hiPrecOut != null) { - hiPrecOut[0] = ya; - hiPrecOut[1] = yb; - } - - return ya + yb; - } - - /** - * Natural logarithm. - * - * @param x a double - * @return log(x) - */ - public static double log(final double x) { - return log(x, null); - } - - /** - * Internal helper method for natural logarithm function. - * @param x original argument of the natural logarithm function - * @param hiPrec extra bits of precision on output (To Be Confirmed) - * @return log(x) - */ - private static double log(final double x, final double[] hiPrec) { - if (x==0) { // Handle special case of +0/-0 - return Double.NEGATIVE_INFINITY; - } - long bits = Double.doubleToRawLongBits(x); - - /* Handle special cases of negative input, and NaN */ - if (((bits & 0x8000000000000000L) != 0 || Double.isNaN(x)) && x != 0.0) { - if (hiPrec != null) { - hiPrec[0] = Double.NaN; - } - - return Double.NaN; - } - - /* Handle special cases of Positive infinity. */ - if (x == Double.POSITIVE_INFINITY) { - if (hiPrec != null) { - hiPrec[0] = Double.POSITIVE_INFINITY; - } - - return Double.POSITIVE_INFINITY; - } - - /* Extract the exponent */ - int exp = (int)(bits >> 52)-1023; - - if ((bits & 0x7ff0000000000000L) == 0) { - // Subnormal! - if (x == 0) { - // Zero - if (hiPrec != null) { - hiPrec[0] = Double.NEGATIVE_INFINITY; - } - - return Double.NEGATIVE_INFINITY; - } - - /* Normalize the subnormal number. */ - bits <<= 1; - while ( (bits & 0x0010000000000000L) == 0) { - --exp; - bits <<= 1; - } - } - - - if ((exp == -1 || exp == 0) && x < 1.01 && x > 0.99 && hiPrec == null) { - /* The normal method doesn't work well in the range [0.99, 1.01], so call do a straight - polynomial expansion in higer precision. */ - - /* Compute x - 1.0 and split it */ - double xa = x - 1.0; - double xb = xa - x + 1.0; - double tmp = xa * HEX_40000000; - double aa = xa + tmp - tmp; - double ab = xa - aa; - xa = aa; - xb = ab; - - final double[] lnCoef_last = LN_QUICK_COEF[LN_QUICK_COEF.length - 1]; - double ya = lnCoef_last[0]; - double yb = lnCoef_last[1]; - - for (int i = LN_QUICK_COEF.length - 2; i >= 0; i--) { - /* Multiply a = y * x */ - aa = ya * xa; - ab = ya * xb + yb * xa + yb * xb; - /* split, so now y = a */ - tmp = aa * HEX_40000000; - ya = aa + tmp - tmp; - yb = aa - ya + ab; - - /* Add a = y + lnQuickCoef */ - final double[] lnCoef_i = LN_QUICK_COEF[i]; - aa = ya + lnCoef_i[0]; - ab = yb + lnCoef_i[1]; - /* Split y = a */ - tmp = aa * HEX_40000000; - ya = aa + tmp - tmp; - yb = aa - ya + ab; - } - - /* Multiply a = y * x */ - aa = ya * xa; - ab = ya * xb + yb * xa + yb * xb; - /* split, so now y = a */ - tmp = aa * HEX_40000000; - ya = aa + tmp - tmp; - yb = aa - ya + ab; - - return ya + yb; - } - - // lnm is a log of a number in the range of 1.0 - 2.0, so 0 <= lnm < ln(2) - final double[] lnm = lnMant.LN_MANT[(int)((bits & 0x000ffc0000000000L) >> 42)]; - - /* - double epsilon = x / Double.longBitsToDouble(bits & 0xfffffc0000000000L); - - epsilon -= 1.0; - */ - - // y is the most significant 10 bits of the mantissa - //double y = Double.longBitsToDouble(bits & 0xfffffc0000000000L); - //double epsilon = (x - y) / y; - final double epsilon = (bits & 0x3ffffffffffL) / (TWO_POWER_52 + (bits & 0x000ffc0000000000L)); - - double lnza = 0.0; - double lnzb = 0.0; - - if (hiPrec != null) { - /* split epsilon -> x */ - double tmp = epsilon * HEX_40000000; - double aa = epsilon + tmp - tmp; - double ab = epsilon - aa; - double xa = aa; - double xb = ab; - - /* Need a more accurate epsilon, so adjust the division. */ - final double numer = bits & 0x3ffffffffffL; - final double denom = TWO_POWER_52 + (bits & 0x000ffc0000000000L); - aa = numer - xa*denom - xb * denom; - xb += aa / denom; - - /* Remez polynomial evaluation */ - final double[] lnCoef_last = LN_HI_PREC_COEF[LN_HI_PREC_COEF.length-1]; - double ya = lnCoef_last[0]; - double yb = lnCoef_last[1]; - - for (int i = LN_HI_PREC_COEF.length - 2; i >= 0; i--) { - /* Multiply a = y * x */ - aa = ya * xa; - ab = ya * xb + yb * xa + yb * xb; - /* split, so now y = a */ - tmp = aa * HEX_40000000; - ya = aa + tmp - tmp; - yb = aa - ya + ab; - - /* Add a = y + lnHiPrecCoef */ - final double[] lnCoef_i = LN_HI_PREC_COEF[i]; - aa = ya + lnCoef_i[0]; - ab = yb + lnCoef_i[1]; - /* Split y = a */ - tmp = aa * HEX_40000000; - ya = aa + tmp - tmp; - yb = aa - ya + ab; - } - - /* Multiply a = y * x */ - aa = ya * xa; - ab = ya * xb + yb * xa + yb * xb; - - /* split, so now lnz = a */ - /* - tmp = aa * 1073741824.0; - lnza = aa + tmp - tmp; - lnzb = aa - lnza + ab; - */ - lnza = aa + ab; - lnzb = -(lnza - aa - ab); - } else { - /* High precision not required. Eval Remez polynomial - using standard double precision */ - lnza = -0.16624882440418567; - lnza = lnza * epsilon + 0.19999954120254515; - lnza = lnza * epsilon + -0.2499999997677497; - lnza = lnza * epsilon + 0.3333333333332802; - lnza = lnza * epsilon + -0.5; - lnza = lnza * epsilon + 1.0; - lnza *= epsilon; - } - - /* Relative sizes: - * lnzb [0, 2.33E-10] - * lnm[1] [0, 1.17E-7] - * ln2B*exp [0, 1.12E-4] - * lnza [0, 9.7E-4] - * lnm[0] [0, 0.692] - * ln2A*exp [0, 709] - */ - - /* Compute the following sum: - * lnzb + lnm[1] + ln2B*exp + lnza + lnm[0] + ln2A*exp; - */ - - //return lnzb + lnm[1] + ln2B*exp + lnza + lnm[0] + ln2A*exp; - double a = LN_2_A*exp; - double b = 0.0; - double c = a+lnm[0]; - double d = -(c-a-lnm[0]); - a = c; - b += d; - - c = a + lnza; - d = -(c - a - lnza); - a = c; - b += d; - - c = a + LN_2_B*exp; - d = -(c - a - LN_2_B*exp); - a = c; - b += d; - - c = a + lnm[1]; - d = -(c - a - lnm[1]); - a = c; - b += d; - - c = a + lnzb; - d = -(c - a - lnzb); - a = c; - b += d; - - if (hiPrec != null) { - hiPrec[0] = a; - hiPrec[1] = b; - } - - return a + b; - } - - /** - * Computes log(1 + x). - * - * @param x Number. - * @return {@code log(1 + x)}. - */ - public static double log1p(final double x) { - if (x == -1) { - return Double.NEGATIVE_INFINITY; - } - - if (x == Double.POSITIVE_INFINITY) { - return Double.POSITIVE_INFINITY; - } - - if (x > 1e-6 || - x < -1e-6) { - final double xpa = 1 + x; - final double xpb = -(xpa - 1 - x); - - final double[] hiPrec = new double[2]; - final double lores = log(xpa, hiPrec); - if (Double.isInfinite(lores)) { // Don't allow this to be converted to NaN - return lores; - } - - // Do a taylor series expansion around xpa: - // f(x+y) = f(x) + f'(x) y + f''(x)/2 y^2 - final double fx1 = xpb / xpa; - final double epsilon = 0.5 * fx1 + 1; - return epsilon * fx1 + hiPrec[1] + hiPrec[0]; - } else { - // Value is small |x| < 1e6, do a Taylor series centered on 1. - final double y = (x * F_1_3 - F_1_2) * x + 1; - return y * x; - } - } - - /** Compute the base 10 logarithm. - * @param x a number - * @return log10(x) - */ - public static double log10(final double x) { - final double hiPrec[] = new double[2]; - - final double lores = log(x, hiPrec); - if (Double.isInfinite(lores)){ // don't allow this to be converted to NaN - return lores; - } - - final double tmp = hiPrec[0] * HEX_40000000; - final double lna = hiPrec[0] + tmp - tmp; - final double lnb = hiPrec[0] - lna + hiPrec[1]; - - final double rln10a = 0.4342944622039795; - final double rln10b = 1.9699272335463627E-8; - - return rln10b * lnb + rln10b * lna + rln10a * lnb + rln10a * lna; - } - - /** - * Computes the - * logarithm in a given base. - * - * Returns {@code NaN} if either argument is negative. - * If {@code base} is 0 and {@code x} is positive, 0 is returned. - * If {@code base} is positive and {@code x} is 0, - * {@code Double.NEGATIVE_INFINITY} is returned. - * If both arguments are 0, the result is {@code NaN}. - * - * @param base Base of the logarithm, must be greater than 0. - * @param x Argument, must be greater than 0. - * @return the value of the logarithm, i.e. the number {@code y} such that - * basey = x. - * @since 1.2 (previously in {@code MathUtils}, moved as of version 3.0) - */ - public static double log(double base, double x) { - return log(x) / log(base); - } - - /** - * Power function. Compute x^y. - * - * @param x a double - * @param y a double - * @return double - */ - public static double pow(final double x, final double y) { - - if (y == 0) { - // y = -0 or y = +0 - return 1.0; - } else { - - final long yBits = Double.doubleToRawLongBits(y); - final int yRawExp = (int) ((yBits & MASK_DOUBLE_EXPONENT) >> 52); - final long yRawMantissa = yBits & MASK_DOUBLE_MANTISSA; - final long xBits = Double.doubleToRawLongBits(x); - final int xRawExp = (int) ((xBits & MASK_DOUBLE_EXPONENT) >> 52); - final long xRawMantissa = xBits & MASK_DOUBLE_MANTISSA; - - if (yRawExp > 1085) { - // y is either a very large integral value that does not fit in a long or it is a special number - - if ((yRawExp == 2047 && yRawMantissa != 0) || - (xRawExp == 2047 && xRawMantissa != 0)) { - // NaN - return Double.NaN; - } else if (xRawExp == 1023 && xRawMantissa == 0) { - // x = -1.0 or x = +1.0 - if (yRawExp == 2047) { - // y is infinite - return Double.NaN; - } else { - // y is a large even integer - return 1.0; - } - } else { - // the absolute value of x is either greater or smaller than 1.0 - - // if yRawExp == 2047 and mantissa is 0, y = -infinity or y = +infinity - // if 1085 < yRawExp < 2047, y is simply a large number, however, due to limited - // accuracy, at this magnitude it behaves just like infinity with regards to x - if ((y > 0) ^ (xRawExp < 1023)) { - // either y = +infinity (or large engouh) and abs(x) > 1.0 - // or y = -infinity (or large engouh) and abs(x) < 1.0 - return Double.POSITIVE_INFINITY; - } else { - // either y = +infinity (or large engouh) and abs(x) < 1.0 - // or y = -infinity (or large engouh) and abs(x) > 1.0 - return +0.0; - } - } - - } else { - // y is a regular non-zero number - - if (yRawExp >= 1023) { - // y may be an integral value, which should be handled specifically - final long yFullMantissa = IMPLICIT_HIGH_BIT | yRawMantissa; - if (yRawExp < 1075) { - // normal number with negative shift that may have a fractional part - final long integralMask = (-1L) << (1075 - yRawExp); - if ((yFullMantissa & integralMask) == yFullMantissa) { - // all fractional bits are 0, the number is really integral - final long l = yFullMantissa >> (1075 - yRawExp); - return FastMath.pow(x, (y < 0) ? -l : l); - } - } else { - // normal number with positive shift, always an integral value - // we know it fits in a primitive long because yRawExp > 1085 has been handled above - final long l = yFullMantissa << (yRawExp - 1075); - return FastMath.pow(x, (y < 0) ? -l : l); - } - } - - // y is a non-integral value - - if (x == 0) { - // x = -0 or x = +0 - // the integer powers have already been handled above - return y < 0 ? Double.POSITIVE_INFINITY : +0.0; - } else if (xRawExp == 2047) { - if (xRawMantissa == 0) { - // x = -infinity or x = +infinity - return (y < 0) ? +0.0 : Double.POSITIVE_INFINITY; - } else { - // NaN - return Double.NaN; - } - } else if (x < 0) { - // the integer powers have already been handled above - return Double.NaN; - } else { - - // this is the general case, for regular fractional numbers x and y - - // Split y into ya and yb such that y = ya+yb - final double tmp = y * HEX_40000000; - final double ya = (y + tmp) - tmp; - final double yb = y - ya; - - /* Compute ln(x) */ - final double lns[] = new double[2]; - final double lores = log(x, lns); - if (Double.isInfinite(lores)) { // don't allow this to be converted to NaN - return lores; - } - - double lna = lns[0]; - double lnb = lns[1]; - - /* resplit lns */ - final double tmp1 = lna * HEX_40000000; - final double tmp2 = (lna + tmp1) - tmp1; - lnb += lna - tmp2; - lna = tmp2; - - // y*ln(x) = (aa+ab) - final double aa = lna * ya; - final double ab = lna * yb + lnb * ya + lnb * yb; - - lna = aa+ab; - lnb = -(lna - aa - ab); - - double z = 1.0 / 120.0; - z = z * lnb + (1.0 / 24.0); - z = z * lnb + (1.0 / 6.0); - z = z * lnb + 0.5; - z = z * lnb + 1.0; - z *= lnb; - - final double result = exp(lna, z, null); - //result = result + result * z; - return result; - - } - } - - } - - } - - /** - * Raise a double to an int power. - * - * @param d Number to raise. - * @param e Exponent. - * @return de - * @since 3.1 - */ - public static double pow(double d, int e) { - return pow(d, (long) e); - } - - - /** - * Raise a double to a long power. - * - * @param d Number to raise. - * @param e Exponent. - * @return de - * @since 3.6 - */ - public static double pow(double d, long e) { - if (e == 0) { - return 1.0; - } else if (e > 0) { - return new Split(d).pow(e).full; - } else { - return new Split(d).reciprocal().pow(-e).full; - } - } - - /** Class operator on double numbers split into one 26 bits number and one 27 bits number. */ - private static class Split { - - /** Split version of NaN. */ - public static final Split NAN = new Split(Double.NaN, 0); - - /** Split version of positive infinity. */ - public static final Split POSITIVE_INFINITY = new Split(Double.POSITIVE_INFINITY, 0); - - /** Split version of negative infinity. */ - public static final Split NEGATIVE_INFINITY = new Split(Double.NEGATIVE_INFINITY, 0); - - /** Full number. */ - private final double full; - - /** High order bits. */ - private final double high; - - /** Low order bits. */ - private final double low; - - /** Simple constructor. - * @param x number to split - */ - Split(final double x) { - full = x; - high = Double.longBitsToDouble(Double.doubleToRawLongBits(x) & ((-1L) << 27)); - low = x - high; - } - - /** Simple constructor. - * @param high high order bits - * @param low low order bits - */ - Split(final double high, final double low) { - this(high == 0.0 ? (low == 0.0 && Double.doubleToRawLongBits(high) == Long.MIN_VALUE /* negative zero */ ? -0.0 : low) : high + low, high, low); - } - - /** Simple constructor. - * @param full full number - * @param high high order bits - * @param low low order bits - */ - Split(final double full, final double high, final double low) { - this.full = full; - this.high = high; - this.low = low; - } - - /** Multiply the instance by another one. - * @param b other instance to multiply by - * @return product - */ - public Split multiply(final Split b) { - // beware the following expressions must NOT be simplified, they rely on floating point arithmetic properties - final Split mulBasic = new Split(full * b.full); - final double mulError = low * b.low - (((mulBasic.full - high * b.high) - low * b.high) - high * b.low); - return new Split(mulBasic.high, mulBasic.low + mulError); - } - - /** Compute the reciprocal of the instance. - * @return reciprocal of the instance - */ - public Split reciprocal() { - - final double approximateInv = 1.0 / full; - final Split splitInv = new Split(approximateInv); - - // if 1.0/d were computed perfectly, remultiplying it by d should give 1.0 - // we want to estimate the error so we can fix the low order bits of approximateInvLow - // beware the following expressions must NOT be simplified, they rely on floating point arithmetic properties - final Split product = multiply(splitInv); - final double error = (product.high - 1) + product.low; - - // better accuracy estimate of reciprocal - return Double.isNaN(error) ? splitInv : new Split(splitInv.high, splitInv.low - error / full); - - } - - /** Computes this^e. - * @param e exponent (beware, here it MUST be > 0; the only exclusion is Long.MIN_VALUE) - * @return d^e, split in high and low bits - * @since 3.6 - */ - private Split pow(final long e) { - - // prepare result - Split result = new Split(1); - - // d^(2p) - Split d2p = new Split(full, high, low); - - for (long p = e; p != 0; p >>>= 1) { - - if ((p & 0x1) != 0) { - // accurate multiplication result = result * d^(2p) using Veltkamp TwoProduct algorithm - result = result.multiply(d2p); - } - - // accurate squaring d^(2(p+1)) = d^(2p) * d^(2p) using Veltkamp TwoProduct algorithm - d2p = d2p.multiply(d2p); - - } - - if (Double.isNaN(result.full)) { - if (Double.isNaN(full)) { - return Split.NAN; - } else { - // some intermediate numbers exceeded capacity, - // and the low order bits became NaN (because infinity - infinity = NaN) - if (FastMath.abs(full) < 1) { - return new Split(FastMath.copySign(0.0, full), 0.0); - } else if (full < 0 && (e & 0x1) == 1) { - return Split.NEGATIVE_INFINITY; - } else { - return Split.POSITIVE_INFINITY; - } - } - } else { - return result; - } - - } - - } - - /** - * Computes sin(x) - x, where |x| < 1/16. - * Use a Remez polynomial approximation. - * @param x a number smaller than 1/16 - * @return sin(x) - x - */ - private static double polySine(final double x) - { - double x2 = x*x; - - double p = 2.7553817452272217E-6; - p = p * x2 + -1.9841269659586505E-4; - p = p * x2 + 0.008333333333329196; - p = p * x2 + -0.16666666666666666; - //p *= x2; - //p *= x; - p = p * x2 * x; - - return p; - } - - /** - * Computes cos(x) - 1, where |x| < 1/16. - * Use a Remez polynomial approximation. - * @param x a number smaller than 1/16 - * @return cos(x) - 1 - */ - private static double polyCosine(double x) { - double x2 = x*x; - - double p = 2.479773539153719E-5; - p = p * x2 + -0.0013888888689039883; - p = p * x2 + 0.041666666666621166; - p = p * x2 + -0.49999999999999994; - p *= x2; - - return p; - } - - /** - * Compute sine over the first quadrant (0 < x < pi/2). - * Use combination of table lookup and rational polynomial expansion. - * @param xa number from which sine is requested - * @param xb extra bits for x (may be 0.0) - * @return sin(xa + xb) - */ - private static double sinQ(double xa, double xb) { - int idx = (int) ((xa * 8.0) + 0.5); - final double epsilon = xa - EIGHTHS[idx]; //idx*0.125; - - // Table lookups - final double sintA = SINE_TABLE_A[idx]; - final double sintB = SINE_TABLE_B[idx]; - final double costA = COSINE_TABLE_A[idx]; - final double costB = COSINE_TABLE_B[idx]; - - // Polynomial eval of sin(epsilon), cos(epsilon) - double sinEpsA = epsilon; - double sinEpsB = polySine(epsilon); - final double cosEpsA = 1.0; - final double cosEpsB = polyCosine(epsilon); - - // Split epsilon xa + xb = x - final double temp = sinEpsA * HEX_40000000; - double temp2 = (sinEpsA + temp) - temp; - sinEpsB += sinEpsA - temp2; - sinEpsA = temp2; - - /* Compute sin(x) by angle addition formula */ - double result; - - /* Compute the following sum: - * - * result = sintA + costA*sinEpsA + sintA*cosEpsB + costA*sinEpsB + - * sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB; - * - * Ranges of elements - * - * xxxtA 0 PI/2 - * xxxtB -1.5e-9 1.5e-9 - * sinEpsA -0.0625 0.0625 - * sinEpsB -6e-11 6e-11 - * cosEpsA 1.0 - * cosEpsB 0 -0.0625 - * - */ - - //result = sintA + costA*sinEpsA + sintA*cosEpsB + costA*sinEpsB + - // sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB; - - //result = sintA + sintA*cosEpsB + sintB + sintB * cosEpsB; - //result += costA*sinEpsA + costA*sinEpsB + costB*sinEpsA + costB * sinEpsB; - double a = 0; - double b = 0; - - double t = sintA; - double c = a + t; - double d = -(c - a - t); - a = c; - b += d; - - t = costA * sinEpsA; - c = a + t; - d = -(c - a - t); - a = c; - b += d; - - b = b + sintA * cosEpsB + costA * sinEpsB; - /* - t = sintA*cosEpsB; - c = a + t; - d = -(c - a - t); - a = c; - b = b + d; - - t = costA*sinEpsB; - c = a + t; - d = -(c - a - t); - a = c; - b = b + d; - */ - - b = b + sintB + costB * sinEpsA + sintB * cosEpsB + costB * sinEpsB; - /* - t = sintB; - c = a + t; - d = -(c - a - t); - a = c; - b = b + d; - - t = costB*sinEpsA; - c = a + t; - d = -(c - a - t); - a = c; - b = b + d; - - t = sintB*cosEpsB; - c = a + t; - d = -(c - a - t); - a = c; - b = b + d; - - t = costB*sinEpsB; - c = a + t; - d = -(c - a - t); - a = c; - b = b + d; - */ - - if (xb != 0.0) { - t = ((costA + costB) * (cosEpsA + cosEpsB) - - (sintA + sintB) * (sinEpsA + sinEpsB)) * xb; // approximate cosine*xb - c = a + t; - d = -(c - a - t); - a = c; - b += d; - } - - result = a + b; - - return result; - } - - /** - * Compute cosine in the first quadrant by subtracting input from PI/2 and - * then calling sinQ. This is more accurate as the input approaches PI/2. - * @param xa number from which cosine is requested - * @param xb extra bits for x (may be 0.0) - * @return cos(xa + xb) - */ - private static double cosQ(double xa, double xb) { - final double pi2a = 1.5707963267948966; - final double pi2b = 6.123233995736766E-17; - - final double a = pi2a - xa; - double b = -(a - pi2a + xa); - b += pi2b - xb; - - return sinQ(a, b); - } - - /** - * Compute tangent (or cotangent) over the first quadrant. 0 < x < pi/2 - * Use combination of table lookup and rational polynomial expansion. - * @param xa number from which sine is requested - * @param xb extra bits for x (may be 0.0) - * @param cotanFlag if true, compute the cotangent instead of the tangent - * @return tan(xa+xb) (or cotangent, depending on cotanFlag) - */ - private static double tanQ(double xa, double xb, boolean cotanFlag) { - - int idx = (int) ((xa * 8.0) + 0.5); - final double epsilon = xa - EIGHTHS[idx]; //idx*0.125; - - // Table lookups - final double sintA = SINE_TABLE_A[idx]; - final double sintB = SINE_TABLE_B[idx]; - final double costA = COSINE_TABLE_A[idx]; - final double costB = COSINE_TABLE_B[idx]; - - // Polynomial eval of sin(epsilon), cos(epsilon) - double sinEpsA = epsilon; - double sinEpsB = polySine(epsilon); - final double cosEpsA = 1.0; - final double cosEpsB = polyCosine(epsilon); - - // Split epsilon xa + xb = x - double temp = sinEpsA * HEX_40000000; - double temp2 = (sinEpsA + temp) - temp; - sinEpsB += sinEpsA - temp2; - sinEpsA = temp2; - - /* Compute sin(x) by angle addition formula */ - - /* Compute the following sum: - * - * result = sintA + costA*sinEpsA + sintA*cosEpsB + costA*sinEpsB + - * sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB; - * - * Ranges of elements - * - * xxxtA 0 PI/2 - * xxxtB -1.5e-9 1.5e-9 - * sinEpsA -0.0625 0.0625 - * sinEpsB -6e-11 6e-11 - * cosEpsA 1.0 - * cosEpsB 0 -0.0625 - * - */ - - //result = sintA + costA*sinEpsA + sintA*cosEpsB + costA*sinEpsB + - // sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB; - - //result = sintA + sintA*cosEpsB + sintB + sintB * cosEpsB; - //result += costA*sinEpsA + costA*sinEpsB + costB*sinEpsA + costB * sinEpsB; - double a = 0; - double b = 0; - - // Compute sine - double t = sintA; - double c = a + t; - double d = -(c - a - t); - a = c; - b += d; - - t = costA*sinEpsA; - c = a + t; - d = -(c - a - t); - a = c; - b += d; - - b += sintA*cosEpsB + costA*sinEpsB; - b += sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB; - - double sina = a + b; - double sinb = -(sina - a - b); - - // Compute cosine - - a = b = c = d = 0.0; - - t = costA*cosEpsA; - c = a + t; - d = -(c - a - t); - a = c; - b += d; - - t = -sintA*sinEpsA; - c = a + t; - d = -(c - a - t); - a = c; - b += d; - - b += costB*cosEpsA + costA*cosEpsB + costB*cosEpsB; - b -= sintB*sinEpsA + sintA*sinEpsB + sintB*sinEpsB; - - double cosa = a + b; - double cosb = -(cosa - a - b); - - if (cotanFlag) { - double tmp; - tmp = cosa; cosa = sina; sina = tmp; - tmp = cosb; cosb = sinb; sinb = tmp; - } - - - /* estimate and correct, compute 1.0/(cosa+cosb) */ - /* - double est = (sina+sinb)/(cosa+cosb); - double err = (sina - cosa*est) + (sinb - cosb*est); - est += err/(cosa+cosb); - err = (sina - cosa*est) + (sinb - cosb*est); - */ - - // f(x) = 1/x, f'(x) = -1/x^2 - - double est = sina/cosa; - - /* Split the estimate to get more accurate read on division rounding */ - temp = est * HEX_40000000; - double esta = (est + temp) - temp; - double estb = est - esta; - - temp = cosa * HEX_40000000; - double cosaa = (cosa + temp) - temp; - double cosab = cosa - cosaa; - - //double err = (sina - est*cosa)/cosa; // Correction for division rounding - double err = (sina - esta*cosaa - esta*cosab - estb*cosaa - estb*cosab)/cosa; // Correction for division rounding - err += sinb/cosa; // Change in est due to sinb - err += -sina * cosb / cosa / cosa; // Change in est due to cosb - - if (xb != 0.0) { - // tan' = 1 + tan^2 cot' = -(1 + cot^2) - // Approximate impact of xb - double xbadj = xb + est*est*xb; - if (cotanFlag) { - xbadj = -xbadj; - } - - err += xbadj; - } - - return est+err; - } - - /** Reduce the input argument using the Payne and Hanek method. - * This is good for all inputs 0.0 < x < inf - * Output is remainder after dividing by PI/2 - * The result array should contain 3 numbers. - * result[0] is the integer portion, so mod 4 this gives the quadrant. - * result[1] is the upper bits of the remainder - * result[2] is the lower bits of the remainder - * - * @param x number to reduce - * @param result placeholder where to put the result - */ - private static void reducePayneHanek(double x, double result[]) - { - /* Convert input double to bits */ - long inbits = Double.doubleToRawLongBits(x); - int exponent = (int) ((inbits >> 52) & 0x7ff) - 1023; - - /* Convert to fixed point representation */ - inbits &= 0x000fffffffffffffL; - inbits |= 0x0010000000000000L; - - /* Normalize input to be between 0.5 and 1.0 */ - exponent++; - inbits <<= 11; - - /* Based on the exponent, get a shifted copy of recip2pi */ - long shpi0; - long shpiA; - long shpiB; - int idx = exponent >> 6; - int shift = exponent - (idx << 6); - - if (shift != 0) { - shpi0 = (idx == 0) ? 0 : (RECIP_2PI[idx-1] << shift); - shpi0 |= RECIP_2PI[idx] >>> (64-shift); - shpiA = (RECIP_2PI[idx] << shift) | (RECIP_2PI[idx+1] >>> (64-shift)); - shpiB = (RECIP_2PI[idx+1] << shift) | (RECIP_2PI[idx+2] >>> (64-shift)); - } else { - shpi0 = (idx == 0) ? 0 : RECIP_2PI[idx-1]; - shpiA = RECIP_2PI[idx]; - shpiB = RECIP_2PI[idx+1]; - } - - /* Multiply input by shpiA */ - long a = inbits >>> 32; - long b = inbits & 0xffffffffL; - - long c = shpiA >>> 32; - long d = shpiA & 0xffffffffL; - - long ac = a * c; - long bd = b * d; - long bc = b * c; - long ad = a * d; - - long prodB = bd + (ad << 32); - long prodA = ac + (ad >>> 32); - - boolean bita = (bd & 0x8000000000000000L) != 0; - boolean bitb = (ad & 0x80000000L ) != 0; - boolean bitsum = (prodB & 0x8000000000000000L) != 0; - - /* Carry */ - if ( (bita && bitb) || - ((bita || bitb) && !bitsum) ) { - prodA++; - } - - bita = (prodB & 0x8000000000000000L) != 0; - bitb = (bc & 0x80000000L ) != 0; - - prodB += bc << 32; - prodA += bc >>> 32; - - bitsum = (prodB & 0x8000000000000000L) != 0; - - /* Carry */ - if ( (bita && bitb) || - ((bita || bitb) && !bitsum) ) { - prodA++; - } - - /* Multiply input by shpiB */ - c = shpiB >>> 32; - d = shpiB & 0xffffffffL; - ac = a * c; - bc = b * c; - ad = a * d; - - /* Collect terms */ - ac += (bc + ad) >>> 32; - - bita = (prodB & 0x8000000000000000L) != 0; - bitb = (ac & 0x8000000000000000L ) != 0; - prodB += ac; - bitsum = (prodB & 0x8000000000000000L) != 0; - /* Carry */ - if ( (bita && bitb) || - ((bita || bitb) && !bitsum) ) { - prodA++; - } - - /* Multiply by shpi0 */ - c = shpi0 >>> 32; - d = shpi0 & 0xffffffffL; - - bd = b * d; - bc = b * c; - ad = a * d; - - prodA += bd + ((bc + ad) << 32); - - /* - * prodA, prodB now contain the remainder as a fraction of PI. We want this as a fraction of - * PI/2, so use the following steps: - * 1.) multiply by 4. - * 2.) do a fixed point muliply by PI/4. - * 3.) Convert to floating point. - * 4.) Multiply by 2 - */ - - /* This identifies the quadrant */ - int intPart = (int)(prodA >>> 62); - - /* Multiply by 4 */ - prodA <<= 2; - prodA |= prodB >>> 62; - prodB <<= 2; - - /* Multiply by PI/4 */ - a = prodA >>> 32; - b = prodA & 0xffffffffL; - - c = PI_O_4_BITS[0] >>> 32; - d = PI_O_4_BITS[0] & 0xffffffffL; - - ac = a * c; - bd = b * d; - bc = b * c; - ad = a * d; - - long prod2B = bd + (ad << 32); - long prod2A = ac + (ad >>> 32); - - bita = (bd & 0x8000000000000000L) != 0; - bitb = (ad & 0x80000000L ) != 0; - bitsum = (prod2B & 0x8000000000000000L) != 0; - - /* Carry */ - if ( (bita && bitb) || - ((bita || bitb) && !bitsum) ) { - prod2A++; - } - - bita = (prod2B & 0x8000000000000000L) != 0; - bitb = (bc & 0x80000000L ) != 0; - - prod2B += bc << 32; - prod2A += bc >>> 32; - - bitsum = (prod2B & 0x8000000000000000L) != 0; - - /* Carry */ - if ( (bita && bitb) || - ((bita || bitb) && !bitsum) ) { - prod2A++; - } - - /* Multiply input by pio4bits[1] */ - c = PI_O_4_BITS[1] >>> 32; - d = PI_O_4_BITS[1] & 0xffffffffL; - ac = a * c; - bc = b * c; - ad = a * d; - - /* Collect terms */ - ac += (bc + ad) >>> 32; - - bita = (prod2B & 0x8000000000000000L) != 0; - bitb = (ac & 0x8000000000000000L ) != 0; - prod2B += ac; - bitsum = (prod2B & 0x8000000000000000L) != 0; - /* Carry */ - if ( (bita && bitb) || - ((bita || bitb) && !bitsum) ) { - prod2A++; - } - - /* Multiply inputB by pio4bits[0] */ - a = prodB >>> 32; - b = prodB & 0xffffffffL; - c = PI_O_4_BITS[0] >>> 32; - d = PI_O_4_BITS[0] & 0xffffffffL; - ac = a * c; - bc = b * c; - ad = a * d; - - /* Collect terms */ - ac += (bc + ad) >>> 32; - - bita = (prod2B & 0x8000000000000000L) != 0; - bitb = (ac & 0x8000000000000000L ) != 0; - prod2B += ac; - bitsum = (prod2B & 0x8000000000000000L) != 0; - /* Carry */ - if ( (bita && bitb) || - ((bita || bitb) && !bitsum) ) { - prod2A++; - } - - /* Convert to double */ - double tmpA = (prod2A >>> 12) / TWO_POWER_52; // High order 52 bits - double tmpB = (((prod2A & 0xfffL) << 40) + (prod2B >>> 24)) / TWO_POWER_52 / TWO_POWER_52; // Low bits - - double sumA = tmpA + tmpB; - double sumB = -(sumA - tmpA - tmpB); - - /* Multiply by PI/2 and return */ - result[0] = intPart; - result[1] = sumA * 2.0; - result[2] = sumB * 2.0; - } - - /** - * Sine function. - * - * @param x Argument. - * @return sin(x) - */ - public static double sin(double x) { - boolean negative = false; - int quadrant = 0; - double xa; - double xb = 0.0; - - /* Take absolute value of the input */ - xa = x; - if (x < 0) { - negative = true; - xa = -xa; - } - - /* Check for zero and negative zero */ - if (xa == 0.0) { - long bits = Double.doubleToRawLongBits(x); - if (bits < 0) { - return -0.0; - } - return 0.0; - } - - if (xa != xa || xa == Double.POSITIVE_INFINITY) { - return Double.NaN; - } - - /* Perform any argument reduction */ - if (xa > 3294198.0) { - // PI * (2**20) - // Argument too big for CodyWaite reduction. Must use - // PayneHanek. - double reduceResults[] = new double[3]; - reducePayneHanek(xa, reduceResults); - quadrant = ((int) reduceResults[0]) & 3; - xa = reduceResults[1]; - xb = reduceResults[2]; - } else if (xa > 1.5707963267948966) { - final CodyWaite cw = new CodyWaite(xa); - quadrant = cw.getK() & 3; - xa = cw.getRemA(); - xb = cw.getRemB(); - } - - if (negative) { - quadrant ^= 2; // Flip bit 1 - } - - switch (quadrant) { - case 0: - return sinQ(xa, xb); - case 1: - return cosQ(xa, xb); - case 2: - return -sinQ(xa, xb); - case 3: - return -cosQ(xa, xb); - default: - return Double.NaN; - } - } - - /** - * Cosine function. - * - * @param x Argument. - * @return cos(x) - */ - public static double cos(double x) { - int quadrant = 0; - - /* Take absolute value of the input */ - double xa = x; - if (x < 0) { - xa = -xa; - } - - if (xa != xa || xa == Double.POSITIVE_INFINITY) { - return Double.NaN; - } - - /* Perform any argument reduction */ - double xb = 0; - if (xa > 3294198.0) { - // PI * (2**20) - // Argument too big for CodyWaite reduction. Must use - // PayneHanek. - double reduceResults[] = new double[3]; - reducePayneHanek(xa, reduceResults); - quadrant = ((int) reduceResults[0]) & 3; - xa = reduceResults[1]; - xb = reduceResults[2]; - } else if (xa > 1.5707963267948966) { - final CodyWaite cw = new CodyWaite(xa); - quadrant = cw.getK() & 3; - xa = cw.getRemA(); - xb = cw.getRemB(); - } - - //if (negative) - // quadrant = (quadrant + 2) % 4; - - switch (quadrant) { - case 0: - return cosQ(xa, xb); - case 1: - return -sinQ(xa, xb); - case 2: - return -cosQ(xa, xb); - case 3: - return sinQ(xa, xb); - default: - return Double.NaN; - } - } - - /** - * Tangent function. - * - * @param x Argument. - * @return tan(x) - */ - public static double tan(double x) { - boolean negative = false; - int quadrant = 0; - - /* Take absolute value of the input */ - double xa = x; - if (x < 0) { - negative = true; - xa = -xa; - } - - /* Check for zero and negative zero */ - if (xa == 0.0) { - long bits = Double.doubleToRawLongBits(x); - if (bits < 0) { - return -0.0; - } - return 0.0; - } - - if (xa != xa || xa == Double.POSITIVE_INFINITY) { - return Double.NaN; - } - - /* Perform any argument reduction */ - double xb = 0; - if (xa > 3294198.0) { - // PI * (2**20) - // Argument too big for CodyWaite reduction. Must use - // PayneHanek. - double reduceResults[] = new double[3]; - reducePayneHanek(xa, reduceResults); - quadrant = ((int) reduceResults[0]) & 3; - xa = reduceResults[1]; - xb = reduceResults[2]; - } else if (xa > 1.5707963267948966) { - final CodyWaite cw = new CodyWaite(xa); - quadrant = cw.getK() & 3; - xa = cw.getRemA(); - xb = cw.getRemB(); - } - - if (xa > 1.5) { - // Accuracy suffers between 1.5 and PI/2 - final double pi2a = 1.5707963267948966; - final double pi2b = 6.123233995736766E-17; - - final double a = pi2a - xa; - double b = -(a - pi2a + xa); - b += pi2b - xb; - - xa = a + b; - xb = -(xa - a - b); - quadrant ^= 1; - negative ^= true; - } - - double result; - if ((quadrant & 1) == 0) { - result = tanQ(xa, xb, false); - } else { - result = -tanQ(xa, xb, true); - } - - if (negative) { - result = -result; - } - - return result; - } - - /** - * Arctangent function - * @param x a number - * @return atan(x) - */ - public static double atan(double x) { - return atan(x, 0.0, false); - } - - /** Internal helper function to compute arctangent. - * @param xa number from which arctangent is requested - * @param xb extra bits for x (may be 0.0) - * @param leftPlane if true, result angle must be put in the left half plane - * @return atan(xa + xb) (or angle shifted by {@code PI} if leftPlane is true) - */ - private static double atan(double xa, double xb, boolean leftPlane) { - if (xa == 0.0) { // Matches +/- 0.0; return correct sign - return leftPlane ? copySign(Math.PI, xa) : xa; - } - - final boolean negate; - if (xa < 0) { - // negative - xa = -xa; - xb = -xb; - negate = true; - } else { - negate = false; - } - - if (xa > 1.633123935319537E16) { // Very large input - return (negate ^ leftPlane) ? (-Math.PI * F_1_2) : (Math.PI * F_1_2); - } - - /* Estimate the closest tabulated arctan value, compute eps = xa-tangentTable */ - final int idx; - if (xa < 1) { - idx = (int) (((-1.7168146928204136 * xa * xa + 8.0) * xa) + 0.5); - } else { - final double oneOverXa = 1 / xa; - idx = (int) (-((-1.7168146928204136 * oneOverXa * oneOverXa + 8.0) * oneOverXa) + 13.07); - } - - final double ttA = TANGENT_TABLE_A[idx]; - final double ttB = TANGENT_TABLE_B[idx]; - - double epsA = xa - ttA; - double epsB = -(epsA - xa + ttA); - epsB += xb - ttB; - - double temp = epsA + epsB; - epsB = -(temp - epsA - epsB); - epsA = temp; - - /* Compute eps = eps / (1.0 + xa*tangent) */ - temp = xa * HEX_40000000; - double ya = xa + temp - temp; - double yb = xb + xa - ya; - xa = ya; - xb += yb; - - //if (idx > 8 || idx == 0) - if (idx == 0) { - /* If the slope of the arctan is gentle enough (< 0.45), this approximation will suffice */ - //double denom = 1.0 / (1.0 + xa*tangentTableA[idx] + xb*tangentTableA[idx] + xa*tangentTableB[idx] + xb*tangentTableB[idx]); - final double denom = 1d / (1d + (xa + xb) * (ttA + ttB)); - //double denom = 1.0 / (1.0 + xa*tangentTableA[idx]); - ya = epsA * denom; - yb = epsB * denom; - } else { - double temp2 = xa * ttA; - double za = 1d + temp2; - double zb = -(za - 1d - temp2); - temp2 = xb * ttA + xa * ttB; - temp = za + temp2; - zb += -(temp - za - temp2); - za = temp; - - zb += xb * ttB; - ya = epsA / za; - - temp = ya * HEX_40000000; - final double yaa = (ya + temp) - temp; - final double yab = ya - yaa; - - temp = za * HEX_40000000; - final double zaa = (za + temp) - temp; - final double zab = za - zaa; - - /* Correct for rounding in division */ - yb = (epsA - yaa * zaa - yaa * zab - yab * zaa - yab * zab) / za; - - yb += -epsA * zb / za / za; - yb += epsB / za; - } - - - epsA = ya; - epsB = yb; - - /* Evaluate polynomial */ - final double epsA2 = epsA * epsA; - - /* - yb = -0.09001346640161823; - yb = yb * epsA2 + 0.11110718400605211; - yb = yb * epsA2 + -0.1428571349122913; - yb = yb * epsA2 + 0.19999999999273194; - yb = yb * epsA2 + -0.33333333333333093; - yb = yb * epsA2 * epsA; - */ - - yb = 0.07490822288864472; - yb = yb * epsA2 - 0.09088450866185192; - yb = yb * epsA2 + 0.11111095942313305; - yb = yb * epsA2 - 0.1428571423679182; - yb = yb * epsA2 + 0.19999999999923582; - yb = yb * epsA2 - 0.33333333333333287; - yb = yb * epsA2 * epsA; - - - ya = epsA; - - temp = ya + yb; - yb = -(temp - ya - yb); - ya = temp; - - /* Add in effect of epsB. atan'(x) = 1/(1+x^2) */ - yb += epsB / (1d + epsA * epsA); - - final double eighths = EIGHTHS[idx]; - - //result = yb + eighths[idx] + ya; - double za = eighths + ya; - double zb = -(za - eighths - ya); - temp = za + yb; - zb += -(temp - za - yb); - za = temp; - - double result = za + zb; - - if (leftPlane) { - // Result is in the left plane - final double resultb = -(result - za - zb); - final double pia = 1.5707963267948966 * 2; - final double pib = 6.123233995736766E-17 * 2; - - za = pia - result; - zb = -(za - pia + result); - zb += pib - resultb; - - result = za + zb; - } - - - if (negate ^ leftPlane) { - result = -result; - } - - return result; - } - - /** - * Two arguments arctangent function - * @param y ordinate - * @param x abscissa - * @return phase angle of point (x,y) between {@code -PI} and {@code PI} - */ - public static double atan2(double y, double x) { - if (Double.isNaN(x) || Double.isNaN(y)) { - return Double.NaN; - } - - if (y == 0) { - final double result = x * y; - final double invx = 1d / x; - final double invy = 1d / y; - - if (invx == 0) { // X is infinite - if (x > 0) { - return y; // return +/- 0.0 - } else { - return copySign(Math.PI, y); - } - } - - if (x < 0 || invx < 0) { - if (y < 0 || invy < 0) { - return -Math.PI; - } else { - return Math.PI; - } - } else { - return result; - } - } - - // y cannot now be zero - - if (y == Double.POSITIVE_INFINITY) { - if (x == Double.POSITIVE_INFINITY) { - return Math.PI * F_1_4; - } - - if (x == Double.NEGATIVE_INFINITY) { - return Math.PI * F_3_4; - } - - return Math.PI * F_1_2; - } - - if (y == Double.NEGATIVE_INFINITY) { - if (x == Double.POSITIVE_INFINITY) { - return -Math.PI * F_1_4; - } - - if (x == Double.NEGATIVE_INFINITY) { - return -Math.PI * F_3_4; - } - - return -Math.PI * F_1_2; - } - - if (x == Double.POSITIVE_INFINITY) { - if (y > 0 || 1 / y > 0) { - return 0d; - } - - if (y < 0 || 1 / y < 0) { - return -0d; - } - } - - if (x == Double.NEGATIVE_INFINITY) - { - if (y > 0.0 || 1 / y > 0.0) { - return Math.PI; - } - - if (y < 0 || 1 / y < 0) { - return -Math.PI; - } - } - - // Neither y nor x can be infinite or NAN here - - if (x == 0) { - if (y > 0 || 1 / y > 0) { - return Math.PI * F_1_2; - } - - if (y < 0 || 1 / y < 0) { - return -Math.PI * F_1_2; - } - } - - // Compute ratio r = y/x - final double r = y / x; - if (Double.isInfinite(r)) { // bypass calculations that can create NaN - return atan(r, 0, x < 0); - } - - double ra = doubleHighPart(r); - double rb = r - ra; - - // Split x - final double xa = doubleHighPart(x); - final double xb = x - xa; - - rb += (y - ra * xa - ra * xb - rb * xa - rb * xb) / x; - - final double temp = ra + rb; - rb = -(temp - ra - rb); - ra = temp; - - if (ra == 0) { // Fix up the sign so atan works correctly - ra = copySign(0d, y); - } - - // Call atan - final double result = atan(ra, rb, x < 0); - - return result; - } - - /** Compute the arc sine of a number. - * @param x number on which evaluation is done - * @return arc sine of x - */ - public static double asin(double x) { - if (Double.isNaN(x)) { - return Double.NaN; - } - - if (x > 1.0 || x < -1.0) { - return Double.NaN; - } - - if (x == 1.0) { - return Math.PI/2.0; - } - - if (x == -1.0) { - return -Math.PI/2.0; - } - - if (x == 0.0) { // Matches +/- 0.0; return correct sign - return x; - } - - /* Compute asin(x) = atan(x/sqrt(1-x*x)) */ - - /* Split x */ - double temp = x * HEX_40000000; - final double xa = x + temp - temp; - final double xb = x - xa; - - /* Square it */ - double ya = xa*xa; - double yb = xa*xb*2.0 + xb*xb; - - /* Subtract from 1 */ - ya = -ya; - yb = -yb; - - double za = 1.0 + ya; - double zb = -(za - 1.0 - ya); - - temp = za + yb; - zb += -(temp - za - yb); - za = temp; - - /* Square root */ - double y; - y = sqrt(za); - temp = y * HEX_40000000; - ya = y + temp - temp; - yb = y - ya; - - /* Extend precision of sqrt */ - yb += (za - ya*ya - 2*ya*yb - yb*yb) / (2.0*y); - - /* Contribution of zb to sqrt */ - double dx = zb / (2.0*y); - - // Compute ratio r = x/y - double r = x/y; - temp = r * HEX_40000000; - double ra = r + temp - temp; - double rb = r - ra; - - rb += (x - ra*ya - ra*yb - rb*ya - rb*yb) / y; // Correct for rounding in division - rb += -x * dx / y / y; // Add in effect additional bits of sqrt. - - temp = ra + rb; - rb = -(temp - ra - rb); - ra = temp; - - return atan(ra, rb, false); - } - - /** Compute the arc cosine of a number. - * @param x number on which evaluation is done - * @return arc cosine of x - */ - public static double acos(double x) { - if (Double.isNaN(x)) { - return Double.NaN; - } - - if (x > 1.0 || x < -1.0) { - return Double.NaN; - } - - if (x == -1.0) { - return Math.PI; - } - - if (x == 1.0) { - return 0.0; - } - - if (x == 0) { - return Math.PI/2.0; - } - - /* Compute acos(x) = atan(sqrt(1-x*x)/x) */ - - /* Split x */ - double temp = x * HEX_40000000; - final double xa = x + temp - temp; - final double xb = x - xa; - - /* Square it */ - double ya = xa*xa; - double yb = xa*xb*2.0 + xb*xb; - - /* Subtract from 1 */ - ya = -ya; - yb = -yb; - - double za = 1.0 + ya; - double zb = -(za - 1.0 - ya); - - temp = za + yb; - zb += -(temp - za - yb); - za = temp; - - /* Square root */ - double y = sqrt(za); - temp = y * HEX_40000000; - ya = y + temp - temp; - yb = y - ya; - - /* Extend precision of sqrt */ - yb += (za - ya*ya - 2*ya*yb - yb*yb) / (2.0*y); - - /* Contribution of zb to sqrt */ - yb += zb / (2.0*y); - y = ya+yb; - yb = -(y - ya - yb); - - // Compute ratio r = y/x - double r = y/x; - - // Did r overflow? - if (Double.isInfinite(r)) { // x is effectively zero - return Math.PI/2; // so return the appropriate value - } - - double ra = doubleHighPart(r); - double rb = r - ra; - - rb += (y - ra*xa - ra*xb - rb*xa - rb*xb) / x; // Correct for rounding in division - rb += yb / x; // Add in effect additional bits of sqrt. - - temp = ra + rb; - rb = -(temp - ra - rb); - ra = temp; - - return atan(ra, rb, x<0); - } - - /** Compute the cubic root of a number. - * @param x number on which evaluation is done - * @return cubic root of x - */ - public static double cbrt(double x) { - /* Convert input double to bits */ - long inbits = Double.doubleToRawLongBits(x); - int exponent = (int) ((inbits >> 52) & 0x7ff) - 1023; - boolean subnormal = false; - - if (exponent == -1023) { - if (x == 0) { - return x; - } - - /* Subnormal, so normalize */ - subnormal = true; - x *= 1.8014398509481984E16; // 2^54 - inbits = Double.doubleToRawLongBits(x); - exponent = (int) ((inbits >> 52) & 0x7ff) - 1023; - } - - if (exponent == 1024) { - // Nan or infinity. Don't care which. - return x; - } - - /* Divide the exponent by 3 */ - int exp3 = exponent / 3; - - /* p2 will be the nearest power of 2 to x with its exponent divided by 3 */ - double p2 = Double.longBitsToDouble((inbits & 0x8000000000000000L) | - (long)(((exp3 + 1023) & 0x7ff)) << 52); - - /* This will be a number between 1 and 2 */ - final double mant = Double.longBitsToDouble((inbits & 0x000fffffffffffffL) | 0x3ff0000000000000L); - - /* Estimate the cube root of mant by polynomial */ - double est = -0.010714690733195933; - est = est * mant + 0.0875862700108075; - est = est * mant + -0.3058015757857271; - est = est * mant + 0.7249995199969751; - est = est * mant + 0.5039018405998233; - - est *= CBRTTWO[exponent % 3 + 2]; - - // est should now be good to about 15 bits of precision. Do 2 rounds of - // Newton's method to get closer, this should get us full double precision - // Scale down x for the purpose of doing newtons method. This avoids over/under flows. - final double xs = x / (p2*p2*p2); - est += (xs - est*est*est) / (3*est*est); - est += (xs - est*est*est) / (3*est*est); - - // Do one round of Newton's method in extended precision to get the last bit right. - double temp = est * HEX_40000000; - double ya = est + temp - temp; - double yb = est - ya; - - double za = ya * ya; - double zb = ya * yb * 2.0 + yb * yb; - temp = za * HEX_40000000; - double temp2 = za + temp - temp; - zb += za - temp2; - za = temp2; - - zb = za * yb + ya * zb + zb * yb; - za *= ya; - - double na = xs - za; - double nb = -(na - xs + za); - nb -= zb; - - est += (na+nb)/(3*est*est); - - /* Scale by a power of two, so this is exact. */ - est *= p2; - - if (subnormal) { - est *= 3.814697265625E-6; // 2^-18 - } - - return est; - } - - /** - * Convert degrees to radians, with error of less than 0.5 ULP - * @param x angle in degrees - * @return x converted into radians - */ - public static double toRadians(double x) - { - if (Double.isInfinite(x) || x == 0.0) { // Matches +/- 0.0; return correct sign - return x; - } - - // These are PI/180 split into high and low order bits - final double facta = 0.01745329052209854; - final double factb = 1.997844754509471E-9; - - double xa = doubleHighPart(x); - double xb = x - xa; - - double result = xb * factb + xb * facta + xa * factb + xa * facta; - if (result == 0) { - result *= x; // ensure correct sign if calculation underflows - } - return result; - } - - /** - * Convert radians to degrees, with error of less than 0.5 ULP - * @param x angle in radians - * @return x converted into degrees - */ - public static double toDegrees(double x) - { - if (Double.isInfinite(x) || x == 0.0) { // Matches +/- 0.0; return correct sign - return x; - } - - // These are 180/PI split into high and low order bits - final double facta = 57.2957763671875; - final double factb = 3.145894820876798E-6; - - double xa = doubleHighPart(x); - double xb = x - xa; - - return xb * factb + xb * facta + xa * factb + xa * facta; - } - - /** - * Absolute value. - * @param x number from which absolute value is requested - * @return abs(x) - */ - public static int abs(final int x) { - final int i = x >>> 31; - return (x ^ (~i + 1)) + i; - } - - /** - * Absolute value. - * @param x number from which absolute value is requested - * @return abs(x) - */ - public static long abs(final long x) { - final long l = x >>> 63; - // l is one if x negative zero else - // ~l+1 is zero if x is positive, -1 if x is negative - // x^(~l+1) is x is x is positive, ~x if x is negative - // add around - return (x ^ (~l + 1)) + l; - } - - /** - * Absolute value. - * @param x number from which absolute value is requested - * @return abs(x) - */ - public static float abs(final float x) { - return Float.intBitsToFloat(MASK_NON_SIGN_INT & Float.floatToRawIntBits(x)); - } - - /** - * Absolute value. - * @param x number from which absolute value is requested - * @return abs(x) - */ - public static double abs(double x) { - return Double.longBitsToDouble(MASK_NON_SIGN_LONG & Double.doubleToRawLongBits(x)); - } - - /** - * Compute least significant bit (Unit in Last Position) for a number. - * @param x number from which ulp is requested - * @return ulp(x) - */ - public static double ulp(double x) { - if (Double.isInfinite(x)) { - return Double.POSITIVE_INFINITY; - } - return abs(x - Double.longBitsToDouble(Double.doubleToRawLongBits(x) ^ 1)); - } - - /** - * Compute least significant bit (Unit in Last Position) for a number. - * @param x number from which ulp is requested - * @return ulp(x) - */ - public static float ulp(float x) { - if (Float.isInfinite(x)) { - return Float.POSITIVE_INFINITY; - } - return abs(x - Float.intBitsToFloat(Float.floatToIntBits(x) ^ 1)); - } - - /** - * Multiply a double number by a power of 2. - * @param d number to multiply - * @param n power of 2 - * @return d × 2n - */ - public static double scalb(final double d, final int n) { - - // first simple and fast handling when 2^n can be represented using normal numbers - if ((n > -1023) && (n < 1024)) { - return d * Double.longBitsToDouble(((long) (n + 1023)) << 52); - } - - // handle special cases - if (Double.isNaN(d) || Double.isInfinite(d) || (d == 0)) { - return d; - } - if (n < -2098) { - return (d > 0) ? 0.0 : -0.0; - } - if (n > 2097) { - return (d > 0) ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY; - } - - // decompose d - final long bits = Double.doubleToRawLongBits(d); - final long sign = bits & 0x8000000000000000L; - int exponent = ((int) (bits >>> 52)) & 0x7ff; - long mantissa = bits & 0x000fffffffffffffL; - - // compute scaled exponent - int scaledExponent = exponent + n; - - if (n < 0) { - // we are really in the case n <= -1023 - if (scaledExponent > 0) { - // both the input and the result are normal numbers, we only adjust the exponent - return Double.longBitsToDouble(sign | (((long) scaledExponent) << 52) | mantissa); - } else if (scaledExponent > -53) { - // the input is a normal number and the result is a subnormal number - - // recover the hidden mantissa bit - mantissa |= 1L << 52; - - // scales down complete mantissa, hence losing least significant bits - final long mostSignificantLostBit = mantissa & (1L << (-scaledExponent)); - mantissa >>>= 1 - scaledExponent; - if (mostSignificantLostBit != 0) { - // we need to add 1 bit to round up the result - mantissa++; - } - return Double.longBitsToDouble(sign | mantissa); - - } else { - // no need to compute the mantissa, the number scales down to 0 - return (sign == 0L) ? 0.0 : -0.0; - } - } else { - // we are really in the case n >= 1024 - if (exponent == 0) { - - // the input number is subnormal, normalize it - while ((mantissa >>> 52) != 1) { - mantissa <<= 1; - --scaledExponent; - } - ++scaledExponent; - mantissa &= 0x000fffffffffffffL; - - if (scaledExponent < 2047) { - return Double.longBitsToDouble(sign | (((long) scaledExponent) << 52) | mantissa); - } else { - return (sign == 0L) ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY; - } - - } else if (scaledExponent < 2047) { - return Double.longBitsToDouble(sign | (((long) scaledExponent) << 52) | mantissa); - } else { - return (sign == 0L) ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY; - } - } - - } - - /** - * Multiply a float number by a power of 2. - * @param f number to multiply - * @param n power of 2 - * @return f × 2n - */ - public static float scalb(final float f, final int n) { - - // first simple and fast handling when 2^n can be represented using normal numbers - if ((n > -127) && (n < 128)) { - return f * Float.intBitsToFloat((n + 127) << 23); - } - - // handle special cases - if (Float.isNaN(f) || Float.isInfinite(f) || (f == 0f)) { - return f; - } - if (n < -277) { - return (f > 0) ? 0.0f : -0.0f; - } - if (n > 276) { - return (f > 0) ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY; - } - - // decompose f - final int bits = Float.floatToIntBits(f); - final int sign = bits & 0x80000000; - int exponent = (bits >>> 23) & 0xff; - int mantissa = bits & 0x007fffff; - - // compute scaled exponent - int scaledExponent = exponent + n; - - if (n < 0) { - // we are really in the case n <= -127 - if (scaledExponent > 0) { - // both the input and the result are normal numbers, we only adjust the exponent - return Float.intBitsToFloat(sign | (scaledExponent << 23) | mantissa); - } else if (scaledExponent > -24) { - // the input is a normal number and the result is a subnormal number - - // recover the hidden mantissa bit - mantissa |= 1 << 23; - - // scales down complete mantissa, hence losing least significant bits - final int mostSignificantLostBit = mantissa & (1 << (-scaledExponent)); - mantissa >>>= 1 - scaledExponent; - if (mostSignificantLostBit != 0) { - // we need to add 1 bit to round up the result - mantissa++; - } - return Float.intBitsToFloat(sign | mantissa); - - } else { - // no need to compute the mantissa, the number scales down to 0 - return (sign == 0) ? 0.0f : -0.0f; - } - } else { - // we are really in the case n >= 128 - if (exponent == 0) { - - // the input number is subnormal, normalize it - while ((mantissa >>> 23) != 1) { - mantissa <<= 1; - --scaledExponent; - } - ++scaledExponent; - mantissa &= 0x007fffff; - - if (scaledExponent < 255) { - return Float.intBitsToFloat(sign | (scaledExponent << 23) | mantissa); - } else { - return (sign == 0) ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY; - } - - } else if (scaledExponent < 255) { - return Float.intBitsToFloat(sign | (scaledExponent << 23) | mantissa); - } else { - return (sign == 0) ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY; - } - } - - } - - /** - * Get the next machine representable number after a number, moving - * in the direction of another number. - *

- * The ordering is as follows (increasing): - *

    - *
  • -INFINITY
  • - *
  • -MAX_VALUE
  • - *
  • -MIN_VALUE
  • - *
  • -0.0
  • - *
  • +0.0
  • - *
  • +MIN_VALUE
  • - *
  • +MAX_VALUE
  • - *
  • +INFINITY
  • - *
  • - *
- *

- * If arguments compare equal, then the second argument is returned. - *

- * If {@code direction} is greater than {@code d}, - * the smallest machine representable number strictly greater than - * {@code d} is returned; if less, then the largest representable number - * strictly less than {@code d} is returned.

- *

- * If {@code d} is infinite and direction does not - * bring it back to finite numbers, it is returned unchanged.

- * - * @param d base number - * @param direction (the only important thing is whether - * {@code direction} is greater or smaller than {@code d}) - * @return the next machine representable number in the specified direction - */ - public static double nextAfter(double d, double direction) { - - // handling of some important special cases - if (Double.isNaN(d) || Double.isNaN(direction)) { - return Double.NaN; - } else if (d == direction) { - return direction; - } else if (Double.isInfinite(d)) { - return (d < 0) ? -Double.MAX_VALUE : Double.MAX_VALUE; - } else if (d == 0) { - return (direction < 0) ? -Double.MIN_VALUE : Double.MIN_VALUE; - } - // special cases MAX_VALUE to infinity and MIN_VALUE to 0 - // are handled just as normal numbers - // can use raw bits since already dealt with infinity and NaN - final long bits = Double.doubleToRawLongBits(d); - final long sign = bits & 0x8000000000000000L; - if ((direction < d) ^ (sign == 0L)) { - return Double.longBitsToDouble(sign | ((bits & 0x7fffffffffffffffL) + 1)); - } else { - return Double.longBitsToDouble(sign | ((bits & 0x7fffffffffffffffL) - 1)); - } - - } - - /** - * Get the next machine representable number after a number, moving - * in the direction of another number. - *

- * The ordering is as follows (increasing): - *

    - *
  • -INFINITY
  • - *
  • -MAX_VALUE
  • - *
  • -MIN_VALUE
  • - *
  • -0.0
  • - *
  • +0.0
  • - *
  • +MIN_VALUE
  • - *
  • +MAX_VALUE
  • - *
  • +INFINITY
  • - *
  • - *
- *

- * If arguments compare equal, then the second argument is returned. - *

- * If {@code direction} is greater than {@code f}, - * the smallest machine representable number strictly greater than - * {@code f} is returned; if less, then the largest representable number - * strictly less than {@code f} is returned.

- *

- * If {@code f} is infinite and direction does not - * bring it back to finite numbers, it is returned unchanged.

- * - * @param f base number - * @param direction (the only important thing is whether - * {@code direction} is greater or smaller than {@code f}) - * @return the next machine representable number in the specified direction - */ - public static float nextAfter(final float f, final double direction) { - - // handling of some important special cases - if (Double.isNaN(f) || Double.isNaN(direction)) { - return Float.NaN; - } else if (f == direction) { - return (float) direction; - } else if (Float.isInfinite(f)) { - return (f < 0f) ? -Float.MAX_VALUE : Float.MAX_VALUE; - } else if (f == 0f) { - return (direction < 0) ? -Float.MIN_VALUE : Float.MIN_VALUE; - } - // special cases MAX_VALUE to infinity and MIN_VALUE to 0 - // are handled just as normal numbers - - final int bits = Float.floatToIntBits(f); - final int sign = bits & 0x80000000; - if ((direction < f) ^ (sign == 0)) { - return Float.intBitsToFloat(sign | ((bits & 0x7fffffff) + 1)); - } else { - return Float.intBitsToFloat(sign | ((bits & 0x7fffffff) - 1)); - } - - } - - /** Get the largest whole number smaller than x. - * @param x number from which floor is requested - * @return a double number f such that f is an integer f <= x < f + 1.0 - */ - public static double floor(double x) { - long y; - - if (Double.isNaN(x)) { - return x; - } - - if (x >= TWO_POWER_52 || x <= -TWO_POWER_52) { - return x; - } - - y = (long) x; - if (x < 0 && y != x) { - y--; - } - - if (y == 0) { - return x*y; - } - - return y; - } - - /** Get the smallest whole number larger than x. - * @param x number from which ceil is requested - * @return a double number c such that c is an integer c - 1.0 < x <= c - */ - public static double ceil(double x) { - double y; - - if (Double.isNaN(x)) { - return x; - } - - y = floor(x); - if (y == x) { - return y; - } - - y += 1.0; - - if (y == 0) { - return x*y; - } - - return y; - } - - /** Get the whole number that is the nearest to x, or the even one if x is exactly half way between two integers. - * @param x number from which nearest whole number is requested - * @return a double number r such that r is an integer r - 0.5 <= x <= r + 0.5 - */ - public static double rint(double x) { - double y = floor(x); - double d = x - y; - - if (d > 0.5) { - if (y == -1.0) { - return -0.0; // Preserve sign of operand - } - return y+1.0; - } - if (d < 0.5) { - return y; - } - - /* half way, round to even */ - long z = (long) y; - return (z & 1) == 0 ? y : y + 1.0; - } - - /** Get the closest long to x. - * @param x number from which closest long is requested - * @return closest long to x - */ - public static long round(double x) { - final long bits = Double.doubleToRawLongBits(x); - final int biasedExp = ((int)(bits>>52)) & 0x7ff; - // Shift to get rid of bits past comma except first one: will need to - // 1-shift to the right to end up with correct magnitude. - final int shift = (52 - 1 + Double.MAX_EXPONENT) - biasedExp; - if ((shift & -64) == 0) { - // shift in [0,63], so unbiased exp in [-12,51]. - long extendedMantissa = 0x0010000000000000L | (bits & 0x000fffffffffffffL); - if (bits < 0) { - extendedMantissa = -extendedMantissa; - } - // If value is positive and first bit past comma is 0, rounding - // to lower integer, else to upper one, which is what "+1" and - // then ">>1" do. - return ((extendedMantissa >> shift) + 1L) >> 1; - } else { - // +-Infinity, NaN, or a mathematical integer. - return (long) x; - } - } - - /** Get the closest int to x. - * @param x number from which closest int is requested - * @return closest int to x - */ - public static int round(final float x) { - final int bits = Float.floatToRawIntBits(x); - final int biasedExp = (bits>>23) & 0xff; - // Shift to get rid of bits past comma except first one: will need to - // 1-shift to the right to end up with correct magnitude. - final int shift = (23 - 1 + Float.MAX_EXPONENT) - biasedExp; - if ((shift & -32) == 0) { - // shift in [0,31], so unbiased exp in [-9,22]. - int extendedMantissa = 0x00800000 | (bits & 0x007fffff); - if (bits < 0) { - extendedMantissa = -extendedMantissa; - } - // If value is positive and first bit past comma is 0, rounding - // to lower integer, else to upper one, which is what "+1" and - // then ">>1" do. - return ((extendedMantissa >> shift) + 1) >> 1; - } else { - // +-Infinity, NaN, or a mathematical integer. - return (int) x; - } - } - - /** Compute the minimum of two values - * @param a first value - * @param b second value - * @return a if a is lesser or equal to b, b otherwise - */ - public static int min(final int a, final int b) { - return (a <= b) ? a : b; - } - - /** Compute the minimum of two values - * @param a first value - * @param b second value - * @return a if a is lesser or equal to b, b otherwise - */ - public static long min(final long a, final long b) { - return (a <= b) ? a : b; - } - - /** Compute the minimum of two values - * @param a first value - * @param b second value - * @return a if a is lesser or equal to b, b otherwise - */ - public static float min(final float a, final float b) { - if (a > b) { - return b; - } - if (a < b) { - return a; - } - /* if either arg is NaN, return NaN */ - if (a != b) { - return Float.NaN; - } - /* min(+0.0,-0.0) == -0.0 */ - /* 0x80000000 == Float.floatToRawIntBits(-0.0d) */ - int bits = Float.floatToRawIntBits(a); - if (bits == 0x80000000) { - return a; - } - return b; - } - - /** Compute the minimum of two values - * @param a first value - * @param b second value - * @return a if a is lesser or equal to b, b otherwise - */ - public static double min(final double a, final double b) { - if (a > b) { - return b; - } - if (a < b) { - return a; - } - /* if either arg is NaN, return NaN */ - if (a != b) { - return Double.NaN; - } - /* min(+0.0,-0.0) == -0.0 */ - /* 0x8000000000000000L == Double.doubleToRawLongBits(-0.0d) */ - long bits = Double.doubleToRawLongBits(a); - if (bits == 0x8000000000000000L) { - return a; - } - return b; - } - - /** Compute the maximum of two values - * @param a first value - * @param b second value - * @return b if a is lesser or equal to b, a otherwise - */ - public static int max(final int a, final int b) { - return (a <= b) ? b : a; - } - - /** Compute the maximum of two values - * @param a first value - * @param b second value - * @return b if a is lesser or equal to b, a otherwise - */ - public static long max(final long a, final long b) { - return (a <= b) ? b : a; - } - - /** Compute the maximum of two values - * @param a first value - * @param b second value - * @return b if a is lesser or equal to b, a otherwise - */ - public static float max(final float a, final float b) { - if (a > b) { - return a; - } - if (a < b) { - return b; - } - /* if either arg is NaN, return NaN */ - if (a != b) { - return Float.NaN; - } - /* min(+0.0,-0.0) == -0.0 */ - /* 0x80000000 == Float.floatToRawIntBits(-0.0d) */ - int bits = Float.floatToRawIntBits(a); - if (bits == 0x80000000) { - return b; - } - return a; - } - - /** Compute the maximum of two values - * @param a first value - * @param b second value - * @return b if a is lesser or equal to b, a otherwise - */ - public static double max(final double a, final double b) { - if (a > b) { - return a; - } - if (a < b) { - return b; - } - /* if either arg is NaN, return NaN */ - if (a != b) { - return Double.NaN; - } - /* min(+0.0,-0.0) == -0.0 */ - /* 0x8000000000000000L == Double.doubleToRawLongBits(-0.0d) */ - long bits = Double.doubleToRawLongBits(a); - if (bits == 0x8000000000000000L) { - return b; - } - return a; - } - - /** - * Returns the hypotenuse of a triangle with sides {@code x} and {@code y} - * - sqrt(x2 +y2)
- * avoiding intermediate overflow or underflow. - * - *
    - *
  • If either argument is infinite, then the result is positive infinity.
  • - *
  • else, if either argument is NaN then the result is NaN.
  • - *
- * - * @param x a value - * @param y a value - * @return sqrt(x2 +y2) - */ - public static double hypot(final double x, final double y) { - if (Double.isInfinite(x) || Double.isInfinite(y)) { - return Double.POSITIVE_INFINITY; - } else if (Double.isNaN(x) || Double.isNaN(y)) { - return Double.NaN; - } else { - - final int expX = getExponent(x); - final int expY = getExponent(y); - if (expX > expY + 27) { - // y is neglectible with respect to x - return abs(x); - } else if (expY > expX + 27) { - // x is neglectible with respect to y - return abs(y); - } else { - - // find an intermediate scale to avoid both overflow and underflow - final int middleExp = (expX + expY) / 2; - - // scale parameters without losing precision - final double scaledX = scalb(x, -middleExp); - final double scaledY = scalb(y, -middleExp); - - // compute scaled hypotenuse - final double scaledH = sqrt(scaledX * scaledX + scaledY * scaledY); - - // remove scaling - return scalb(scaledH, middleExp); - - } - - } - } - - /** - * Computes the remainder as prescribed by the IEEE 754 standard. - * The remainder value is mathematically equal to {@code x - y*n} - * where {@code n} is the mathematical integer closest to the exact mathematical value - * of the quotient {@code x/y}. - * If two mathematical integers are equally close to {@code x/y} then - * {@code n} is the integer that is even. - *
    - *
  • If either operand is NaN, the result is NaN.
  • - *
  • If the result is not NaN, the sign of the result equals the sign of the dividend.
  • - *
  • If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
  • - *
  • If the dividend is finite and the divisor is an infinity, the result equals the dividend.
  • - *
  • If the dividend is a zero and the divisor is finite, the result equals the dividend.
  • - *
- * @param dividend the number to be divided - * @param divisor the number by which to divide - * @return the remainder, rounded - */ - public static double IEEEremainder(final double dividend, final double divisor) { - if (getExponent(dividend) == 1024 || getExponent(divisor) == 1024 || divisor == 0.0) { - // we are in one of the special cases - if (Double.isInfinite(divisor) && !Double.isInfinite(dividend)) { - return dividend; - } else { - return Double.NaN; - } - } else { - // we are in the general case - final double n = FastMath.rint(dividend / divisor); - final double remainder = Double.isInfinite(n) ? 0.0 : dividend - divisor * n; - return (remainder == 0) ? FastMath.copySign(remainder, dividend) : remainder; - } - } - - /** Convert a long to integer, detecting overflows - * @param n number to convert to int - * @return integer with same value as n if no overflows occur - * @exception MathArithmeticException if n cannot fit into an int - * @since 3.4 - */ - public static int toIntExact(final long n) throws MathArithmeticException { - if (n < Integer.MIN_VALUE || n > Integer.MAX_VALUE) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW); - } - return (int) n; - } - - /** Increment a number, detecting overflows. - * @param n number to increment - * @return n+1 if no overflows occur - * @exception MathArithmeticException if an overflow occurs - * @since 3.4 - */ - public static int incrementExact(final int n) throws MathArithmeticException { - - if (n == Integer.MAX_VALUE) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_ADDITION, n, 1); - } - - return n + 1; - - } - - /** Increment a number, detecting overflows. - * @param n number to increment - * @return n+1 if no overflows occur - * @exception MathArithmeticException if an overflow occurs - * @since 3.4 - */ - public static long incrementExact(final long n) throws MathArithmeticException { - - if (n == Long.MAX_VALUE) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_ADDITION, n, 1); - } - - return n + 1; - - } - - /** Decrement a number, detecting overflows. - * @param n number to decrement - * @return n-1 if no overflows occur - * @exception MathArithmeticException if an overflow occurs - * @since 3.4 - */ - public static int decrementExact(final int n) throws MathArithmeticException { - - if (n == Integer.MIN_VALUE) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_SUBTRACTION, n, 1); - } - - return n - 1; - - } - - /** Decrement a number, detecting overflows. - * @param n number to decrement - * @return n-1 if no overflows occur - * @exception MathArithmeticException if an overflow occurs - * @since 3.4 - */ - public static long decrementExact(final long n) throws MathArithmeticException { - - if (n == Long.MIN_VALUE) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_SUBTRACTION, n, 1); - } - - return n - 1; - - } - - /** Add two numbers, detecting overflows. - * @param a first number to add - * @param b second number to add - * @return a+b if no overflows occur - * @exception MathArithmeticException if an overflow occurs - * @since 3.4 - */ - public static int addExact(final int a, final int b) throws MathArithmeticException { - - // compute sum - final int sum = a + b; - - // check for overflow - if ((a ^ b) >= 0 && (sum ^ b) < 0) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_ADDITION, a, b); - } - - return sum; - - } - - /** Add two numbers, detecting overflows. - * @param a first number to add - * @param b second number to add - * @return a+b if no overflows occur - * @exception MathArithmeticException if an overflow occurs - * @since 3.4 - */ - public static long addExact(final long a, final long b) throws MathArithmeticException { - - // compute sum - final long sum = a + b; - - // check for overflow - if ((a ^ b) >= 0 && (sum ^ b) < 0) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_ADDITION, a, b); - } - - return sum; - - } - - /** Subtract two numbers, detecting overflows. - * @param a first number - * @param b second number to subtract from a - * @return a-b if no overflows occur - * @exception MathArithmeticException if an overflow occurs - * @since 3.4 - */ - public static int subtractExact(final int a, final int b) { - - // compute subtraction - final int sub = a - b; - - // check for overflow - if ((a ^ b) < 0 && (sub ^ b) >= 0) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_SUBTRACTION, a, b); - } - - return sub; - - } - - /** Subtract two numbers, detecting overflows. - * @param a first number - * @param b second number to subtract from a - * @return a-b if no overflows occur - * @exception MathArithmeticException if an overflow occurs - * @since 3.4 - */ - public static long subtractExact(final long a, final long b) { - - // compute subtraction - final long sub = a - b; - - // check for overflow - if ((a ^ b) < 0 && (sub ^ b) >= 0) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_SUBTRACTION, a, b); - } - - return sub; - - } - - /** Multiply two numbers, detecting overflows. - * @param a first number to multiply - * @param b second number to multiply - * @return a*b if no overflows occur - * @exception MathArithmeticException if an overflow occurs - * @since 3.4 - */ - public static int multiplyExact(final int a, final int b) { - if (((b > 0) && (a > Integer.MAX_VALUE / b || a < Integer.MIN_VALUE / b)) || - ((b < -1) && (a > Integer.MIN_VALUE / b || a < Integer.MAX_VALUE / b)) || - ((b == -1) && (a == Integer.MIN_VALUE))) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_MULTIPLICATION, a, b); - } - return a * b; - } - - /** Multiply two numbers, detecting overflows. - * @param a first number to multiply - * @param b second number to multiply - * @return a*b if no overflows occur - * @exception MathArithmeticException if an overflow occurs - * @since 3.4 - */ - public static long multiplyExact(final long a, final long b) { - if (((b > 0l) && (a > Long.MAX_VALUE / b || a < Long.MIN_VALUE / b)) || - ((b < -1l) && (a > Long.MIN_VALUE / b || a < Long.MAX_VALUE / b)) || - ((b == -1l) && (a == Long.MIN_VALUE))) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_MULTIPLICATION, a, b); - } - return a * b; - } - - /** Finds q such that a = q b + r with 0 <= r < b if b > 0 and b < r <= 0 if b < 0. - *

- * This methods returns the same value as integer division when - * a and b are same signs, but returns a different value when - * they are opposite (i.e. q is negative). - *

- * @param a dividend - * @param b divisor - * @return q such that a = q b + r with 0 <= r < b if b > 0 and b < r <= 0 if b < 0 - * @exception MathArithmeticException if b == 0 - * @see #floorMod(int, int) - * @since 3.4 - */ - public static int floorDiv(final int a, final int b) throws MathArithmeticException { - - if (b == 0) { - throw new MathArithmeticException(LocalizedFormats.ZERO_DENOMINATOR); - } - - final int m = a % b; - if ((a ^ b) >= 0 || m == 0) { - // a an b have same sign, or division is exact - return a / b; - } else { - // a and b have opposite signs and division is not exact - return (a / b) - 1; - } - - } - - /** Finds q such that a = q b + r with 0 <= r < b if b > 0 and b < r <= 0 if b < 0. - *

- * This methods returns the same value as integer division when - * a and b are same signs, but returns a different value when - * they are opposite (i.e. q is negative). - *

- * @param a dividend - * @param b divisor - * @return q such that a = q b + r with 0 <= r < b if b > 0 and b < r <= 0 if b < 0 - * @exception MathArithmeticException if b == 0 - * @see #floorMod(long, long) - * @since 3.4 - */ - public static long floorDiv(final long a, final long b) throws MathArithmeticException { - - if (b == 0l) { - throw new MathArithmeticException(LocalizedFormats.ZERO_DENOMINATOR); - } - - final long m = a % b; - if ((a ^ b) >= 0l || m == 0l) { - // a an b have same sign, or division is exact - return a / b; - } else { - // a and b have opposite signs and division is not exact - return (a / b) - 1l; - } - - } - - /** Finds r such that a = q b + r with 0 <= r < b if b > 0 and b < r <= 0 if b < 0. - *

- * This methods returns the same value as integer modulo when - * a and b are same signs, but returns a different value when - * they are opposite (i.e. q is negative). - *

- * @param a dividend - * @param b divisor - * @return r such that a = q b + r with 0 <= r < b if b > 0 and b < r <= 0 if b < 0 - * @exception MathArithmeticException if b == 0 - * @see #floorDiv(int, int) - * @since 3.4 - */ - public static int floorMod(final int a, final int b) throws MathArithmeticException { - - if (b == 0) { - throw new MathArithmeticException(LocalizedFormats.ZERO_DENOMINATOR); - } - - final int m = a % b; - if ((a ^ b) >= 0 || m == 0) { - // a an b have same sign, or division is exact - return m; - } else { - // a and b have opposite signs and division is not exact - return b + m; - } - - } - - /** Finds r such that a = q b + r with 0 <= r < b if b > 0 and b < r <= 0 if b < 0. - *

- * This methods returns the same value as integer modulo when - * a and b are same signs, but returns a different value when - * they are opposite (i.e. q is negative). - *

- * @param a dividend - * @param b divisor - * @return r such that a = q b + r with 0 <= r < b if b > 0 and b < r <= 0 if b < 0 - * @exception MathArithmeticException if b == 0 - * @see #floorDiv(long, long) - * @since 3.4 - */ - public static long floorMod(final long a, final long b) { - - if (b == 0l) { - throw new MathArithmeticException(LocalizedFormats.ZERO_DENOMINATOR); - } - - final long m = a % b; - if ((a ^ b) >= 0l || m == 0l) { - // a an b have same sign, or division is exact - return m; - } else { - // a and b have opposite signs and division is not exact - return b + m; - } - - } - - /** - * Returns the first argument with the sign of the second argument. - * A NaN {@code sign} argument is treated as positive. - * - * @param magnitude the value to return - * @param sign the sign for the returned value - * @return the magnitude with the same sign as the {@code sign} argument - */ - public static double copySign(double magnitude, double sign){ - // The highest order bit is going to be zero if the - // highest order bit of m and s is the same and one otherwise. - // So (m^s) will be positive if both m and s have the same sign - // and negative otherwise. - final long m = Double.doubleToRawLongBits(magnitude); // don't care about NaN - final long s = Double.doubleToRawLongBits(sign); - if ((m^s) >= 0) { - return magnitude; - } - return -magnitude; // flip sign - } - - /** - * Returns the first argument with the sign of the second argument. - * A NaN {@code sign} argument is treated as positive. - * - * @param magnitude the value to return - * @param sign the sign for the returned value - * @return the magnitude with the same sign as the {@code sign} argument - */ - public static float copySign(float magnitude, float sign){ - // The highest order bit is going to be zero if the - // highest order bit of m and s is the same and one otherwise. - // So (m^s) will be positive if both m and s have the same sign - // and negative otherwise. - final int m = Float.floatToRawIntBits(magnitude); - final int s = Float.floatToRawIntBits(sign); - if ((m^s) >= 0) { - return magnitude; - } - return -magnitude; // flip sign - } - - /** - * Return the exponent of a double number, removing the bias. - *

- * For double numbers of the form 2x, the unbiased - * exponent is exactly x. - *

- * @param d number from which exponent is requested - * @return exponent for d in IEEE754 representation, without bias - */ - public static int getExponent(final double d) { - // NaN and Infinite will return 1024 anywho so can use raw bits - return (int) ((Double.doubleToRawLongBits(d) >>> 52) & 0x7ff) - 1023; - } - - /** - * Return the exponent of a float number, removing the bias. - *

- * For float numbers of the form 2x, the unbiased - * exponent is exactly x. - *

- * @param f number from which exponent is requested - * @return exponent for d in IEEE754 representation, without bias - */ - public static int getExponent(final float f) { - // NaN and Infinite will return the same exponent anywho so can use raw bits - return ((Float.floatToRawIntBits(f) >>> 23) & 0xff) - 127; - } - - /** - * Print out contents of arrays, and check the length. - *

used to generate the preset arrays originally.

- * @param a unused - */ - public static void main(String[] a) { - PrintStream out = System.out; - FastMathCalc.printarray(out, "EXP_INT_TABLE_A", EXP_INT_TABLE_LEN, ExpIntTable.EXP_INT_TABLE_A); - FastMathCalc.printarray(out, "EXP_INT_TABLE_B", EXP_INT_TABLE_LEN, ExpIntTable.EXP_INT_TABLE_B); - FastMathCalc.printarray(out, "EXP_FRAC_TABLE_A", EXP_FRAC_TABLE_LEN, ExpFracTable.EXP_FRAC_TABLE_A); - FastMathCalc.printarray(out, "EXP_FRAC_TABLE_B", EXP_FRAC_TABLE_LEN, ExpFracTable.EXP_FRAC_TABLE_B); - FastMathCalc.printarray(out, "LN_MANT",LN_MANT_LEN, lnMant.LN_MANT); - FastMathCalc.printarray(out, "SINE_TABLE_A", SINE_TABLE_LEN, SINE_TABLE_A); - FastMathCalc.printarray(out, "SINE_TABLE_B", SINE_TABLE_LEN, SINE_TABLE_B); - FastMathCalc.printarray(out, "COSINE_TABLE_A", SINE_TABLE_LEN, COSINE_TABLE_A); - FastMathCalc.printarray(out, "COSINE_TABLE_B", SINE_TABLE_LEN, COSINE_TABLE_B); - FastMathCalc.printarray(out, "TANGENT_TABLE_A", SINE_TABLE_LEN, TANGENT_TABLE_A); - FastMathCalc.printarray(out, "TANGENT_TABLE_B", SINE_TABLE_LEN, TANGENT_TABLE_B); - } - - /** Enclose large data table in nested static class so it's only loaded on first access. */ - private static class ExpIntTable { - /** Exponential evaluated at integer values, - * exp(x) = expIntTableA[x + EXP_INT_TABLE_MAX_INDEX] + expIntTableB[x+EXP_INT_TABLE_MAX_INDEX]. - */ - private static final double[] EXP_INT_TABLE_A; - /** Exponential evaluated at integer values, - * exp(x) = expIntTableA[x + EXP_INT_TABLE_MAX_INDEX] + expIntTableB[x+EXP_INT_TABLE_MAX_INDEX] - */ - private static final double[] EXP_INT_TABLE_B; - - static { - if (RECOMPUTE_TABLES_AT_RUNTIME) { - EXP_INT_TABLE_A = new double[FastMath.EXP_INT_TABLE_LEN]; - EXP_INT_TABLE_B = new double[FastMath.EXP_INT_TABLE_LEN]; - - final double tmp[] = new double[2]; - final double recip[] = new double[2]; - - // Populate expIntTable - for (int i = 0; i < FastMath.EXP_INT_TABLE_MAX_INDEX; i++) { - FastMathCalc.expint(i, tmp); - EXP_INT_TABLE_A[i + FastMath.EXP_INT_TABLE_MAX_INDEX] = tmp[0]; - EXP_INT_TABLE_B[i + FastMath.EXP_INT_TABLE_MAX_INDEX] = tmp[1]; - - if (i != 0) { - // Negative integer powers - FastMathCalc.splitReciprocal(tmp, recip); - EXP_INT_TABLE_A[FastMath.EXP_INT_TABLE_MAX_INDEX - i] = recip[0]; - EXP_INT_TABLE_B[FastMath.EXP_INT_TABLE_MAX_INDEX - i] = recip[1]; - } - } - } else { - EXP_INT_TABLE_A = FastMathLiteralArrays.loadExpIntA(); - EXP_INT_TABLE_B = FastMathLiteralArrays.loadExpIntB(); - } - } - } - - /** Enclose large data table in nested static class so it's only loaded on first access. */ - private static class ExpFracTable { - /** Exponential over the range of 0 - 1 in increments of 2^-10 - * exp(x/1024) = expFracTableA[x] + expFracTableB[x]. - * 1024 = 2^10 - */ - private static final double[] EXP_FRAC_TABLE_A; - /** Exponential over the range of 0 - 1 in increments of 2^-10 - * exp(x/1024) = expFracTableA[x] + expFracTableB[x]. - */ - private static final double[] EXP_FRAC_TABLE_B; - - static { - if (RECOMPUTE_TABLES_AT_RUNTIME) { - EXP_FRAC_TABLE_A = new double[FastMath.EXP_FRAC_TABLE_LEN]; - EXP_FRAC_TABLE_B = new double[FastMath.EXP_FRAC_TABLE_LEN]; - - final double tmp[] = new double[2]; - - // Populate expFracTable - final double factor = 1d / (EXP_FRAC_TABLE_LEN - 1); - for (int i = 0; i < EXP_FRAC_TABLE_A.length; i++) { - FastMathCalc.slowexp(i * factor, tmp); - EXP_FRAC_TABLE_A[i] = tmp[0]; - EXP_FRAC_TABLE_B[i] = tmp[1]; - } - } else { - EXP_FRAC_TABLE_A = FastMathLiteralArrays.loadExpFracA(); - EXP_FRAC_TABLE_B = FastMathLiteralArrays.loadExpFracB(); - } - } - } - - /** Enclose large data table in nested static class so it's only loaded on first access. */ - private static class lnMant { - /** Extended precision logarithm table over the range 1 - 2 in increments of 2^-10. */ - private static final double[][] LN_MANT; - - static { - if (RECOMPUTE_TABLES_AT_RUNTIME) { - LN_MANT = new double[FastMath.LN_MANT_LEN][]; - - // Populate lnMant table - for (int i = 0; i < LN_MANT.length; i++) { - final double d = Double.longBitsToDouble( (((long) i) << 42) | 0x3ff0000000000000L ); - LN_MANT[i] = FastMathCalc.slowLog(d); - } - } else { - LN_MANT = FastMathLiteralArrays.loadLnMant(); - } - } - } - - /** Enclose the Cody/Waite reduction (used in "sin", "cos" and "tan"). */ - private static class CodyWaite { - /** k */ - private final int finalK; - /** remA */ - private final double finalRemA; - /** remB */ - private final double finalRemB; - - /** - * @param xa Argument. - */ - CodyWaite(double xa) { - // Estimate k. - //k = (int)(xa / 1.5707963267948966); - int k = (int)(xa * 0.6366197723675814); - - // Compute remainder. - double remA; - double remB; - while (true) { - double a = -k * 1.570796251296997; - remA = xa + a; - remB = -(remA - xa - a); - - a = -k * 7.549789948768648E-8; - double b = remA; - remA = a + b; - remB += -(remA - b - a); - - a = -k * 6.123233995736766E-17; - b = remA; - remA = a + b; - remB += -(remA - b - a); - - if (remA > 0) { - break; - } - - // Remainder is negative, so decrement k and try again. - // This should only happen if the input is very close - // to an even multiple of pi/2. - --k; - } - - this.finalK = k; - this.finalRemA = remA; - this.finalRemB = remB; - } - - /** - * @return k - */ - int getK() { - return finalK; - } - /** - * @return remA - */ - double getRemA() { - return finalRemA; - } - /** - * @return remB - */ - double getRemB() { - return finalRemB; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/FastMathCalc.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/FastMathCalc.java deleted file mode 100644 index 7beba2a4e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/FastMathCalc.java +++ /dev/null @@ -1,658 +0,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. - */ -package org.apache.commons.math4.util; - -import java.io.PrintStream; - -import org.apache.commons.math4.exception.DimensionMismatchException; - -/** Class used to compute the classical functions tables. - * @since 3.0 - */ -class FastMathCalc { - - /** - * 0x40000000 - used to split a double into two parts, both with the low order bits cleared. - * Equivalent to 2^30. - */ - private static final long HEX_40000000 = 0x40000000L; // 1073741824L - - /** Factorial table, for Taylor series expansions. 0!, 1!, 2!, ... 19! */ - private static final double FACT[] = new double[] - { - +1.0d, // 0 - +1.0d, // 1 - +2.0d, // 2 - +6.0d, // 3 - +24.0d, // 4 - +120.0d, // 5 - +720.0d, // 6 - +5040.0d, // 7 - +40320.0d, // 8 - +362880.0d, // 9 - +3628800.0d, // 10 - +39916800.0d, // 11 - +479001600.0d, // 12 - +6227020800.0d, // 13 - +87178291200.0d, // 14 - +1307674368000.0d, // 15 - +20922789888000.0d, // 16 - +355687428096000.0d, // 17 - +6402373705728000.0d, // 18 - +121645100408832000.0d, // 19 - }; - - /** Coefficients for slowLog. */ - private static final double LN_SPLIT_COEF[][] = { - {2.0, 0.0}, - {0.6666666269302368, 3.9736429850260626E-8}, - {0.3999999761581421, 2.3841857910019882E-8}, - {0.2857142686843872, 1.7029898543501842E-8}, - {0.2222222089767456, 1.3245471311735498E-8}, - {0.1818181574344635, 2.4384203044354907E-8}, - {0.1538461446762085, 9.140260083262505E-9}, - {0.13333332538604736, 9.220590270857665E-9}, - {0.11764700710773468, 1.2393345855018391E-8}, - {0.10526403784751892, 8.251545029714408E-9}, - {0.0952233225107193, 1.2675934823758863E-8}, - {0.08713622391223907, 1.1430250008909141E-8}, - {0.07842259109020233, 2.404307984052299E-9}, - {0.08371849358081818, 1.176342548272881E-8}, - {0.030589580535888672, 1.2958646899018938E-9}, - {0.14982303977012634, 1.225743062930824E-8}, - }; - - /** Table start declaration. */ - private static final String TABLE_START_DECL = " {"; - - /** Table end declaration. */ - private static final String TABLE_END_DECL = " };"; - - /** - * Private Constructor. - */ - private FastMathCalc() { - } - - /** Build the sine and cosine tables. - * @param SINE_TABLE_A table of the most significant part of the sines - * @param SINE_TABLE_B table of the least significant part of the sines - * @param COSINE_TABLE_A table of the most significant part of the cosines - * @param COSINE_TABLE_B table of the most significant part of the cosines - * @param SINE_TABLE_LEN length of the tables - * @param TANGENT_TABLE_A table of the most significant part of the tangents - * @param TANGENT_TABLE_B table of the most significant part of the tangents - */ - @SuppressWarnings("unused") - private static void buildSinCosTables(double[] SINE_TABLE_A, double[] SINE_TABLE_B, - double[] COSINE_TABLE_A, double[] COSINE_TABLE_B, - int SINE_TABLE_LEN, double[] TANGENT_TABLE_A, double[] TANGENT_TABLE_B) { - final double result[] = new double[2]; - - /* Use taylor series for 0 <= x <= 6/8 */ - for (int i = 0; i < 7; i++) { - double x = i / 8.0; - - slowSin(x, result); - SINE_TABLE_A[i] = result[0]; - SINE_TABLE_B[i] = result[1]; - - slowCos(x, result); - COSINE_TABLE_A[i] = result[0]; - COSINE_TABLE_B[i] = result[1]; - } - - /* Use angle addition formula to complete table to 13/8, just beyond pi/2 */ - for (int i = 7; i < SINE_TABLE_LEN; i++) { - double xs[] = new double[2]; - double ys[] = new double[2]; - double as[] = new double[2]; - double bs[] = new double[2]; - double temps[] = new double[2]; - - if ( (i & 1) == 0) { - // Even, use double angle - xs[0] = SINE_TABLE_A[i/2]; - xs[1] = SINE_TABLE_B[i/2]; - ys[0] = COSINE_TABLE_A[i/2]; - ys[1] = COSINE_TABLE_B[i/2]; - - /* compute sine */ - splitMult(xs, ys, result); - SINE_TABLE_A[i] = result[0] * 2.0; - SINE_TABLE_B[i] = result[1] * 2.0; - - /* Compute cosine */ - splitMult(ys, ys, as); - splitMult(xs, xs, temps); - temps[0] = -temps[0]; - temps[1] = -temps[1]; - splitAdd(as, temps, result); - COSINE_TABLE_A[i] = result[0]; - COSINE_TABLE_B[i] = result[1]; - } else { - xs[0] = SINE_TABLE_A[i/2]; - xs[1] = SINE_TABLE_B[i/2]; - ys[0] = COSINE_TABLE_A[i/2]; - ys[1] = COSINE_TABLE_B[i/2]; - as[0] = SINE_TABLE_A[i/2+1]; - as[1] = SINE_TABLE_B[i/2+1]; - bs[0] = COSINE_TABLE_A[i/2+1]; - bs[1] = COSINE_TABLE_B[i/2+1]; - - /* compute sine */ - splitMult(xs, bs, temps); - splitMult(ys, as, result); - splitAdd(result, temps, result); - SINE_TABLE_A[i] = result[0]; - SINE_TABLE_B[i] = result[1]; - - /* Compute cosine */ - splitMult(ys, bs, result); - splitMult(xs, as, temps); - temps[0] = -temps[0]; - temps[1] = -temps[1]; - splitAdd(result, temps, result); - COSINE_TABLE_A[i] = result[0]; - COSINE_TABLE_B[i] = result[1]; - } - } - - /* Compute tangent = sine/cosine */ - for (int i = 0; i < SINE_TABLE_LEN; i++) { - double xs[] = new double[2]; - double ys[] = new double[2]; - double as[] = new double[2]; - - as[0] = COSINE_TABLE_A[i]; - as[1] = COSINE_TABLE_B[i]; - - splitReciprocal(as, ys); - - xs[0] = SINE_TABLE_A[i]; - xs[1] = SINE_TABLE_B[i]; - - splitMult(xs, ys, as); - - TANGENT_TABLE_A[i] = as[0]; - TANGENT_TABLE_B[i] = as[1]; - } - - } - - /** - * For x between 0 and pi/4 compute cosine using Talor series - * cos(x) = 1 - x^2/2! + x^4/4! ... - * @param x number from which cosine is requested - * @param result placeholder where to put the result in extended precision - * (may be null) - * @return cos(x) - */ - static double slowCos(final double x, final double result[]) { - - final double xs[] = new double[2]; - final double ys[] = new double[2]; - final double facts[] = new double[2]; - final double as[] = new double[2]; - split(x, xs); - ys[0] = ys[1] = 0.0; - - for (int i = FACT.length-1; i >= 0; i--) { - splitMult(xs, ys, as); - ys[0] = as[0]; ys[1] = as[1]; - - if ( (i & 1) != 0) { // skip odd entries - continue; - } - - split(FACT[i], as); - splitReciprocal(as, facts); - - if ( (i & 2) != 0 ) { // alternate terms are negative - facts[0] = -facts[0]; - facts[1] = -facts[1]; - } - - splitAdd(ys, facts, as); - ys[0] = as[0]; ys[1] = as[1]; - } - - if (result != null) { - result[0] = ys[0]; - result[1] = ys[1]; - } - - return ys[0] + ys[1]; - } - - /** - * For x between 0 and pi/4 compute sine using Taylor expansion: - * sin(x) = x - x^3/3! + x^5/5! - x^7/7! ... - * @param x number from which sine is requested - * @param result placeholder where to put the result in extended precision - * (may be null) - * @return sin(x) - */ - static double slowSin(final double x, final double result[]) { - final double xs[] = new double[2]; - final double ys[] = new double[2]; - final double facts[] = new double[2]; - final double as[] = new double[2]; - split(x, xs); - ys[0] = ys[1] = 0.0; - - for (int i = FACT.length-1; i >= 0; i--) { - splitMult(xs, ys, as); - ys[0] = as[0]; ys[1] = as[1]; - - if ( (i & 1) == 0) { // Ignore even numbers - continue; - } - - split(FACT[i], as); - splitReciprocal(as, facts); - - if ( (i & 2) != 0 ) { // alternate terms are negative - facts[0] = -facts[0]; - facts[1] = -facts[1]; - } - - splitAdd(ys, facts, as); - ys[0] = as[0]; ys[1] = as[1]; - } - - if (result != null) { - result[0] = ys[0]; - result[1] = ys[1]; - } - - return ys[0] + ys[1]; - } - - - /** - * For x between 0 and 1, returns exp(x), uses extended precision - * @param x argument of exponential - * @param result placeholder where to place exp(x) split in two terms - * for extra precision (i.e. exp(x) = result[0] + result[1] - * @return exp(x) - */ - static double slowexp(final double x, final double result[]) { - final double xs[] = new double[2]; - final double ys[] = new double[2]; - final double facts[] = new double[2]; - final double as[] = new double[2]; - split(x, xs); - ys[0] = ys[1] = 0.0; - - for (int i = FACT.length-1; i >= 0; i--) { - splitMult(xs, ys, as); - ys[0] = as[0]; - ys[1] = as[1]; - - split(FACT[i], as); - splitReciprocal(as, facts); - - splitAdd(ys, facts, as); - ys[0] = as[0]; - ys[1] = as[1]; - } - - if (result != null) { - result[0] = ys[0]; - result[1] = ys[1]; - } - - return ys[0] + ys[1]; - } - - /** Compute split[0], split[1] such that their sum is equal to d, - * and split[0] has its 30 least significant bits as zero. - * @param d number to split - * @param split placeholder where to place the result - */ - private static void split(final double d, final double split[]) { - if (d < 8e298 && d > -8e298) { - final double a = d * HEX_40000000; - split[0] = (d + a) - a; - split[1] = d - split[0]; - } else { - final double a = d * 9.31322574615478515625E-10; - split[0] = (d + a - d) * HEX_40000000; - split[1] = d - split[0]; - } - } - - /** Recompute a split. - * @param a input/out array containing the split, changed - * on output - */ - private static void resplit(final double a[]) { - final double c = a[0] + a[1]; - final double d = -(c - a[0] - a[1]); - - if (c < 8e298 && c > -8e298) { // MAGIC NUMBER - double z = c * HEX_40000000; - a[0] = (c + z) - z; - a[1] = c - a[0] + d; - } else { - double z = c * 9.31322574615478515625E-10; - a[0] = (c + z - c) * HEX_40000000; - a[1] = c - a[0] + d; - } - } - - /** Multiply two numbers in split form. - * @param a first term of multiplication - * @param b second term of multiplication - * @param ans placeholder where to put the result - */ - private static void splitMult(double a[], double b[], double ans[]) { - ans[0] = a[0] * b[0]; - ans[1] = a[0] * b[1] + a[1] * b[0] + a[1] * b[1]; - - /* Resplit */ - resplit(ans); - } - - /** Add two numbers in split form. - * @param a first term of addition - * @param b second term of addition - * @param ans placeholder where to put the result - */ - private static void splitAdd(final double a[], final double b[], final double ans[]) { - ans[0] = a[0] + b[0]; - ans[1] = a[1] + b[1]; - - resplit(ans); - } - - /** Compute the reciprocal of in. Use the following algorithm. - * in = c + d. - * want to find x + y such that x+y = 1/(c+d) and x is much - * larger than y and x has several zero bits on the right. - * - * Set b = 1/(2^22), a = 1 - b. Thus (a+b) = 1. - * Use following identity to compute (a+b)/(c+d) - * - * (a+b)/(c+d) = a/c + (bc - ad) / (c^2 + cd) - * set x = a/c and y = (bc - ad) / (c^2 + cd) - * This will be close to the right answer, but there will be - * some rounding in the calculation of X. So by carefully - * computing 1 - (c+d)(x+y) we can compute an error and - * add that back in. This is done carefully so that terms - * of similar size are subtracted first. - * @param in initial number, in split form - * @param result placeholder where to put the result - */ - static void splitReciprocal(final double in[], final double result[]) { - final double b = 1.0/4194304.0; - final double a = 1.0 - b; - - if (in[0] == 0.0) { - in[0] = in[1]; - in[1] = 0.0; - } - - result[0] = a / in[0]; - result[1] = (b*in[0]-a*in[1]) / (in[0]*in[0] + in[0]*in[1]); - - if (result[1] != result[1]) { // can happen if result[1] is NAN - result[1] = 0.0; - } - - /* Resplit */ - resplit(result); - - for (int i = 0; i < 2; i++) { - /* this may be overkill, probably once is enough */ - double err = 1.0 - result[0] * in[0] - result[0] * in[1] - - result[1] * in[0] - result[1] * in[1]; - /*err = 1.0 - err; */ - err *= result[0] + result[1]; - /*printf("err = %16e\n", err); */ - result[1] += err; - } - } - - /** Compute (a[0] + a[1]) * (b[0] + b[1]) in extended precision. - * @param a first term of the multiplication - * @param b second term of the multiplication - * @param result placeholder where to put the result - */ - private static void quadMult(final double a[], final double b[], final double result[]) { - final double xs[] = new double[2]; - final double ys[] = new double[2]; - final double zs[] = new double[2]; - - /* a[0] * b[0] */ - split(a[0], xs); - split(b[0], ys); - splitMult(xs, ys, zs); - - result[0] = zs[0]; - result[1] = zs[1]; - - /* a[0] * b[1] */ - split(b[1], ys); - splitMult(xs, ys, zs); - - double tmp = result[0] + zs[0]; - result[1] -= tmp - result[0] - zs[0]; - result[0] = tmp; - tmp = result[0] + zs[1]; - result[1] -= tmp - result[0] - zs[1]; - result[0] = tmp; - - /* a[1] * b[0] */ - split(a[1], xs); - split(b[0], ys); - splitMult(xs, ys, zs); - - tmp = result[0] + zs[0]; - result[1] -= tmp - result[0] - zs[0]; - result[0] = tmp; - tmp = result[0] + zs[1]; - result[1] -= tmp - result[0] - zs[1]; - result[0] = tmp; - - /* a[1] * b[0] */ - split(a[1], xs); - split(b[1], ys); - splitMult(xs, ys, zs); - - tmp = result[0] + zs[0]; - result[1] -= tmp - result[0] - zs[0]; - result[0] = tmp; - tmp = result[0] + zs[1]; - result[1] -= tmp - result[0] - zs[1]; - result[0] = tmp; - } - - /** Compute exp(p) for a integer p in extended precision. - * @param p integer whose exponential is requested - * @param result placeholder where to put the result in extended precision - * @return exp(p) in standard precision (equal to result[0] + result[1]) - */ - static double expint(int p, final double result[]) { - //double x = M_E; - final double xs[] = new double[2]; - final double as[] = new double[2]; - final double ys[] = new double[2]; - //split(x, xs); - //xs[1] = (double)(2.7182818284590452353602874713526625L - xs[0]); - //xs[0] = 2.71827697753906250000; - //xs[1] = 4.85091998273542816811e-06; - //xs[0] = Double.longBitsToDouble(0x4005bf0800000000L); - //xs[1] = Double.longBitsToDouble(0x3ed458a2bb4a9b00L); - - /* E */ - xs[0] = 2.718281828459045; - xs[1] = 1.4456468917292502E-16; - - split(1.0, ys); - - while (p > 0) { - if ((p & 1) != 0) { - quadMult(ys, xs, as); - ys[0] = as[0]; ys[1] = as[1]; - } - - quadMult(xs, xs, as); - xs[0] = as[0]; xs[1] = as[1]; - - p >>= 1; - } - - if (result != null) { - result[0] = ys[0]; - result[1] = ys[1]; - - resplit(result); - } - - return ys[0] + ys[1]; - } - /** xi in the range of [1, 2]. - * 3 5 7 - * x+1 / x x x \ - * ln ----- = 2 * | x + ---- + ---- + ---- + ... | - * 1-x \ 3 5 7 / - * - * So, compute a Remez approximation of the following function - * - * ln ((sqrt(x)+1)/(1-sqrt(x))) / x - * - * This will be an even function with only positive coefficents. - * x is in the range [0 - 1/3]. - * - * Transform xi for input to the above function by setting - * x = (xi-1)/(xi+1). Input to the polynomial is x^2, then - * the result is multiplied by x. - * @param xi number from which log is requested - * @return log(xi) - */ - static double[] slowLog(double xi) { - double x[] = new double[2]; - double x2[] = new double[2]; - double y[] = new double[2]; - double a[] = new double[2]; - - split(xi, x); - - /* Set X = (x-1)/(x+1) */ - x[0] += 1.0; - resplit(x); - splitReciprocal(x, a); - x[0] -= 2.0; - resplit(x); - splitMult(x, a, y); - x[0] = y[0]; - x[1] = y[1]; - - /* Square X -> X2*/ - splitMult(x, x, x2); - - - //x[0] -= 1.0; - //resplit(x); - - y[0] = LN_SPLIT_COEF[LN_SPLIT_COEF.length-1][0]; - y[1] = LN_SPLIT_COEF[LN_SPLIT_COEF.length-1][1]; - - for (int i = LN_SPLIT_COEF.length-2; i >= 0; i--) { - splitMult(y, x2, a); - y[0] = a[0]; - y[1] = a[1]; - splitAdd(y, LN_SPLIT_COEF[i], a); - y[0] = a[0]; - y[1] = a[1]; - } - - splitMult(y, x, a); - y[0] = a[0]; - y[1] = a[1]; - - return y; - } - - - /** - * Print an array. - * @param out text output stream where output should be printed - * @param name array name - * @param expectedLen expected length of the array - * @param array2d array data - */ - static void printarray(PrintStream out, String name, int expectedLen, double[][] array2d) { - out.println(name); - checkLen(expectedLen, array2d.length); - out.println(TABLE_START_DECL + " "); - int i = 0; - for(double[] array : array2d) { // "double array[]" causes PMD parsing error - out.print(" {"); - for(double d : array) { // assume inner array has very few entries - out.printf("%-25.25s", format(d)); // multiple entries per line - } - out.println("}, // " + i++); - } - out.println(TABLE_END_DECL); - } - - /** - * Print an array. - * @param out text output stream where output should be printed - * @param name array name - * @param expectedLen expected length of the array - * @param array array data - */ - static void printarray(PrintStream out, String name, int expectedLen, double[] array) { - out.println(name + "="); - checkLen(expectedLen, array.length); - out.println(TABLE_START_DECL); - for(double d : array){ - out.printf(" %s%n", format(d)); // one entry per line - } - out.println(TABLE_END_DECL); - } - - /** Format a double. - * @param d double number to format - * @return formatted number - */ - static String format(double d) { - if (d != d) { - return "Double.NaN,"; - } else { - return ((d >= 0) ? "+" : "") + Double.toString(d) + "d,"; - } - } - - /** - * Check two lengths are equal. - * @param expectedLen expected length - * @param actual actual length - * @exception DimensionMismatchException if the two lengths are not equal - */ - private static void checkLen(int expectedLen, int actual) - throws DimensionMismatchException { - if (expectedLen != actual) { - throw new DimensionMismatchException(actual, expectedLen); - } - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/FastMathLiteralArrays.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/FastMathLiteralArrays.java deleted file mode 100644 index 90bbf67c6..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/FastMathLiteralArrays.java +++ /dev/null @@ -1,6175 +0,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. - */ - -package org.apache.commons.math4.util; - -/** - * Utility class for loading tabulated data used by {@link FastMath}. - * - */ -class FastMathLiteralArrays { - /** Exponential evaluated at integer values, - * exp(x) = expIntTableA[x + EXP_INT_TABLE_MAX_INDEX] + expIntTableB[x+EXP_INT_TABLE_MAX_INDEX]. - */ - private static final double[] EXP_INT_A = new double[] { - +0.0d, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - +1.2167807682331913E-308d, - +3.3075532478807267E-308d, - +8.990862214387203E-308d, - +2.4439696075216986E-307d, - +6.64339758024534E-307d, - +1.8058628951432254E-306d, - +4.908843759498681E-306d, - +1.334362017065677E-305d, - +3.627172425759641E-305d, - +9.85967600992008E-305d, - +2.680137967689915E-304d, - +7.285370725133842E-304d, - +1.9803689272433392E-303d, - +5.3832011494782624E-303d, - +1.463305638201413E-302d, - +3.9776772027043775E-302d, - +1.0812448255518705E-301d, - +2.9391280956327795E-301d, - +7.989378677301346E-301d, - +2.1717383041010577E-300d, - +5.903396499766243E-300d, - +1.604709595901607E-299d, - +4.3620527352131126E-299d, - +1.1857289715706991E-298d, - +3.2231452986239366E-298d, - +8.761416875971053E-298d, - +2.381600167287677E-297d, - +6.473860152384321E-297d, - +1.7597776278732318E-296d, - +4.7835721669653157E-296d, - +1.3003096668152053E-295d, - +3.5346080979652066E-295d, - +9.608060944124859E-295d, - +2.6117415961302846E-294d, - +7.099449830809996E-294d, - +1.9298305829106006E-293d, - +5.245823134132673E-293d, - +1.4259627797225802E-292d, - +3.8761686729764145E-292d, - +1.0536518897078156E-291d, - +2.864122672853628E-291d, - +7.785491934690374E-291d, - +2.116316283183901E-290d, - +5.7527436249968E-290d, - +1.5637579898345352E-289d, - +4.250734424415339E-289d, - +1.1554696041977512E-288d, - +3.1408919441362495E-288d, - +8.537829238438662E-288d, - +2.320822576772103E-287d, - +6.308649765138419E-287d, - +1.7148689119310826E-286d, - +4.66149719271323E-286d, - +1.267126226441217E-285d, - +3.444406231880653E-285d, - +9.362866914115166E-285d, - +2.5450911557068313E-284d, - +6.918275021321188E-284d, - +1.880582039589629E-283d, - +5.111952261540649E-283d, - +1.3895726688907995E-282d, - +3.7772500667438066E-282d, - +1.026763015362553E-281d, - +2.791031173360063E-281d, - +7.586808748646825E-281d, - +2.0623086887184633E-280d, - +5.605936171588964E-280d, - +1.5238514098804918E-279d, - +4.1422578754033235E-279d, - +1.1259823210174452E-278d, - +3.060737220976933E-278d, - +8.319947089683576E-278d, - +2.2615958035357106E-277d, - +6.147655179898435E-277d, - +1.6711060014400145E-276d, - +4.542536646012133E-276d, - +1.2347896500246374E-275d, - +3.3565057475434694E-275d, - +9.123929070778758E-275d, - +2.4801413921885483E-274d, - +6.741722283079056E-274d, - +1.8325902719086093E-273d, - +4.981496462621207E-273d, - +1.3541112064618357E-272d, - +3.68085620656127E-272d, - +1.0005602916630382E-271d, - +2.719805132368625E-271d, - +7.393196131284108E-271d, - +2.0096791226867E-270d, - +5.462874707256208E-270d, - +1.4849631831943512E-269d, - +4.036548930895323E-269d, - +1.0972476870931676E-268d, - +2.9826282194717127E-268d, - +8.107624153838987E-268d, - +2.2038806519542315E-267d, - +5.990769236615968E-267d, - +1.628459873440512E-266d, - +4.4266130556431266E-266d, - +1.203278237867575E-265d, - +3.270849446965521E-265d, - +8.891090288030614E-265d, - +2.4168487931443637E-264d, - +6.569676185250389E-264d, - +1.7858231429575898E-263d, - +4.85437090269903E-263d, - +1.3195548295785448E-262d, - +3.5869215528816054E-262d, - +9.750264097807267E-262d, - +2.650396454019762E-261d, - +7.204525142098426E-261d, - +1.958392846081373E-260d, - +5.32346341339996E-260d, - +1.4470673509275515E-259d, - +3.9335373658569176E-259d, - +1.0692462289051038E-258d, - +2.9065128598079075E-258d, - +7.900720862969045E-258d, - +2.147638465376883E-257d, - +5.8378869339035456E-257d, - +1.5869022483809747E-256d, - +4.3136475849391444E-256d, - +1.1725710340687719E-255d, - +3.1873780814410126E-255d, - +8.66419234315257E-255d, - +2.35517168886351E-254d, - +6.402020300783889E-254d, - +1.740249660600677E-253d, - +4.7304887145310405E-253d, - +1.2858802448614707E-252d, - +3.495384792953975E-252d, - +9.501439740542955E-252d, - +2.582759362004277E-251d, - +7.020668578160457E-251d, - +1.908415302517694E-250d, - +5.1876107490791666E-250d, - +1.4101386971763257E-249d, - +3.8331545111676784E-249d, - +1.0419594359065132E-248d, - +2.8323395451363237E-248d, - +7.699097067385825E-248d, - +2.0928317096428755E-247d, - +5.688906371296133E-247d, - +1.5464049837965422E-246d, - +4.2035646586788297E-246d, - +1.1426473877336358E-245d, - +3.106037603716254E-245d, - +8.443084996839363E-245d, - +2.2950686306677644E-244d, - +6.238642390386363E-244d, - +1.695838923802857E-243d, - +4.6097680405580995E-243d, - +1.2530649392922358E-242d, - +3.4061835424180075E-242d, - +9.25896798127602E-242d, - +2.5168480541429286E-241d, - +6.841502859109196E-241d, - +1.8597132378953187E-240d, - +5.055224959032211E-240d, - +1.374152583940637E-239d, - +3.735333866258403E-239d, - +1.0153690688015855E-238d, - +2.7600590782738726E-238d, - +7.502618487550056E-238d, - +2.0394233446495043E-237d, - +5.543727690168612E-237d, - +1.5069412868172555E-236d, - +4.0962906236847E-236d, - +1.1134873918971586E-235d, - +3.026772467749944E-235d, - +8.227620163729258E-235d, - +2.2364990583200056E-234d, - +6.079434951446575E-234d, - +1.6525617499662284E-233d, - +4.4921289690525345E-233d, - +1.2210872189854344E-232d, - +3.3192593301633E-232d, - +9.02268127425393E-232d, - +2.4526190464373087E-231d, - +6.666909874218774E-231d, - +1.8122539547625083E-230d, - +4.926216840507529E-230d, - +1.3390847149416908E-229d, - +3.6400093808551196E-229d, - +9.894571625944288E-229d, - +2.689623698321582E-228d, - +7.31115423069187E-228d, - +1.9873779569310022E-227d, - +5.402252865260326E-227d, - +1.4684846983789053E-226d, - +3.991755413823315E-226d, - +1.0850715739509136E-225d, - +2.9495302004590423E-225d, - +8.017654713159388E-225d, - +2.179424521221378E-224d, - +5.924290380648597E-224d, - +1.6103890140790331E-223d, - +4.377491272857675E-223d, - +1.1899254154663847E-222d, - +3.2345523990372546E-222d, - +8.792425221770645E-222d, - +2.3900289095512176E-221d, - +6.496772856703278E-221d, - +1.7660059778220905E-220d, - +4.800501435803201E-220d, - +1.3049116216750674E-219d, - +3.5471180281159325E-219d, - +9.642065709892252E-219d, - +2.6209850274990846E-218d, - +7.124574366530717E-218d, - +1.9366601417010147E-217d, - +5.264388476949737E-217d, - +1.431009021985696E-216d, - +3.889885799962507E-216d, - +1.057380684430436E-215d, - +2.8742587656021775E-215d, - +7.813044552050569E-215d, - +2.1238058974550874E-214d, - +5.773102661099307E-214d, - +1.5692921723471877E-213d, - +4.2657777816050375E-213d, - +1.1595585743839232E-212d, - +3.1520070828798975E-212d, - +8.568043768122183E-212d, - +2.329035966595791E-211d, - +6.33097561889469E-211d, - +1.720937714565362E-210d, - +4.677993239821998E-210d, - +1.2716105485691878E-209d, - +3.456595573934475E-209d, - +9.396000024637834E-209d, - +2.55409795397022E-208d, - +6.942757623821567E-208d, - +1.887237361505784E-207d, - +5.13004286606108E-207d, - +1.3944901709366118E-206d, - +3.7906173667738715E-206d, - +1.0303966192973381E-205d, - +2.8009086220877197E-205d, - +7.613657850210907E-205d, - +2.0696069842597556E-204d, - +5.6257755605305175E-204d, - +1.5292444435954893E-203d, - +4.156916476922876E-203d, - +1.12996721591364E-202d, - +3.071569248856111E-202d, - +8.349390727162016E-202d, - +2.2695999828608633E-201d, - +6.1694117899971836E-201d, - +1.677020107827128E-200d, - +4.558612479525779E-200d, - +1.2391595516612638E-199d, - +3.3683846288580648E-199d, - +9.156218120779494E-199d, - +2.4889182184335247E-198d, - +6.765580431441772E-198d, - +1.839075686473352E-197d, - +4.999126524757713E-197d, - +1.3589033107846643E-196d, - +3.6938826366068014E-196d, - +1.0041012794280992E-195d, - +2.7294301888986675E-195d, - +7.419361045185406E-195d, - +2.016791373353671E-194d, - +5.482208065983983E-194d, - +1.490218341008089E-193d, - +4.050833763855709E-193d, - +1.101130773265179E-192d, - +2.993183789477209E-192d, - +8.136316299122392E-192d, - +2.2116799789922265E-191d, - +6.011969568315371E-191d, - +1.6342228966392253E-190d, - +4.4422779589171113E-190d, - +1.2075364784547675E-189d, - +3.282424571107068E-189d, - +8.92255448602772E-189d, - +2.425402115319395E-188d, - +6.592926904915355E-188d, - +1.79214305133496E-187d, - +4.871550528055661E-187d, - +1.3242245776666673E-186d, - +3.599615946028287E-186d, - +9.78476998200719E-186d, - +2.659776075359514E-185d, - +7.230020851688713E-185d, - +1.9653234116333892E-184d, - +5.34230278107224E-184d, - +1.4521887058451231E-183d, - +3.947457923821984E-183d, - +1.0730302255093144E-182d, - +2.9167986204137332E-182d, - +7.928680793406766E-182d, - +2.1552386987482013E-181d, - +5.858546779607288E-181d, - +1.5925182066949723E-180d, - +4.328913614497258E-180d, - +1.1767205227552116E-179d, - +3.198658219194836E-179d, - +8.694853785564504E-179d, - +2.363506255864984E-178d, - +6.42467573615509E-178d, - +1.746408207555959E-177d, - +4.747229597770176E-177d, - +1.2904307529671472E-176d, - +3.507754341050756E-176d, - +9.535066345267336E-176d, - +2.591899541396432E-175d, - +7.045512786902009E-175d, - +1.9151693415969248E-174d, - +5.205969622575851E-174d, - +1.4151292367806538E-173d, - +3.846720258072078E-173d, - +1.045647032279984E-172d, - +2.8423629805010285E-172d, - +7.726344058192276E-172d, - +2.1002377128928765E-171d, - +5.709039546124285E-171d, - +1.5518778128928824E-170d, - +4.218440703602533E-170d, - +1.1466910691560932E-169d, - +3.1170298734336303E-169d, - +8.472965161251656E-169d, - +2.303190374523956E-168d, - +6.260720440258473E-168d, - +1.701840523821621E-167d, - +4.62608152166211E-167d, - +1.2574995962791943E-166d, - +3.418237608335161E-166d, - +9.29173407843235E-166d, - +2.5257552661512635E-165d, - +6.865714679174435E-165d, - +1.866294830116931E-164d, - +5.073114566291778E-164d, - +1.3790154522394582E-163d, - +3.7485528226129495E-163d, - +1.0189624503698769E-162d, - +2.7698267293941856E-162d, - +7.529170882336924E-162d, - +2.0466404088178596E-161d, - +5.56334611651382E-161d, - +1.512274346576166E-160d, - +4.110787043867721E-160d, - +1.1174279267498045E-159d, - +3.0374839443564585E-159d, - +8.25673801176584E-159d, - +2.244414150254963E-158d, - +6.1009492034592176E-158d, - +1.6584100275603453E-157d, - +4.50802633729044E-157d, - +1.2254085656601853E-156d, - +3.3310057014599044E-156d, - +9.054612259832416E-156d, - +2.4612985502035675E-155d, - +6.690503835950083E-155d, - +1.8186679660152888E-154d, - +4.9436516047443576E-154d, - +1.3438240331106108E-153d, - +3.652892398145774E-153d, - +9.92958982547828E-153d, - +2.6991427376823027E-152d, - +7.3370297995122135E-152d, - +1.994411660450821E-151d, - +5.421372463189529E-151d, - +1.4736818914204564E-150d, - +4.005882964287806E-150d, - +1.088911919926534E-149d, - +2.9599693109692324E-149d, - +8.046030012041041E-149d, - +2.18713790898745E-148d, - +5.945256705384597E-148d, - +1.6160884846515524E-147d, - +4.392983574030969E-147d, - +1.1941366764543551E-146d, - +3.2460001983475855E-146d, - +8.8235440586675E-146d, - +2.3984878190403553E-145d, - +6.519765758635405E-145d, - +1.772256261139753E-144d, - +4.817491674217065E-144d, - +1.3095299991573769E-143d, - +3.559671483107555E-143d, - +9.676190774054103E-143d, - +2.630261301303634E-142d, - +7.149792225695347E-142d, - +1.943514969662872E-141d, - +5.283020542151163E-141d, - +1.4360739330834996E-140d, - +3.9036541111764032E-140d, - +1.0611230602364477E-139d, - +2.8844319473099593E-139d, - +7.84069876400596E-139d, - +2.1313228444765414E-138d, - +5.793536445518422E-138d, - +1.5748463788034308E-137d, - +4.2808762411845363E-137d, - +1.1636629220608724E-136d, - +3.163163464591171E-136d, - +8.598369704466743E-136d, - +2.337279322276433E-135d, - +6.353384093665193E-135d, - +1.7270287031459572E-134d, - +4.694550492773212E-134d, - +1.2761111606368036E-133d, - +3.4688299108856403E-133d, - +9.429257929713919E-133d, - +2.5631381141873417E-132d, - +6.967331001069377E-132d, - +1.8939170679975288E-131d, - +5.148199748336684E-131d, - +1.3994258162094293E-130d, - +3.804034213613942E-130d, - +1.0340436948077763E-129d, - +2.8108219632627907E-129d, - +7.640606938467665E-129d, - +2.0769322678328357E-128d, - +5.645687086879944E-128d, - +1.5346568127351796E-127d, - +4.171630237420918E-127d, - +1.1339665711932977E-126d, - +3.0824406750909563E-126d, - +8.37894218404787E-126d, - +2.2776327994966818E-125d, - +6.191247522703296E-125d, - +1.6829556040859853E-124d, - +4.5747479502862494E-124d, - +1.2435453481209945E-123d, - +3.3803067202247166E-123d, - +9.188625696750548E-123d, - +2.4977273040076145E-122d, - +6.789527378582775E-122d, - +1.845584943222965E-121d, - +5.016820182185716E-121d, - +1.3637129731022491E-120d, - +3.706956710275979E-120d, - +1.0076552294433743E-119d, - +2.739090595934893E-119d, - +7.445620503219039E-119d, - +2.023929422267303E-118d, - +5.501611507503037E-118d, - +1.4954928881576769E-117d, - +4.0651709187617596E-117d, - +1.1050280679513555E-116d, - +3.003777734030334E-116d, - +8.165114384910189E-116d, - +2.219508285637377E-115d, - +6.033249389304709E-115d, - +1.6400070480930697E-114d, - +4.458001565878111E-114d, - +1.2118105325725891E-113d, - +3.2940421731384895E-113d, - +8.954135150208654E-113d, - +2.433986351722258E-112d, - +6.616260705434716E-112d, - +1.7984863104885375E-111d, - +4.888792154132158E-111d, - +1.3289115531074511E-110d, - +3.612356038181234E-110d, - +9.819402293160495E-110d, - +2.6691899766673256E-109d, - +7.255611264437603E-109d, - +1.9722796756250217E-108d, - +5.361211684173837E-108d, - +1.4573285967670963E-107d, - +3.961429477016909E-107d, - +1.0768281419102595E-106d, - +2.9271223293841774E-106d, - +7.956744351476403E-106d, - +2.1628672925745152E-105d, - +5.879282834821692E-105d, - +1.5981547034872092E-104d, - +4.344234755347641E-104d, - +1.1808855501885005E-103d, - +3.2099795870407646E-103d, - +8.725629524586503E-103d, - +2.3718718327094683E-102d, - +6.44741641521183E-102d, - +1.7525895549820557E-101d, - +4.7640323331013947E-101d, - +1.2949980563724296E-100d, - +3.5201699899499525E-100d, - +9.56881327374431E-100d, - +2.6010732940533088E-99d, - +7.070450309820548E-99d, - +1.9219478787856753E-98d, - +5.2243955659975294E-98d, - +1.4201378353978042E-97d, - +3.8603349913851996E-97d, - +1.0493479260117497E-96d, - +2.8524232604238555E-96d, - +7.753690709912764E-96d, - +2.1076716069929933E-95d, - +5.72924572981599E-95d, - +1.5573703263204683E-94d, - +4.233371554108682E-94d, - +1.1507496472539512E-93d, - +3.1280620563875923E-93d, - +8.5029538631631E-93d, - +2.3113425190436427E-92d, - +6.28287989314225E-92d, - +1.7078641226055994E-91d, - +4.6424556110307644E-91d, - +1.261950308999819E-90d, - +3.430336362898836E-90d, - +9.324622137237299E-90d, - +2.5346947846365435E-89d, - +6.890014851450124E-89d, - +1.8729003560057785E-88d, - +5.091070300111434E-88d, - +1.3838964592430477E-87d, - +3.761820584522275E-87d, - +1.0225689628581036E-86d, - +2.7796303536272215E-86d, - +7.555818934379333E-86d, - +2.053884626293416E-85d, - +5.583037134407759E-85d, - +1.5176268538776042E-84d, - +4.125337057189083E-84d, - +1.121383042095528E-83d, - +3.0482348236054953E-83d, - +8.285962249116636E-83d, - +2.2523580600947705E-82d, - +6.122543452787843E-82d, - +1.664279766968299E-81d, - +4.523982262003404E-81d, - +1.2297456769063303E-80d, - +3.342795345742034E-80d, - +9.086660081726823E-80d, - +2.4700104681773258E-79d, - +6.714184569587689E-79d, - +1.8251046352720517E-78d, - +4.961148056969105E-78d, - +1.3485799924445315E-77d, - +3.665820371396835E-77d, - +9.964732578705785E-77d, - +2.708695208461993E-76d, - +7.362996533913695E-76d, - +2.0014700145557332E-75d, - +5.440559532453721E-75d, - +1.4788974793889734E-74d, - +4.020060558571273E-74d, - +1.092765612182012E-73d, - +2.970445258959489E-73d, - +8.074507236705857E-73d, - +2.1948784599535102E-72d, - +5.966298125808066E-72d, - +1.6218081151910012E-71d, - +4.408531734441582E-71d, - +1.198363039426718E-70d, - +3.257488853378793E-70d, - +8.854771398921902E-70d, - +2.406976727302894E-69d, - +6.542840888268955E-69d, - +1.778528517418201E-68d, - +4.834541417183388E-68d, - +1.3141647465063647E-67d, - +3.572270133517001E-67d, - +9.710435805122717E-67d, - +2.63957027915428E-66d, - +7.175096392165733E-66d, - +1.9503931430716318E-65d, - +5.3017188565638215E-65d, - +1.4411566290936352E-64d, - +3.9174693825966044E-64d, - +1.0648786018364265E-63d, - +2.8946401383311E-63d, - +7.868447965383903E-63d, - +2.1388659707647114E-62d, - +5.814040618670345E-62d, - +1.5804200403673568E-61d, - +4.296027044486766E-61d, - +1.1677812418806031E-60d, - +3.174358801839755E-60d, - +8.62880163941313E-60d, - +2.345551464945955E-59d, - +6.3758692300917355E-59d, - +1.733140900346534E-58d, - +4.711165925070571E-58d, - +1.2806275683797178E-57d, - +3.481106736845E-57d, - +9.462629520363307E-57d, - +2.5722094667974783E-56d, - +6.9919903587080315E-56d, - +1.9006201022568844E-55d, - +5.166420404109835E-55d, - +1.4043786616805493E-54d, - +3.8174968984748894E-54d, - +1.03770335512154E-53d, - +2.820769858672565E-53d, - +7.667647949477605E-53d, - +2.0842827711783212E-52d, - +5.6656680900216754E-52d, - +1.5400881501571645E-51d, - +4.1863938339341257E-51d, - +1.1379799629071911E-50d, - +3.093350150840571E-50d, - +8.408597060399334E-50d, - +2.2856938448387544E-49d, - +6.2131591878042886E-49d, - +1.688911928929718E-48d, - +4.5909386437919143E-48d, - +1.2479464696643861E-47d, - +3.3922703599272275E-47d, - +9.221146830884422E-47d, - +2.5065676066043174E-46d, - +6.8135571305481364E-46d, - +1.8521166948363666E-45d, - +5.0345752964740226E-45d, - +1.368539456379101E-44d, - +3.720075801577098E-44d, - +1.0112214979786464E-43d, - +2.7487849807248755E-43d, - +7.47197247068667E-43d, - +2.0310928323153876E-42d, - +5.521082422279256E-42d, - +1.5007857288519654E-41d, - +4.0795586181406803E-41d, - +1.108938997126179E-40d, - +3.0144088843073416E-40d, - +8.194012195477669E-40d, - +2.2273635587196807E-39d, - +6.054601485195952E-39d, - +1.6458113136245473E-38d, - +4.473779311490168E-38d, - +1.2160992719555806E-37d, - +3.3057007442449645E-37d, - +8.985825281444118E-37d, - +2.442600707513088E-36d, - +6.639677673630215E-36d, - +1.8048513285848406E-35d, - +4.906094420881007E-35d, - +1.3336148713971936E-34d, - +3.625141007634431E-34d, - +9.854154449263851E-34d, - +2.6786368134431636E-33d, - +7.28128971953363E-33d, - +1.9792597720953414E-32d, - +5.380185921962174E-32d, - +1.4624861244004054E-31d, - +3.975449484028966E-31d, - +1.080639291795678E-30d, - +2.9374821418009058E-30d, - +7.984904044796711E-30d, - +2.1705221445447534E-29d, - +5.900089995748943E-29d, - +1.6038109389511792E-28d, - +4.359610133382778E-28d, - +1.185064946717304E-27d, - +3.221340469489223E-27d, - +8.756510122348782E-27d, - +2.380266370880709E-26d, - +6.47023467943241E-26d, - +1.75879225876483E-25d, - +4.780892502168074E-25d, - +1.2995814853898995E-24d, - +3.5326287852455166E-24d, - +9.602680736954162E-24d, - +2.6102792042257208E-23d, - +7.095474414148981E-23d, - +1.9287497671359936E-22d, - +5.242885191553114E-22d, - +1.4251641388208515E-21d, - +3.873997809109103E-21d, - +1.0530616658562386E-20d, - +2.862518609581133E-20d, - +7.78113163345177E-20d, - +2.1151310700892382E-19d, - +5.74952254077566E-19d, - +1.5628822871880503E-18d, - +4.24835413113866E-18d, - +1.1548223864099742E-17d, - +3.139132557537509E-17d, - +8.533046968331264E-17d, - +2.3195229636950566E-16d, - +6.305116324200775E-16d, - +1.71390848833098E-15d, - +4.6588861918718874E-15d, - +1.2664165777252073E-14d, - +3.442477422913037E-14d, - +9.357622912219837E-14d, - +2.5436656904062604E-13d, - +6.914399608426436E-13d, - +1.879528650772233E-12d, - +5.1090893668503945E-12d, - +1.3887944613766301E-11d, - +3.775134371775124E-11d, - +1.0261880234452292E-10d, - +2.789468100949932E-10d, - +7.582560135332983E-10d, - +2.061153470123145E-9d, - +5.602796449011294E-9d, - +1.5229979055675358E-8d, - +4.139937459513021E-8d, - +1.1253517584464134E-7d, - +3.059023470086686E-7d, - +8.315287232107949E-7d, - +2.260329438286135E-6d, - +6.1442124206223525E-6d, - +1.670170240686275E-5d, - +4.539993096841499E-5d, - +1.2340981629677117E-4d, - +3.35462624207139E-4d, - +9.118819143623114E-4d, - +0.0024787522852420807d, - +0.006737947463989258d, - +0.018315639346837997d, - +0.049787066876888275d, - +0.1353352963924408d, - +0.3678794503211975d, - +1.0d, - +2.7182817459106445d, - +7.389056205749512d, - +20.08553695678711d, - +54.59815216064453d, - +148.41314697265625d, - +403.42877197265625d, - +1096.633056640625d, - +2980.9580078125d, - +8103.083984375d, - +22026.46484375d, - +59874.140625d, - +162754.78125d, - +442413.375d, - +1202604.25d, - +3269017.5d, - +8886110.0d, - +2.4154952E7d, - +6.5659968E7d, - +1.78482304E8d, - +4.85165184E8d, - +1.318815744E9d, - +3.584912896E9d, - +9.74480384E9d, - +2.6489122816E10d, - +7.200489472E10d, - +1.95729620992E11d, - +5.32048248832E11d, - +1.446257098752E12d, - +3.9313342464E12d, - +1.0686474223616E13d, - +2.904884772864E13d, - +7.8962956959744E13d, - +2.14643574308864E14d, - +5.83461777702912E14d, - +1.586013579247616E15d, - +4.31123180027904E15d, - +1.1719142537166848E16d, - +3.1855931348221952E16d, - +8.6593395455164416E16d, - +2.35385270340419584E17d, - +6.3984347447610573E17d, - +1.73927483790327808E18d, - +4.7278395262972723E18d, - +1.285159987981792E19d, - +3.493427277593156E19d, - +9.496119530068797E19d, - +2.581312717296228E20d, - +7.016736290557636E20d, - +1.907346499785443E21d, - +5.1847060206155E21d, - +1.4093490364499379E22d, - +3.831007739580998E22d, - +1.0413759887481643E23d, - +2.8307533984544136E23d, - +7.694785471490595E23d, - +2.0916595931561093E24d, - +5.685720022003016E24d, - +1.545539007875769E25d, - +4.201209991636407E25d, - +1.142007304008196E26d, - +3.104297782658242E26d, - +8.43835682327257E26d, - +2.2937832658080656E27d, - +6.23514943204966E27d, - +1.694889206675675E28d, - +4.607187019879158E28d, - +1.2523630909973607E29d, - +3.4042761729010895E29d, - +9.253781621373885E29d, - +2.5154385492401904E30d, - +6.837671137556327E30d, - +1.8586717056324128E31d, - +5.05239404378821E31d, - +1.3733830589835937E32d, - +3.733241849647479E32d, - +1.014800418749161E33d, - +2.758513549969986E33d, - +7.498416981578345E33d, - +2.0382811492597872E34d, - +5.540622484676759E34d, - +1.5060972626944096E35d, - +4.0939972479624634E35d, - +1.1128638067747114E36d, - +3.0250770246136387E36d, - +8.223012393018281E36d, - +2.2352467822017166E37d, - +6.076029840339376E37d, - +1.6516361647240826E38d, - +4.4896127778163155E38d, - +1.2204032949639917E39d, - +3.3174000012927697E39d, - +9.017628107716908E39d, - +2.451245443147225E40d, - +6.663175904917432E40d, - +1.8112388823726723E41d, - +4.923458004084836E41d, - +1.3383347029375378E42d, - +3.637970747803715E42d, - +9.889030935681123E42d, - +2.6881169167589747E43d, - +7.307059786371152E43d, - +1.986264756071962E44d, - +5.399227989109673E44d, - +1.467662348860426E45d, - +3.989519470441919E45d, - +1.0844638420493122E46d, - +2.9478781225754055E46d, - +8.013164089994031E46d, - +2.1782039447564253E47d, - +5.920972420778763E47d, - +1.609486943324346E48d, - +4.3750396394525074E48d, - +1.1892591576149107E49d, - +3.2327411123173475E49d, - +8.787501601904039E49d, - +2.3886908001521312E50d, - +6.493134033643613E50d, - +1.7650169203544438E51d, - +4.7978130078372714E51d, - +1.3041809768060802E52d, - +3.5451314095271004E52d, - +9.636666808527841E52d, - +2.6195174357581655E53d, - +7.120586694432509E53d, - +1.9355758655647052E54d, - +5.2614409704305464E54d, - +1.4302079642723736E55d, - +3.8877083524279136E55d, - +1.0567886837680406E56d, - +2.872649515690124E56d, - +7.808670894670738E56d, - +2.1226166967029073E57d, - +5.769871153180574E57d, - +1.568413405104933E58d, - +4.263390023436419E58d, - +1.1589095247718807E59d, - +3.150242850860434E59d, - +8.563247933339596E59d, - +2.3277319969498524E60d, - +6.327431953939798E60d, - +1.719974302355042E61d, - +4.675374788964851E61d, - +1.2708985520400816E62d, - +3.454660807101683E62d, - +9.390740355567705E62d, - +2.5526681615684215E63d, - +6.938871462941557E63d, - +1.8861808782043154E64d, - +5.1271712215233855E64d, - +1.3937096689052236E65d, - +3.7884955399150257E65d, - +1.0298199046367501E66d, - +2.799340708992666E66d, - +7.609396391563323E66d, - +2.0684484008569103E67d, - +5.622626080395226E67d, - +1.528388084444653E68d, - +4.1545899609113734E68d, - +1.1293346659459732E69d, - +3.069849599753188E69d, - +8.344717266683004E69d, - +2.268329019570017E70d, - +6.165958325782564E70d, - +1.676081191364984E71d, - +4.556060380835955E71d, - +1.2384658100355657E72d, - +3.3664990715562672E72d, - +9.15109220707761E72d, - +2.4875248571153216E73d, - +6.761793219649385E73d, - +1.8380461271305958E74d, - +4.996327312938759E74d, - +1.3581426848077408E75d, - +3.691814001080034E75d, - +1.0035391101975138E76d, - +2.7279024753382288E76d, - +7.415207287657125E76d, - +2.0156621983963848E77d, - +5.479138512760614E77d, - +1.4893842728520671E78d, - +4.048565732162643E78d, - +1.1005142643914475E79d, - +2.991508131437659E79d, - +8.131762373533769E79d, - +2.210442148596269E80d, - +6.008604166110734E80d, - +1.633308028614055E81d, - +4.439791652732591E81d, - +1.206860599814453E82d, - +3.280586734644871E82d, - +8.917559854082513E82d, - +2.4240442814945802E83d, - +6.589235682116406E83d, - +1.7911398904871E84d, - +4.86882298924053E84d, - +1.3234832005748183E85d, - +3.597600556519039E85d, - +9.77929222446451E85d, - +2.658286976862848E86d, - +7.225974166887662E86d, - +1.9642232209552433E87d, - +5.3393125705958075E87d, - +1.4513757076459615E88d, - +3.945247871835613E88d, - +1.0724295693252266E89d, - +2.915165904253785E89d, - +7.924242330665303E89d, - +2.1540322390343345E90d, - +5.855267177907345E90d, - +1.5916266807316476E91d, - +4.326489915443873E91d, - +1.1760619079592718E92d, - +3.1968677404735245E92d, - +8.689987517871135E92d, - +2.3621834216830225E93d, - +6.421080550439423E93d, - +1.7454306955949023E94d, - +4.744571892885607E94d, - +1.2897084285532175E95d, - +3.505791114318544E95d, - +9.529727908157224E95d, - +2.5904487437231458E96d, - +7.041568925985714E96d, - +1.9140971884979424E97d, - +5.203055142575272E97d, - +1.4143368931719686E98d, - +3.8445667684706366E98d, - +1.0450615121235744E99d, - +2.8407720200442806E99d, - +7.722018663521402E99d, - +2.0990624115923312E100d, - +5.705842978547001E100d, - +1.5510089388648915E101d, - +4.216079296087462E101d, - +1.1460491592124923E102d, - +3.1152847602082673E102d, - +8.468222063292654E102d, - +2.3019011105282883E103d, - +6.257216813084462E103d, - +1.7008878437355237E104d, - +4.62349260394851E104d, - +1.2567956334920216E105d, - +3.416324322370112E105d, - +9.286532888251822E105d, - +2.5243410574836706E106d, - +6.861870970598542E106d, - +1.8652499723625443E107d, - +5.070274654122399E107d, - +1.3782437251846782E108d, - +3.746454626411946E108d, - +1.0183920005400422E109d, - +2.768276122845335E109d, - +7.524954624697075E109d, - +2.0454950851007314E110d, - +5.56023190218245E110d, - +1.511427628805191E111d, - +4.1084862677372065E111d, - +1.1168024085164686E112d, - +3.0357834799588566E112d, - +8.252116273466952E112d, - +2.2431576057283144E113d, - +6.097534318207731E113d, - +1.65748157925005E114d, - +4.5055022172222453E114d, - +1.2247224482958058E115d, - +3.329140840363789E115d, - +9.049543313665034E115d, - +2.4599209935197392E116d, - +6.686758417135634E116d, - +1.817649308779104E117d, - +4.940883275207154E117d, - +1.3430713954289087E118d, - +3.6508464654683645E118d, - +9.924030156169606E118d, - +2.697631034485758E119d, - +7.332921137166064E119d, - +1.9932945470297703E120d, - +5.418336099279846E120d, - +1.472856595860236E121d, - +4.0036393271908754E121d, - +1.0883019300873278E122d, - +2.9583112936666607E122d, - +8.041523923017192E122d, - +2.1859129781586158E123d, - +5.941927186144745E123d, - +1.6151834292371802E124d, - +4.390523815859274E124d, - +1.1934680816813702E125d, - +3.2441826014060764E125d, - +8.81860282490643E125d, - +2.3971445233885962E126d, - +6.516115189736396E126d, - +1.7712635751001657E127d, - +4.814793918384117E127d, - +1.3087966177291396E128d, - +3.557678449715009E128d, - +9.670771210463886E128d, - +2.628788218289742E129d, - +7.145787619369324E129d, - +1.9424264981694277E130d, - +5.280062387569078E130d, - +1.4352697002457768E131d, - +3.901467289560222E131d, - +1.0605288965077546E132d, - +2.882816299252225E132d, - +7.836307815186044E132d, - +2.1301292155181736E133d, - +5.790291758828013E133d, - +1.573964437869041E134d, - +4.278478878300888E134d, - +1.1630112062985817E135d, - +3.1613917467297413E135d, - +8.593554223894477E135d, - +2.335970335559215E136d, - +6.349826172787151E136d, - +1.7260616357651607E137d, - +4.691921416188566E137d, - +1.2753966504932798E138d, - +3.466887271843006E138d, - +9.423976538577447E138d, - +2.561702766944378E139d, - +6.963429563637273E139d, - +1.892856346657855E140d, - +5.1453167686439515E140d, - +1.3986421289359558E141d, - +3.8019036618832785E141d, - +1.033464507572145E142d, - +2.809247950589945E142d, - +7.636326960498012E142d, - +2.075769060297565E143d, - +5.64252553828769E143d, - +1.5337974510118784E144d, - +4.169293918423203E144d, - +1.1333315586787883E145d, - +3.080714152600695E145d, - +8.374250298636991E145d, - +2.276357074042286E146d, - +6.187780443461367E146d, - +1.6820131331794073E147d, - +4.572185635487065E147d, - +1.2428488853188662E148d, - +3.378413594504258E148d, - +9.183480622172801E148d, - +2.4963286658278886E149d, - +6.785725312893433E149d, - +1.8445514681108982E150d, - +5.014010481958507E150d, - +1.3629491735708616E151d, - +3.7048805655699485E151d, - +1.0070909418550386E152d, - +2.7375567044077912E152d, - +7.441451374243517E152d, - +2.022795961737854E153d, - +5.4985298195094216E153d, - +1.494655405262451E154d, - +4.062894701808608E154d, - +1.1044092571980793E155d, - +3.002095574584687E155d, - +8.160542326793782E155d, - +2.218265110516721E156d, - +6.02987028472758E156d, - +1.6390888071605646E157d, - +4.455504920700703E157d, - +1.2111317421229415E158d, - +3.2921976772303727E158d, - +8.94912101169977E158d, - +2.432623425087251E159d, - +6.612555731556604E159d, - +1.7974788874847574E160d, - +4.8860545948985793E160d, - +1.328167263606087E161d, - +3.610333312791256E161d, - +9.813901863427107E161d, - +2.667695552814763E162d, - +7.251548346906463E162d, - +1.9711751621240536E163d, - +5.3582093498119173E163d, - +1.4565123573071036E164d, - +3.959211091077107E164d, - +1.0762251933089556E165d, - +2.9254832789181E165d, - +7.952287052787358E165d, - +2.161656025361765E166d, - +5.8759898326913254E166d, - +1.597259768214821E167d, - +4.3418021646459346E167d, - +1.1802241249113175E168d, - +3.2081817253680657E168d, - +8.720743087611513E168d, - +2.3705435424427623E169d, - +6.443805025317327E169d, - +1.7516078165936552E170d, - +4.7613641572445654E170d, - +1.2942728582966776E171d, - +3.518198614137319E171d, - +9.563454814394247E171d, - +2.5996166206245285E172d, - +7.066491077377918E172d, - +1.920871394985668E173d, - +5.221469250951617E173d, - +1.4193426880442385E174d, - +3.8581732071331E174d, - +1.0487601931965087E175d, - +2.850825930161946E175d, - +7.749348772180658E175d, - +2.1064911705560668E176d, - +5.726036941135634E176d, - +1.5564982816556894E177d, - +4.231000988846797E177d, - +1.1501053030837989E178d, - +3.1263099916916113E178d, - +8.498192212235393E178d, - +2.3100480183046895E179d, - +6.279361500971995E179d, - +1.7069074829463731E180d, - +4.63985600437427E180d, - +1.2612435745231905E181d, - +3.4284156709489884E181d, - +9.319400030019162E181d, - +2.5332752658571312E182d, - +6.88615578404537E182d, - +1.8718514371423056E183d, - +5.088219872370737E183d, - +1.3831214731781958E184d, - +3.759713966511158E184d, - +1.021996184153141E185d, - +2.778073442169904E185d, - +7.55158797540476E185d, - +2.0527342305586606E186d, - +5.579910641313343E186d, - +1.5167767828844167E187d, - +4.123026721295484E187d, - +1.1207549425651513E188d, - +3.0465278560980536E188d, - +8.281321669236493E188d, - +2.251096660331649E189d, - +6.119114404399683E189d, - +1.6633478556884994E190d, - +4.521448560089285E190d, - +1.2290570545894685E191d, - +3.340923580982338E191d, - +9.081571104550255E191d, - +2.468626868232408E192d, - +6.710424255583952E192d, - +1.8240823171621646E193d, - +4.958369974640573E193d, - +1.3478247120462365E194d, - +3.6637673548790206E194d, - +9.959152908532152E194d, - +2.707178052117959E195d, - +7.358873642076596E195d, - +2.0003490682463053E196d, - +5.4375131636754E196d, - +1.4780692924846082E197d, - +4.01780853635105E197d, - +1.0921536132159379E198d, - +2.968781250496917E198d, - +8.069984512111955E198d, - +2.193649279840519E199d, - +5.962956589227457E199d, - +1.620899738203635E200d, - +4.406062052965071E200d, - +1.1976919074588434E201d, - +3.2556641859513496E201d, - +8.849812639395597E201d, - +2.40562867677584E202d, - +6.539175932653188E202d, - +1.7775323307944624E203d, - +4.831833881898182E203d, - +1.3134287685114547E204d, - +3.5702693195009266E204d, - +9.704997606668411E204d, - +2.63809219778715E205d, - +7.171077244202293E205d, - +1.949300880034352E206d, - +5.298749302736127E206d, - +1.4403494631058154E207d, - +3.91527572177694E207d, - +1.0642823992403076E208d, - +2.8930193727937684E208d, - +7.8640411896421955E208d, - +2.1376680994038112E209d, - +5.8107841809216616E209d, - +1.5795351101531684E210d, - +4.293620869258453E210d, - +1.1671272667059652E211d, - +3.172580666390786E211d, - +8.623968972387222E211d, - +2.3442378838418366E212d, - +6.372298757235201E212d, - +1.7321703934464356E213d, - +4.708527306855985E213d, - +1.279910496643312E214d, - +3.479157135998568E214d, - +9.45732984079136E214d, - +2.5707689593428096E215d, - +6.988074107282322E215d, - +1.8995553996578656E216d, - +5.1635269305465607E216d, - +1.4035923083915864E217d, - +3.815359096108819E217d, - +1.0371220592190472E218d, - +2.819190456167585E218d, - +7.663353127378024E218d, - +2.083115484919861E219d, - +5.662495731848751E219d, - +1.5392257142577226E220d, - +4.184049381430498E220d, - +1.1373425785132867E221d, - +3.091617462831603E221d, - +8.403887374207366E221d, - +2.2844135610697528E222d, - +6.209679892802781E222d, - +1.6879660933816274E223d, - +4.588367423411997E223d, - +1.2472476068464461E224d, - +3.3903703993793316E224d, - +9.215982463319503E224d, - +2.5051637206758385E225d, - +6.809741127603255E225d, - +1.8510795864289367E226d, - +5.031755776868959E226d, - +1.3677729802316034E227d, - +3.7179924024793253E227d, - +1.0106552237522032E228d, - +2.7472456017809066E228d, - +7.467788172398272E228d, - +2.029955237703202E229d, - +5.517990469846618E229d, - +1.4999452522236406E230d, - +4.0772734783595525E230d, - +1.1083180046837618E231d, - +3.012720614547867E231d, - +8.18942426109357E231d, - +2.2261161215322043E232d, - +6.051211457626543E232d, - +1.6448897917725177E233d, - +4.471273900208441E233d, - +1.2154183152078517E234d, - +3.3038494682728794E234d, - +8.98079409878202E234d, - +2.4412328161430576E235d, - +6.63595840453991E235d, - +1.8038406914061554E236d, - +4.90334700062756E236d, - +1.3328680266667662E237d, - +3.623110695743118E237d, - +9.848636053777669E237d, - +2.677136737066629E238d, - +7.277212447141125E238d, - +1.978151484427976E239d, - +5.377173488599035E239d, - +1.4616672175682191E240d, - +3.973222981713661E240d, - +1.0800340064859439E241d, - +2.935837009891444E241d, - +7.980432566722885E241d, - +2.169306470354036E242d, - +5.896786161387733E242d, - +1.6029126916635028E243d, - +4.357168123448786E243d, - +1.1844011798406507E244d, - +3.2195361624179725E244d, - +8.751606149833694E244d, - +2.3789334438756013E245d, - +6.466611224443739E245d, - +1.7578073785142153E246d, - +4.7782149589194885E246d, - +1.2988535295611824E247d, - +3.5306502960727705E247d, - +9.597302512507479E247d, - +2.608817438130718E248d, - +7.091500562953208E248d, - +1.9276698418065647E249d, - +5.239949786641934E249d, - +1.42436589329759E250d, - +3.8718282216768776E250d, - +1.0524719896550007E251d, - +2.860915548426704E251d, - +7.77677492833005E251d, - +2.113946677051906E252d, - +5.7463023795153145E252d, - +1.56200679236425E253d, - +4.2459748085663055E253d, - +1.1541756557557508E254d, - +3.137374584307575E254d, - +8.528268445871411E254d, - +2.3182239583484444E255d, - +6.301585387776819E255d, - +1.7129486892266285E256d, - +4.6562769567905925E256d, - +1.26570724146049E257d, - +3.4405490416979487E257d, - +9.352382323649647E257d, - +2.54224113415832E258d, - +6.910528108396216E258d, - +1.8784760208391767E259d, - +5.106228040084293E259d, - +1.3880166914480165E260d, - +3.7730204737910044E260d, - +1.0256131352582533E261d, - +2.787906051540986E261d, - +7.578313650939932E261d, - +2.0599991793068063E262d, - +5.5996586041611455E262d, - +1.522145133131402E263d, - +4.137618951061827E263d, - +1.1247213964487372E264d, - +3.0573102223682595E264d, - +8.310629417537063E264d, - +2.2590636576955473E265d, - +6.1407711078356886E265d, - +1.6692346202615142E266d, - +4.5374504961394207E266d, - +1.2334070098307164E267d, - +3.3527476928456816E267d, - +9.113713162029408E267d, - +2.4773638527240193E268d, - +6.734172833429278E268d, - +1.8305382378470305E269d, - +4.9759187284770303E269d, - +1.352594940263854E270d, - +3.6767339705169146E270d, - +9.994400500679653E270d, - +2.716759624268743E271d, - +7.384918458508588E271d, - +2.007428933605617E272d, - +5.456757565532369E272d, - +1.4833003969415539E273d, - +4.0320284712983994E273d, - +1.096019026243815E274d, - +2.979288529962515E274d, - +8.098545495417704E274d, - +2.201412886580694E275d, - +5.984060832462728E275d, - +1.6266362950862408E276d, - +4.4216561713555547E276d, - +1.2019307065458128E277d, - +3.2671863888979078E277d, - +8.881133159512924E277d, - +2.4141423627760256E278d, - +6.562319473965767E278d, - +1.7838233889223407E279d, - +4.848934634563382E279d, - +1.3180771991576186E280d, - +3.5829049382293792E280d, - +9.739345931419228E280d, - +2.6474285478041252E281d, - +7.196457718729758E281d, - +1.956199868121249E282d, - +5.31750271790054E282d, - +1.4454470027638629E283d, - +3.929132560365955E283d, - +1.0680488848057261E284d, - +2.9032581477488686E284d, - +7.89187408872514E284d, - +2.1452336456259667E285d, - +5.831349876080173E285d, - +1.5851251724785243E286d, - +4.308816643345461E286d, - +1.1712579802975851E287d, - +3.1838092090922606E287d, - +8.654490685278886E287d, - +2.3525345191912968E288d, - +6.39485115791896E288d, - +1.7383009254496851E289d, - +4.725191397657393E289d, - +1.2844402232816276E290d, - +3.491470347090126E290d, - +9.490800658395667E290d, - +2.579867270991543E291d, - +7.012806239173502E291d, - +1.906278351789277E292d, - +5.181801397059486E292d, - +1.408559707497606E293d, - +3.8288623079292884E293d, - +1.0407926842436056E294d, - +2.829168201470791E294d, - +7.690475570840264E294d, - +2.0904882610105383E295d, - +5.68253547942899E295d, - +1.544673396032028E296d, - +4.1988574190754736E296d, - +1.1413677466646359E297d, - +3.102559332875688E297d, - +8.433630296371073E297d, - +2.292498520423419E298d, - +6.23165710486722E298d, - +1.6939399242810123E299d, - +4.604606371472047E299d, - +1.2516618713553432E300d, - +3.402369329874797E300d, - +9.248598815279678E300d, - +2.51402968559859E301d, - +6.833842035076675E301d, - +1.8576309291617257E302d, - +5.049564425991982E302d, - +1.3726137091534984E303d, - +3.7311513682845094E303d, - +1.0142320772726397E304d, - +2.7569686255975333E304d, - +7.494218049456063E304d, - +2.037139607241041E305d, - +5.5375196488302575E305d, - +1.5052539519895093E306d, - +4.091704288360009E306d, - +1.1122405335641184E307d, - +3.023383151402969E307d, - +8.218407798110846E307d, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - }; - - /** Exponential evaluated at integer values, - * exp(x) = expIntTableA[x + EXP_INT_TABLE_MAX_INDEX] + expIntTableB[x+EXP_INT_TABLE_MAX_INDEX] - */ - private static final double[] EXP_INT_B = new double[] { - +0.0d, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - -1.76097684E-316d, - -2.44242319E-315d, - -9.879317845E-315d, - -1.3811462167E-314d, - +2.1775261204E-314d, - -1.4379095864E-313d, - +1.4219324087E-313d, - +1.00605438061E-312d, - -1.287101187097E-312d, - +5.33839690397E-312d, - -9.35130825405E-313d, - -4.15218681073E-311d, - +4.546040329134E-311d, - -1.57333572310673E-310d, - +1.05387548454467E-309d, - +2.095732474644446E-309d, - -2.62524392470767E-310d, - +5.86440876259637E-309d, - -2.401816502004675E-309d, - -2.2711230715729753E-308d, - +2.0670460065057715E-307d, - +3.436860020483706E-308d, - +2.0862243734177337E-306d, - -4.637025318037353E-306d, - +9.222671009756424E-306d, - +6.704597874020559E-305d, - +4.351284159444109E-305d, - +4.232889602759328E-304d, - +1.2840977763293412E-303d, - -2.6993478083348727E-303d, - -1.053265874779237E-303d, - +1.207746682843556E-303d, - +5.21281096513035E-303d, - +1.6515377082609677E-301d, - +3.3951607353932444E-301d, - +5.609418227003629E-301d, - +4.238775357914848E-300d, - -9.441842771290538E-300d, - -2.1745347282493023E-299d, - -6.203839803215248E-299d, - -5.617718879466363E-299d, - +5.2869976233132615E-298d, - -1.4300075619643524E-298d, - +4.3198234936686506E-297d, - -2.6448316331572387E-297d, - +4.315655444002347E-296d, - -7.253671992213344E-296d, - -1.1288398461391523E-295d, - -4.83901764243093E-296d, - +1.7407497662694827E-295d, - +1.1969717029666017E-294d, - -7.752519943329177E-294d, - -4.019569741253664E-293d, - -2.4467928392518484E-293d, - -1.0269233640424235E-292d, - -3.2330960700986594E-292d, - -1.440995270758115E-291d, - -3.726946038150935E-291d, - -1.3424576100819801E-291d, - -3.128894928199484E-290d, - -5.989337506920005E-290d, - -9.438168176533759E-290d, - -1.9220613500411237E-289d, - +2.1186736024949195E-289d, - +6.3015208029537436E-288d, - -8.168129112703755E-288d, - -1.6040513288090055E-287d, - -1.0809972724404233E-287d, - -3.080380385962424E-286d, - +2.6399157174374624E-286d, - +1.3317127674213423E-285d, - -3.5821668044872306E-285d, - +1.978536584535392E-284d, - +1.3399392455370071E-284d, - -2.870168560029448E-284d, - +3.5311184272663063E-283d, - -7.204247881190918E-283d, - +3.2425604548983798E-282d, - +3.913063150326019E-282d, - -2.260957518848075E-281d, - +3.807242187736102E-281d, - -5.095591405025083E-281d, - +2.3400625068490396E-280d, - -1.1564717694090882E-280d, - -3.517594695450786E-279d, - +6.666544384808297E-279d, - -9.204784113858607E-279d, - +4.8677119923665573E-278d, - +7.942176091555472E-278d, - -2.5113270522478854E-277d, - +5.332900939354667E-277d, - -3.491241408725929E-276d, - -2.1141094074221325E-276d, - +1.722049095222509E-275d, - +4.0430160253378594E-275d, - +1.9888195459082551E-274d, - +3.230089643550739E-275d, - +5.077824728028163E-274d, - -3.526547961682877E-274d, - -6.4376298274983765E-273d, - -2.5338279333399964E-272d, - -3.614847626733713E-272d, - +2.510812179067931E-272d, - +3.953806005373127E-272d, - +7.112596406315374E-272d, - -2.850217520533226E-270d, - -8.571477929711754E-270d, - +1.2902019831221148E-269d, - -6.978783784755863E-270d, - +9.89845486618531E-269d, - -3.538563171970534E-268d, - +3.537475449241181E-268d, - +3.6924578046381256E-267d, - +1.3555502536444713E-266d, - -1.1279742372661484E-266d, - +5.475072932318336E-266d, - -1.1679889049814275E-265d, - -8.946297908979776E-266d, - +1.0565816011650582E-264d, - -3.2161237736296753E-265d, - -6.022045553485609E-264d, - -2.0332050860436034E-263d, - -1.0488538406930105E-262d, - +1.6793752843984384E-262d, - +3.2558720916543104E-263d, - -1.9546569053899882E-262d, - +5.082190670014963E-262d, - -1.0188117475357564E-260d, - +3.7920054509691455E-261d, - -8.330969967504819E-260d, - -1.1623181434592597E-259d, - +9.09665088462258E-259d, - -1.56400149127482E-259d, - -7.796557225750673E-258d, - +6.751460509863465E-258d, - +7.243157658226935E-258d, - +1.2574668958946027E-256d, - +2.2678858131411216E-256d, - +5.1079306249351287E-256d, - -5.672261759108003E-257d, - +3.476539491009769E-256d, - -1.3481093992496937E-254d, - -3.314051560952014E-254d, - +7.408112967339146E-255d, - -7.164884605413269E-254d, - -6.456588023278983E-253d, - -1.4881197370811587E-252d, - +1.7534012237555307E-252d, - -1.3070101381473173E-251d, - +6.081420141954215E-251d, - +6.591143677421159E-251d, - +2.6917461073773043E-250d, - +3.683043641790553E-251d, - +1.2195076420741757E-249d, - -8.220283439582378E-249d, - +1.637852737426943E-248d, - -8.332543237340988E-249d, - +2.9581193516975647E-248d, - -1.7790661150204172E-247d, - -1.7809679916043692E-247d, - +8.378574405736031E-247d, - -2.883847036065813E-246d, - +1.3223776943337897E-245d, - +3.098547586845664E-245d, - -1.1036542789147287E-244d, - -5.7187703271582225E-244d, - -1.8058492822440396E-244d, - +4.4373726292703545E-243d, - -3.4631935816990754E-243d, - -1.82770041073856E-243d, - +3.845535085273936E-242d, - +8.446532344375812E-242d, - +2.7751016140238277E-242d, - +1.3158882241538003E-241d, - -3.579433051074272E-240d, - -6.151751570213211E-240d, - -2.990535475079021E-239d, - +2.3396028616528764E-239d, - +7.233790684263346E-239d, - +1.0847913100494912E-238d, - +7.103148400942551E-238d, - +3.463600299750966E-237d, - -4.873121855093712E-237d, - +1.3407295326570417E-236d, - +9.390271617387205E-237d, - -2.4767709454727603E-235d, - +3.205923535388443E-235d, - -1.0074984709952582E-234d, - +2.4747880175747574E-234d, - -5.146939682310558E-234d, - -2.827581009333298E-233d, - -3.0307641004671077E-233d, - +5.92044714050651E-233d, - -2.0582596893119236E-232d, - -6.58066591313112E-232d, - -4.869955151949929E-231d, - -5.763495903609913E-231d, - -2.3580462372762525E-230d, - +1.8559980428862584E-230d, - +2.854978560542175E-229d, - +5.637945686485334E-229d, - +2.1454644909004582E-228d, - -1.1918070206953359E-228d, - -5.021851606912854E-228d, - +3.861525553653117E-227d, - +6.533561982617909E-227d, - -3.015709444206057E-226d, - -5.042005018212734E-227d, - +1.5959614205422845E-225d, - +2.0402105689098835E-224d, - +5.164902728917601E-224d, - +9.981031744879876E-224d, - +4.0281104210095145E-223d, - +1.1158160971176672E-222d, - +2.0736172194624895E-222d, - +4.983162653734032E-222d, - +2.1753390051977871E-221d, - +3.969413618002761E-221d, - +1.3961255018698695E-220d, - +2.1290855095314206E-220d, - +1.1927747883417406E-219d, - +3.7264401117998796E-219d, - +9.318532410862293E-219d, - +2.3414841777613345E-218d, - +4.3791842770430786E-218d, - +1.7173159016511951E-217d, - +3.5037536832675478E-217d, - +1.4300098613455884E-216d, - +2.4189403362149483E-216d, - +9.306541421999056E-216d, - +3.442100456607687E-215d, - +5.94407068841904E-215d, - +2.0483260435783403E-214d, - +3.8410992889527954E-214d, - +1.2038281262953917E-213d, - +3.865007795216205E-213d, - +9.754659138599756E-213d, - +2.7653605770745684E-212d, - +5.359568079675375E-212d, - +2.61726605666378E-211d, - +5.054202073556894E-211d, - +8.707092668016246E-211d, - +1.4080573899148006E-210d, - +1.288124387778789E-209d, - +1.8639901642011898E-209d, - +6.076014540574561E-209d, - +1.798489141298457E-208d, - +2.1525406805994896E-208d, - +1.1864056832305874E-207d, - +2.1077440662171152E-207d, - +1.3784853708457332E-206d, - +1.6965806532093783E-206d, - +7.241626420445137E-206d, - +2.575584299085016E-205d, - +6.151951078101721E-205d, - +2.40652042118887E-204d, - +4.022633486003565E-204d, - +5.8840879519086286E-204d, - +3.2820308007277566E-203d, - +4.31880454864738E-203d, - +2.427240455243201E-202d, - +7.326955749884755E-202d, - +1.4310184489676175E-201d, - +4.464279133463661E-201d, - +4.895131474682867E-201d, - +4.48614966943544E-200d, - +8.924048768324976E-200d, - +2.5035535029701945E-199d, - +6.627829836338812E-199d, - +2.6066826304502746E-198d, - +8.042275310036546E-198d, - +2.115062964308555E-197d, - +4.413745413236018E-197d, - +1.644449394585716E-196d, - +3.138217752973845E-196d, - +7.48533983136081E-196d, - +2.613626422028823E-195d, - +3.6741841454219095E-195d, - +5.906102862953403E-195d, - +4.4940857547850743E-194d, - +5.840064709376958E-194d, - +3.087661273836024E-193d, - +4.995552216100365E-193d, - +1.991444798915497E-192d, - +7.097454751809522E-192d, - +2.0510193986749737E-191d, - +5.759440286608551E-191d, - +1.7013941257113314E-190d, - +2.1383323934483528E-190d, - +8.280292810015406E-190d, - +3.138655772049104E-189d, - +7.961506427685701E-189d, - +2.0579001228504997E-188d, - +7.530840351477639E-188d, - +1.4582863136475673E-187d, - +3.149267215638608E-187d, - +5.443114553057336E-187d, - +3.4672966834277804E-186d, - +7.374944406615125E-186d, - +2.7318417252599104E-185d, - +7.913674211949961E-185d, - +2.5217716516462005E-184d, - +4.0866585874353075E-184d, - +1.2087698972768686E-183d, - +3.7072473866919033E-183d, - +1.1333588840402273E-182d, - +1.61949812578045E-182d, - +6.567779607147072E-182d, - +2.422974840736314E-181d, - +2.551170809294396E-181d, - +1.0905890688083124E-180d, - +3.221279639653057E-180d, - +7.068244813489027E-180d, - +1.3752309224575428E-179d, - +7.20154303462761E-179d, - +1.5391707185581056E-178d, - +7.708777608683431E-178d, - +5.597398155472547E-178d, - +1.8487854656676722E-177d, - +1.0577249492414076E-176d, - +2.8926683313922764E-176d, - +4.090184282164232E-176d, - +1.6142943398013813E-175d, - +7.873864351702525E-175d, - +2.242630017261011E-174d, - +3.4637009373878283E-174d, - +1.5907089565090164E-173d, - +1.6985075903314236E-173d, - +1.1552273904608563E-172d, - +2.237894048535414E-172d, - +5.321990399912051E-172d, - +1.4106062639738257E-171d, - +2.9850404523368767E-171d, - +1.5683802588004895E-170d, - +4.880146806045633E-170d, - +1.1489352403441815E-169d, - +1.6401586605693734E-169d, - +8.29169700697816E-169d, - +1.0380723705441457E-168d, - +7.126414081261746E-168d, - +1.253325949455206E-167d, - +2.595079206183114E-167d, - +1.537490712803659E-166d, - +2.6338455225993276E-166d, - +7.994936425058567E-166d, - +1.5716634677516025E-165d, - +3.669404761339415E-165d, - +1.9941628263579332E-164d, - +4.5012079983352374E-164d, - +7.283163019991001E-164d, - +2.398038505188316E-163d, - +7.868666894503849E-163d, - +2.1478649410390003E-162d, - +8.306111510463843E-162d, - +1.5453160659068463E-161d, - -4.590496588813841E-162d, - +3.5449293983801232E-161d, - -1.0440854056870505E-160d, - -2.321064927632431E-160d, - +5.707867001443433E-160d, - -2.238614484037969E-159d, - +2.482282821883242E-159d, - -1.1508772192025259E-158d, - +1.9903990578876104E-158d, - -1.2116165315442256E-158d, - -2.9084557554502667E-157d, - -1.1211083853006645E-156d, - -1.309893394818129E-156d, - +4.2269712317468864E-156d, - -7.678973146281339E-156d, - +3.2021376921211934E-155d, - -7.08313012515209E-155d, - +1.944398214330544E-154d, - +1.1860061363751161E-153d, - +1.5234465914578058E-153d, - -2.9020908354550263E-153d, - +4.980100072851796E-153d, - +2.3101551448625578E-152d, - -1.1959241322537072E-151d, - -9.27398924154364E-153d, - +5.999390491704392E-152d, - +1.3373196561281372E-150d, - -1.0271780540759147E-150d, - +2.575620466387945E-150d, - -6.56250013356227E-149d, - -1.1961357917482867E-148d, - +5.5807813570926636E-148d, - +9.252840189663807E-148d, - -1.830335419852293E-147d, - +9.350990339947455E-147d, - -1.6072409939877762E-146d, - -2.5309995887229526E-146d, - -1.6014373376410622E-146d, - -3.303297758377758E-145d, - +1.5640419864850202E-145d, - +9.544642884951585E-145d, - -8.64864445321803E-144d, - +7.580392204597681E-144d, - +2.678334184447568E-143d, - -3.7269289985326055E-143d, - -2.851965258161176E-142d, - +7.243267286265823E-142d, - +4.4510805312036926E-141d, - +9.008499734799015E-141d, - +1.130435759928337E-140d, - -3.096539751496479E-140d, - -1.497405487919762E-139d, - +3.51519845948652E-139d, - -4.713790209541894E-139d, - +4.740753295616865E-138d, - +9.517570994930463E-138d, - -1.8842098029339485E-137d, - -3.825558165008403E-137d, - +1.1817638600528107E-136d, - -3.514601201473235E-136d, - -6.344612631552417E-136d, - -1.6754164785291923E-136d, - +4.445372986583078E-135d, - -3.89604237755475E-134d, - -1.0155552195374609E-134d, - +2.1858142063550155E-134d, - +3.497714990137842E-133d, - -7.635830383612894E-133d, - +1.2050744860079718E-132d, - -7.683019590615251E-133d, - -3.344806129021162E-131d, - -1.6737914131474577E-131d, - -4.30610076666344E-131d, - +5.184023388254773E-130d, - +2.6290763595212492E-129d, - +7.90041744728452E-130d, - -3.204473056113754E-129d, - -2.552517201762272E-128d, - +7.130134251490065E-128d, - -3.2244113258340395E-127d, - -1.064920993515727E-127d, - +2.7466520735457463E-126d, - +4.368312797746065E-126d, - +1.8802599072446818E-125d, - -4.257625799463564E-125d, - +5.491672256552995E-125d, - +3.7298611779671127E-124d, - +5.724180836308973E-124d, - +1.3861841053630075E-123d, - +4.2303826056297614E-123d, - +3.5335436928899096E-123d, - -2.522906629540626E-122d, - +1.0147808005267102E-121d, - +6.734406065735473E-122d, - -4.948973160958133E-121d, - +2.4256181927024344E-120d, - +4.9056283164780554E-120d, - +6.846440394397547E-120d, - +3.512747689569002E-119d, - -9.020907406701404E-119d, - +2.5718749916003624E-118d, - +4.3724191002977524E-119d, - +1.001455050575191E-117d, - -2.4442443105031435E-117d, - +2.38873950760028E-116d, - -4.831068747037129E-118d, - -5.148989321866988E-116d, - +1.7875271881514469E-115d, - -1.1821586412088555E-114d, - +4.43247726423679E-115d, - +4.634817120492781E-114d, - +1.671311907037975E-113d, - -4.595250028278979E-113d, - -5.905511605694905E-113d, - -1.3657642265608213E-112d, - +2.881416869529271E-112d, - +2.1253302469985373E-111d, - -5.301386276260592E-111d, - +1.4198782892306878E-112d, - -3.395494928605007E-110d, - +9.284633292147283E-110d, - -6.054133004896379E-110d, - -8.324100783330331E-109d, - -2.193190669794277E-108d, - +1.3613655394659198E-107d, - +6.463452607647978E-108d, - +1.0187183636134904E-106d, - +1.0705673935006142E-106d, - +2.509050608571019E-106d, - -1.5096182622106617E-105d, - +1.7794190449526737E-106d, - +1.2261246749706581E-104d, - +2.1377905661197194E-104d, - -2.2015877944429946E-104d, - +7.873970951802825E-104d, - -1.7999197335480384E-103d, - +1.0487383011058756E-105d, - -2.9988278531841556E-102d, - +4.7976477743232285E-102d, - +3.452316818502442E-102d, - +5.89953246760617E-101d, - -4.0785601577267006E-101d, - +2.7214076662438963E-100d, - +5.237807655758373E-100d, - +6.180972117932364E-99d, - -1.3019742873005683E-98d, - +4.501188264957416E-99d, - -2.4075054705261798E-98d, - +1.6503086546628772E-97d, - -6.878666975101243E-97d, - +1.196718116616528E-96d, - +2.476190162339265E-96d, - -7.1844969234484515E-96d, - +5.088386759261555E-95d, - +6.749368983223726E-95d, - +1.965737856765605E-94d, - -5.574080023496771E-94d, - +1.2493696959436675E-93d, - +8.533262777516794E-94d, - -7.225259028588793E-93d, - -7.340587186324432E-93d, - -3.482412195764625E-92d, - +3.4742610108480497E-91d, - -7.177274244758699E-91d, - +1.2736636153072213E-90d, - -5.730160886217076E-90d, - -1.545495535488274E-89d, - +1.1304179460367007E-89d, - +1.249260560756154E-88d, - -4.7439719382414206E-88d, - +7.164663249266942E-88d, - +1.7617425105337704E-87d, - +2.4175248449172035E-87d, - -1.043079666926483E-86d, - -2.8137609614326677E-86d, - -1.2091497144395591E-85d, - +3.7944631664558904E-85d, - -2.8144926807308225E-85d, - +3.9782728352520784E-85d, - +4.313978872469646E-84d, - +5.82190887044604E-84d, - +5.883385169571802E-83d, - +1.134857098306787E-82d, - +3.468049324128309E-82d, - +2.625423995658143E-82d, - -3.42827917465521E-81d, - +5.119461911618321E-81d, - -2.134387988350615E-80d, - -4.4703076268400615E-80d, - +4.806078883451016E-80d, - +2.3820250362443495E-79d, - -7.258551497833573E-79d, - -4.0297835558876335E-78d, - +2.1424166787650852E-78d, - -3.2117127164185917E-77d, - +4.8459153070935316E-77d, - -1.766924303914492E-76d, - -2.6921749814579492E-76d, - -4.1291070428848755E-76d, - +2.2086994756104319E-75d, - -7.814146377574201E-75d, - -1.9589778310104216E-74d, - +6.52658129486538E-74d, - +1.7804909509998055E-74d, - -4.1900132227036916E-73d, - +1.5705861683841123E-72d, - -1.904714978998808E-72d, - -7.81295459930537E-72d, - +2.818537910881676E-71d, - +5.840507984320445E-71d, - +1.7331720051707087E-70d, - +1.936946987935961E-70d, - -5.86517231340979E-71d, - -1.3277440528416646E-69d, - +1.9906256185827793E-69d, - +8.668714514280051E-69d, - +6.643105496829061E-69d, - -2.5436254170647032E-67d, - -4.8279217213630774E-67d, - -1.2640304072937576E-66d, - +3.51187258511716E-66d, - +1.4199501303738373E-65d, - -1.2351697477129173E-65d, - +7.0542365522414836E-65d, - +1.030593104122615E-64d, - -5.452692909894593E-65d, - -9.415506349675128E-64d, - -3.6206211446779087E-63d, - -1.6699188275658641E-62d, - +2.287280262665656E-62d, - +7.076135457313529E-62d, - +2.9019628518165404E-61d, - -3.1305705497720186E-61d, - +2.2978757040142953E-60d, - +1.2424439441817321E-60d, - +7.140343013236265E-60d, - +8.633726388939636E-60d, - +1.3483035574114863E-58d, - +1.653701058949654E-58d, - -8.939932297357388E-58d, - -1.395320103272191E-57d, - +6.440430933947252E-58d, - -1.681200826841738E-56d, - +3.9904382022898837E-56d, - -4.870518577546228E-56d, - -1.6990896855901115E-55d, - -6.751434891261518E-56d, - -1.669012123121194E-54d, - -4.079585475491198E-54d, - -1.3070436427679952E-53d, - -3.090028378908628E-53d, - +7.468160889798606E-53d, - +6.229095980733463E-53d, - +1.4794751934479566E-52d, - +1.7444373785853918E-51d, - -5.3681978363391484E-52d, - +2.71853394036182E-51d, - -1.3334367969274016E-50d, - -1.6958057665854177E-49d, - -1.452507231312146E-49d, - +3.3855429446520427E-49d, - +4.903687986212687E-49d, - +2.2185957416622524E-48d, - -9.924196700842429E-48d, - +4.285128462851149E-47d, - +3.076063086193525E-48d, - +4.102052341676543E-46d, - +1.1745772638457318E-45d, - -5.309047216809048E-47d, - +2.72972449891179E-45d, - -1.1748423022293739E-44d, - +6.626052626622228E-44d, - +3.0227439688367925E-44d, - -4.740494808228372E-43d, - +5.926057457356852E-43d, - +3.09768273342776E-42d, - -5.589493227475577E-42d, - -8.84908716783327E-42d, - +2.3684740712822874E-41d, - +1.4836491430755657E-40d, - +4.5878801324451396E-40d, - +1.0585156316103144E-39d, - +2.3805896467049493E-39d, - +1.0285082556185196E-38d, - +2.5187968110874885E-38d, - -1.4088399542613178E-38d, - -3.00901028043488E-38d, - +2.0089026801414973E-37d, - -1.3324111396289096E-36d, - +5.458481186294964E-36d, - -4.8402541351522003E-36d, - -1.3331969720555312E-35d, - -8.248332290732976E-35d, - -1.8349670703969982E-34d, - +6.403477383195494E-34d, - +3.7813691654412385E-34d, - +2.4621305031382827E-33d, - -5.634051826192439E-33d, - +3.817173955083142E-32d, - -6.038239639506472E-32d, - -2.130447095555397E-31d, - -6.824454861992054E-31d, - -1.3455801602048414E-30d, - -2.518642767561659E-30d, - +8.082792416221215E-30d, - +4.718103502869148E-29d, - -5.607991635038776E-29d, - -1.8042191582018579E-28d, - +6.989914264479507E-28d, - -2.9031739430339586E-28d, - +6.076820259849921E-27d, - -3.24981577480893E-27d, - -2.7648210023059463E-26d, - -9.785306155980342E-26d, - +1.241529292737115E-25d, - +3.0891604448087654E-25d, - +2.3451052074796954E-24d, - +6.574128018028633E-24d, - -1.3345148716925826E-23d, - +4.3594621428644293E-23d, - -5.678896695157704E-23d, - -4.676849004137386E-23d, - -2.281578975407609E-22d, - -3.144430608076357E-21d, - +5.662033727488754E-22d, - -4.30293375386492E-21d, - +4.985137671479376E-20d, - +1.657668502165438E-19d, - -3.3878706977811337E-19d, - -7.488022803661722E-19d, - +1.725039737424264E-18d, - -6.0275040161173166E-18d, - -8.081007442213538E-19d, - +2.9257892371894816E-17d, - +1.5231541295722552E-16d, - -1.1474026049124666E-17d, - +6.890372706231206E-16d, - +2.592721454922832E-15d, - -1.1253822296423454E-15d, - -2.650684279637763E-14d, - -4.107226967119929E-15d, - -3.130508064738312E-14d, - -6.729414275200856E-14d, - -1.6166170913368169E-12d, - -1.2059301405584488E-12d, - -1.2210091619211167E-11d, - +3.695372823623631E-12d, - +5.119220484478292E-11d, - -1.0857572226543142E-10d, - -4.6490379071586397E-10d, - -4.5810381714280557E-10d, - +1.4909756678328582E-9d, - -1.3155828104004438E-8d, - -9.149755188170102E-9d, - +0.0d, - +8.254840070411029E-8d, - -1.0681886149151956E-7d, - -3.359944163407147E-8d, - -2.1275002921718894E-6d, - +1.2129920353421116E-5d, - +2.1520078872608393E-5d, - +1.0178783359926372E-4d, - -2.077077172525637E-5d, - -5.67996159922899E-5d, - +9.510567165169581E-4d, - +0.0010901978184553272d, - +0.010169003920808009d, - +0.017008920503326107d, - +0.03416477677774927d, - -0.1275278893606981d, - +0.5205078726367633d, - +0.7535752982147762d, - +1.1373305111387886d, - -3.036812739155085d, - +11.409790277969124d, - -9.516785302789955d, - -49.86840843831867d, - -393.7510973999651d, - -686.1565277058598d, - +4617.385872524165d, - -11563.161235730215d, - -8230.201383316231d, - -34460.52482632287d, - +50744.04207438878d, - +357908.46214699093d, - +1936607.425231087d, - +3222936.695160983d, - +5477052.0646243105d, - -3.517545711859706E7d, - -1.2693418527187027E8d, - -2.5316384477288628E8d, - -1.6436423669122624E8d, - +4.0889180422033095E8d, - +4.968829330953611E9d, - -3.503399598592085E9d, - +1.905394922122271E10d, - +1.0361722296739479E11d, - -5.806792575852521E10d, - +2.3454138776381036E11d, - -1.718446464587963E12d, - -1.0946634815588584E12d, - +1.6889383928999305E13d, - -3.784600043778247E13d, - +7.270965670658928E13d, - -4.9202842786896806E14d, - +4.597700093952774E14d, - +2.6113557852262235E15d, - -4.544525556171388E15d, - -9.517971970450354E15d, - -2.0634857819227416E16d, - -9.7143113104549808E16d, - -2.2667083759873216E16d, - -7.2285665164439578E17d, - +4.1215410760803866E18d, - +8.5807488300972206E18d, - +1.530436781375042E19d, - -1.5453111533064765E19d, - -1.0633845571643594E20d, - -3.512380426745336E20d, - +3.7734658676841284E20d, - -3.855478664503271E21d, - +7.984485303520287E21d, - -1.2296934902142301E22d, - +1.042139023692827E22d, - +1.2167897656061312E23d, - +9.22064170155394E22d, - +3.965171513035854E23d, - -4.135121057126514E24d, - -7.944341754299148E24d, - +1.4715152230577016E25d, - -3.0635272288480756E25d, - -9.54468158713835E25d, - +1.5411775738825048E25d, - -8.274711842374368E26d, - -1.0028324930788433E27d, - +5.189062091114782E27d, - -2.8583500869462184E28d, - -5.198295198128238E28d, - +2.9758750368256437E29d, - +3.216046320616945E29d, - -1.7846700158234043E30d, - +3.847174961282827E30d, - +9.026991921214922E30d, - +4.1358029739592175E30d, - -6.461509354879894E29d, - +9.704297297526684E31d, - +2.9731739067444943E32d, - +9.97728609663656E32d, - +3.1149346370027763E33d, - +2.0051635097366476E34d, - +2.819272221032373E34d, - +1.6266731695798413E34d, - +1.998050894021586E35d, - -6.1633417615076335E35d, - +2.2505716077585116E36d, - +1.9299691540987203E36d, - +8.006569251375383E36d, - -3.785295042408568E37d, - -1.1870498357197593E38d, - +1.0010529668998112E38d, - +1.3240710866573994E38d, - +2.6888010385137123E39d, - +1.7400655988987023E39d, - -6.402740469853475E39d, - -3.93114092562274E40d, - +1.2363717201084252E41d, - -1.9219116633978794E41d, - -1.347867098583136E42d, - +7.87675118338788E41d, - +3.3932984011177642E41d, - -1.9872713979884691E43d, - +2.220208491349658E43d, - -3.466267817480825E43d, - +3.19462030745197E44d, - -9.841244788104406E44d, - -2.2676593395522725E45d, - -1.1349246400274207E46d, - -1.1700910284427406E46d, - -3.6754317105801715E46d, - +1.7647101734915075E47d, - +2.122358392979746E47d, - +3.156243682143956E47d, - +5.356668151937413E47d, - +2.7668218233914262E48d, - +3.5127708120698784E48d, - +1.7884841356632925E49d, - +1.716531820904728E50d, - -2.9114757102866277E50d, - +1.0657703081219677E51d, - -7.512169809356372E50d, - +1.764200470879736E51d, - -1.0088898215431471E52d, - -3.1085734725176E52d, - +4.3529009584292495E52d, - -2.467842129213774E53d, - -3.9317379627195146E53d, - -4.332335454045836E52d, - +7.979013724931926E54d, - -1.5038413653121357E55d, - +9.310799925566843E55d, - -2.2042966348036592E55d, - -4.518315366841937E55d, - -6.971366338144781E56d, - -2.0461505570781806E57d, - -8.823884392655312E57d, - -1.1264032993918548E58d, - -7.692065092509875E58d, - -1.8472516879728875E59d, - +8.72220314694275E58d, - +1.6525336989036362E59d, - -3.343201925128334E60d, - +5.493352163155986E60d, - -2.548073509300398E61d, - -9.566541624209933E61d, - +4.0891054447206644E61d, - -7.724182294653349E62d, - +1.0143022354947225E63d, - -4.952031310451961E63d, - -7.877410133454722E63d, - +4.505432606253564E64d, - -7.330635250808021E64d, - -1.642361029990822E65d, - +5.982180242124184E65d, - +7.120242132370469E65d, - +5.908356249789671E66d, - -2.8477710945673134E65d, - +6.65688196961235E66d, - -9.233295580238604E67d, - +3.2850043261803593E68d, - +7.041681569694413E68d, - -1.5652761725518397E69d, - +1.5377053215489084E68d, - +1.282130763903269E70d, - -2.380286345847567E70d, - -7.207022875977515E70d, - +2.7641662602473095E71d, - +7.685235201534525E71d, - +4.3239378585884645E70d, - -1.6840562544109314E72d, - -5.04128025464686E71d, - +5.4557485189210095E73d, - +7.160277784358221E73d, - +7.636179075087608E73d, - -8.18804507680012E74d, - +2.807397988979441E75d, - +2.165163304600171E75d, - -1.3208450062862734E76d, - -5.1939252391404724E76d, - -6.985952908805853E76d, - -1.6259920998287064E77d, - +6.098975200926637E77d, - -5.63383579957466E77d, - -1.5876819186852907E78d, - +2.1487475413123092E79d, - -3.987619123706934E79d, - +9.772655251656639E79d, - -1.638756156057952E79d, - -7.83892088580041E80d, - +1.274413296252691E81d, - +2.51946651720982E81d, - -2.516866097506943E81d, - +1.053956282234684E82d, - +1.8279051206232177E83d, - +1.2250764591564252E82d, - -4.0353723442917463E83d, - -1.4121324224340735E84d, - -5.45287716696021E84d, - -1.7514953095665195E85d, - -5.0706081370522526E85d, - -4.35799392139009E85d, - -3.982538093450217E86d, - -1.4591838284752642E87d, - +2.5313735821872488E87d, - -3.718501227185903E86d, - -1.3907979640327008E88d, - -5.79002114093961E86d, - -1.2500675565781447E89d, - +4.8182788286170926E89d, - -1.7198866036687559E90d, - -4.690417668647599E88d, - +1.3020631859056421E91d, - -1.3850458263351744E91d, - +4.87301010703588E91d, - -1.695546877943826E92d, - -1.6353756659909833E92d, - -1.5483926773679628E93d, - -1.8921091400297595E93d, - -6.183525570536406E93d, - -4.987913342551977E93d, - +1.0186485886120274E93d, - -1.5343120819745468E95d, - -5.262123923229857E95d, - +1.618327917706804E96d, - -4.135185828158998E96d, - -8.016793741945299E96d, - -3.0399439534134115E97d, - -1.2319346292749103E98d, - +7.536337311795176E97d, - -3.577715974851322E98d, - +2.0521614818695524E99d, - +1.2627736197958951E98d, - -5.206910481915062E99d, - +3.0974593993948837E100d, - -9.522726334561169E100d, - -1.1909272509710985E100d, - -5.056512677995137E101d, - +2.0902045062932175E102d, - +6.243669516810509E102d, - -1.7375090618655787E103d, - -2.5445477450140954E103d, - +3.619891246849381E103d, - +8.90737333900943E103d, - -2.7897360297480367E104d, - +1.3725786770437066E105d, - -8.316530604593264E105d, - -6.054541568735673E105d, - +7.523374196797555E105d, - +1.1475955030427985E107d, - +1.5260756679495707E107d, - +7.370294848920685E107d, - +1.3608995799112174E108d, - +1.0700758858011432E108d, - -4.989318918773146E108d, - -1.6629755787634093E108d, - +7.635999584053557E109d, - +1.892621828736983E109d, - -6.793094743406533E110d, - -8.160628910742724E110d, - -7.724219106106896E111d, - -1.6059226011778748E112d, - -1.5277127454062126E112d, - +3.911086668967361E112d, - +3.529920406834134E113d, - -4.3991443996021166E113d, - -1.2631909085915044E114d, - +3.8656278695544835E114d, - +1.71845288713123E115d, - +3.7660598745907915E115d, - -4.048086182363988E115d, - +2.3093822298965837E116d, - -9.684925795536813E116d, - -3.137992585221854E117d, - -5.637415935329794E117d, - -1.5536658521931418E118d, - -6.336314643222911E118d, - +8.550658957115427E118d, - -5.591880480212007E119d, - +2.4137404318673354E119d, - -2.631656656397244E120d, - -7.653117429165879E119d, - -4.073965591445897E121d, - +3.634781057940233E121d, - +4.537273754534966E121d, - -2.5138919966097735E122d, - -1.0292817180691822E123d, - -1.4265564976097062E122d, - +6.000235114895513E123d, - +4.186590347846346E124d, - -1.8950538406321535E124d, - +7.716762345695022E124d, - -4.443798187035849E125d, - -2.268994961992292E125d, - -2.8169291774231604E126d, - -2.749127978087685E126d, - -2.2929764629585683E126d, - -7.369842361872221E127d, - +2.81312841469177E128d, - +2.7856896414497757E128d, - -3.096733638475319E128d, - -5.4199510725063615E129d, - -7.315860999413894E129d, - +3.6424644535156437E130d, - -7.886250961456327E130d, - +5.289988151341401E130d, - +2.7758613753516344E131d, - -2.738246981762776E132d, - -2.2667181460478093E132d, - -3.614672661225457E131d, - +2.325337720526947E133d, - +4.16603235883392E133d, - -6.50348962894948E133d, - +3.851445905038431E134d, - -5.46060534001412E134d, - +5.4679180659102885E135d, - -3.037477806841494E135d, - -3.0417051809209134E136d, - -6.995964550587914E136d, - -3.6897084415718804E137d, - -6.938000231893302E137d, - +2.403806217004454E138d, - -3.4552363953199905E138d, - +7.3409917428393E138d, - -1.7445917446236717E139d, - -6.680679913078676E139d, - -8.193572619487537E139d, - +5.337290292186291E139d, - -3.951314467739045E140d, - -4.4662073456574476E141d, - +6.249381778908997E141d, - -2.928362616578011E142d, - -1.6661676835672304E143d, - -1.974465323891493E143d, - +1.3083870531380308E144d, - -2.382825271750576E144d, - -5.4826958838142734E144d, - +1.5340733916570804E145d, - -3.1327120557842516E145d, - +1.5790297768522832E146d, - +1.1518771984292262E146d, - -4.789917000227385E145d, - -8.689594184775204E146d, - +3.0680417869552433E146d, - +4.877860620031438E147d, - -3.4650891244084597E148d, - +1.8702183451052442E149d, - -3.5727227900139915E148d, - -1.3457821696677932E150d, - +3.3212950284273017E149d, - +7.316033240396569E150d, - -7.187723217018267E150d, - -8.537194547485455E150d, - -1.4561530066010593E152d, - -7.548155147049997E151d, - +1.0047353208353007E153d, - -1.2489460589853119E153d, - +4.426120229279107E153d, - -2.5466223330961086E154d, - +8.831699889789037E154d, - -2.0258084311749475E155d, - -5.525009099476396E155d, - -1.0235056525096769E156d, - -4.117971654572494E154d, - -4.7559175309753334E156d, - -1.4656240137098836E157d, - -7.675790582869644E157d, - -1.0126616322947826E158d, - +7.084865265284368E158d, - -9.374695893307895E158d, - +2.05597910889115E159d, - -7.368602086210704E159d, - -1.6167825196198978E160d, - +2.3832096207000712E160d, - +1.3166970112139726E161d, - -6.432337568761393E161d, - +2.9279594746502846E161d, - +4.8926595743317624E162d, - +1.2704793774453618E163d, - -1.1345910784680524E163d, - +7.75933511025868E163d, - -1.1441115218462356E163d, - +5.162248481759758E164d, - +6.362563919556132E164d, - -2.8362173224732088E165d, - -4.342161053332263E165d, - +4.388125271425036E166d, - -7.049068240916723E166d, - +3.8520227881415595E166d, - +2.9274120974020826E167d, - -7.500936767542933E167d, - -6.540181860667302E168d, - +4.664436780622191E168d, - -1.436111169285268E169d, - -1.0407581736224179E170d, - -2.7670181051374297E170d, - -6.788169932297778E170d, - +1.6997387217850427E171d, - -1.0965324942770584E171d, - +9.841563119484623E171d, - +3.175748919314254E172d, - +2.9621181706527444E172d, - -3.30101656090905E173d, - -3.791840683760427E173d, - -2.841347842666459E174d, - -7.836327226971707E174d, - +9.650358667643114E174d, - +5.9994277301267294E175d, - -6.0490084078440215E175d, - -2.8964095485948707E176d, - +9.916187343252014E175d, - +2.7535627955313556E176d, - +3.886891475472745E177d, - +3.1962472803616787E178d, - -5.50599549115449E178d, - +5.672812341879918E178d, - -3.295268490032475E179d, - +9.761163062156018E179d, - +3.107837179570674E180d, - +3.3894811576571423E179d, - -5.235397688850367E180d, - -5.004237248003625E181d, - -1.7544995191195304E182d, - +2.645622651144787E182d, - -3.459885432869825E182d, - -4.0361435606199565E183d, - -1.8382923511801317E183d, - -1.7332235571505177E184d, - +2.847653455671381E184d, - +1.7991060813894693E185d, - -2.0937429891059164E185d, - +5.744446753652847E185d, - -2.1349396267483754E184d, - -1.2542332720182776E186d, - +3.3730714236579374E186d, - -5.923734606208998E187d, - +2.24669039465627E188d, - -1.2588742703536392E188d, - +1.474522484905093E189d, - -2.4006971787803736E189d, - -3.52597540499141E189d, - +2.6676722922838097E190d, - +5.27579825970359E190d, - +2.1360492104281465E191d, - +1.9442210982008953E191d, - -1.4691239161932232E190d, - +3.8218180377739526E192d, - +1.9722862688653467E192d, - +3.047601928063002E193d, - +1.6747356805175311E193d, - +7.710512446969693E192d, - +1.7780021277684035E194d, - -1.4015110811648513E195d, - +4.0447634595724164E195d, - +9.023639664212642E195d, - +1.976868146639626E196d, - -9.084495133765657E196d, - -1.2023077889892748E196d, - +5.7455368446308694E197d, - -1.7766273910482863E198d, - +3.5590470673352285E198d, - +1.1304970373249033E199d, - +1.6496143246803731E199d, - -2.394588390685223E199d, - -1.4677321100833294E199d, - -1.1843870433971731E201d, - -1.8853982316037226E201d, - +2.8829871423339434E201d, - +5.369687677705385E200d, - +1.8356062677502141E202d, - -1.5544655377217875E203d, - +2.955364187248884E203d, - -2.7651059253677425E203d, - +9.903174064539538E203d, - -3.284204788892967E204d, - -1.5843229740595697E205d, - +5.333371443528904E204d, - +1.2781631468016048E205d, - +3.2188292385399854E205d, - -6.619064395428225E206d, - +1.291561142865928E207d, - +1.3142988156905172E207d, - -1.3841980097978606E208d, - +6.380177790989479E207d, - +1.0386032577072378E209d, - +2.7681631086098026E209d, - -9.053874899534375E209d, - +1.2424707839848734E210d, - +1.045546633850141E211d, - -1.2448938139338362E211d, - +7.221902646057552E211d, - +6.651345415954053E211d, - -5.8180712702152444E212d, - +5.275183961165903E212d, - +5.092753117288608E212d, - -2.437796532151255E213d, - +1.3480763914637323E214d, - +5.619995933180841E214d, - +2.547000388735681E214d, - +4.817319356453926E214d, - -7.897146442236022E215d, - -7.93844120619577E215d, - -4.9489938500591624E216d, - -2.862720607805682E216d, - -2.9275804461593914E217d, - -3.411186219855533E217d, - -2.0110092718356274E218d, - -8.472642266772353E218d, - -4.357990742470246E217d, - +4.793444363780116E219d, - +1.6544084224626834E220d, - -6.017988576347111E220d, - -3.580397221598409E220d, - -4.7208848667217906E221d, - -7.724899660259369E221d, - -2.4459728627968634E222d, - +3.667348665023154E221d, - +4.544122762558404E223d, - -4.0573420909530794E223d, - -3.2552002992257195E223d, - -6.488296536838142E224d, - +1.7544839352461719E224d, - -4.0873400635183405E225d, - -8.833499967268279E225d, - -1.0953484767704112E226d, - -8.56825295972308E226d, - -1.8097633115378247E227d, - -6.171564449018882E227d, - -4.351843341274115E227d, - +2.8032429752543687E228d, - -1.0065901934522996E229d, - +9.863720960170636E228d, - -9.481088691357648E229d, - -1.6843492713373762E229d, - -1.3282890219894906E230d, - +6.883577595238845E230d, - -1.153577281189635E231d, - -8.009548754642203E231d, - -4.722612904888278E232d, - -4.768909872963015E232d, - +3.2542391242036633E233d, - +6.513425781583774E233d, - -1.8889614379831606E233d, - -2.227647301474917E234d, - -4.7971208532986115E234d, - +6.693500938105557E234d, - -6.587776621471115E234d, - +3.0099905634916516E236d, - -4.6694407626686244E235d, - +2.965546585110978E236d, - +5.771457643937893E237d, - -9.029878114318277E237d, - +8.169926810324408E237d, - -1.779945804977441E239d, - +4.1218749988429474E239d, - +7.201319954099161E239d, - -1.530845432304069E240d, - -3.861762510530086E240d, - -2.4090696463777446E241d, - -1.8196842273916379E241d, - -1.7959243076374794E242d, - -3.7257346819782323E242d, - +3.413310324247329E242d, - -2.0406580894051073E243d, - -1.5335923091350053E243d, - -1.056727406551016E244d, - -4.6753408714233723E244d, - -2.0697130057384643E245d, - -1.0356006160554071E245d, - +1.1339195187304043E246d, - +1.792783182582235E246d, - +9.599214853681978E245d, - +1.5367645598839362E247d, - +2.934570385464815E247d, - -1.6411525886171892E248d, - +2.2638862982382794E248d, - -1.2268014119628852E249d, - +4.737693450915584E247d, - +6.3818993714899675E249d, - +1.2639113706171572E250d, - -4.011320021817099E249d, - -5.2744376732859406E250d, - -3.732266217624991E251d, - +1.7591819833844019E252d, - -3.292458622014749E252d, - -9.161340309319204E252d, - -1.728610646009749E253d, - +1.1698424008604891E254d, - -1.8494343291160577E254d, - +2.0568656302182574E254d, - +1.0537591246531136E255d, - +1.803052068234866E254d, - -1.053036399720808E256d, - +2.1836166619192508E256d, - +1.0368403169781264E257d, - -2.0648015610276362E257d, - +8.426174035728768E257d, - -1.3577357192972777E258d, - +2.1313950901331177E258d, - +8.919141843592823E258d, - -1.1800039972549816E259d, - -1.1878772398311421E260d, - -1.538273497873993E260d, - -4.51305093266001E260d, - +1.1241179396053055E261d, - +6.154786508667658E261d, - -1.0626125049032536E262d, - -1.8908603201210102E262d, - -4.571195152299358E262d, - +1.526100002923062E263d, - -9.457084582570225E263d, - -1.5460500618825853E264d, - -5.598276199126451E264d, - -1.2074097381167957E265d, - -3.015972957475025E265d, - +1.4345106852061226E265d, - +8.28479585346867E265d, - -3.118741081244705E266d, - -1.2054747399765794E266d, - +3.4454766202661184E267d, - +1.1279135096919439E268d, - +1.2066382528772518E268d, - +1.1984128162292276E269d, - +3.685169705587367E268d, - +6.570047690198998E269d, - +1.8836492887460383E270d, - +7.4364594917181125E270d, - +1.2773080633674971E271d, - +1.8928981707279692E271d, - +4.039437286589528E271d, - +1.785277385538302E272d, - -6.017681359527226E272d, - +1.9716943051755635E273d, - -8.772048092842086E271d, - +1.5645672698520312E274d, - -3.7979660725865874E274d, - +5.324902289537048E274d, - -1.8806716685063293E274d, - +9.320900373401115E275d, - +1.4615985810260016E275d, - +8.321226457219046E276d, - -4.608112855795952E276d, - -3.476352191116455E277d, - +5.266381689434054E277d, - -9.622106063561645E277d, - +4.1719443712336026E278d, - +4.222411269063919E279d, - -6.714376022102489E279d, - -1.0732735585199074E280d, - -2.5866883048437488E280d, - -1.1306860837934988E281d, - +3.690690354793168E281d, - -5.5299180508885456E281d, - +2.7006726968568243E282d, - +4.135457669031131E282d, - +2.8401159516008676E283d, - +5.127265762024798E283d, - -3.4893601256685762E283d, - -1.145160459652136E283d, - +2.1742808735341656E284d, - +4.656972469326391E285d, - +7.672307991205681E285d, - +1.5781599575584034E286d, - +4.218682431618625E286d, - -2.4602260687026867E287d, - +2.7211316452521414E287d, - -1.8740018211089393E288d, - +2.6367639658206183E288d, - -3.102678910525039E288d, - +1.1992295328636466E289d, - +6.8190133180135345E289d, - +5.783203879030497E289d, - +5.171047077293295E290d, - +1.8396930096213817E290d, - +1.4977047507315718E290d, - +1.0672499803427623E292d, - +3.3310942289102464E291d, - -7.962256961838823E292d, - +1.7396889119023863E293d, - +3.8072183820435085E293d, - +2.2772059538865722E294d, - -2.0549866377878678E294d, - -1.2277120342804144E295d, - -3.609949022969024E295d, - +1.1479863663699871E296d, - -1.5314373779304356E296d, - -2.2537635160762597E296d, - -6.1370690793508674E296d, - -4.996854125490041E297d, - -6.883499809714189E297d, - -2.595456638706416E298d, - -1.1892631528580186E299d, - -1.4672600326020399E299d, - -3.200068509818696E299d, - -7.126913872617518E298d, - -3.3655587417265094E300d, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - Double.NaN, - }; - - - /** Exponential over the range of 0 - 1 in increments of 2^-10 - * exp(x/1024) = expFracTableA[x] + expFracTableB[x]. - * 1024 = 2^10 - */ - private static final double[] EXP_FRAC_A = new double[] { - +1.0d, - +1.0009770393371582d, - +1.0019550323486328d, - +1.0029339790344238d, - +1.0039138793945312d, - +1.004894733428955d, - +1.0058765411376953d, - +1.006859302520752d, - +1.007843017578125d, - +1.0088276863098145d, - +1.0098135471343994d, - +1.0108001232147217d, - +1.0117876529693604d, - +1.0127761363983154d, - +1.013765811920166d, - +1.014756202697754d, - +1.0157477855682373d, - +1.016740083694458d, - +1.0177335739135742d, - +1.0187277793884277d, - +1.0197231769561768d, - +1.0207195281982422d, - +1.021716833114624d, - +1.0227150917053223d, - +1.023714303970337d, - +1.024714469909668d, - +1.0257158279418945d, - +1.0267179012298584d, - +1.0277209281921387d, - +1.0287251472473145d, - +1.0297303199768066d, - +1.0307364463806152d, - +1.0317435264587402d, - +1.0327515602111816d, - +1.0337605476379395d, - +1.0347704887390137d, - +1.0357816219329834d, - +1.0367934703826904d, - +1.037806510925293d, - +1.038820505142212d, - +1.0398354530334473d, - +1.040851354598999d, - +1.0418684482574463d, - +1.0428862571716309d, - +1.043905258178711d, - +1.0449252128601074d, - +1.0459461212158203d, - +1.0469679832458496d, - +1.0479910373687744d, - +1.0490150451660156d, - +1.0500397682189941d, - +1.0510656833648682d, - +1.0520927906036377d, - +1.0531206130981445d, - +1.0541496276855469d, - +1.0551795959472656d, - +1.0562105178833008d, - +1.0572423934936523d, - +1.0582754611968994d, - +1.059309482574463d, - +1.0603444576263428d, - +1.061380386352539d, - +1.0624175071716309d, - +1.06345534324646d, - +1.0644943714141846d, - +1.0655345916748047d, - +1.066575527191162d, - +1.067617654800415d, - +1.0686607360839844d, - +1.0697050094604492d, - +1.0707499980926514d, - +1.071796178817749d, - +1.072843313217163d, - +1.0738916397094727d, - +1.0749409198760986d, - +1.075991153717041d, - +1.0770423412322998d, - +1.078094720840454d, - +1.0791480541229248d, - +1.080202341079712d, - +1.0812578201293945d, - +1.0823142528533936d, - +1.083371639251709d, - +1.08443021774292d, - +1.0854897499084473d, - +1.086550235748291d, - +1.0876119136810303d, - +1.088674545288086d, - +1.089738130569458d, - +1.0908029079437256d, - +1.0918686389923096d, - +1.092935562133789d, - +1.094003438949585d, - +1.0950722694396973d, - +1.096142053604126d, - +1.0972130298614502d, - +1.09828519821167d, - +1.099358320236206d, - +1.1004323959350586d, - +1.1015074253082275d, - +1.102583646774292d, - +1.103661060333252d, - +1.1047391891479492d, - +1.105818748474121d, - +1.1068990230560303d, - +1.107980489730835d, - +1.1090631484985352d, - +1.1101467609405518d, - +1.1112313270568848d, - +1.1123170852661133d, - +1.1134037971496582d, - +1.1144917011260986d, - +1.1155805587768555d, - +1.1166706085205078d, - +1.1177616119384766d, - +1.1188538074493408d, - +1.1199469566345215d, - +1.1210410594940186d, - +1.1221363544464111d, - +1.1232328414916992d, - +1.1243302822113037d, - +1.1254286766052246d, - +1.126528263092041d, - +1.127629041671753d, - +1.1287307739257812d, - +1.129833459854126d, - +1.1309373378753662d, - +1.132042407989502d, - +1.133148431777954d, - +1.1342556476593018d, - +1.1353638172149658d, - +1.1364731788635254d, - +1.1375834941864014d, - +1.1386950016021729d, - +1.1398074626922607d, - +1.1409211158752441d, - +1.142035961151123d, - +1.1431517601013184d, - +1.14426851272583d, - +1.1453864574432373d, - +1.14650559425354d, - +1.1476259231567383d, - +1.148747205734253d, - +1.149869441986084d, - +1.1509928703308105d, - +1.1521174907684326d, - +1.153243064880371d, - +1.154369831085205d, - +1.1554977893829346d, - +1.1566267013549805d, - +1.1577568054199219d, - +1.1588881015777588d, - +1.160020351409912d, - +1.161153793334961d, - +1.1622881889343262d, - +1.163423776626587d, - +1.1645605564117432d, - +1.1656982898712158d, - +1.166837215423584d, - +1.1679773330688477d, - +1.1691184043884277d, - +1.1702606678009033d, - +1.1714041233062744d, - +1.172548532485962d, - +1.173694133758545d, - +1.1748409271240234d, - +1.1759889125823975d, - +1.177137851715088d, - +1.1782879829406738d, - +1.1794393062591553d, - +1.1805915832519531d, - +1.1817450523376465d, - +1.1828997135162354d, - +1.1840553283691406d, - +1.1852121353149414d, - +1.1863701343536377d, - +1.1875293254852295d, - +1.1886897087097168d, - +1.1898510456085205d, - +1.1910135746002197d, - +1.1921772956848145d, - +1.1933419704437256d, - +1.1945080757141113d, - +1.1956751346588135d, - +1.1968433856964111d, - +1.1980125904083252d, - +1.1991832256317139d, - +1.200354814529419d, - +1.2015275955200195d, - +1.2027015686035156d, - +1.2038767337799072d, - +1.2050528526306152d, - +1.2062301635742188d, - +1.2074086666107178d, - +1.2085883617401123d, - +1.2097692489624023d, - +1.210951328277588d, - +1.2121343612670898d, - +1.2133188247680664d, - +1.2145042419433594d, - +1.2156908512115479d, - +1.2168786525726318d, - +1.2180676460266113d, - +1.2192575931549072d, - +1.2204489707946777d, - +1.2216413021087646d, - +1.222834825515747d, - +1.224029779434204d, - +1.2252256870269775d, - +1.2264227867126465d, - +1.227621078491211d, - +1.2288203239440918d, - +1.2300209999084473d, - +1.2312228679656982d, - +1.2324256896972656d, - +1.2336299419403076d, - +1.234835147857666d, - +1.23604154586792d, - +1.2372493743896484d, - +1.2384581565856934d, - +1.2396681308746338d, - +1.2408792972564697d, - +1.2420918941497803d, - +1.2433054447174072d, - +1.2445201873779297d, - +1.2457361221313477d, - +1.2469532489776611d, - +1.2481715679168701d, - +1.2493910789489746d, - +1.2506117820739746d, - +1.2518336772918701d, - +1.2530567646026611d, - +1.2542810440063477d, - +1.2555065155029297d, - +1.2567331790924072d, - +1.2579610347747803d, - +1.2591900825500488d, - +1.260420322418213d, - +1.2616519927978516d, - +1.2628846168518066d, - +1.2641184329986572d, - +1.2653534412384033d, - +1.266589879989624d, - +1.2678272724151611d, - +1.2690660953521729d, - +1.27030611038208d, - +1.2715470790863037d, - +1.272789478302002d, - +1.2740330696105957d, - +1.275277853012085d, - +1.2765238285064697d, - +1.27777099609375d, - +1.2790195941925049d, - +1.2802691459655762d, - +1.281519889831543d, - +1.2827720642089844d, - +1.2840254306793213d, - +1.2852799892425537d, - +1.2865357398986816d, - +1.287792682647705d, - +1.2890510559082031d, - +1.2903103828430176d, - +1.2915711402893066d, - +1.2928330898284912d, - +1.2940962314605713d, - +1.2953605651855469d, - +1.296626091003418d, - +1.2978930473327637d, - +1.2991611957550049d, - +1.3004305362701416d, - +1.3017010688781738d, - +1.3029727935791016d, - +1.304245948791504d, - +1.3055200576782227d, - +1.3067958354949951d, - +1.308072566986084d, - +1.3093504905700684d, - +1.3106298446655273d, - +1.3119103908538818d, - +1.3131921291351318d, - +1.3144752979278564d, - +1.3157594203948975d, - +1.317044973373413d, - +1.3183319568634033d, - +1.31961989402771d, - +1.3209092617034912d, - +1.322199821472168d, - +1.3234915733337402d, - +1.324784755706787d, - +1.3260791301727295d, - +1.3273746967315674d, - +1.3286716938018799d, - +1.329969882965088d, - +1.3312692642211914d, - +1.3325698375701904d, - +1.333871841430664d, - +1.3351752758026123d, - +1.336479663848877d, - +1.3377854824066162d, - +1.339092493057251d, - +1.3404009342193604d, - +1.3417105674743652d, - +1.3430213928222656d, - +1.3443336486816406d, - +1.3456470966339111d, - +1.3469617366790771d, - +1.3482778072357178d, - +1.349595069885254d, - +1.3509137630462646d, - +1.352233648300171d, - +1.3535549640655518d, - +1.3548774719238281d, - +1.356201171875d, - +1.3575263023376465d, - +1.3588526248931885d, - +1.360180139541626d, - +1.361509084701538d, - +1.3628394603729248d, - +1.364171028137207d, - +1.3655037879943848d, - +1.366837978363037d, - +1.368173360824585d, - +1.3695101737976074d, - +1.3708481788635254d, - +1.372187614440918d, - +1.373528242111206d, - +1.3748703002929688d, - +1.376213550567627d, - +1.3775582313537598d, - +1.378904104232788d, - +1.380251407623291d, - +1.3815999031066895d, - +1.3829498291015625d, - +1.384300947189331d, - +1.3856534957885742d, - +1.387007236480713d, - +1.3883624076843262d, - +1.389719009399414d, - +1.3910768032073975d, - +1.3924360275268555d, - +1.393796443939209d, - +1.395158290863037d, - +1.3965213298797607d, - +1.397885799407959d, - +1.3992514610290527d, - +1.4006187915802002d, - +1.401987075805664d, - +1.4033570289611816d, - +1.4047281742095947d, - +1.4061005115509033d, - +1.4074742794036865d, - +1.4088494777679443d, - +1.4102261066436768d, - +1.4116039276123047d, - +1.4129831790924072d, - +1.4143636226654053d, - +1.415745496749878d, - +1.4171288013458252d, - +1.418513298034668d, - +1.4198992252349854d, - +1.4212865829467773d, - +1.4226751327514648d, - +1.424065351486206d, - +1.4254565238952637d, - +1.426849365234375d, - +1.4282433986663818d, - +1.4296388626098633d, - +1.4310357570648193d, - +1.432433843612671d, - +1.433833360671997d, - +1.4352343082427979d, - +1.4366366863250732d, - +1.4380402565002441d, - +1.4394452571868896d, - +1.4408516883850098d, - +1.4422595500946045d, - +1.4436686038970947d, - +1.4450790882110596d, - +1.446491003036499d, - +1.447904348373413d, - +1.4493188858032227d, - +1.450735092163086d, - +1.4521524906158447d, - +1.4535713195800781d, - +1.454991340637207d, - +1.4564130306243896d, - +1.4578359127044678d, - +1.4592602252960205d, - +1.460686206817627d, - +1.4621131420135498d, - +1.4635417461395264d, - +1.4649717807769775d, - +1.4664030075073242d, - +1.4678359031677246d, - +1.4692699909210205d, - +1.470705509185791d, - +1.4721424579620361d, - +1.4735808372497559d, - +1.475020408630371d, - +1.47646164894104d, - +1.4779040813446045d, - +1.4793481826782227d, - +1.4807934761047363d, - +1.4822404384613037d, - +1.4836885929107666d, - +1.485138177871704d, - +1.4865891933441162d, - +1.488041639328003d, - +1.4894955158233643d, - +1.4909508228302002d, - +1.4924075603485107d, - +1.493865728378296d, - +1.4953253269195557d, - +1.49678635597229d, - +1.49824857711792d, - +1.4997124671936035d, - +1.5011777877807617d, - +1.5026445388793945d, - +1.504112720489502d, - +1.505582332611084d, - +1.5070531368255615d, - +1.5085256099700928d, - +1.5099995136260986d, - +1.511474847793579d, - +1.5129516124725342d, - +1.5144298076629639d, - +1.5159096717834473d, - +1.5173907279968262d, - +1.5188732147216797d, - +1.5203571319580078d, - +1.5218427181243896d, - +1.523329496383667d, - +1.524817943572998d, - +1.5263078212738037d, - +1.5277988910675049d, - +1.5292916297912598d, - +1.5307857990264893d, - +1.5322813987731934d, - +1.5337786674499512d, - +1.5352771282196045d, - +1.5367772579193115d, - +1.538278579711914d, - +1.5397815704345703d, - +1.5412859916687012d, - +1.5427920818328857d, - +1.5442993640899658d, - +1.5458080768585205d, - +1.547318458557129d, - +1.548830270767212d, - +1.5503435134887695d, - +1.5518584251403809d, - +1.5533745288848877d, - +1.5548923015594482d, - +1.5564115047454834d, - +1.5579321384429932d, - +1.5594542026519775d, - +1.5609779357910156d, - +1.5625030994415283d, - +1.5640296936035156d, - +1.5655577182769775d, - +1.5670874118804932d, - +1.5686185359954834d, - +1.5701510906219482d, - +1.5716853141784668d, - +1.5732207298278809d, - +1.5747578144073486d, - +1.5762965679168701d, - +1.577836513519287d, - +1.5793781280517578d, - +1.5809214115142822d, - +1.5824658870697021d, - +1.5840120315551758d, - +1.5855598449707031d, - +1.587108850479126d, - +1.5886595249176025d, - +1.5902118682861328d, - +1.5917654037475586d, - +1.593320608139038d, - +1.5948774814605713d, - +1.596435785293579d, - +1.5979955196380615d, - +1.5995566844940186d, - +1.6011195182800293d, - +1.6026840209960938d, - +1.6042497158050537d, - +1.6058173179626465d, - +1.6073861122131348d, - +1.6089565753936768d, - +1.6105287075042725d, - +1.6121022701263428d, - +1.6136772632598877d, - +1.6152539253234863d, - +1.6168320178985596d, - +1.6184117794036865d, - +1.619992971420288d, - +1.6215758323669434d, - +1.6231601238250732d, - +1.6247460842132568d, - +1.626333475112915d, - +1.627922534942627d, - +1.6295130252838135d, - +1.6311051845550537d, - +1.6326987743377686d, - +1.634294033050537d, - +1.6358907222747803d, - +1.6374890804290771d, - +1.6390891075134277d, - +1.640690565109253d, - +1.6422934532165527d, - +1.6438980102539062d, - +1.6455042362213135d, - +1.6471118927001953d, - +1.6487212181091309d, - +1.6503322124481201d, - +1.651944637298584d, - +1.6535584926605225d, - +1.6551742553710938d, - +1.6567914485931396d, - +1.6584100723266602d, - +1.6600303649902344d, - +1.6616523265838623d, - +1.663275957107544d, - +1.6649010181427002d, - +1.666527509689331d, - +1.6681559085845947d, - +1.669785737991333d, - +1.671417236328125d, - +1.6730501651763916d, - +1.674684762954712d, - +1.676321029663086d, - +1.6779589653015137d, - +1.679598331451416d, - +1.681239366531372d, - +1.6828820705413818d, - +1.6845262050628662d, - +1.6861720085144043d, - +1.687819480895996d, - +1.6894686222076416d, - +1.6911191940307617d, - +1.6927716732025146d, - +1.6944255828857422d, - +1.6960809230804443d, - +1.6977381706237793d, - +1.6993968486785889d, - +1.7010571956634521d, - +1.7027192115783691d, - +1.7043828964233398d, - +1.7060482501983643d, - +1.7077150344848633d, - +1.709383487701416d, - +1.7110536098480225d, - +1.7127254009246826d, - +1.7143988609313965d, - +1.716073989868164d, - +1.7177505493164062d, - +1.7194287776947021d, - +1.7211089134216309d, - +1.7227904796600342d, - +1.7244737148284912d, - +1.726158618927002d, - +1.7278449535369873d, - +1.7295331954956055d, - +1.7312231063842773d, - +1.7329144477844238d, - +1.7346076965332031d, - +1.736302375793457d, - +1.7379989624023438d, - +1.739696979522705d, - +1.7413966655731201d, - +1.7430980205535889d, - +1.7448012828826904d, - +1.7465059757232666d, - +1.7482123374938965d, - +1.74992036819458d, - +1.7516300678253174d, - +1.7533416748046875d, - +1.7550547122955322d, - +1.7567694187164307d, - +1.7584857940673828d, - +1.7602040767669678d, - +1.7619237899780273d, - +1.7636451721191406d, - +1.7653684616088867d, - +1.7670931816101074d, - +1.768819808959961d, - +1.770547866821289d, - +1.77227783203125d, - +1.7740094661712646d, - +1.775742769241333d, - +1.777477741241455d, - +1.7792143821716309d, - +1.7809526920318604d, - +1.7826926708221436d, - +1.7844345569610596d, - +1.7861778736114502d, - +1.7879230976104736d, - +1.7896699905395508d, - +1.7914185523986816d, - +1.7931687831878662d, - +1.7949209213256836d, - +1.7966744899749756d, - +1.7984299659729004d, - +1.800187110900879d, - +1.8019459247589111d, - +1.8037066459655762d, - +1.8054687976837158d, - +1.8072328567504883d, - +1.8089985847473145d, - +1.8107659816741943d, - +1.812535285949707d, - +1.8143062591552734d, - +1.8160789012908936d, - +1.8178532123565674d, - +1.819629430770874d, - +1.8214070796966553d, - +1.8231868743896484d, - +1.8249680995941162d, - +1.8267512321472168d, - +1.828536033630371d, - +1.830322504043579d, - +1.83211088180542d, - +1.8339009284973145d, - +1.8356926441192627d, - +1.8374862670898438d, - +1.8392815589904785d, - +1.841078519821167d, - +1.8428773880004883d, - +1.8446779251098633d, - +1.846480131149292d, - +1.8482842445373535d, - +1.8500902652740479d, - +1.8518977165222168d, - +1.8537070751190186d, - +1.8555183410644531d, - +1.8573312759399414d, - +1.8591458797454834d, - +1.8609623908996582d, - +1.8627805709838867d, - +1.864600658416748d, - +1.866422414779663d, - +1.8682458400726318d, - +1.8700714111328125d, - +1.8718984127044678d, - +1.8737273216247559d, - +1.8755581378936768d, - +1.8773906230926514d, - +1.8792247772216797d, - +1.8810608386993408d, - +1.8828988075256348d, - +1.8847384452819824d, - +1.886579990386963d, - +1.888423204421997d, - +1.890268325805664d, - +1.8921151161193848d, - +1.8939638137817383d, - +1.8958141803741455d, - +1.8976664543151855d, - +1.8995206356048584d, - +1.901376485824585d, - +1.9032342433929443d, - +1.9050939083099365d, - +1.9069552421569824d, - +1.908818244934082d, - +1.9106833934783936d, - +1.9125502109527588d, - +1.9144186973571777d, - +1.9162893295288086d, - +1.9181616306304932d, - +1.9200356006622314d, - +1.9219114780426025d, - +1.9237892627716064d, - +1.9256689548492432d, - +1.9275505542755127d, - +1.929433822631836d, - +1.931318759918213d, - +1.9332058429718018d, - +1.9350945949554443d, - +1.9369852542877197d, - +1.938877820968628d, - +1.940772294998169d, - +1.9426684379577637d, - +1.9445664882659912d, - +1.9464664459228516d, - +1.9483680725097656d, - +1.9502718448638916d, - +1.9521772861480713d, - +1.9540846347808838d, - +1.955993890762329d, - +1.9579050540924072d, - +1.959817886352539d, - +1.9617326259613037d, - +1.9636495113372803d, - +1.9655680656433105d, - +1.9674885272979736d, - +1.9694106578826904d, - +1.9713349342346191d, - +1.9732608795166016d, - +1.975188970565796d, - +1.977118730545044d, - +1.9790503978729248d, - +1.9809842109680176d, - +1.982919692993164d, - +1.9848570823669434d, - +1.9867963790893555d, - +1.9887375831604004d, - +1.990680456161499d, - +1.9926254749298096d, - +1.994572401046753d, - +1.996521234512329d, - +1.998471736907959d, - +2.000424385070801d, - +2.0023789405822754d, - +2.004335403442383d, - +2.006293773651123d, - +2.008254051208496d, - +2.010216236114502d, - +2.0121798515319824d, - +2.014145851135254d, - +2.016113758087158d, - +2.0180835723876953d, - +2.0200552940368652d, - +2.022029399871826d, - +2.0240049362182617d, - +2.02598237991333d, - +2.0279617309570312d, - +2.0299429893493652d, - +2.0319266319274902d, - +2.03391170501709d, - +2.0358991622924805d, - +2.0378880500793457d, - +2.039879322052002d, - +2.041872501373291d, - +2.0438671112060547d, - +2.0458641052246094d, - +2.047863006591797d, - +2.049863815307617d, - +2.0518670082092285d, - +2.0538716316223145d, - +2.055878162384033d, - +2.057887077331543d, - +2.0598974227905273d, - +2.0619101524353027d, - +2.063924789428711d, - +2.065941333770752d, - +2.067959785461426d, - +2.0699801445007324d, - +2.07200288772583d, - +2.0740270614624023d, - +2.0760536193847656d, - +2.0780820846557617d, - +2.0801124572753906d, - +2.0821447372436523d, - +2.084178924560547d, - +2.0862154960632324d, - +2.0882534980773926d, - +2.0902938842773438d, - +2.0923361778259277d, - +2.0943803787231445d, - +2.0964269638061523d, - +2.0984749794006348d, - +2.100525379180908d, - +2.1025776863098145d, - +2.1046319007873535d, - +2.1066884994506836d, - +2.1087465286254883d, - +2.110806941986084d, - +2.1128692626953125d, - +2.114933490753174d, - +2.117000102996826d, - +2.1190686225891113d, - +2.1211390495300293d, - +2.12321138381958d, - +2.1252856254577637d, - +2.1273622512817383d, - +2.1294407844543457d, - +2.131521224975586d, - +2.133604049682617d, - +2.135688304901123d, - +2.13777494430542d, - +2.139863967895508d, - +2.1419544219970703d, - +2.144047260284424d, - +2.14614200592041d, - +2.1482391357421875d, - +2.1503376960754395d, - +2.1524391174316406d, - +2.1545419692993164d, - +2.156647205352783d, - +2.1587538719177246d, - +2.1608633995056152d, - +2.1629743576049805d, - +2.1650876998901367d, - +2.167203426361084d, - +2.169320583343506d, - +2.1714401245117188d, - +2.1735615730285645d, - +2.175685405731201d, - +2.1778111457824707d, - +2.179938793182373d, - +2.1820688247680664d, - +2.1842007637023926d, - +2.1863350868225098d, - +2.1884708404541016d, - +2.1906094551086426d, - +2.192749500274658d, - +2.194891929626465d, - +2.1970362663269043d, - +2.1991829872131348d, - +2.201331615447998d, - +2.2034826278686523d, - +2.2056355476379395d, - +2.2077903747558594d, - +2.2099475860595703d, - +2.212106704711914d, - +2.214268207550049d, - +2.2164316177368164d, - +2.218596935272217d, - +2.220764636993408d, - +2.2229342460632324d, - +2.2251062393188477d, - +2.2272801399230957d, - +2.2294564247131348d, - +2.2316346168518066d, - +2.2338151931762695d, - +2.2359976768493652d, - +2.2381820678710938d, - +2.2403693199157715d, - +2.242558002471924d, - +2.244749069213867d, - +2.2469425201416016d, - +2.2491378784179688d, - +2.2513351440429688d, - +2.2535347938537598d, - +2.2557363510131836d, - +2.2579402923583984d, - +2.2601466178894043d, - +2.262354850769043d, - +2.2645654678344727d, - +2.266777992248535d, - +2.2689924240112305d, - +2.271209716796875d, - +2.273428440093994d, - +2.2756495475769043d, - +2.2778730392456055d, - +2.2800989151000977d, - +2.2823266983032227d, - +2.2845563888549805d, - +2.2867884635925293d, - +2.289022922515869d, - +2.291259288787842d, - +2.2934980392456055d, - +2.295738697052002d, - +2.2979817390441895d, - +2.300227165222168d, - +2.3024744987487793d, - +2.3047242164611816d, - +2.306975841522217d, - +2.309229850769043d, - +2.31148624420166d, - +2.31374454498291d, - +2.316005229949951d, - +2.318267822265625d, - +2.32053279876709d, - +2.3228001594543457d, - +2.3250694274902344d, - +2.3273415565490723d, - +2.3296151161193848d, - +2.3318915367126465d, - +2.334169864654541d, - +2.3364500999450684d, - +2.338733196258545d, - +2.3410181999206543d, - +2.3433055877685547d, - +2.345594882965088d, - +2.347886562347412d, - +2.3501806259155273d, - +2.3524770736694336d, - +2.3547754287719727d, - +2.3570761680603027d, - +2.3593788146972656d, - +2.3616843223571777d, - +2.3639917373657227d, - +2.3663015365600586d, - +2.3686132431030273d, - +2.370927333831787d, - +2.373243808746338d, - +2.3755626678466797d, - +2.3778839111328125d, - +2.380207061767578d, - +2.3825325965881348d, - +2.3848605155944824d, - +2.387190818786621d, - +2.3895230293273926d, - +2.391857624053955d, - +2.3941946029663086d, - +2.396533966064453d, - +2.3988752365112305d, - +2.401218891143799d, - +2.4035654067993164d, - +2.4059133529663086d, - +2.40826416015625d, - +2.4106173515319824d, - +2.4129724502563477d, - +2.415329933166504d, - +2.417689800262451d, - +2.4200520515441895d, - +2.4224166870117188d, - +2.424783229827881d, - +2.427152633666992d, - +2.4295239448547363d, - +2.4318976402282715d, - +2.4342737197875977d, - +2.436652183532715d, - +2.439032554626465d, - +2.441415786743164d, - +2.4438014030456543d, - +2.4461889266967773d, - +2.4485788345336914d, - +2.4509711265563965d, - +2.4533658027648926d, - +2.4557628631591797d, - +2.458162307739258d, - +2.460564136505127d, - +2.462968349456787d, - +2.46537446975708d, - +2.4677834510803223d, - +2.4701943397521973d, - +2.4726080894470215d, - +2.4750237464904785d, - +2.4774417877197266d, - +2.479862689971924d, - +2.482285499572754d, - +2.484710693359375d, - +2.487138271331787d, - +2.4895682334899902d, - +2.4920010566711426d, - +2.4944357872009277d, - +2.496872901916504d, - +2.499312400817871d, - +2.5017542839050293d, - +2.5041985511779785d, - +2.5066452026367188d, - +2.50909423828125d, - +2.5115456581115723d, - +2.5139999389648438d, - +2.516456127166748d, - +2.5189146995544434d, - +2.5213756561279297d, - +2.5238394737243652d, - +2.5263051986694336d, - +2.528773307800293d, - +2.5312442779541016d, - +2.533717155456543d, - +2.5361928939819336d, - +2.538670539855957d, - +2.5411510467529297d, - +2.5436339378356934d, - +2.546119213104248d, - +2.5486068725585938d, - +2.5510969161987305d, - +2.553589344024658d, - +2.556084632873535d, - +2.558581829071045d, - +2.5610814094543457d, - +2.5635838508605957d, - +2.5660886764526367d, - +2.5685958862304688d, - +2.571105480194092d, - +2.573617458343506d, - +2.576131820678711d, - +2.5786490440368652d, - +2.5811686515808105d, - +2.5836901664733887d, - +2.586214542388916d, - +2.5887417793273926d, - +2.591270923614502d, - +2.5938024520874023d, - +2.596336841583252d, - +2.5988736152648926d, - +2.601412773132324d, - +2.603954315185547d, - +2.6064987182617188d, - +2.6090455055236816d, - +2.6115946769714355d, - +2.6141462326049805d, - +2.6167001724243164d, - +2.6192569732666016d, - +2.6218161582946777d, - +2.624377727508545d, - +2.626941680908203d, - +2.6295084953308105d, - +2.632077217102051d, - +2.6346492767333984d, - +2.637223243713379d, - +2.6398000717163086d, - +2.6423792839050293d, - +2.644960880279541d, - +2.6475448608398438d, - +2.6501317024230957d, - +2.6527209281921387d, - +2.655313014984131d, - +2.657907009124756d, - +2.6605043411254883d, - +2.6631035804748535d, - +2.665705680847168d, - +2.6683101654052734d, - +2.67091703414917d, - +2.6735267639160156d, - +2.6761388778686523d, - +2.67875337600708d, - +2.681370735168457d, - +2.683990478515625d, - +2.686613082885742d, - +2.689237594604492d, - +2.6918654441833496d, - +2.69449520111084d, - +2.6971278190612793d, - +2.699763298034668d, - +2.7024011611938477d, - +2.7050414085388184d, - +2.70768404006958d, - +2.710329532623291d, - +2.712977886199951d, - +2.7156286239624023d, - +2.7182817459106445d, - }; - - /** Exponential over the range of 0 - 1 in increments of 2^-10 - * exp(x/1024) = expFracTableA[x] + expFracTableB[x]. - */ - private static final double[] EXP_FRAC_B = new double[] { - +0.0d, - +1.552583321178453E-10d, - +1.2423699995465188E-9d, - +4.194022929828008E-9d, - +9.94381632344361E-9d, - +1.9426261544163577E-8d, - +3.3576783010266685E-8d, - +5.3331719086630523E-8d, - +7.962832297769345E-8d, - +1.1340476362128895E-7d, - -8.281845251820919E-8d, - -3.126416414805498E-8d, - +3.058997113995161E-8d, - +1.0368579417304741E-7d, - -4.9452513107409435E-8d, - +4.8955889659397494E-8d, - -7.698155155722897E-8d, - +5.051784853384516E-8d, - -4.443661736519001E-8d, - +1.1593958457401774E-7d, - +5.575759739697068E-8d, - +1.4385227981629147E-8d, - -7.227368462584163E-9d, - -8.129108387083023E-9d, - +1.263202100290635E-8d, - +5.600896265625552E-8d, - -1.154629885168314E-7d, - -2.399186832888246E-8d, - +9.295948298604103E-8d, - -2.070841011504222E-9d, - -6.97066538508643E-8d, - -1.0898941254272996E-7d, - -1.1895963756343625E-7d, - -9.865691193993138E-8d, - -4.711988033385175E-8d, - +3.6613751875298095E-8d, - -8.491135959370133E-8d, - +6.610611940107793E-8d, - +1.3794148633283659E-8d, - -2.462631860370667E-9d, - +1.830278273495162E-8d, - +7.705834203598065E-8d, - -6.364563771711373E-8d, - +7.39978436695387E-8d, - +1.4122417557484554E-8d, - -3.881598887298574E-9d, - +2.0958481826069642E-8d, - +8.96162975425619E-8d, - -3.535214171178576E-8d, - -1.1455271549574576E-7d, - +9.140964977432485E-8d, - +1.0667524445105459E-7d, - -6.777752790396222E-8d, - +4.586785041291296E-8d, - -2.8245462428022094E-8d, - -5.071761314397018E-8d, - -2.0566368810068663E-8d, - +6.319146317890346E-8d, - -3.687854305539139E-8d, - -8.137269363160008E-8d, - -6.930491127388755E-8d, - +3.1184473002226595E-10d, - -1.0995299963140049E-7d, - +7.772668425499348E-8d, - +8.750367485925089E-8d, - -7.963112393823186E-8d, - +5.415131809829094E-8d, - +1.3006683896462346E-8d, - +3.634736373360733E-8d, - -1.132504393233074E-7d, - +4.2046187038837375E-8d, - +2.6396811618001066E-8d, - +7.92177143584738E-8d, - -3.691100820545433E-8d, - -8.257112559083188E-8d, - -5.676200971739166E-8d, - +4.151794514828518E-8d, - -2.5147255753587636E-8d, - -1.7335469415174996E-8d, - +6.595784859136531E-8d, - -1.2680354928109105E-8d, - -1.3824992526093461E-8d, - +6.353142754175797E-8d, - -1.8021197722549054E-8d, - -1.9054827792903468E-8d, - +6.144098503892116E-8d, - -1.3940903373095247E-8d, - -5.7694907599522404E-9d, - +8.696863522320578E-8d, - +2.6869297963554945E-8d, - +5.3366470162689076E-8d, - -7.094204160127543E-8d, - -1.0662027949814858E-7d, - -5.26498707801063E-8d, - +9.198855229106814E-8d, - +8.989677431456647E-8d, - -5.790384407322479E-8d, - -1.1197236522467887E-7d, - -7.12854317090566E-8d, - +6.51813137650059E-8d, - +6.003465022483798E-8d, - -8.569906238528267E-8d, - +1.0584469687624562E-7d, - -7.956144278281947E-8d, - +7.43676272093501E-8d, - +9.182512565315022E-8d, - -2.6157563728873715E-8d, - -4.012947040998503E-8d, - +5.094280572218447E-8d, - +9.675095351161728E-9d, - +7.552139802281006E-8d, - +1.1099566726533146E-8d, - +5.58656252899437E-8d, - -2.756054703800197E-8d, - +2.791018095971047E-10d, - -9.799351869734466E-8d, - -8.291832428736212E-8d, - +4.654720780112994E-8d, - +5.302803981406403E-8d, - -6.243126731995636E-8d, - -6.036655299348577E-8d, - +6.026878587378257E-8d, - +6.210379583313526E-8d, - -5.381287389094251E-8d, - -4.8012970400697E-8d, - +8.055420567281602E-8d, - +9.452180117175641E-8d, - -5.057430382371206E-9d, - +2.1288872215266507E-8d, - -6.380305844689076E-8d, - -2.0858800984600168E-8d, - -8.724006061713588E-8d, - -2.3470351753125604E-8d, - -6.690931338790221E-8d, - +2.192160831263035E-8d, - +5.6648446166177225E-9d, - -1.1461755745719884E-7d, - -9.944393412663547E-8d, - +5.2249837964645906E-8d, - +1.0311034276196487E-7d, - +5.4203784018566126E-8d, - -9.340259278913173E-8d, - -1.0022192034216903E-7d, - +3.481513333662908E-8d, - +7.436036590244714E-8d, - +1.9485199912395296E-8d, - +1.0968068384729757E-7d, - +1.0760175582979094E-7d, - +1.4322981952798675E-8d, - +6.933855730431659E-8d, - +3.530656968851287E-8d, - -8.669526204279467E-8d, - -5.7169586962345785E-8d, - -1.1345515834332824E-7d, - -1.605251622332555E-8d, - -2.298302779758532E-9d, - -7.110952399338234E-8d, - +1.70164513845372E-8d, - +2.4746155561368937E-8d, - -4.6834239957353325E-8d, - +4.1781076667923185E-8d, - +5.326182134294869E-8d, - -1.1302647617762544E-8d, - +8.759667154796094E-8d, - +1.126326877851684E-7d, - +6.48979555673987E-8d, - -5.451390316294111E-8d, - -6.0896188500539086E-9d, - -2.7152010585461855E-8d, - -1.1660424775832058E-7d, - -3.492984900939992E-8d, - -1.944841848873016E-8d, - -6.905990750285027E-8d, - +5.575538653428039E-8d, - +1.1768108384670781E-7d, - +1.178204606523101E-7d, - +5.727787111340131E-8d, - -6.284125161007433E-8d, - -3.0118152047565877E-9d, - -5.448044533034374E-10d, - -5.433154287341921E-8d, - +7.515630833946181E-8d, - -8.780756503572527E-8d, - -6.527407547535494E-8d, - -9.45487863616303E-8d, - +6.390098458668406E-8d, - -6.564672913105876E-8d, - -5.238488022920792E-9d, - +7.824500749252316E-9d, - -2.5339299158309795E-8d, - -1.036103313062145E-7d, - +1.2550633697348567E-8d, - +8.584676196065558E-8d, - +1.1740089468291563E-7d, - +1.0833697012353316E-7d, - +5.978002467397905E-8d, - -2.7143806069290897E-8d, - +8.711129287069315E-8d, - -7.316349947981893E-8d, - -3.00015852582934E-8d, - -2.0691000399732483E-8d, - -4.4100097152254264E-8d, - -9.909612209943178E-8d, - +5.38733640215475E-8d, - -6.0893829005035E-8d, - +3.457553391989844E-8d, - +1.0300006058273187E-7d, - -9.290053015365092E-8d, - -7.514966995961323E-8d, - -8.10254145615142E-8d, - -1.0938612624777085E-7d, - +7.932952721989251E-8d, - +9.428257290008738E-9d, - -7.952636967837795E-8d, - +5.203033137154554E-8d, - -7.159157201731446E-8d, - +2.7593424989059015E-8d, - +1.1231621190000476E-7d, - -5.469119869891027E-8d, - +4.560067256086347E-9d, - +5.280427179595944E-8d, - +9.119538242455128E-8d, - -1.1753008498403413E-7d, - -9.537874867759656E-8d, - -7.96118345325538E-8d, - -6.907085854395348E-8d, - -6.259620482221904E-8d, - -5.902712448725381E-8d, - -5.720173456146447E-8d, - -5.5957016861703E-8d, - -5.412881689012608E-8d, - -5.0551842723970724E-8d, - -4.405966390424518E-8d, - -3.348471032333413E-8d, - -1.7658271111516935E-8d, - +4.589506477601956E-9d, - +3.4429618182751655E-8d, - +7.303420385174346E-8d, - -1.168420305422519E-7d, - -5.718749537552229E-8d, - +1.4754809136835937E-8d, - +1.001616104682875E-7d, - -3.8207793300052055E-8d, - +7.766278405014509E-8d, - -2.7883635712109803E-8d, - -1.1524714043067699E-7d, - +5.517333625963128E-8d, - +7.724278756071081E-9d, - -1.7990934773848504E-8d, - -2.0786347668702902E-8d, - +5.251554594269693E-10d, - +4.7131849857076246E-8d, - -1.1819540733893871E-7d, - -1.742885956093543E-8d, - +1.1220467571570283E-7d, - +3.347954541376715E-8d, - -1.399157980498908E-8d, - -2.9013441705763093E-8d, - -1.0389614239253089E-8d, - +4.307749759934266E-8d, - -1.0583192018912101E-7d, - +2.0919226941745448E-8d, - -5.2305110482722706E-8d, - -8.588407110184028E-8d, - -7.861419797923639E-8d, - -2.929085835358592E-8d, - +6.329175751021792E-8d, - -3.807794163054899E-8d, - -9.377320954068088E-8d, - -1.0258469865953145E-7d, - -6.330187984612758E-8d, - +2.5286958775281306E-8d, - -7.40238661307607E-8d, - +1.1681688445204168E-7d, - -1.1623125976292733E-7d, - -5.6696107089038004E-8d, - +5.822140627806124E-8d, - -8.678466172071259E-9d, - -1.7757121899175995E-8d, - +3.220665454652531E-8d, - -9.598330731102836E-8d, - +7.573375369829243E-8d, - +7.174547784678893E-8d, - -1.0672213971363184E-7d, - +1.8395252217743006E-8d, - -2.8511112548600118E-8d, - -7.79306270997787E-9d, - +8.178019529487065E-8d, - +3.0220784595602374E-9d, - -4.4156343103298585E-9d, - +6.07014616741277E-8d, - -3.8809601937571554E-8d, - -6.329342805230603E-8d, - -1.1511990258493999E-8d, - +1.177739474561431E-7d, - +8.738625278484571E-8d, - -1.0143341551207646E-7d, - +2.9394972678456236E-8d, - +4.278345398213486E-9d, - +6.28805835150457E-8d, - -3.197037359731606E-8d, - -4.060821046423735E-8d, - +3.82160283750664E-8d, - -3.2666060441373307E-8d, - -1.3584500601329896E-8d, - +9.671332777035621E-8d, - +6.10626893063691E-8d, - +1.1913723189736356E-7d, - +3.3774671482641995E-8d, - +4.4651109654500895E-8d, - -8.539328154875224E-8d, - -1.166799420361101E-7d, - -4.794765976694151E-8d, - -1.1635256954820579E-7d, - -8.221241452580445E-8d, - +5.5737717715868425E-8d, - +6.034539636024073E-8d, - -6.712199323081945E-8d, - -8.697724830833087E-8d, - +2.0494942705297694E-9d, - -3.718924074653624E-8d, - +3.499747150995707E-8d, - -1.8535359161566028E-8d, - +4.1905679587096103E-8d, - -2.0821912536551675E-8d, - +3.297776915751238E-8d, - -3.3835280846270374E-8d, - +1.8437339356553904E-8d, - -4.734187609526424E-8d, - +8.527976799299225E-9d, - -5.1088103279787804E-8d, - +1.3513294656751725E-8d, - -3.480032127343472E-8d, - +4.367697180842916E-8d, - +1.1815196363705356E-8d, - +1.0932279207149782E-7d, - +9.907230065250944E-8d, - -1.764389559496152E-8d, - -1.1135725625095859E-9d, - -8.846040040259342E-8d, - -3.996962588736431E-8d, - -9.276238757878814E-8d, - -7.12139818505956E-9d, - -2.016525972830718E-8d, - +1.0782585410141121E-7d, - -9.868269632073771E-8d, - +7.686861750031585E-8d, - -7.947087669425045E-8d, - -8.955768055535647E-8d, - +4.791582240886607E-8d, - +9.583994718167641E-8d, - +5.5524866689108584E-8d, - -7.171796605211277E-8d, - -4.6157237582310713E-8d, - -1.0489751005162237E-7d, - -8.204903560604627E-9d, - +6.818588687884566E-9d, - -5.850916105103205E-8d, - +3.5549586192569994E-8d, - +5.1896700056778354E-8d, - -8.146080588190463E-9d, - +9.516285362051742E-8d, - -1.1368933260611668E-7d, - +8.187871486648885E-8d, - -3.206182925646474E-8d, - +2.265440168347286E-8d, - +8.938334752179552E-9d, - -7.187922490287331E-8d, - +1.9952407216533937E-8d, - +4.734805892507655E-8d, - +1.1642439930208906E-8d, - -8.582843599651953E-8d, - -5.3086706437795354E-9d, - +1.6121782610217253E-8d, - -2.0197142620980974E-8d, - -1.129242035557684E-7d, - -2.2298267863810133E-8d, - +1.4605950309628873E-8d, - -8.663710700190489E-10d, - -6.736873974532501E-8d, - +5.486523121881414E-8d, - -1.0965249168570443E-7d, - -8.27343074126263E-8d, - -1.0144703278439455E-7d, - +7.39809943048038E-8d, - -3.193297932837415E-8d, - +5.900393284617182E-8d, - +1.0973020465397083E-7d, - -1.1681436418514489E-7d, - +9.5985669644661E-8d, - +3.423560333632085E-8d, - -6.22836197265283E-8d, - +4.621027492345726E-8d, - -1.1575484316683829E-7d, - -6.997545435826076E-8d, - -5.3502441327259514E-8d, - -6.49667713553005E-8d, - -1.029980741248172E-7d, - +7.219393868923887E-8d, - -1.4854841678687828E-8d, - +1.1406713393562271E-7d, - -1.650155887561251E-8d, - +7.165331603232264E-8d, - -9.692697614257269E-8d, - -4.402550702194912E-8d, - -6.679737442193143E-9d, - +1.6492800268960003E-8d, - +2.68759245092879E-8d, - +2.5854805721793077E-8d, - +1.4815967715704613E-8d, - -4.852711011229633E-9d, - -3.176199594915881E-8d, - -6.452129525125173E-8d, - -1.01738658407525E-7d, - +9.639780418418697E-8d, - +5.4445606140746644E-8d, - +1.2219361033150988E-8d, - -2.8883532688356087E-8d, - -6.746431126005811E-8d, - -1.0212284427080097E-7d, - +1.0696094577483825E-7d, - +8.43527683868743E-8d, - +6.987544103716777E-8d, - +6.493457409236137E-8d, - +7.093715125593688E-8d, - +8.929153091001965E-8d, - -1.1701113164306871E-7d, - -6.972256643013266E-8d, - -5.848862070736576E-9d, - +7.602385197610123E-8d, - -6.110775144284437E-8d, - +6.101012058093429E-8d, - -3.304167134225169E-8d, - -1.0342514383702196E-7d, - +8.969907328603505E-8d, - +7.091600108064668E-8d, - +8.006778743052707E-8d, - +1.1857939200074815E-7d, - -5.0541412403312774E-8d, - +5.0970277930552287E-8d, - -5.229355472795119E-8d, - +1.1793478462381443E-7d, - +8.625007227318527E-8d, - +9.250422086873268E-8d, - -1.0028661472061573E-7d, - -1.384914052949463E-8d, - +1.1483560326413004E-7d, - +4.878798101459259E-8d, - +2.7866921183936055E-8d, - +5.3514180410849046E-8d, - -1.1124565511436785E-7d, - +1.186914813275767E-8d, - -5.253258132241335E-8d, - -6.458486486369316E-8d, - -2.2838888809969377E-8d, - +7.415557606805398E-8d, - -1.0568403170659571E-8d, - -3.7139182948393606E-8d, - -4.1022790876160215E-9d, - +8.999821367768787E-8d, - +8.201043988912348E-9d, - -9.616457442665051E-9d, - +3.8005886250603055E-8d, - -8.588890051473289E-8d, - +9.699937202692456E-8d, - +1.11298006674538E-7d, - -4.1527104733570825E-8d, - +1.1682852007826251E-7d, - +1.1099648061301941E-7d, - -5.755303038890997E-8d, - +8.948877445235827E-8d, - +7.675780395028194E-8d, - -9.427143563390596E-8d, - +5.471416081500162E-8d, - +4.8354824064383506E-8d, - -1.118706134478866E-7d, - +5.235528379688445E-8d, - +6.567708120053687E-8d, - -7.042204992948526E-8d, - -1.1603891006723397E-7d, - -6.968742825553785E-8d, - +7.01199184127881E-8d, - +6.645352711199266E-8d, - -7.919617109348822E-8d, - +1.1149986927391714E-7d, - -7.522074418324674E-8d, - +7.739252980388984E-8d, - +9.39987974788905E-8d, - -2.390421480210064E-8d, - -3.639873824357815E-8d, - +5.8015881615938497E-8d, - +2.2423186335040668E-8d, - +9.674534330665206E-8d, - +4.4068830785712375E-8d, - +1.0431875573076199E-7d, - +4.0584538834428926E-8d, - +9.279423236781974E-8d, - +2.404020521381534E-8d, - +7.425346071427343E-8d, - +6.529321706138789E-9d, - +6.080174837146273E-8d, - +1.6902327633329284E-10d, - +6.456806922371733E-8d, - +1.7100134295216033E-8d, - +9.770510970673519E-8d, - +6.94872148530716E-8d, - -6.602926393514549E-8d, - -6.889997193778161E-8d, - +6.240235720677117E-8d, - +9.098790295810902E-8d, - +1.8386917534879182E-8d, - +8.454972737414241E-8d, - +5.259099728747365E-8d, - -7.595453077213505E-8d, - -6.113203624663034E-8d, - +9.859622328905143E-8d, - -7.206766550807255E-8d, - -9.474579567171831E-8d, - +3.210408693366267E-8d, - +7.160716418525417E-8d, - +2.530870537724554E-8d, - -1.0524451040704701E-7d, - -8.008561371849434E-8d, - +1.0233519853128553E-7d, - -3.326791455362767E-8d, - -8.504961764629757E-9d, - -6.024017201863256E-8d, - +5.1500902632092514E-8d, - +8.98570720774568E-8d, - +5.638724693948384E-8d, - -4.734813904255994E-8d, - +1.8631451577542948E-8d, - +1.7470924137873214E-8d, - -4.926470933588261E-8d, - +5.84096713620797E-8d, - +1.0364355880696472E-7d, - +8.800655674349468E-8d, - +1.3069802481237792E-8d, - +1.1882454749452428E-7d, - -6.999215748398631E-8d, - -7.49674072510849E-8d, - +1.054760847603618E-7d, - -3.920012014371067E-9d, - +7.526183084319617E-8d, - +1.0618494853096868E-7d, - +9.043280094115832E-8d, - +2.9590395068826316E-8d, - -7.475571347653619E-8d, - +1.7401160143611842E-8d, - +6.923209420670962E-8d, - +8.232829924979753E-8d, - +5.82825404854514E-8d, - -1.3108606792380822E-9d, - -9.485602512220194E-8d, - +1.7663064617118723E-8d, - +9.942682855652123E-8d, - -8.638275100090915E-8d, - -6.132639063569726E-8d, - -6.221897889344726E-8d, - -8.745525834919404E-8d, - +1.029901759234897E-7d, - +3.3888561478632076E-8d, - -5.47315553588771E-8d, - +7.715994473741065E-8d, - -4.566098167230033E-8d, - +5.5257514455273825E-8d, - -9.530545662611411E-8d, - -1.889488909834863E-8d, - +4.769006625301079E-8d, - +1.0607041998938709E-7d, - -8.054981263802322E-8d, - -3.370929373457322E-8d, - +9.799164177397836E-9d, - +5.160291611526656E-8d, - +9.333090708652975E-8d, - -1.0180490545927503E-7d, - -5.533523366931846E-8d, - -4.044932340334176E-9d, - +5.370131904567218E-8d, - -1.1887814032213867E-7d, - -4.3307634616102625E-8d, - +4.363437558318513E-8d, - -9.482896784430338E-8d, - +1.9782818312325887E-8d, - -8.77224935488516E-8d, - +6.113879253864931E-8d, - -8.822335132515693E-9d, - -5.753754066078771E-8d, - -8.335545536862392E-8d, - -8.462309712606694E-8d, - -5.968586877433824E-8d, - -6.887556547891059E-9d, - +7.542967150507818E-8d, - -4.949331199790077E-8d, - +9.684172421525468E-8d, - +3.9260317944365246E-8d, - +1.784536881359796E-8d, - +3.426282345243592E-8d, - +9.018025618601154E-8d, - -5.1151708476133135E-8d, - +8.877492215808044E-8d, - +3.479545684576179E-8d, - +2.7002575714977818E-8d, - +6.707201545505014E-8d, - -8.173742908533777E-8d, - +5.909041310777802E-8d, - +1.439903710393587E-8d, - +2.4289317341982113E-8d, - +9.044519282818302E-8d, - -2.3866331257845713E-8d, - -7.853944465095286E-8d, - -7.188526769607005E-8d, - -2.2132706360079843E-9d, - -1.0624985110080394E-7d, - +9.453598391231829E-8d, - -1.134160131581847E-7d, - -1.315295870404327E-8d, - -7.981320644583728E-8d, - -7.327771300038971E-8d, - +8.155647334672472E-9d, - -7.222791579580787E-8d, - -7.430436987497092E-8d, - +3.633404807819848E-9d, - -7.512438321498593E-8d, - -7.044869765481105E-8d, - +1.9372589859580955E-8d, - -4.2365298585101096E-8d, - -1.552830824758035E-8d, - +1.0160071259930585E-7d, - +7.232201430620959E-8d, - -1.0164389431039905E-7d, - +5.826233477413577E-8d, - +7.6927415825689E-8d, - -4.392309439525734E-8d, - -6.414337408955734E-8d, - +1.799550702470095E-8d, - -3.4194410638967946E-8d, - +1.9437762419688045E-8d, - -5.7792549966531335E-8d, - -2.5731071572354522E-8d, - +1.173595905705643E-7d, - -1.0361863127101014E-7d, - +2.8330789837569332E-8d, - +3.81131861433539E-8d, - -7.252724942149532E-8d, - -6.342604067787756E-8d, - +6.716441526213986E-8d, - +8.257484966196574E-8d, - -1.5443717968117592E-8d, - +1.3280021798948244E-8d, - -6.79180673261558E-8d, - -1.8863249269709046E-8d, - -7.62162303263991E-8d, - +2.011589233663723E-10d, - -2.62683511147141E-8d, - +8.455684903712996E-8d, - +9.602293320384794E-8d, - +9.896378545255258E-9d, - +6.636396724067746E-8d, - +2.8777050870552646E-8d, - -1.0109271059094341E-7d, - -8.305334708631055E-8d, - +8.467026501338835E-8d, - -7.29821745001452E-8d, - -7.739491336852633E-8d, - +7.321238022013781E-8d, - -9.621538067089515E-8d, - -1.0705722541811197E-7d, - +4.247240125405735E-8d, - +1.1574222007764044E-7d, - +1.145412771487496E-7d, - +4.066036653218687E-8d, - -1.0410796803072171E-7d, - -7.955085231106037E-8d, - +1.1612776191572459E-7d, - +7.888519481107568E-9d, - +7.436813814737735E-8d, - +7.894935661289349E-8d, - +2.343525263620692E-8d, - -9.036933434595339E-8d, - -2.2239222395888823E-8d, - -8.784622656707742E-9d, - -4.819540032304379E-8d, - +9.975892708522332E-8d, - -3.9945124955316294E-8d, - +1.1345047468988893E-8d, - +1.702808472925844E-8d, - -2.10770182066344E-8d, - -1.0114948914089626E-7d, - +1.70518021921727E-8d, - +9.693260855961159E-8d, - -9.809953482725758E-8d, - -8.937957126662392E-8d, - -1.134963954323427E-7d, - +6.980004387880031E-8d, - -1.4494150014095534E-8d, - +1.122932337832262E-7d, - -2.483811732227808E-8d, - +5.278759515330048E-8d, - +1.0859222881334994E-7d, - -9.400056055939758E-8d, - -7.630957994128623E-8d, - -7.490757191850264E-8d, - -8.794689652049879E-8d, - -1.1357810855950775E-7d, - +8.846862323478745E-8d, - +4.32092015744956E-8d, - -9.082923009890997E-9d, - -6.655106680680314E-8d, - +1.1108184705020206E-7d, - +4.8838973948592766E-8d, - -1.2998975819628988E-8d, - -7.25680516883106E-8d, - -1.280024819379844E-7d, - -1.7743467191652895E-7d, - -2.1899520225809197E-7d, - +2.2602433110285232E-7d, - +2.0582268590356215E-7d, - +1.9911192455808124E-7d, - +2.0776878313278689E-7d, - +2.3367183133931002E-7d, - -1.9813568387704588E-7d, - -1.320972037315105E-7d, - -4.316580502355056E-8d, - +7.054443447243064E-8d, - +2.109212796025238E-7d, - -9.698281856949837E-8d, - +1.0239791185239086E-7d, - -1.4271754202157014E-7d, - +1.232402895636637E-7d, - -5.150590480969644E-8d, - -1.882201085012735E-7d, - +1.918355503889933E-7d, - +1.368893262241355E-7d, - +1.256828068633383E-7d, - +1.601222826656464E-7d, - -2.3472125169205568E-7d, - -1.032634625827871E-7d, - +7.957037517331382E-8d, - -1.6114314525832115E-7d, - +1.3018591370778052E-7d, - +1.8007284821359149E-9d, - -6.75421764491544E-8d, - -7.592155950645605E-8d, - -2.1414301981236817E-8d, - +9.79045937979623E-8d, - -1.9287515190177685E-7d, - +6.184953843236509E-8d, - -8.966500602352001E-8d, - -1.686490951669855E-7d, - -1.7316830893872364E-7d, - -1.0128633727463388E-7d, - +4.8935021740786486E-8d, - -1.9740129448026905E-7d, - +1.1532102163380318E-7d, - +3.5371542244169364E-8d, - +4.153321337726989E-8d, - +1.3575372396796738E-7d, - -1.5685449228299222E-7d, - +1.1933437776279623E-7d, - +1.2599421120614435E-8d, - +1.7331079674066365E-9d, - +8.869266069401045E-8d, - -2.013999442282902E-7d, - +8.709065843311144E-8d, - +2.453117120472083E-9d, - +2.3489472779602617E-8d, - +1.5216652792122652E-7d, - -8.638415150333099E-8d, - -2.1335475961524608E-7d, - -2.2677272333821516E-7d, - -1.246635423141374E-7d, - +9.494921297991565E-8d, - -4.27932550865546E-8d, - -5.907349480138712E-8d, - +4.809072216941908E-8d, - -1.9615359732789476E-7d, - +1.6385396676990034E-7d, - +1.7642714221524228E-7d, - -1.564440844355254E-7d, - +1.2090653407564583E-7d, - +5.679855838941285E-8d, - +1.3006497185242537E-7d, - -1.341336085949317E-7d, - +2.1987686050231372E-7d, - -2.3641341460419062E-7d, - -7.048932272279454E-8d, - -2.3401958604540354E-7d, - +2.2867766559333004E-7d, - -1.1089952719756529E-7d, - +1.7977178878541792E-7d, - +1.4903074102418675E-7d, - -2.011072593789072E-7d, - +8.504948422097802E-8d, - +5.5846006716348844E-8d, - +1.9014079059505456E-7d, - +1.3119976852347583E-8d, - +3.645999732952202E-9d, - +1.6374611405314333E-7d, - +1.8612397134087598E-8d, - +4.7113225346448296E-8d, - -2.2555535676499395E-7d, - +1.5631615647329739E-7d, - -2.3574653182047758E-7d, - +3.08072210937242E-8d, - +4.344259288116142E-9d, - +1.6374489573868447E-7d, - +3.42171232580676E-8d, - +9.46452492584643E-8d, - -1.297587351085525E-7d, - -1.601065201853145E-7d, - +5.6550495386976275E-9d, - -1.0725602261510391E-7d, - -1.9945408945084193E-8d, - -2.071910882200156E-7d, - -1.900947109027913E-7d, - +3.34069282059055E-8d, - -1.145810806477298E-8d, - +1.5421457732308477E-7d, - +5.5657084775121975E-8d, - +1.7177785285061278E-7d, - +2.7813027425289027E-8d, - +1.0267509648109748E-7d, - -7.839574072711142E-8d, - -3.648293887796095E-8d, - +2.3049492079013518E-7d, - -2.290530257391564E-7d, - +1.747018414872141E-8d, - +1.8477759656842807E-8d, - -2.2394073401050633E-7d, - -2.3085653185818848E-7d, - -1.7598351175286083E-10d, - -6.640551220774385E-9d, - +2.2868466674913266E-7d, - +2.3106230530437902E-7d, - +2.594209135294356E-9d, - +2.2221434720602702E-8d, - -1.847872222755186E-7d, - -1.3948659218254467E-7d, - +1.6023339607737848E-7d, - -2.3718944120137026E-7d, - +1.0087056692827474E-7d, - +2.228553660510707E-7d, - +1.3088328582956644E-7d, - -1.7292527438195104E-7d, - -2.0961068531216087E-7d, - +2.2951597845188004E-8d, - +5.005103745740068E-8d, - -1.2618366811281002E-7d, - -2.6784582477238417E-8d, - -1.2645600379949252E-7d, - +5.3774170051560117E-8d, - +3.9205810725333715E-8d, - -1.6802196396307013E-7d, - -8.893078799284047E-8d, - -1.9821451970481713E-7d, - -1.689060694498032E-8d, - -1.9648717830943396E-8d, - -2.0433926409457167E-7d, - -9.1973399031975E-8d, - -1.5723449006087263E-7d, - +7.887051614592191E-8d, - +1.4166246290402286E-7d, - +3.330146018487787E-8d, - +2.3278688667580978E-7d, - -2.1139124097042925E-7d, - +1.334449995534113E-7d, - -1.6104730195920897E-7d, - -1.3902314592614197E-7d, - +2.0169027167169864E-7d, - -9.040643863751471E-8d, - -5.946190852360168E-8d, - -1.8013411720005014E-7d, - +2.6595401669835947E-8d, - +8.607292924069425E-8d, - +4.84038176769263E-10d, - -2.2798356346688802E-7d, - -1.203028719549339E-7d, - -1.5111906039270745E-7d, - +1.5859915617670956E-7d, - -1.426262681506497E-7d, - -9.892260062323546E-8d, - -1.8492643515928268E-7d, - +7.840210076743552E-8d, - +2.1643071541578027E-7d, - +2.313664294893465E-7d, - +1.2541842003811723E-7d, - -9.920197743470107E-8d, - +3.655589133934081E-8d, - +5.807052689551411E-8d, - -3.244024724169575E-8d, - -2.327564406466327E-7d, - -6.38187356721971E-8d, - -2.3995994000400915E-10d, - -3.9793609609721186E-8d, - -1.802510054588344E-7d, - +5.745586744591196E-8d, - +1.987228872666507E-7d, - -2.3105188606976847E-7d, - +2.0088042407239129E-7d, - +6.624793114025702E-8d, - -1.5587043044056635E-7d, - +1.3606464059428694E-8d, - +1.0008761540741556E-7d, - +1.058213771597129E-7d, - +3.3058299602856804E-8d, - -1.1594886810010702E-7d, - +1.378919824418909E-7d, - -1.5683631181406778E-7d, - -4.4200075770425176E-8d, - +1.2250985436706623E-9d, - -1.8297013058336644E-8d, - -1.005004229646318E-7d, - +2.337202285991116E-7d, - +3.296104292035678E-8d, - -2.23668185816307E-7d, - -5.7055442971184756E-8d, - +5.82391923137467E-8d, - +1.244950238958056E-7d, - +1.4399358260219398E-7d, - +1.1901862840583523E-7d, - +5.1856152603337505E-8d, - -5.520562000491495E-8d, - -1.9987622893254038E-7d, - +9.697418238031897E-8d, - -1.1603376405901542E-7d, - +1.170714288147407E-7d, - -1.550851303094034E-7d, - +2.3472546699189522E-8d, - +1.78211222185955E-7d, - -1.6540009048230807E-7d, - -5.137865010872577E-8d, - +4.57490653163866E-8d, - +1.2829599363166098E-7d, - +1.985773325073412E-7d, - -2.1792661654989742E-7d, - -1.652218131743459E-7d, - -1.178234251477505E-7d, - -7.34071933723896E-8d, - -2.9646587857612632E-8d, - +1.5787194498912167E-8d, - +6.52252321321176E-8d, - +1.2100088103262734E-7d, - +1.8544977697201776E-7d, - -2.159273204728711E-7d, - -1.2711589287782304E-7d, - -2.2610609958205195E-8d, - +9.993330547750349E-8d, - -2.33974236642384E-7d, - -6.830955860192377E-8d, - +1.2244183812423448E-7d, - -1.3620325027706252E-7d, - +1.1178574689680927E-7d, - -8.490693031052439E-8d, - +2.2975389535985893E-7d, - +1.0445707500867073E-7d, - +1.8405243253979117E-8d, - -2.6033812325397097E-8d, - -2.6489990728664908E-8d, - +1.9409124727247465E-8d, - +1.1403826867020365E-7d, - -2.1706266226554237E-7d, - -1.7839974359909697E-8d, - +2.3725087624341041E-7d, - +7.37567604176979E-8d, - -2.9098805266958403E-8d, - -6.892713087722722E-8d, - -4.333719263537725E-8d, - +5.006436936098099E-8d, - +2.1367325342138113E-7d, - -2.6949659655907758E-8d, - -1.9256682968755803E-7d, - +1.960616287777496E-7d, - +1.876664741413704E-7d, - -2.1534486893602122E-7d, - -5.688830723853217E-8d, - +1.8861113228746644E-7d, - +4.6730779443102234E-8d, - -3.275360514112964E-9d, - +4.1011920825226876E-8d, - +1.820141955326842E-7d, - -5.468175655175594E-8d, - -1.8981247089866317E-7d, - -2.209492705846306E-7d, - -1.4566110577298295E-7d, - +3.848544860465368E-8d, - -1.429109630340783E-7d, - -2.105749999899302E-7d, - -1.6206609756618993E-7d, - +5.058693461947143E-9d, - -1.8359244902596882E-7d, - +2.2810251664891242E-7d, - -1.8791776732592608E-7d, - +1.3106843166204263E-9d, - -1.5543153797220025E-7d, - -1.7884997059081524E-7d, - -6.648490725635754E-8d, - +1.8412576154421806E-7d, - +9.860939269906055E-8d, - +1.5627006743114285E-7d, - -1.17260039161597E-7d, - +2.3416513526430908E-7d, - -2.1749172296989992E-7d, - -3.9242560971295217E-8d, - -1.822826971477839E-7d, - -1.6729355321895212E-7d, - +8.208715337901827E-9d, - -1.301267783434537E-7d, - -1.029741755377153E-7d, - +9.215765583599035E-8d, - -1.907487641016455E-8d, - +4.2661388254716074E-8d, - -1.9697226735187428E-7d, - +2.1819935527247946E-7d, - -1.398318929248588E-7d, - +1.6195123407015624E-7d, - +1.723826394935661E-7d, - -1.0602700638269148E-7d, - -1.9392742205954563E-7d, - -8.880302882034106E-8d, - +2.1186420987133E-7d, - +2.3375763256988976E-7d, - -2.0599801342241997E-8d, - -7.184550924856607E-8d, - +8.254840070367875E-8d, - }; - - /** Extended precision logarithm table over the range 1 - 2 in increments of 2^-10. */ - private static final double[][] LN_MANT = new double[][] { - {+0.0d, +0.0d, }, // 0 - {+9.760860120877624E-4d, -3.903230345984362E-11d, }, // 1 - {+0.0019512202125042677d, -8.124251825289188E-11d, }, // 2 - {+0.0029254043474793434d, -1.8374207360194882E-11d,}, // 3 - {+0.0038986406289041042d, -2.1324678121885073E-10d,}, // 4 - {+0.004870930686593056d, -4.5199654318611534E-10d,}, // 5 - {+0.00584227591753006d, -2.933016992001806E-10d, }, // 6 - {+0.006812678650021553d, -2.325147219074669E-10d, }, // 7 - {+0.007782140746712685d, -3.046577356838847E-10d, }, // 8 - {+0.008750664070248604d, -5.500631513861575E-10d, }, // 9 - {+0.00971824862062931d, +8.48292035519895E-10d, }, // 10 - {+0.010684899985790253d, +1.1422610134013436E-10d,}, // 11 - {+0.01165061630308628d, +9.168889933128375E-10d, }, // 12 - {+0.012615403160452843d, -5.303786078838E-10d, }, // 13 - {+0.013579258695244789d, -5.688639355498786E-10d, }, // 14 - {+0.01454218477010727d, +7.296670293275653E-10d, }, // 15 - {+0.015504186972975731d, -4.370104767451421E-10d, }, // 16 - {+0.016465261578559875d, +1.43695591408832E-9d, }, // 17 - {+0.01742541790008545d, -1.1862263158849434E-9d, }, // 18 - {+0.018384650349617004d, -9.482976524690715E-10d, }, // 19 - {+0.01934296265244484d, +1.9068609515836638E-10d,}, // 20 - {+0.020300358533859253d, +2.655990315697216E-10d, }, // 21 - {+0.021256837993860245d, +1.0315548713040775E-9d, }, // 22 - {+0.022212404757738113d, +5.13345647019085E-10d, }, // 23 - {+0.02316705882549286d, +4.5604151934208014E-10d,}, // 24 - {+0.02412080392241478d, -1.1255706987475148E-9d, }, // 25 - {+0.025073636323213577d, +1.2289023836765196E-9d, }, // 26 - {+0.02602556347846985d, +1.7990281828096504E-9d, }, // 27 - {+0.026976589113473892d, -1.4152718164638451E-9d, }, // 28 - {+0.02792670577764511d, +7.568772963781632E-10d, }, // 29 - {+0.0288759246468544d, -1.1449998592111558E-9d, }, // 30 - {+0.029824241995811462d, -1.6850976862319495E-9d, }, // 31 - {+0.030771657824516296d, +8.422373919843096E-10d, }, // 32 - {+0.0317181795835495d, +6.872350402175489E-10d, }, // 33 - {+0.03266380727291107d, -4.541194749189272E-10d, }, // 34 - {+0.03360854089260101d, -8.9064764856495E-10d, }, // 35 - {+0.034552380442619324d, +1.0640404096769032E-9d, }, // 36 - {+0.0354953333735466d, -3.5901655945224663E-10d,}, // 37 - {+0.03643739968538284d, -3.4829517943661266E-9d, }, // 38 - {+0.037378571927547455d, +8.149473794244232E-10d, }, // 39 - {+0.03831886500120163d, -6.990650304449166E-10d, }, // 40 - {+0.03925827145576477d, +1.0883076226453258E-9d, }, // 41 - {+0.040196798741817474d, +3.845192807999274E-10d, }, // 42 - {+0.04113444685935974d, -1.1570594692045927E-9d, }, // 43 - {+0.04207121580839157d, -1.8877045166697178E-9d, }, // 44 - {+0.043007105588912964d, -1.6332083257987747E-10d,}, // 45 - {+0.04394212365150452d, -1.7950057534514933E-9d, }, // 46 - {+0.04487626254558563d, +2.302710041648838E-9d, }, // 47 - {+0.045809537172317505d, -1.1410233017161343E-9d, }, // 48 - {+0.04674194008111954d, -3.0498741599744685E-9d, }, // 49 - {+0.04767347127199173d, -1.8026348269183678E-9d, }, // 50 - {+0.04860413819551468d, -3.233204600453039E-9d, }, // 51 - {+0.04953393340110779d, +1.7211688427961583E-9d, }, // 52 - {+0.05046287178993225d, -2.329967807055457E-10d, }, // 53 - {+0.05139094591140747d, -4.191810118556531E-11d, }, // 54 - {+0.052318163216114044d, -3.5574324788328143E-9d, }, // 55 - {+0.053244516253471375d, -1.7346590916458485E-9d, }, // 56 - {+0.05417001247406006d, -4.343048751383674E-10d, }, // 57 - {+0.055094651877880096d, +1.92909364037955E-9d, }, // 58 - {+0.056018441915512085d, -5.139745677199588E-10d, }, // 59 - {+0.05694137513637543d, +1.2637629975129189E-9d, }, // 60 - {+0.05786345899105072d, +1.3840561112481119E-9d, }, // 61 - {+0.058784693479537964d, +1.414889689612056E-9d, }, // 62 - {+0.05970507860183716d, +2.9199191907666474E-9d, }, // 63 - {+0.0606246218085289d, +7.90594243412116E-12d, }, // 64 - {+0.06154331564903259d, +1.6844747839686189E-9d, }, // 65 - {+0.06246116757392883d, +2.0498074572151747E-9d, }, // 66 - {+0.06337818503379822d, -4.800180493433863E-9d, }, // 67 - {+0.06429435312747955d, -2.4220822960064277E-9d, }, // 68 - {+0.06520968675613403d, -4.179048566709334E-9d, }, // 69 - {+0.06612417101860046d, +6.363872957010456E-9d, }, // 70 - {+0.06703783571720123d, +9.339468680056365E-10d, }, // 71 - {+0.06795066595077515d, -4.04226739708981E-9d, }, // 72 - {+0.0688626617193222d, -7.043545052852817E-9d, }, // 73 - {+0.06977382302284241d, -6.552819560439773E-9d, }, // 74 - {+0.07068414986133575d, -1.0571674860370546E-9d, }, // 75 - {+0.07159365713596344d, -3.948954622015801E-9d, }, // 76 - {+0.07250232994556427d, +1.1776625988228244E-9d, }, // 77 - {+0.07341018319129944d, +9.221072639606492E-10d, }, // 78 - {+0.07431721687316895d, -3.219119568928366E-9d, }, // 79 - {+0.0752234160900116d, +5.147575929018918E-9d, }, // 80 - {+0.07612881064414978d, -2.291749683541979E-9d, }, // 81 - {+0.07703337073326111d, +5.749565906124772E-9d, }, // 82 - {+0.07793712615966797d, +9.495158151301779E-10d, }, // 83 - {+0.07884006202220917d, -3.144331429489291E-10d, }, // 84 - {+0.0797421783208847d, +3.430029236134205E-9d, }, // 85 - {+0.08064348995685577d, -1.2499290483167703E-9d, }, // 86 - {+0.08154398202896118d, +2.011215719133196E-9d, }, // 87 - {+0.08244366943836212d, -2.2728753031387152E-10d,}, // 88 - {+0.0833425521850586d, -6.508966857277253E-9d, }, // 89 - {+0.0842406153678894d, -4.801131671405377E-10d, }, // 90 - {+0.08513787388801575d, +4.406750291994231E-9d, }, // 91 - {+0.08603434264659882d, -5.304795662536171E-9d, }, // 92 - {+0.08692999184131622d, +1.6284313912612293E-9d, }, // 93 - {+0.08782485127449036d, -3.158898981674071E-9d, }, // 94 - {+0.08871890604496002d, -3.3324878834139977E-9d, }, // 95 - {+0.08961215615272522d, +2.536961912893389E-9d, }, // 96 - {+0.09050461649894714d, +9.737596728980696E-10d, }, // 97 - {+0.0913962870836258d, -6.600437262505396E-9d, }, // 98 - {+0.09228715300559998d, -3.866609889222889E-9d, }, // 99 - {+0.09317722916603088d, -4.311847594020281E-9d, }, // 100 - {+0.09406651556491852d, -6.525851105645959E-9d, }, // 101 - {+0.09495499730110168d, +5.799080912675435E-9d, }, // 102 - {+0.09584270417690277d, +4.2634204358490415E-9d, }, // 103 - {+0.09672962129116058d, +5.167390528799477E-9d, }, // 104 - {+0.09761576354503632d, -4.994827392841906E-9d, }, // 105 - {+0.09850110113620758d, +4.970725577861395E-9d, }, // 106 - {+0.09938566386699677d, +6.6496705953229645E-9d, }, // 107 - {+0.10026945173740387d, +1.4262712796792241E-9d, }, // 108 - {+0.1011524498462677d, +5.5822855204629114E-9d, }, // 109 - {+0.10203467309474945d, +5.593494835247651E-9d, }, // 110 - {+0.10291612148284912d, +2.8332008343480686E-9d, }, // 111 - {+0.10379679501056671d, -1.3289231465997192E-9d, }, // 112 - {+0.10467669367790222d, -5.526819276639527E-9d, }, // 113 - {+0.10555580258369446d, +6.503128678219282E-9d, }, // 114 - {+0.10643415153026581d, +6.317463237641817E-9d, }, // 115 - {+0.10731174051761627d, -4.728528221305482E-9d, }, // 116 - {+0.10818853974342346d, +4.519199083083901E-9d, }, // 117 - {+0.10906457901000977d, +5.606492666349878E-9d, }, // 118 - {+0.10993985831737518d, -1.220176214398581E-10d, }, // 119 - {+0.11081436276435852d, +3.5759315936869937E-9d, }, // 120 - {+0.11168810725212097d, +3.1367659571899855E-9d, }, // 121 - {+0.11256109178066254d, -1.0543075713098835E-10d,}, // 122 - {+0.11343331634998322d, -4.820065619207094E-9d, }, // 123 - {+0.11430476605892181d, +5.221136819669415E-9d, }, // 124 - {+0.11517547070980072d, +1.5395018670011342E-9d, }, // 125 - {+0.11604541540145874d, +3.5638391501880846E-10d,}, // 126 - {+0.11691460013389587d, +2.9885336757136527E-9d, }, // 127 - {+0.11778303980827332d, -4.151889860890893E-9d, }, // 128 - {+0.11865071952342987d, -4.853823938804204E-9d, }, // 129 - {+0.11951763927936554d, +2.189226237170704E-9d, }, // 130 - {+0.12038381397724152d, +3.3791993048776982E-9d, }, // 131 - {+0.1212492436170578d, +1.5811884868243975E-11d,}, // 132 - {+0.12211392819881439d, -6.6045909118908625E-9d, }, // 133 - {+0.1229778528213501d, -2.8786263916116364E-10d,}, // 134 - {+0.12384103238582611d, +5.354472503748251E-9d, }, // 135 - {+0.12470348179340363d, -3.2924463896248744E-9d, }, // 136 - {+0.12556517124176025d, +4.856678149580005E-9d, }, // 137 - {+0.12642613053321838d, +1.2791850600366742E-9d, }, // 138 - {+0.12728634476661682d, +2.1525945093362843E-9d, }, // 139 - {+0.12814581394195557d, +8.749974471767862E-9d, }, // 140 - {+0.129004567861557d, -7.461209161105275E-9d, }, // 141 - {+0.12986254692077637d, +1.4390208226263824E-8d, }, // 142 - {+0.1307198405265808d, -1.3839477920475328E-8d, }, // 143 - {+0.13157635927200317d, -1.483283901239408E-9d, }, // 144 - {+0.13243216276168823d, -6.889072914229094E-9d, }, // 145 - {+0.1332872211933136d, +9.990351100568362E-10d, }, // 146 - {+0.13414156436920166d, -6.370937412495338E-9d, }, // 147 - {+0.13499516248703003d, +2.05047480130511E-9d, }, // 148 - {+0.1358480453491211d, -2.29509872547079E-9d, }, // 149 - {+0.13670018315315247d, +1.16354361977249E-8d, }, // 150 - {+0.13755163550376892d, -1.452496267904829E-8d, }, // 151 - {+0.1384023129940033d, +9.865115839786888E-9d, }, // 152 - {+0.13925230503082275d, -3.369999130712228E-9d, }, // 153 - {+0.14010155200958252d, +6.602496401651853E-9d, }, // 154 - {+0.14095008373260498d, +1.1205312852298845E-8d, }, // 155 - {+0.14179790019989014d, +1.1660367213160203E-8d, }, // 156 - {+0.142645001411438d, +9.186471222585239E-9d, }, // 157 - {+0.14349138736724854d, +4.999341878263704E-9d, }, // 158 - {+0.14433705806732178d, +3.11611905696257E-10d, }, // 159 - {+0.14518201351165771d, -3.6671598175618173E-9d, }, // 160 - {+0.14602625370025635d, -5.730477881659618E-9d, }, // 161 - {+0.14686977863311768d, -4.674900007989718E-9d, }, // 162 - {+0.1477125883102417d, +6.999732437141968E-10d, }, // 163 - {+0.14855468273162842d, +1.159150872494107E-8d, }, // 164 - {+0.14939609169960022d, -6.082714828488485E-10d, }, // 165 - {+0.15023678541183472d, -4.905712741596318E-9d, }, // 166 - {+0.1510767638683319d, -1.124848988733307E-10d, }, // 167 - {+0.15191605687141418d, -1.484557220949851E-8d, }, // 168 - {+0.15275460481643677d, +1.1682026251371384E-8d, }, // 169 - {+0.15359249711036682d, -8.757272519238786E-9d, }, // 170 - {+0.15442964434623718d, +1.4419920764774415E-8d, }, // 171 - {+0.15526613593101501d, -7.019891063126053E-9d, }, // 172 - {+0.15610191226005554d, -1.230153548825964E-8d, }, // 173 - {+0.15693697333335876d, -2.574172005933276E-10d, }, // 174 - {+0.15777134895324707d, +4.748140799544371E-10d, }, // 175 - {+0.15860503911972046d, -8.943081874891003E-9d, }, // 176 - {+0.15943801403045654d, +2.4500739038517657E-9d, }, // 177 - {+0.1602703034877777d, +6.007922084557054E-9d, }, // 178 - {+0.16110190749168396d, +2.8835418231126645E-9d, }, // 179 - {+0.1619328260421753d, -5.772862039728412E-9d, }, // 180 - {+0.16276302933692932d, +1.0988372954605789E-8d, }, // 181 - {+0.16359257698059082d, -5.292913162607026E-9d, }, // 182 - {+0.16442140936851501d, +6.12956339275823E-9d, }, // 183 - {+0.16524958610534668d, -1.3210039516811888E-8d, }, // 184 - {+0.16607704758644104d, -2.5711014608334873E-9d, }, // 185 - {+0.16690382361412048d, +9.37721319457112E-9d, }, // 186 - {+0.1677299439907074d, -6.0370682395944045E-9d, }, // 187 - {+0.168555349111557d, +1.1918249660105651E-8d, }, // 188 - {+0.1693800985813141d, +4.763282949656017E-9d, }, // 189 - {+0.17020416259765625d, +3.4223342273948817E-9d, }, // 190 - {+0.1710275411605835d, +9.014612241310916E-9d, }, // 191 - {+0.1718502640724182d, -7.145758990550526E-9d, }, // 192 - {+0.172672301530838d, -1.4142763934081504E-8d, }, // 193 - {+0.1734936535358429d, -1.0865453656579032E-8d, }, // 194 - {+0.17431432008743286d, +3.794385569450774E-9d, }, // 195 - {+0.1751343309879303d, +1.1399188501627291E-9d, }, // 196 - {+0.17595365643501282d, +1.2076238768270153E-8d, }, // 197 - {+0.1767723262310028d, +7.901084730502162E-9d, }, // 198 - {+0.17759034037590027d, -1.0288181007465474E-8d, }, // 199 - {+0.1784076690673828d, -1.15945645153806E-8d, }, // 200 - {+0.17922431230545044d, +5.073923825786778E-9d, }, // 201 - {+0.18004029989242554d, +1.1004278077575267E-8d, }, // 202 - {+0.1808556318283081d, +7.2831502374676964E-9d, }, // 203 - {+0.18167030811309814d, -5.0054634662706464E-9d, }, // 204 - {+0.18248429894447327d, +5.022108460298934E-9d, }, // 205 - {+0.18329763412475586d, +8.642254225732676E-9d, }, // 206 - {+0.18411031365394592d, +6.931054493326395E-9d, }, // 207 - {+0.18492233753204346d, +9.619685356326533E-10d, }, // 208 - {+0.18573370575904846d, -8.194157257980706E-9d, }, // 209 - {+0.18654438853263855d, +1.0333241479437797E-8d, }, // 210 - {+0.1873544454574585d, -1.9948340196027965E-9d, }, // 211 - {+0.1881638467311859d, -1.4313002926259948E-8d, }, // 212 - {+0.1889725625514984d, +4.241536392174967E-9d, }, // 213 - {+0.18978065252304077d, -4.877952454011428E-9d, }, // 214 - {+0.1905880868434906d, -1.0813801247641613E-8d, }, // 215 - {+0.1913948655128479d, -1.2513218445781325E-8d, }, // 216 - {+0.19220098853111267d, -8.925958555729115E-9d, }, // 217 - {+0.1930064558982849d, +9.956860681280245E-10d, }, // 218 - {+0.193811297416687d, -1.1505428993246996E-8d, }, // 219 - {+0.1946154534816742d, +1.4217997464522202E-8d, }, // 220 - {+0.19541901350021362d, -1.0200858727747717E-8d, }, // 221 - {+0.19622188806533813d, +5.682607223902455E-9d, }, // 222 - {+0.1970241367816925d, +3.2988908516009827E-9d, }, // 223 - {+0.19782572984695435d, +1.3482965534659446E-8d, }, // 224 - {+0.19862669706344604d, +7.462678536479685E-9d, }, // 225 - {+0.1994270384311676d, -1.3734273888891115E-8d, }, // 226 - {+0.20022669434547424d, +1.0521983802642893E-8d, }, // 227 - {+0.20102575421333313d, -8.152742388541905E-9d, }, // 228 - {+0.2018241584300995d, -9.133484280193855E-9d, }, // 229 - {+0.20262190699577332d, +8.59763959528144E-9d, }, // 230 - {+0.2034190595149994d, -1.3548568223001414E-8d, }, // 231 - {+0.20421552658081055d, +1.4847880344628818E-8d, }, // 232 - {+0.20501139760017395d, +5.390620378060543E-9d, }, // 233 - {+0.2058066427707672d, -1.1109834472051523E-8d, }, // 234 - {+0.20660123229026794d, -3.845373872038116E-9d, }, // 235 - {+0.20739519596099854d, -1.6149279479975042E-9d, }, // 236 - {+0.20818853378295898d, -3.4174925203771133E-9d, }, // 237 - {+0.2089812457561493d, -8.254443919468538E-9d, }, // 238 - {+0.20977330207824707d, +1.4672790944499144E-8d, }, // 239 - {+0.2105647623538971d, +6.753452542942992E-9d, }, // 240 - {+0.21135559678077698d, -1.218609462241927E-9d, }, // 241 - {+0.21214580535888672d, -8.254218316367887E-9d, }, // 242 - {+0.21293538808822632d, -1.3366540360587255E-8d, }, // 243 - {+0.2137243151664734d, +1.4231244750190031E-8d, }, // 244 - {+0.2145126760005951d, -1.3885660525939072E-8d, }, // 245 - {+0.21530038118362427d, -7.3304404046850136E-9d, }, // 246 - {+0.2160874605178833d, +5.072117654842356E-9d, }, // 247 - {+0.21687394380569458d, -5.505080220459036E-9d, }, // 248 - {+0.21765980124473572d, -8.286782292266659E-9d, }, // 249 - {+0.2184450328350067d, -2.302351152358085E-9d, }, // 250 - {+0.21922963857650757d, +1.3416565858314603E-8d, }, // 251 - {+0.22001364827156067d, +1.0033721426962048E-8d, }, // 252 - {+0.22079706192016602d, -1.1487079818684332E-8d, }, // 253 - {+0.22157981991767883d, +9.420348186357043E-9d, }, // 254 - {+0.2223619818687439d, +1.4110645699377834E-8d, }, // 255 - {+0.2231435477733612d, +3.5408485497116107E-9d, }, // 256 - {+0.22392448782920837d, +8.468072777056227E-9d, }, // 257 - {+0.2247048318386078d, +4.255446699237779E-11d, }, // 258 - {+0.22548454999923706d, +9.016946273084244E-9d, }, // 259 - {+0.22626367211341858d, +6.537034810260226E-9d, }, // 260 - {+0.22704219818115234d, -6.451285264969768E-9d, }, // 261 - {+0.22782009840011597d, +7.979956357126066E-10d, }, // 262 - {+0.22859740257263184d, -5.759582672039005E-10d, }, // 263 - {+0.22937411069869995d, -9.633854121180397E-9d, }, // 264 - {+0.23015019297599792d, +4.363736368635843E-9d, }, // 265 - {+0.23092567920684814d, +1.2549416560182509E-8d, }, // 266 - {+0.231700599193573d, -1.3946383592553814E-8d, }, // 267 - {+0.2324748933315277d, -1.458843364504023E-8d, }, // 268 - {+0.23324856162071228d, +1.1551692104697154E-8d, }, // 269 - {+0.23402166366577148d, +5.795621295524984E-9d, }, // 270 - {+0.23479416966438293d, -1.1301979046684263E-9d, }, // 271 - {+0.23556607961654663d, -8.303779721781787E-9d, }, // 272 - {+0.23633739352226257d, -1.4805271785394075E-8d, }, // 273 - {+0.23710808157920837d, +1.0085373835899469E-8d, }, // 274 - {+0.2378782033920288d, +7.679117635349454E-9d, }, // 275 - {+0.2386477291584015d, +8.69177352065934E-9d, }, // 276 - {+0.23941665887832642d, +1.4034725764547136E-8d, }, // 277 - {+0.24018502235412598d, -5.185064518887831E-9d, }, // 278 - {+0.2409527599811554d, +1.1544236628121676E-8d, }, // 279 - {+0.24171993136405945d, +5.523085719902123E-9d, }, // 280 - {+0.24248650670051575d, +7.456824943331887E-9d, }, // 281 - {+0.24325251579284668d, -1.1555923403029638E-8d, }, // 282 - {+0.24401789903640747d, +8.988361382732908E-9d, }, // 283 - {+0.2447827160358429d, +1.0381848020926893E-8d, }, // 284 - {+0.24554696679115295d, -6.480706118857055E-9d, }, // 285 - {+0.24631062150001526d, -1.0904271124793968E-8d, }, // 286 - {+0.2470736801624298d, -1.998183061531611E-9d, }, // 287 - {+0.247836172580719d, -8.676137737360023E-9d, }, // 288 - {+0.24859806895256042d, -2.4921733203932487E-10d,}, // 289 - {+0.2493593990802765d, -5.635173762130303E-9d, }, // 290 - {+0.2501201629638672d, -2.3951455355985637E-8d, }, // 291 - {+0.25088030099868774d, +5.287121672447825E-9d, }, // 292 - {+0.2516399025917053d, -6.447877375049486E-9d, }, // 293 - {+0.25239890813827515d, +1.32472428796441E-9d, }, // 294 - {+0.2531573176383972d, +2.9479464287605006E-8d, }, // 295 - {+0.2539151906967163d, +1.9284247135543574E-8d, }, // 296 - {+0.2546725273132324d, -2.8390360197221716E-8d, }, // 297 - {+0.255429208278656d, +6.533522495226226E-9d, }, // 298 - {+0.2561853528022766d, +5.713225978895991E-9d, }, // 299 - {+0.25694090127944946d, +2.9618050962556135E-8d, }, // 300 - {+0.25769591331481934d, +1.950605015323617E-8d, }, // 301 - {+0.25845038890838623d, -2.3762031507525576E-8d, }, // 302 - {+0.2592042088508606d, +1.98818938195077E-8d, }, // 303 - {+0.25995755195617676d, -2.751925069084042E-8d, }, // 304 - {+0.2607102394104004d, +1.3703391844683932E-8d, }, // 305 - {+0.26146239042282104d, +2.5193525310038174E-8d, }, // 306 - {+0.2622140049934387d, +7.802219817310385E-9d, }, // 307 - {+0.26296502351760864d, +2.1983272709242607E-8d, }, // 308 - {+0.2637155055999756d, +8.979279989292184E-9d, }, // 309 - {+0.2644653916358948d, +2.9240221157844312E-8d, }, // 310 - {+0.265214741230011d, +2.4004885823813374E-8d, }, // 311 - {+0.2659635543823242d, -5.885186277410878E-9d, }, // 312 - {+0.2667117714881897d, +1.4300386517357162E-11d,}, // 313 - {+0.2674594521522522d, -1.7063531531989365E-8d, }, // 314 - {+0.26820653676986694d, +3.3218524692903896E-9d, }, // 315 - {+0.2689530849456787d, +2.3998252479954764E-9d, }, // 316 - {+0.2696990966796875d, -1.8997462070389404E-8d, }, // 317 - {+0.27044451236724854d, -4.350745270980051E-10d, }, // 318 - {+0.2711893916130066d, -6.892221115467135E-10d, }, // 319 - {+0.27193373441696167d, -1.89333199110902E-8d, }, // 320 - {+0.272677481174469d, +5.262017392507765E-9d, }, // 321 - {+0.27342069149017334d, +1.3115046679980076E-8d, }, // 322 - {+0.2741633653640747d, +5.4468361834451975E-9d, }, // 323 - {+0.2749055027961731d, -1.692337384653611E-8d, }, // 324 - {+0.27564704418182373d, +6.426479056697412E-9d, }, // 325 - {+0.2763880491256714d, +1.670735065191342E-8d, }, // 326 - {+0.27712851762771606d, +1.4733029698334834E-8d, }, // 327 - {+0.27786844968795776d, +1.315498542514467E-9d, }, // 328 - {+0.2786078453063965d, -2.2735061539223372E-8d, }, // 329 - {+0.27934664487838745d, +2.994379757313727E-9d, }, // 330 - {+0.28008490800857544d, +1.970577274107218E-8d, }, // 331 - {+0.28082263469696045d, +2.820392733542077E-8d, }, // 332 - {+0.2815598249435425d, +2.929187356678173E-8d, }, // 333 - {+0.28229647874832153d, +2.377086680926386E-8d, }, // 334 - {+0.2830325961112976d, +1.2440393009992529E-8d, }, // 335 - {+0.2837681770324707d, -3.901826104778096E-9d, }, // 336 - {+0.2845032215118408d, -2.4459827842685974E-8d, }, // 337 - {+0.2852376699447632d, +1.1165241398059789E-8d, }, // 338 - {+0.28597164154052734d, -1.54434478239181E-8d, }, // 339 - {+0.28670501708984375d, +1.5714110564653245E-8d, }, // 340 - {+0.28743791580200195d, -1.3782394940142479E-8d, }, // 341 - {+0.2881702184677124d, +1.6063569876284005E-8d, }, // 342 - {+0.28890204429626465d, -1.317176818216125E-8d, }, // 343 - {+0.28963327407836914d, +1.8504673536253893E-8d, }, // 344 - {+0.29036402702331543d, -7.334319635123628E-9d, }, // 345 - {+0.29109418392181396d, +2.9300903540317107E-8d, }, // 346 - {+0.2918238639831543d, +9.979706999541057E-9d, }, // 347 - {+0.29255300760269165d, -4.916314210412424E-9d, }, // 348 - {+0.293281614780426d, -1.4611908070155308E-8d, }, // 349 - {+0.2940096855163574d, -1.833351586679361E-8d, }, // 350 - {+0.29473721981048584d, -1.530926726615185E-8d, }, // 351 - {+0.2954642176628113d, -4.7689754029101934E-9d, }, // 352 - {+0.29619067907333374d, +1.4055868011423819E-8d, }, // 353 - {+0.296916663646698d, -1.7672547212604003E-8d, }, // 354 - {+0.2976420521736145d, +2.0020234215759705E-8d, }, // 355 - {+0.2983669638633728d, +8.688424478730524E-9d, }, // 356 - {+0.2990913391113281d, +8.69851089918337E-9d, }, // 357 - {+0.29981517791748047d, +2.0810681643102672E-8d, }, // 358 - {+0.3005385398864746d, -1.3821169493779352E-8d, }, // 359 - {+0.301261305809021d, +2.4769140784919128E-8d, }, // 360 - {+0.3019835948944092d, +1.8127576600610336E-8d, }, // 361 - {+0.3027053475379944d, +2.6612401062437074E-8d, }, // 362 - {+0.3034266233444214d, -8.629042891789934E-9d, }, // 363 - {+0.3041473627090454d, -2.724174869314043E-8d, }, // 364 - {+0.30486756563186646d, -2.8476975783775358E-8d, }, // 365 - {+0.3055872321128845d, -1.1587600174449919E-8d, }, // 366 - {+0.3063063621520996d, +2.417189020581056E-8d, }, // 367 - {+0.3070250153541565d, +1.99407553679345E-8d, }, // 368 - {+0.3077431917190552d, -2.35387025694381E-8d, }, // 369 - {+0.3084607720375061d, +1.3683509995845583E-8d, }, // 370 - {+0.30917787551879883d, +1.3137214081023085E-8d, }, // 371 - {+0.30989450216293335d, -2.444006866174775E-8d, }, // 372 - {+0.3106105327606201d, +2.0896888605749563E-8d, }, // 373 - {+0.31132614612579346d, -2.893149098508887E-8d, }, // 374 - {+0.31204116344451904d, +5.621509038251498E-9d, }, // 375 - {+0.3127557039260864d, +6.0778104626050015E-9d, }, // 376 - {+0.3134697675704956d, -2.6832941696716294E-8d, }, // 377 - {+0.31418323516845703d, +2.6826625274495256E-8d, }, // 378 - {+0.31489628553390503d, -1.1030897183911054E-8d, }, // 379 - {+0.31560879945755005d, -2.047124671392676E-8d, }, // 380 - {+0.3163207769393921d, -7.709990443086711E-10d, }, // 381 - {+0.3170322775840759d, -1.0812918808112342E-8d, }, // 382 - {+0.3177432417869568d, +9.727979174888975E-9d, }, // 383 - {+0.31845372915267944d, +1.9658551724508715E-9d, }, // 384 - {+0.3191636800765991d, +2.6222628001695826E-8d, }, // 385 - {+0.3198731541633606d, +2.3609400272358744E-8d, }, // 386 - {+0.32058215141296387d, -5.159602957634814E-9d, }, // 387 - {+0.32129061222076416d, +2.329701319016099E-10d, }, // 388 - {+0.32199859619140625d, -1.910633190395738E-8d, }, // 389 - {+0.32270604372024536d, -2.863180390093667E-9d, }, // 390 - {+0.32341301441192627d, -9.934041364456825E-9d, }, // 391 - {+0.3241194486618042d, +1.999240777687192E-8d, }, // 392 - {+0.3248254060745239d, +2.801670341647724E-8d, }, // 393 - {+0.32553088665008545d, +1.4842534265191358E-8d, }, // 394 - {+0.32623589038848877d, -1.882789920477354E-8d, }, // 395 - {+0.3269403576850891d, -1.268923579073577E-8d, }, // 396 - {+0.32764434814453125d, -2.564688370677835E-8d, }, // 397 - {+0.3283478021621704d, +2.6015626820520968E-9d, }, // 398 - {+0.32905077934265137d, +1.3147747907784344E-8d, }, // 399 - {+0.3297532796859741d, +6.686493860720675E-9d, }, // 400 - {+0.33045530319213867d, -1.608884086544153E-8d, }, // 401 - {+0.33115679025650024d, +5.118287907840204E-9d, }, // 402 - {+0.3318578004837036d, +1.139367970944884E-8d, }, // 403 - {+0.3325583338737488d, +3.426327822115399E-9d, }, // 404 - {+0.33325839042663574d, -1.809622142990733E-8d, }, // 405 - {+0.3339579105377197d, +7.116780143398601E-9d, }, // 406 - {+0.3346569538116455d, +2.0145352306345386E-8d, }, // 407 - {+0.3353555202484131d, +2.167272474431968E-8d, }, // 408 - {+0.33605360984802246d, +1.2380696294966822E-8d, }, // 409 - {+0.33675122261047363d, -7.050361059209181E-9d, }, // 410 - {+0.3374482989311218d, +2.366314656322868E-8d, }, // 411 - {+0.3381449580192566d, -1.4010540194086646E-8d, }, // 412 - {+0.3388410806655884d, -1.860165465666482E-10d, }, // 413 - {+0.33953672647476196d, +6.206776940880773E-9d, }, // 414 - {+0.34023189544677734d, +5.841137379010982E-9d, }, // 415 - {+0.3409265875816345d, -6.11041311179286E-10d, }, // 416 - {+0.3416208028793335d, -1.2479264502054702E-8d, }, // 417 - {+0.34231454133987427d, -2.909443297645926E-8d, }, // 418 - {+0.34300774335861206d, +9.815805717097634E-9d, }, // 419 - {+0.3437005281448364d, -1.4291517981101049E-8d, }, // 420 - {+0.3443927764892578d, +1.8457821628427503E-8d, }, // 421 - {+0.34508460760116577d, -1.0481908869377813E-8d, }, // 422 - {+0.34577590227127075d, +1.876076001514746E-8d, }, // 423 - {+0.3464667797088623d, -1.2362653723769037E-8d, }, // 424 - {+0.3471571207046509d, +1.6016578405624026E-8d, }, // 425 - {+0.347847044467926d, -1.4652759033760925E-8d, }, // 426 - {+0.3485364317893982d, +1.549533655901835E-8d, }, // 427 - {+0.34922540187835693d, -1.2093068629412478E-8d, }, // 428 - {+0.3499138355255127d, +2.244531711424792E-8d, }, // 429 - {+0.35060185194015503d, +5.538565518604807E-10d, }, // 430 - {+0.35128939151763916d, -1.7511499366215853E-8d, }, // 431 - {+0.3519763946533203d, +2.850385787215544E-8d, }, // 432 - {+0.35266298055648804d, +2.003926370146842E-8d, }, // 433 - {+0.35334908962249756d, +1.734665280502264E-8d, }, // 434 - {+0.3540347218513489d, +2.1071983674869414E-8d, }, // 435 - {+0.35471993684768677d, -2.774475773922311E-8d, }, // 436 - {+0.3554046154022217d, -9.250975291734664E-9d, }, // 437 - {+0.3560888171195984d, +1.7590672330295415E-8d, }, // 438 - {+0.35677260160446167d, -6.1837904549178745E-9d, }, // 439 - {+0.35745590925216675d, -2.0330362973820856E-8d, }, // 440 - {+0.3581387400627136d, -2.42109990366786E-8d, }, // 441 - {+0.3588210940361023d, -1.7188958587407816E-8d, }, // 442 - {+0.35950297117233276d, +1.3711958590112228E-9d, }, // 443 - {+0.3601844310760498d, -2.7501042008405925E-8d, }, // 444 - {+0.36086535453796387d, +1.6036460343275798E-8d, }, // 445 - {+0.3615458607673645d, +1.3405964389498495E-8d, }, // 446 - {+0.36222589015960693d, +2.484237749027735E-8d, }, // 447 - {+0.36290550231933594d, -8.629967484362177E-9d, }, // 448 - {+0.36358463764190674d, -2.6778729562324134E-8d, }, // 449 - {+0.36426329612731934d, -2.8977490516960565E-8d, }, // 450 - {+0.36494147777557373d, -1.4601106624823502E-8d, }, // 451 - {+0.3656191825866699d, +1.69742947894444E-8d, }, // 452 - {+0.3662964701652527d, +6.7666740211281175E-9d, }, // 453 - {+0.36697328090667725d, +1.500201674336832E-8d, }, // 454 - {+0.3676496744155884d, -1.730424167425052E-8d, }, // 455 - {+0.36832553148269653d, +2.9676011119845104E-8d, }, // 456 - {+0.36900103092193604d, -2.2253590346826743E-8d, }, // 457 - {+0.36967599391937256d, +6.3372065441089185E-9d, }, // 458 - {+0.37035053968429565d, -3.145816653215968E-9d, }, // 459 - {+0.37102460861206055d, +9.515812117036965E-9d, }, // 460 - {+0.371698260307312d, -1.4669965113042639E-8d, }, // 461 - {+0.3723714351654053d, -1.548715389333397E-8d, }, // 462 - {+0.37304413318634033d, +7.674361647125109E-9d, }, // 463 - {+0.37371641397476196d, -4.181177882069608E-9d, }, // 464 - {+0.3743882179260254d, +9.158530500130718E-9d, }, // 465 - {+0.3750596046447754d, -1.13047236597869E-8d, }, // 466 - {+0.3757305145263672d, -5.36108186384227E-9d, }, // 467 - {+0.3764009475708008d, +2.7593452284747873E-8d, }, // 468 - {+0.37707096338272095d, +2.8557016344085205E-8d, }, // 469 - {+0.3777405619621277d, -1.868818164036E-9d, }, // 470 - {+0.3784096837043762d, -3.479042513414447E-9d, }, // 471 - {+0.37907832860946655d, +2.432550290565648E-8d, }, // 472 - {+0.37974655628204346d, +2.2538131805476768E-8d, }, // 473 - {+0.38041436672210693d, -8.244395239939089E-9d, }, // 474 - {+0.3810817003250122d, -7.821867597227376E-9d, }, // 475 - {+0.3817485570907593d, +2.4400089062515914E-8d, }, // 476 - {+0.3824149966239929d, +2.9410015940087773E-8d, }, // 477 - {+0.38308101892471313d, +7.799913824734797E-9d, }, // 478 - {+0.38374656438827515d, +1.976524624939355E-8d, }, // 479 - {+0.38441169261932373d, +6.291008309266035E-9d, }, // 480 - {+0.3850763440132141d, +2.757030889767851E-8d, }, // 481 - {+0.38574057817459106d, +2.4585794728405612E-8d, }, // 482 - {+0.3864043951034546d, -2.0764122246389383E-9d, }, // 483 - {+0.3870677351951599d, +7.77328837578952E-9d, }, // 484 - {+0.3877306580543518d, -4.8859560029989374E-9d, }, // 485 - {+0.3883931040763855d, +2.0133131420595028E-8d, }, // 486 - {+0.38905513286590576d, +2.380738071335498E-8d, }, // 487 - {+0.3897167444229126d, +6.7171126157142075E-9d, }, // 488 - {+0.39037787914276123d, +2.9046141593926277E-8d, }, // 489 - {+0.3910386562347412d, -2.7836800219410262E-8d, }, // 490 - {+0.3916988968849182d, +1.545909820981726E-8d, }, // 491 - {+0.39235877990722656d, -1.930436269002062E-8d, }, // 492 - {+0.3930181860923767d, -1.2343297554921835E-8d, }, // 493 - {+0.3936771750450134d, -2.268889128622553E-8d, }, // 494 - {+0.39433568716049194d, +9.835827818608177E-9d, }, // 495 - {+0.39499378204345703d, +2.6197411946856397E-8d, }, // 496 - {+0.3956514596939087d, +2.6965931069318893E-8d, }, // 497 - {+0.3963087201118469d, +1.2710331127772166E-8d, }, // 498 - {+0.39696556329727173d, -1.6001563011916016E-8d, }, // 499 - {+0.39762192964553833d, +1.0016001590267064E-9d, }, // 500 - {+0.3982778787612915d, +4.680767399874334E-9d, }, // 501 - {+0.39893341064453125d, -4.399582029272418E-9d, }, // 502 - {+0.39958852529525757d, -2.5676078228301587E-8d, }, // 503 - {+0.4002431631088257d, +1.0181870233355787E-9d, }, // 504 - {+0.40089738368988037d, +1.6639728835984655E-8d, }, // 505 - {+0.40155118703842163d, +2.174860642202632E-8d, }, // 506 - {+0.40220457315444946d, +1.6903781197123503E-8d, }, // 507 - {+0.40285754203796387d, +2.663119647467697E-9d, }, // 508 - {+0.40351009368896484d, -2.0416603812329616E-8d, }, // 509 - {+0.4041621685028076d, +7.82494078472695E-9d, }, // 510 - {+0.40481382608413696d, +2.833770747113627E-8d, }, // 511 - {+0.40546512603759766d, -1.7929433274271985E-8d, }, // 512 - {+0.40611594915390015d, -1.1214757379328965E-8d, }, // 513 - {+0.4067663550376892d, -1.0571553019207106E-8d, }, // 514 - {+0.40741634368896484d, -1.5449538712332313E-8d, }, // 515 - {+0.40806591510772705d, -2.529950530235105E-8d, }, // 516 - {+0.40871500968933105d, +2.0031331601617008E-8d, }, // 517 - {+0.4093637466430664d, +1.880755298741952E-9d, }, // 518 - {+0.41001206636428833d, -1.9600580584843318E-8d, }, // 519 - {+0.41065990924835205d, +1.573691633515306E-8d, }, // 520 - {+0.4113073945045471d, -1.0772154376548336E-8d, }, // 521 - {+0.411954402923584d, +2.0624330192486066E-8d, }, // 522 - {+0.4126010537147522d, -8.741139170029572E-9d, }, // 523 - {+0.4132472276687622d, +2.0881457123894216E-8d, }, // 524 - {+0.41389304399490356d, -9.177488027521808E-9d, }, // 525 - {+0.4145383834838867d, +2.0829952491625585E-8d, }, // 526 - {+0.4151833653450012d, -7.767915492597301E-9d, }, // 527 - {+0.4158278703689575d, +2.4774753446082082E-8d, }, // 528 - {+0.41647201776504517d, -2.1581119071750435E-10d,}, // 529 - {+0.4171157479286194d, -2.260047972865202E-8d, }, // 530 - {+0.4177590012550354d, +1.775884601423381E-8d, }, // 531 - {+0.41840189695358276d, +2.185301053838889E-9d, }, // 532 - {+0.4190443754196167d, -9.185071463667081E-9d, }, // 533 - {+0.4196864366531372d, -1.5821896727910552E-8d, }, // 534 - {+0.4203280806541443d, -1.719582086188318E-8d, }, // 535 - {+0.42096930742263794d, -1.2778508303324259E-8d, }, // 536 - {+0.42161011695861816d, -2.042639194493364E-9d, }, // 537 - {+0.42225050926208496d, +1.5538093219698803E-8d, }, // 538 - {+0.4228905439376831d, -1.9115659590156936E-8d, }, // 539 - {+0.42353010177612305d, +1.3729680248843432E-8d, }, // 540 - {+0.42416930198669434d, -4.611893838830296E-9d, }, // 541 - {+0.4248080849647522d, -1.4013456880651706E-8d, }, // 542 - {+0.42544645071029663d, -1.3953728897042917E-8d, }, // 543 - {+0.42608439922332764d, -3.912427573594197E-9d, }, // 544 - {+0.4267219305038452d, +1.6629734283189315E-8d, }, // 545 - {+0.42735910415649414d, -1.1413593493354881E-8d, }, // 546 - {+0.42799586057662964d, -2.792046157580119E-8d, }, // 547 - {+0.42863214015960693d, +2.723009182661306E-8d, }, // 548 - {+0.42926812171936035d, -2.4260535621557444E-8d, }, // 549 - {+0.42990362644195557d, -3.064060124024764E-9d, }, // 550 - {+0.43053877353668213d, -2.787640178598121E-8d, }, // 551 - {+0.4311734437942505d, +2.102412085257792E-8d, }, // 552 - {+0.4318077564239502d, +2.4939635093999683E-8d, }, // 553 - {+0.43244171142578125d, -1.5619414792273914E-8d, }, // 554 - {+0.4330751895904541d, +1.9065734894871523E-8d, }, // 555 - {+0.4337083101272583d, +1.0294301092654604E-8d, }, // 556 - {+0.4343410134315491d, +1.8178469851136E-8d, }, // 557 - {+0.4349733591079712d, -1.6379825102473853E-8d, }, // 558 - {+0.4356052279472351d, +2.6334323946685834E-8d, }, // 559 - {+0.43623673915863037d, +2.761628769925529E-8d, }, // 560 - {+0.436867892742157d, -1.2030229087793677E-8d, }, // 561 - {+0.4374985694885254d, +2.7106814809424793E-8d, }, // 562 - {+0.43812888860702515d, +2.631993083235205E-8d, }, // 563 - {+0.43875885009765625d, -1.3890028312254422E-8d, }, // 564 - {+0.43938833475112915d, +2.6186133735555794E-8d, }, // 565 - {+0.4400174617767334d, +2.783809071694788E-8d, }, // 566 - {+0.440646231174469d, -8.436135220472006E-9d, }, // 567 - {+0.44127458333969116d, -2.2534815932619883E-8d, }, // 568 - {+0.4419025182723999d, -1.3961804471714283E-8d, }, // 569 - {+0.4425300359725952d, +1.7778112039716255E-8d, }, // 570 - {+0.4431571960449219d, +1.3574569976673652E-8d, }, // 571 - {+0.4437839984893799d, -2.607907890164073E-8d, }, // 572 - {+0.4444103240966797d, +1.8518879652136628E-8d, }, // 573 - {+0.44503629207611084d, +2.865065604247164E-8d, }, // 574 - {+0.44566190242767334d, +4.806827797299427E-9d, }, // 575 - {+0.4462870955467224d, +7.0816970994232115E-9d, }, // 576 - {+0.44691193103790283d, -2.3640641240074437E-8d, }, // 577 - {+0.4475363492965698d, -2.7267718387865538E-8d, }, // 578 - {+0.4481603503227234d, -3.3126235292976077E-9d, }, // 579 - {+0.4487839937210083d, -1.0894001590268427E-8d, }, // 580 - {+0.4494072198867798d, +1.0077883359971829E-8d, }, // 581 - {+0.4500300884246826d, +4.825712712114668E-10d, }, // 582 - {+0.450652539730072d, +2.0407987470746858E-8d, }, // 583 - {+0.4512746334075928d, +1.073186581170719E-8d, }, // 584 - {+0.4518963694572449d, -2.8064314757880205E-8d, }, // 585 - {+0.45251762866973877d, +2.3709316816226527E-8d, }, // 586 - {+0.4531385898590088d, -1.2281487504266522E-8d, }, // 587 - {+0.4537591338157654d, -1.634864487421458E-8d, }, // 588 - {+0.45437926054000854d, +1.1985747222409522E-8d, }, // 589 - {+0.45499902963638306d, +1.3594057956219485E-8d, }, // 590 - {+0.4556184411048889d, -1.1047585095328619E-8d, }, // 591 - {+0.45623743534088135d, -1.8592937532754405E-9d, }, // 592 - {+0.4568560719490051d, -1.797135137545755E-8d, }, // 593 - {+0.4574742913246155d, +6.943684261645378E-10d, }, // 594 - {+0.4580921530723572d, -4.994175141684681E-9d, }, // 595 - {+0.45870959758758545d, +2.5039391215625133E-8d, }, // 596 - {+0.45932674407958984d, -2.7943366835352838E-8d, }, // 597 - {+0.45994341373443604d, +1.534146910128904E-8d, }, // 598 - {+0.46055978536605835d, -2.3450920230816267E-8d, }, // 599 - {+0.46117573976516724d, -2.4642997069960124E-8d, }, // 600 - {+0.4617912769317627d, +1.2232622070370946E-8d, }, // 601 - {+0.4624064564704895d, +2.80378133047839E-8d, }, // 602 - {+0.46302127838134766d, +2.3238237048117092E-8d, }, // 603 - {+0.46363574266433716d, -1.7013046451109475E-9d, }, // 604 - {+0.46424978971481323d, +1.3287778803035383E-8d, }, // 605 - {+0.46486347913742065d, +9.06393426961373E-9d, }, // 606 - {+0.4654768109321594d, -1.3910598647592876E-8d, }, // 607 - {+0.46608972549438477d, +4.430214458933614E-9d, }, // 608 - {+0.46670228242874146d, +4.942270562885745E-9d, }, // 609 - {+0.4673144817352295d, -1.1914734393460718E-8d, }, // 610 - {+0.4679262638092041d, +1.3922696570638494E-8d, }, // 611 - {+0.46853768825531006d, +2.3307929211781914E-8d, }, // 612 - {+0.46914875507354736d, +1.669813444584674E-8d, }, // 613 - {+0.469759464263916d, -5.450354376430758E-9d, }, // 614 - {+0.47036975622177124d, +1.6922605350647674E-8d, }, // 615 - {+0.4709796905517578d, +2.4667033200046904E-8d, }, // 616 - {+0.47158926725387573d, +1.8236762070433784E-8d, }, // 617 - {+0.472198486328125d, -1.915204563140137E-9d, }, // 618 - {+0.47280728816986084d, +2.426795414605756E-8d, }, // 619 - {+0.4734157919883728d, -2.19717006713618E-8d, }, // 620 - {+0.47402387857437134d, -2.0974352165535873E-8d, }, // 621 - {+0.47463154792785645d, +2.770970558184228E-8d, }, // 622 - {+0.4752389192581177d, +5.32006955298355E-9d, }, // 623 - {+0.47584593296051025d, -2.809054633964104E-8d, }, // 624 - {+0.4764525294303894d, -1.2470243596102937E-8d, }, // 625 - {+0.4770587682723999d, -6.977226702440138E-9d, }, // 626 - {+0.47766464948654175d, -1.1165866833118273E-8d, }, // 627 - {+0.47827017307281494d, -2.4591344661022708E-8d, }, // 628 - {+0.4788752794265747d, +1.2794996377383974E-8d, }, // 629 - {+0.4794800877571106d, -1.7772927065973874E-8d, }, // 630 - {+0.48008447885513306d, +3.35657712457243E-9d, }, // 631 - {+0.48068851232528687d, +1.7020465042442242E-8d, }, // 632 - {+0.481292188167572d, +2.365953779624783E-8d, }, // 633 - {+0.4818955063819885d, +2.3713798664443718E-8d, }, // 634 - {+0.4824984669685364d, +1.7622455019548098E-8d, }, // 635 - {+0.4831010699272156d, +5.823920246566496E-9d, }, // 636 - {+0.4837033152580261d, -1.1244184344361017E-8d, }, // 637 - {+0.48430514335632324d, +2.645961716432205E-8d, }, // 638 - {+0.4849066734313965d, +1.6207809718247905E-10d,}, // 639 - {+0.4855077862739563d, +2.9507744508973654E-8d, }, // 640 - {+0.48610860109329224d, -4.278201128741098E-9d, }, // 641 - {+0.48670899868011475d, +1.844722015961139E-8d, }, // 642 - {+0.4873090982437134d, -2.1092372471088425E-8d, }, // 643 - {+0.4879087805747986d, -3.2555596107382053E-9d, }, // 644 - {+0.48850810527801514d, +1.2784366845429667E-8d, }, // 645 - {+0.48910707235336304d, +2.7457984659996047E-8d, }, // 646 - {+0.48970574140548706d, -1.8409546441412518E-8d, }, // 647 - {+0.49030399322509766d, -5.179903818099661E-9d, }, // 648 - {+0.4909018874168396d, +7.97053127828682E-9d, }, // 649 - {+0.4914994239807129d, +2.146925464473481E-8d, }, // 650 - {+0.4920966625213623d, -2.3861648589988232E-8d, }, // 651 - {+0.4926934838294983d, -8.386923035320549E-9d, }, // 652 - {+0.4932899475097656d, +8.713990131749256E-9d, }, // 653 - {+0.4938860535621643d, +2.7865534085810115E-8d, }, // 654 - {+0.4944818615913391d, -1.011325138560159E-8d, }, // 655 - {+0.4950772523880005d, +1.4409851026316708E-8d, }, // 656 - {+0.495672345161438d, -1.735227547472004E-8d, }, // 657 - {+0.49626702070236206d, +1.4231078209064581E-8d, }, // 658 - {+0.49686139822006226d, -9.628709342929729E-9d, }, // 659 - {+0.4974554181098938d, -2.8907074856577267E-8d, }, // 660 - {+0.4980490207672119d, +1.6419797090870802E-8d, }, // 661 - {+0.49864232540130615d, +7.561041519403049E-9d, }, // 662 - {+0.49923527240753174d, +4.538983468118194E-9d, }, // 663 - {+0.49982786178588867d, +7.770560657946324E-9d, }, // 664 - {+0.500420093536377d, +1.767197002609876E-8d, }, // 665 - {+0.5010119676589966d, +3.46586694799214E-8d, }, // 666 - {+0.5016034841537476d, +5.914537964556077E-8d, }, // 667 - {+0.5021947622299194d, -2.7663203939320167E-8d, }, // 668 - {+0.5027855634689331d, +1.3064749115929298E-8d, }, // 669 - {+0.5033761262893677d, -5.667682106730711E-8d, }, // 670 - {+0.503966212272644d, +1.9424534974370594E-9d, }, // 671 - {+0.5045560598373413d, -4.908494602153544E-8d, }, // 672 - {+0.5051454305648804d, +2.906989285008994E-8d, }, // 673 - {+0.5057345628738403d, -1.602000800745108E-9d, }, // 674 - {+0.5063233375549316d, -2.148245271118002E-8d, }, // 675 - {+0.5069117546081543d, -3.016329994276181E-8d, }, // 676 - {+0.5074998140335083d, -2.7237099632871992E-8d, }, // 677 - {+0.5080875158309937d, -1.2297127301923986E-8d, }, // 678 - {+0.5086748600006104d, +1.5062624834468093E-8d, }, // 679 - {+0.5092618465423584d, +5.524744954836658E-8d, }, // 680 - {+0.5098485946655273d, -1.054736327333046E-8d, }, // 681 - {+0.5104348659515381d, +5.650063324725722E-8d, }, // 682 - {+0.5110208988189697d, +1.8376017791642605E-8d, }, // 683 - {+0.5116065740585327d, -5.309470636324855E-9d, }, // 684 - {+0.512191891670227d, -1.4154089255217218E-8d, }, // 685 - {+0.5127768516540527d, -7.756800301729815E-9d, }, // 686 - {+0.5133614540100098d, +1.4282730618002001E-8d, }, // 687 - {+0.5139456987380981d, +5.2364136172269755E-8d, }, // 688 - {+0.5145297050476074d, -1.2322940607922115E-8d, }, // 689 - {+0.5151132345199585d, +5.903831350855322E-8d, }, // 690 - {+0.5156965255737305d, +2.8426856726994483E-8d, }, // 691 - {+0.5162794589996338d, +1.544882070711032E-8d, }, // 692 - {+0.5168620347976685d, +2.0500353979930155E-8d, }, // 693 - {+0.5174442529678345d, +4.397691311390564E-8d, }, // 694 - {+0.5180262327194214d, -3.2936025225250634E-8d, }, // 695 - {+0.5186077356338501d, +2.857419553449673E-8d, }, // 696 - {+0.5191890001296997d, -9.51761338269325E-9d, }, // 697 - {+0.5197699069976807d, -2.7609457648450225E-8d, }, // 698 - {+0.520350456237793d, -2.5309316441333305E-8d, }, // 699 - {+0.5209306478500366d, -2.2258513086839407E-9d, }, // 700 - {+0.5215104818344116d, +4.203159541613745E-8d, }, // 701 - {+0.5220900774002075d, -1.1356287358852729E-8d, }, // 702 - {+0.5226693153381348d, -4.279090925831093E-8d, }, // 703 - {+0.5232481956481934d, -5.188364552285819E-8d, }, // 704 - {+0.5238267183303833d, -3.82465458937857E-8d, }, // 705 - {+0.5244048833847046d, -1.4923330530645769E-9d, }, // 706 - {+0.5249826908111572d, +5.8765598932137004E-8d, }, // 707 - {+0.5255602598190308d, +2.3703896609663678E-8d, }, // 708 - {+0.5261374711990356d, +1.2917117341231647E-8d, }, // 709 - {+0.5267143249511719d, +2.6789862192139226E-8d, }, // 710 - {+0.527290940284729d, -5.350322253112414E-8d, }, // 711 - {+0.5278670787811279d, +1.0839714455426386E-8d, }, // 712 - {+0.5284429788589478d, -1.821729591343314E-8d, }, // 713 - {+0.5290185213088989d, -2.1083014672301448E-8d, }, // 714 - {+0.5295937061309814d, +2.623848491704216E-9d, }, // 715 - {+0.5301685333251953d, +5.328392630534142E-8d, }, // 716 - {+0.5307431221008301d, +1.206790586971942E-8d, }, // 717 - {+0.5313173532485962d, -1.4356011804377797E-9d, }, // 718 - {+0.5318912267684937d, +1.3152074173459994E-8d, }, // 719 - {+0.5324647426605225d, +5.6208949382936426E-8d, }, // 720 - {+0.5330380201339722d, +8.90310227565917E-9d, }, // 721 - {+0.5336109399795532d, -9.179458802504127E-9d, }, // 722 - {+0.5341835021972656d, +2.337337845617735E-9d, }, // 723 - {+0.5347557067871094d, +4.3828918300477925E-8d, }, // 724 - {+0.535327672958374d, -3.5392250480081715E-9d, }, // 725 - {+0.53589928150177d, -2.0183663375378704E-8d, }, // 726 - {+0.5364705324172974d, -5.730898606435436E-9d, }, // 727 - {+0.537041425704956d, +4.0191927599879235E-8d, }, // 728 - {+0.5376120805740356d, -1.2522542401353875E-9d, }, // 729 - {+0.5381823778152466d, -1.0482571326594316E-8d, }, // 730 - {+0.5387523174285889d, +1.2871924223480165E-8d, }, // 731 - {+0.539322018623352d, -5.002774317612589E-8d, }, // 732 - {+0.539891242980957d, +3.960668706590162E-8d, }, // 733 - {+0.5404602289199829d, +4.372568630242375E-8d, }, // 734 - {+0.5410289764404297d, -3.730232461206926E-8d, }, // 735 - {+0.5415972471237183d, +3.5309026109857795E-8d, }, // 736 - {+0.5421652793884277d, +2.3508325311148225E-8d, }, // 737 - {+0.5427329540252686d, +4.6871403168921666E-8d, }, // 738 - {+0.5433003902435303d, -1.3445113140270216E-8d, }, // 739 - {+0.5438674688339233d, -3.786663982218041E-8d, }, // 740 - {+0.5444341897964478d, -2.602850370608209E-8d, }, // 741 - {+0.5450005531311035d, +2.2433348713144506E-8d, }, // 742 - {+0.5455666780471802d, -1.1326936872620137E-8d, }, // 743 - {+0.5461324453353882d, -7.737252533211342E-9d, }, // 744 - {+0.5466978549957275d, +3.3564604642699844E-8d, }, // 745 - {+0.5472630262374878d, -6.269066061111782E-9d, }, // 746 - {+0.5478278398513794d, -7.667998948729528E-9d, }, // 747 - {+0.5483922958374023d, +2.9728170818998143E-8d, }, // 748 - {+0.5489565134048462d, -1.2930091396008281E-8d, }, // 749 - {+0.5495203733444214d, -1.607434968107079E-8d, }, // 750 - {+0.5500838756561279d, +2.0653935146671156E-8d, }, // 751 - {+0.5506471395492554d, -2.1596593091833788E-8d, }, // 752 - {+0.5512100458145142d, -2.3259315921149476E-8d, }, // 753 - {+0.5517725944519043d, +1.6022492496522704E-8d, }, // 754 - {+0.5523349046707153d, -2.260433328226171E-8d, }, // 755 - {+0.5528968572616577d, -1.957497997726303E-8d, }, // 756 - {+0.5534584522247314d, +2.5465477111883854E-8d, }, // 757 - {+0.5540198087692261d, -6.33792454933092E-9d, }, // 758 - {+0.554580807685852d, +4.577835263278281E-9d, }, // 759 - {+0.5551414489746094d, +5.856589221771548E-8d, }, // 760 - {+0.5557018518447876d, +3.6769498759522324E-8d, }, // 761 - {+0.5562618970870972d, +5.874989409410614E-8d, }, // 762 - {+0.5568217039108276d, +5.649147309876989E-9d, }, // 763 - {+0.5573811531066895d, -2.9726830960751796E-9d, }, // 764 - {+0.5579402446746826d, +3.323458344853057E-8d, }, // 765 - {+0.5584990978240967d, -4.588749093664028E-9d, }, // 766 - {+0.5590575933456421d, +3.115616594184543E-9d, }, // 767 - {+0.5596157312393188d, +5.6696103838614634E-8d, }, // 768 - {+0.5601736307144165d, +3.7291263280048303E-8d, }, // 769 - {+0.5607312917709351d, -5.4751646725093355E-8d, }, // 770 - {+0.5612884759902954d, +1.9332630743320287E-8d, }, // 771 - {+0.5618454217910767d, +2.147161515775941E-8d, }, // 772 - {+0.5624021291732788d, -4.7989172862560625E-8d, }, // 773 - {+0.5629583597183228d, +4.971378973445109E-8d, }, // 774 - {+0.5635144710540771d, -4.2702997139152675E-8d, }, // 775 - {+0.5640701055526733d, +3.273212962622764E-8d, }, // 776 - {+0.5646255016326904d, +3.79438125545842E-8d, }, // 777 - {+0.5651806592941284d, -2.6725298288329835E-8d, }, // 778 - {+0.5657354593276978d, -4.1723833577410244E-8d, }, // 779 - {+0.5662899017333984d, -6.71028256490915E-9d, }, // 780 - {+0.56684410572052d, -4.055299181908475E-8d, }, // 781 - {+0.567397952079773d, -2.3702295314000405E-8d, }, // 782 - {+0.5679514408111572d, +4.4181618172507453E-8d, }, // 783 - {+0.5685046911239624d, +4.4228706309734985E-8d, }, // 784 - {+0.5690577030181885d, -2.3222346436879016E-8d, }, // 785 - {+0.5696103572845459d, -3.862412756175274E-8d, }, // 786 - {+0.5701626539230347d, -1.6390743801589046E-9d, }, // 787 - {+0.5707147121429443d, -3.1139472791083883E-8d, }, // 788 - {+0.5712664127349854d, -7.579587391156013E-9d, }, // 789 - {+0.5718178749084473d, -4.983281844744412E-8d, }, // 790 - {+0.5723689794540405d, -3.835454246739619E-8d, }, // 791 - {+0.5729197263717651d, +2.7190020372374008E-8d, }, // 792 - {+0.5734702348709106d, +2.7925807446276126E-8d, }, // 793 - {+0.574020504951477d, -3.5813506001861646E-8d, }, // 794 - {+0.5745704174041748d, -4.448550564530588E-8d, }, // 795 - {+0.5751199722290039d, +2.2423840341717488E-9d, }, // 796 - {+0.5756692886352539d, -1.450709904687712E-8d, }, // 797 - {+0.5762182474136353d, +2.4806815282282017E-8d, }, // 798 - {+0.5767669677734375d, +1.3057724436551892E-9d, }, // 799 - {+0.5773153305053711d, +3.4529452510568104E-8d, }, // 800 - {+0.5778634548187256d, +5.598413198183808E-9d, }, // 801 - {+0.5784112215042114d, +3.405124925700107E-8d, }, // 802 - {+0.5789587497711182d, +1.0074354568442952E-9d, }, // 803 - {+0.5795059204101562d, +2.600448597385527E-8d, }, // 804 - {+0.5800528526306152d, -9.83920263200211E-9d, }, // 805 - {+0.5805994272232056d, +1.3012807963586057E-8d, }, // 806 - {+0.5811457633972168d, -2.432215917965441E-8d, }, // 807 - {+0.5816917419433594d, -2.308736892479391E-9d, }, // 808 - {+0.5822374820709229d, -3.983067093146514E-8d, }, // 809 - {+0.5827828645706177d, -1.735366061128156E-8d, }, // 810 - {+0.5833280086517334d, -5.376251584638963E-8d, }, // 811 - {+0.5838727951049805d, -2.952399778965259E-8d, }, // 812 - {+0.5844172239303589d, +5.5685313670430624E-8d, }, // 813 - {+0.5849615335464478d, -3.6230268489088716E-8d, }, // 814 - {+0.5855053663253784d, +5.267948957869391E-8d, }, // 815 - {+0.5860490798950195d, -3.489144132234588E-8d, }, // 816 - {+0.5865923166275024d, +5.9006122320612716E-8d, }, // 817 - {+0.5871354341506958d, -2.2934896740542648E-8d, }, // 818 - {+0.5876781940460205d, -4.1975650319859075E-8d, }, // 819 - {+0.5882205963134766d, +2.2036094805348692E-9d, }, // 820 - {+0.5887627601623535d, -9.287179048539306E-9d, }, // 821 - {+0.5893045663833618d, +4.3079982556221595E-8d, }, // 822 - {+0.589846134185791d, +4.041399585161321E-8d, }, // 823 - {+0.5903874635696411d, -1.696746473863933E-8d, }, // 824 - {+0.5909284353256226d, -9.53795080582038E-9d, }, // 825 - {+0.5914691686630249d, -5.619010749352923E-8d, }, // 826 - {+0.5920095443725586d, -3.7398514182529506E-8d, }, // 827 - {+0.5925495624542236d, +4.71524479659295E-8d, }, // 828 - {+0.5930894613265991d, -4.0640692434639215E-8d, }, // 829 - {+0.5936288833618164d, +5.716453096255401E-8d, }, // 830 - {+0.5941681861877441d, -1.6745661720946737E-8d, }, // 831 - {+0.5947071313858032d, -2.3639110433141897E-8d, }, // 832 - {+0.5952457189559937d, +3.67972590471072E-8d, }, // 833 - {+0.595784068107605d, +4.566672575206695E-8d, }, // 834 - {+0.5963221788406372d, +3.2813537149653483E-9d, }, // 835 - {+0.5968599319458008d, +2.916199305533732E-8d, }, // 836 - {+0.5973974466323853d, +4.410412409109416E-9d, }, // 837 - {+0.5979346036911011d, +4.85464582112459E-8d, }, // 838 - {+0.5984715223312378d, +4.267089756924666E-8d, }, // 839 - {+0.5990082025527954d, -1.2906712010774655E-8d, }, // 840 - {+0.5995445251464844d, +1.3319784467641742E-9d, }, // 841 - {+0.6000806093215942d, -3.35137581974451E-8d, }, // 842 - {+0.6006163358688354d, +2.0734340706476473E-9d, }, // 843 - {+0.6011518239974976d, -1.0808162722402073E-8d, }, // 844 - {+0.601686954498291d, +4.735781872502109E-8d, }, // 845 - {+0.6022218465805054d, +5.76686738430634E-8d, }, // 846 - {+0.6027565002441406d, +2.043049589651736E-8d, }, // 847 - {+0.6032907962799072d, +5.515817703577808E-8d, }, // 848 - {+0.6038248538970947d, +4.2947540692649586E-8d, }, // 849 - {+0.6043586730957031d, -1.589678872195875E-8d, }, // 850 - {+0.6048921346664429d, -1.8613847754677912E-9d, }, // 851 - {+0.6054253578186035d, -3.3851886626187444E-8d, }, // 852 - {+0.6059582233428955d, +7.64416021682279E-9d, }, // 853 - {+0.6064908504486084d, +3.7201467248814224E-9d, }, // 854 - {+0.6070232391357422d, -4.532172996647129E-8d, }, // 855 - {+0.6075552701950073d, -1.997046552871766E-8d, }, // 856 - {+0.6080870628356934d, -3.913411606668587E-8d, }, // 857 - {+0.6086184978485107d, +1.6697361107868944E-8d, }, // 858 - {+0.609149694442749d, +2.8614950293715483E-8d, }, // 859 - {+0.6096806526184082d, -3.081552929643174E-9d, }, // 860 - {+0.6102112531661987d, +4.111645931319645E-8d, }, // 861 - {+0.6107416152954102d, +4.2298539553668435E-8d, }, // 862 - {+0.6112717390060425d, +7.630546413718035E-10d, }, // 863 - {+0.6118015050888062d, +3.601718675118614E-8d, }, // 864 - {+0.6123310327529907d, +2.914906573537692E-8d, }, // 865 - {+0.6128603219985962d, -1.9544361222269494E-8d, }, // 866 - {+0.613389253616333d, +9.442671392695732E-9d, }, // 867 - {+0.6139179468154907d, -2.8031202304593286E-9d, }, // 868 - {+0.6144464015960693d, -5.598619958143586E-8d, }, // 869 - {+0.6149744987487793d, -3.060220883766096E-8d, }, // 870 - {+0.6155023574829102d, -4.556583652800433E-8d, }, // 871 - {+0.6160298585891724d, +1.8626341656366314E-8d, }, // 872 - {+0.6165571212768555d, +4.305870564227991E-8d, }, // 873 - {+0.6170841455459595d, +2.8024460607734262E-8d, }, // 874 - {+0.6176109313964844d, -2.6183651590639875E-8d, }, // 875 - {+0.6181373596191406d, -6.406189112730307E-11d, }, // 876 - {+0.6186635494232178d, -1.2534241706168776E-8d, }, // 877 - {+0.6191893815994263d, +5.5906456251308664E-8d, }, // 878 - {+0.6197150945663452d, -3.286964881802063E-8d, }, // 879 - {+0.6202404499053955d, -4.0153537978961E-8d, }, // 880 - {+0.6207654476165771d, +3.434477109643361E-8d, }, // 881 - {+0.6212903261184692d, -4.750377491075032E-8d, }, // 882 - {+0.6218148469924927d, -4.699152670372743E-8d, }, // 883 - {+0.6223390102386475d, +3.617013128065961E-8d, }, // 884 - {+0.6228630542755127d, -3.6149218175202596E-8d, }, // 885 - {+0.6233867406845093d, -2.5243286814648133E-8d, }, // 886 - {+0.6239101886749268d, -5.003410681432538E-8d, }, // 887 - {+0.6244332790374756d, +8.974417915105033E-9d, }, // 888 - {+0.6249561309814453d, +3.285935446876949E-8d, }, // 889 - {+0.6254787445068359d, +2.190661054038537E-8d, }, // 890 - {+0.6260011196136475d, -2.3598354190515998E-8d, }, // 891 - {+0.6265231370925903d, +1.5838762427747586E-8d, }, // 892 - {+0.6270449161529541d, +2.129323729978037E-8d, }, // 893 - {+0.6275664567947388d, -6.950808333865794E-9d, }, // 894 - {+0.6280876398086548d, +5.059959203156465E-8d, }, // 895 - {+0.6286087036132812d, -4.41909071122557E-8d, }, // 896 - {+0.6291294097900391d, -5.262093550784066E-8d, }, // 897 - {+0.6296497583389282d, +2.559185648444699E-8d, }, // 898 - {+0.6301699876785278d, -4.768920119497491E-8d, }, // 899 - {+0.6306898593902588d, -3.376406008397877E-8d, }, // 900 - {+0.6312094926834106d, -5.156097914033476E-8d, }, // 901 - {+0.6317287683486938d, +1.840992392368355E-8d, }, // 902 - {+0.632247805595398d, +5.721951534729663E-8d, }, // 903 - {+0.6327667236328125d, -5.406177467045421E-8d, }, // 904 - {+0.6332851648330688d, +4.247320713683124E-8d, }, // 905 - {+0.6338034868240356d, -1.0524557502830645E-8d, }, // 906 - {+0.6343214511871338d, +2.5641927558519502E-8d, }, // 907 - {+0.6348391771316528d, +3.204135737993823E-8d, }, // 908 - {+0.6353566646575928d, +8.951285029786536E-9d, }, // 909 - {+0.6358739137649536d, -4.335116707228395E-8d, }, // 910 - {+0.6363908052444458d, -5.380016714089483E-9d, }, // 911 - {+0.6369074583053589d, +3.931710344901743E-9d, }, // 912 - {+0.6374238729476929d, -1.5140150088220166E-8d, }, // 913 - {+0.6379399299621582d, +5.688910024377372E-8d, }, // 914 - {+0.638455867767334d, -1.8124135273572568E-8d, }, // 915 - {+0.6389714479446411d, -1.486720391901626E-9d, }, // 916 - {+0.6394867897033691d, -1.2133811978747018E-8d, }, // 917 - {+0.6400018930435181d, -4.9791700939901716E-8d, }, // 918 - {+0.6405166387557983d, +5.022188652837274E-9d, }, // 919 - {+0.6410311460494995d, +3.337143177933685E-8d, }, // 920 - {+0.6415454149246216d, +3.55284719912458E-8d, }, // 921 - {+0.6420594453811646d, +1.1765332726757802E-8d, }, // 922 - {+0.6425732374191284d, -3.7646381826067834E-8d, }, // 923 - {+0.6430866718292236d, +6.773803682579552E-9d, }, // 924 - {+0.6435998678207397d, +2.608736797081283E-8d, }, // 925 - {+0.6441128253936768d, +2.056466263408266E-8d, }, // 926 - {+0.6446255445480347d, -9.524376551107945E-9d, }, // 927 - {+0.6451379060745239d, +5.5299060775883977E-8d, }, // 928 - {+0.6456501483917236d, -2.3114497793159813E-8d, }, // 929 - {+0.6461620330810547d, -6.077779731902102E-9d, }, // 930 - {+0.6466736793518066d, -1.2531793589140273E-8d, }, // 931 - {+0.6471850872039795d, -4.220866994206517E-8d, }, // 932 - {+0.6476961374282837d, +2.4368339445199057E-8d, }, // 933 - {+0.6482070684432983d, -5.095229574221907E-8d, }, // 934 - {+0.6487176418304443d, -2.9485356677301627E-8d, }, // 935 - {+0.6492279767990112d, -3.0173901411577916E-8d, }, // 936 - {+0.649738073348999d, -5.275210583909726E-8d, }, // 937 - {+0.6502478122711182d, +2.2254737134350224E-8d, }, // 938 - {+0.6507574319839478d, -4.330693978322885E-8d, }, // 939 - {+0.6512666940689087d, -1.0753950588009912E-8d, }, // 940 - {+0.6517757177352905d, +9.686179886293545E-10d, }, // 941 - {+0.6522845029830933d, -7.875434494414498E-9d, }, // 942 - {+0.6527930498123169d, -3.702271091849158E-8d, }, // 943 - {+0.6533012390136719d, +3.2999073763758614E-8d, }, // 944 - {+0.6538093090057373d, -3.5966064858620067E-8d, }, // 945 - {+0.6543170213699341d, -5.23735298540578E-9d, }, // 946 - {+0.6548244953155518d, +6.237715351293023E-9d, }, // 947 - {+0.6553317308425903d, -1.279462699936282E-9d, }, // 948 - {+0.6558387279510498d, -2.7527887552743672E-8d, }, // 949 - {+0.6563453674316406d, +4.696233317356646E-8d, }, // 950 - {+0.6568518877029419d, -1.5967172745329108E-8d, }, // 951 - {+0.6573580503463745d, +2.2361985518423144E-8d, }, // 952 - {+0.657863974571228d, +4.2999935789083046E-8d, }, // 953 - {+0.6583696603775024d, +4.620570188811826E-8d, }, // 954 - {+0.6588751077651978d, +3.223791487908353E-8d, }, // 955 - {+0.659380316734314d, +1.3548138612715822E-9d, }, // 956 - {+0.6598852872848511d, -4.618575323863973E-8d, }, // 957 - {+0.6603899002075195d, +9.082960673843353E-9d, }, // 958 - {+0.6608942747116089d, +4.820873399634487E-8d, }, // 959 - {+0.6613985300064087d, -4.776104368314602E-8d, }, // 960 - {+0.6619024276733398d, -4.0151502150238136E-8d, }, // 961 - {+0.6624060869216919d, -4.791602708710648E-8d, }, // 962 - {+0.6629093885421753d, +4.8410188461165925E-8d, }, // 963 - {+0.6634125709533691d, +1.0663697110471944E-8d, }, // 964 - {+0.6639155149459839d, -4.1691464781797555E-8d, }, // 965 - {+0.66441810131073d, +1.080835500478704E-8d, }, // 966 - {+0.664920449256897d, +4.920784622407246E-8d, }, // 967 - {+0.6654226779937744d, -4.544868396511241E-8d, }, // 968 - {+0.6659245491027832d, -3.448944157854234E-8d, }, // 969 - {+0.6664261817932129d, -3.6870882345139385E-8d, }, // 970 - {+0.6669275760650635d, -5.234055273962444E-8d, }, // 971 - {+0.6674286127090454d, +3.856291077979099E-8d, }, // 972 - {+0.6679295301437378d, -2.327375671320742E-9d, }, // 973 - {+0.6684302091598511d, -5.555080534042001E-8d, }, // 974 - {+0.6689305305480957d, -1.6471487337453832E-9d, }, // 975 - {+0.6694306135177612d, +4.042486803683015E-8d, }, // 976 - {+0.6699305772781372d, -4.8293856891818295E-8d, }, // 977 - {+0.6704301834106445d, -2.9134931730784303E-8d, }, // 978 - {+0.6709295511245728d, -2.1058207594753368E-8d, }, // 979 - {+0.6714286804199219d, -2.3814619551682855E-8d, }, // 980 - {+0.6719275712966919d, -3.7155475428252136E-8d, }, // 981 - {+0.6724261045455933d, +5.8376834484391746E-8d, }, // 982 - {+0.6729245185852051d, +2.4611679969129262E-8d, }, // 983 - {+0.6734226942062378d, -1.899407107267079E-8d, }, // 984 - {+0.6739205121994019d, +4.7016079464436395E-8d, }, // 985 - {+0.6744182109832764d, -1.5529608026276525E-8d, }, // 986 - {+0.6749155521392822d, +3.203391672602453E-8d, }, // 987 - {+0.6754127740859985d, -4.8465821804075345E-8d, }, // 988 - {+0.6759096384048462d, -1.8364507801369988E-8d, }, // 989 - {+0.6764062643051147d, +3.3739397633046517E-9d, }, // 990 - {+0.6769026517868042d, +1.6994526063192333E-8d, }, // 991 - {+0.6773988008499146d, +2.2741891590028428E-8d, }, // 992 - {+0.6778947114944458d, +2.0860312877435047E-8d, }, // 993 - {+0.678390383720398d, +1.1593703222523284E-8d, }, // 994 - {+0.678885817527771d, -4.814386594291911E-9d, }, // 995 - {+0.6793810129165649d, -2.812076759125914E-8d, }, // 996 - {+0.6798759698867798d, -5.808261186903479E-8d, }, // 997 - {+0.680370569229126d, +2.4751837654582522E-8d, }, // 998 - {+0.6808650493621826d, -1.7793890245755405E-8d, }, // 999 - {+0.6813591718673706d, +5.294053246347931E-8d, }, // 1000 - {+0.681853175163269d, -1.2220826223585654E-9d, }, // 1001 - {+0.6823468208312988d, +5.8377876767612725E-8d, }, // 1002 - {+0.6828403472900391d, -6.437492120743254E-9d, }, // 1003 - {+0.6833335161209106d, +4.2990710043633113E-8d, }, // 1004 - {+0.6838265657424927d, -3.1516131027023284E-8d, }, // 1005 - {+0.684319257736206d, +8.70017386744679E-9d, }, // 1006 - {+0.6848117113113403d, +4.466959125843237E-8d, }, // 1007 - {+0.6853040456771851d, -4.25782656420497E-8d, }, // 1008 - {+0.6857960224151611d, -1.4386267593671393E-8d, }, // 1009 - {+0.6862877607345581d, +1.0274494061148778E-8d, }, // 1010 - {+0.686779260635376d, +3.164186629229597E-8d, }, // 1011 - {+0.6872705221176147d, +4.995334552140326E-8d, }, // 1012 - {+0.687761664390564d, -5.3763211240398744E-8d, }, // 1013 - {+0.6882524490356445d, -4.0852427502515625E-8d, }, // 1014 - {+0.688742995262146d, -3.0287143914420064E-8d, }, // 1015 - {+0.6892333030700684d, -2.183125937905008E-8d, }, // 1016 - {+0.6897233724594116d, -1.524901992178814E-8d, }, // 1017 - {+0.6902132034301758d, -1.0305018010328949E-8d, }, // 1018 - {+0.6907027959823608d, -6.764191876212205E-9d, }, // 1019 - {+0.6911921501159668d, -4.391824838015402E-9d, }, // 1020 - {+0.6916812658309937d, -2.9535446262017846E-9d, }, // 1021 - {+0.6921701431274414d, -2.2153227096187463E-9d, }, // 1022 - {+0.6926587820053101d, -1.943473623641502E-9d, }, // 1023 - }; - - - /** - * Class contains only static methods. - */ - private FastMathLiteralArrays() {} - - /** - * Load "EXP_INT_A". - * - * @return a clone of the data array. - */ - static double[] loadExpIntA() { - return EXP_INT_A.clone(); - } - /** - * Load "EXP_INT_B". - * - * @return a clone of the data array. - */ - static double[] loadExpIntB() { - return EXP_INT_B.clone(); - } - /** - * Load "EXP_FRAC_A". - * - * @return a clone of the data array. - */ - static double[] loadExpFracA() { - return EXP_FRAC_A.clone(); - } - /** - * Load "EXP_FRAC_B". - * - * @return a clone of the data array. - */ - static double[] loadExpFracB() { - return EXP_FRAC_B.clone(); - } - /** - * Load "LN_MANT". - * - * @return a clone of the data array. - */ - static double[][] loadLnMant() { - return LN_MANT.clone(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/Incrementor.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/Incrementor.java deleted file mode 100644 index 0898ec504..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/Incrementor.java +++ /dev/null @@ -1,183 +0,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. - */ -package org.apache.commons.math4.util; - -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NullArgumentException; - -/** - * Utility that increments a counter until a maximum is reached, at - * which point, the instance will by default throw a - * {@link MaxCountExceededException}. - * However, the user is able to override this behaviour by defining a - * custom {@link MaxCountExceededCallback callback}, in order to e.g. - * select which exception must be thrown. - * - * @since 3.0 - * - * @deprecated Use {@link IntegerSequence.Incrementor} instead. - */ -@Deprecated -public class Incrementor { - /** - * Upper limit for the counter. - */ - private int maximalCount; - /** - * Current count. - */ - private int count = 0; - /** - * Function called at counter exhaustion. - */ - private final MaxCountExceededCallback maxCountCallback; - - /** - * Default constructor. - * For the new instance to be useful, the maximal count must be set - * by calling {@link #setMaximalCount(int) setMaximalCount}. - */ - public Incrementor() { - this(0); - } - - /** - * Defines a maximal count. - * - * @param max Maximal count. - */ - public Incrementor(int max) { - this(max, - new MaxCountExceededCallback() { - /** {@inheritDoc} */ - @Override - public void trigger(int max) throws MaxCountExceededException { - throw new MaxCountExceededException(max); - } - }); - } - - /** - * Defines a maximal count and a callback method to be triggered at - * counter exhaustion. - * - * @param max Maximal count. - * @param cb Function to be called when the maximal count has been reached. - * @throws NullArgumentException if {@code cb} is {@code null} - */ - public Incrementor(int max, MaxCountExceededCallback cb) - throws NullArgumentException { - if (cb == null){ - throw new NullArgumentException(); - } - maximalCount = max; - maxCountCallback = cb; - } - - /** - * Sets the upper limit for the counter. - * This does not automatically reset the current count to zero (see - * {@link #resetCount()}). - * - * @param max Upper limit of the counter. - */ - public void setMaximalCount(int max) { - maximalCount = max; - } - - /** - * Gets the upper limit of the counter. - * - * @return the counter upper limit. - */ - public int getMaximalCount() { - return maximalCount; - } - - /** - * Gets the current count. - * - * @return the current count. - */ - public int getCount() { - return count; - } - - /** - * Checks whether a single increment is allowed. - * - * @return {@code false} if the next call to {@link #incrementCount(int) - * incrementCount} will trigger a {@code MaxCountExceededException}, - * {@code true} otherwise. - */ - public boolean canIncrement() { - return count < maximalCount; - } - - /** - * Performs multiple increments. - * See the other {@link #incrementCount() incrementCount} method). - * - * @param value Number of increments. - * @throws MaxCountExceededException at counter exhaustion. - */ - public void incrementCount(int value) throws MaxCountExceededException { - for (int i = 0; i < value; i++) { - incrementCount(); - } - } - - /** - * Adds one to the current iteration count. - * At counter exhaustion, this method will call the - * {@link MaxCountExceededCallback#trigger(int) trigger} method of the - * callback object passed to the - * {@link #Incrementor(int,MaxCountExceededCallback) constructor}. - * If not explictly set, a default callback is used that will throw - * a {@code MaxCountExceededException}. - * - * @throws MaxCountExceededException at counter exhaustion, unless a - * custom {@link MaxCountExceededCallback callback} has been set at - * construction. - */ - public void incrementCount() throws MaxCountExceededException { - if (++count > maximalCount) { - maxCountCallback.trigger(maximalCount); - } - } - - /** - * Resets the counter to 0. - */ - public void resetCount() { - count = 0; - } - - /** - * Defines a method to be called at counter exhaustion. - * The {@link #trigger(int) trigger} method should usually throw an exception. - */ - public interface MaxCountExceededCallback { - /** - * Function called when the maximal count has been reached. - * - * @param maximalCount Maximal count. - * @throws MaxCountExceededException at counter exhaustion - */ - void trigger(int maximalCount) throws MaxCountExceededException; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/IntegerSequence.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/IntegerSequence.java deleted file mode 100644 index b4db78cda..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/IntegerSequence.java +++ /dev/null @@ -1,376 +0,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. - */ -package org.apache.commons.math4.util; - -import java.util.Iterator; -import java.util.NoSuchElementException; -import org.apache.commons.math4.exception.MaxCountExceededException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.MathUnsupportedOperationException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.ZeroException; - -/** - * Provides a sequence of integers. - * - * @since 3.6 - */ -public class IntegerSequence { - /** - * Utility class contains only static methods. - */ - private IntegerSequence() {} - - /** - * Creates a sequence {@code [start .. end]}. - * It calls {@link #range(int,int,int) range(start, end, 1)}. - * - * @param start First value of the range. - * @param end Last value of the range. - * @return a range. - */ - public static Range range(int start, - int end) { - return range(start, end, 1); - } - - /** - * Creates a sequence ai, i < 0 < n - * where ai = start + i * step - * and {@code n} is such that an <= max - * and an+1 > max. - * - * @param start First value of the range. - * @param max Last value of the range that satisfies the above - * construction rule. - * @param step Increment. - * @return a range. - */ - public static Range range(final int start, - final int max, - final int step) { - return new Range(start, max, step); - } - - /** - * Generates a sequence of integers. - */ - public static class Range implements Iterable { - /** Number of integers contained in this range. */ - private final int size; - /** First value. */ - private final int start; - /** Final value. */ - private final int max; - /** Increment. */ - private final int step; - - /** - * Creates a sequence ai, i < 0 < n - * where ai = start + i * step - * and {@code n} is such that an <= max - * and an+1 > max. - * - * @param start First value of the range. - * @param max Last value of the range that satisfies the above - * construction rule. - * @param step Increment. - */ - public Range(int start, - int max, - int step) { - this.start = start; - this.max = max; - this.step = step; - - final int s = (max - start) / step + 1; - this.size = s < 0 ? 0 : s; - } - - /** - * Gets the number of elements contained in the range. - * - * @return the size of the range. - */ - public int size() { - return size; - } - - /** {@inheritDoc} */ - @Override - public Iterator iterator() { - return Incrementor.create() - .withStart(start) - .withMaximalCount(max + (step > 0 ? 1 : -1)) - .withIncrement(step); - } - } - - /** - * Utility that increments a counter until a maximum is reached, at - * which point, the instance will by default throw a - * {@link MaxCountExceededException}. - * However, the user is able to override this behaviour by defining a - * custom {@link MaxCountExceededCallback callback}, in order to e.g. - * select which exception must be thrown. - */ - public static class Incrementor implements Iterator { - /** Default callback. */ - private static final MaxCountExceededCallback CALLBACK - = new MaxCountExceededCallback() { - /** {@inheritDoc} */ - @Override - public void trigger(int max) throws MaxCountExceededException { - throw new MaxCountExceededException(max); - } - }; - - /** Initial value the counter. */ - private final int init; - /** Upper limit for the counter. */ - private final int maximalCount; - /** Increment. */ - private final int increment; - /** Function called at counter exhaustion. */ - private final MaxCountExceededCallback maxCountCallback; - /** Current count. */ - private int count = 0; - - /** - * Defines a method to be called at counter exhaustion. - * The {@link #trigger(int) trigger} method should usually throw an exception. - */ - public interface MaxCountExceededCallback { - /** - * Function called when the maximal count has been reached. - * - * @param maximalCount Maximal count. - * @throws MaxCountExceededException at counter exhaustion - */ - void trigger(int maximalCount) throws MaxCountExceededException; - } - - /** - * Creates an incrementor. - * The counter will be exhausted either when {@code max} is reached - * or when {@code nTimes} increments have been performed. - * - * @param start Initial value. - * @param max Maximal count. - * @param step Increment. - * @param cb Function to be called when the maximal count has been reached. - * @throws NullArgumentException if {@code cb} is {@code null}. - */ - private Incrementor(int start, - int max, - int step, - MaxCountExceededCallback cb) - throws NullArgumentException { - if (cb == null) { - throw new NullArgumentException(); - } - this.init = start; - this.maximalCount = max; - this.increment = step; - this.maxCountCallback = cb; - this.count = start; - } - - /** - * Factory method that creates a default instance. - * The initial and maximal values are set to 0. - * For the new instance to be useful, the maximal count must be set - * by calling {@link #withMaximalCount(int) withMaximalCount}. - * - * @return an new instance. - */ - public static Incrementor create() { - return new Incrementor(0, 0, 1, CALLBACK); - } - - /** - * Creates a new instance with a given initial value. - * The counter is reset to the initial value. - * - * @param start Initial value of the counter. - * @return a new instance. - */ - public Incrementor withStart(int start) { - return new Incrementor(start, - this.maximalCount, - this.increment, - this.maxCountCallback); - } - - /** - * Creates a new instance with a given maximal count. - * The counter is reset to the initial value. - * - * @param max Maximal count. - * @return a new instance. - */ - public Incrementor withMaximalCount(int max) { - return new Incrementor(this.init, - max, - this.increment, - this.maxCountCallback); - } - - /** - * Creates a new instance with a given increment. - * The counter is reset to the initial value. - * - * @param step Increment. - * @return a new instance. - */ - public Incrementor withIncrement(int step) { - if (step == 0) { - throw new ZeroException(); - } - return new Incrementor(this.init, - this.maximalCount, - step, - this.maxCountCallback); - } - - /** - * Creates a new instance with a given callback. - * The counter is reset to the initial value. - * - * @param cb Callback to be called at counter exhaustion. - * @return a new instance. - */ - public Incrementor withCallback(MaxCountExceededCallback cb) { - return new Incrementor(this.init, - this.maximalCount, - this.increment, - cb); - } - - /** - * Gets the upper limit of the counter. - * - * @return the counter upper limit. - */ - public int getMaximalCount() { - return maximalCount; - } - - /** - * Gets the current count. - * - * @return the current count. - */ - public int getCount() { - return count; - } - - /** - * Checks whether incrementing the counter {@code nTimes} is allowed. - * - * @return {@code false} if calling {@link #increment()} - * will trigger a {@code MaxCountExceededException}, - * {@code true} otherwise. - */ - public boolean canIncrement() { - return canIncrement(1); - } - - /** - * Checks whether incrementing the counter several times is allowed. - * - * @param nTimes Number of increments. - * @return {@code false} if calling {@link #increment(int) - * increment(nTimes)} would call the {@link MaxCountExceededCallback callback} - * {@code true} otherwise. - */ - public boolean canIncrement(int nTimes) { - final int finalCount = count + nTimes * increment; - return increment < 0 ? - finalCount > maximalCount : - finalCount < maximalCount; - } - - /** - * Performs multiple increments. - * - * @param nTimes Number of increments. - * @throws MaxCountExceededException at counter exhaustion. - * @throws NotStrictlyPositiveException if {@code nTimes <= 0}. - * - * @see #increment() - */ - public void increment(int nTimes) throws MaxCountExceededException { - if (nTimes <= 0) { - throw new NotStrictlyPositiveException(nTimes); - } - - count += nTimes * increment; - - if (!canIncrement(0)) { - maxCountCallback.trigger(maximalCount); - } - } - - /** - * Adds the increment value to the current iteration count. - * At counter exhaustion, this method will call the - * {@link MaxCountExceededCallback#trigger(int) trigger} method of the - * callback object passed to the - * {@link #withCallback(MaxCountExceededCallback)} method. - * If not explictly set, a default callback is used that will throw - * a {@code MaxCountExceededException}. - * - * @throws MaxCountExceededException at counter exhaustion, unless a - * custom {@link MaxCountExceededCallback callback} has been set. - * - * @see #increment(int) - */ - public void increment() throws MaxCountExceededException { - increment(1); - } - - /** {@inheritDoc} */ - @Override - public boolean hasNext() { - return canIncrement(0); - } - - /** {@inheritDoc} */ - @Override - public Integer next() { - if (canIncrement(0)) { - final int value = count; - count += increment; - return value; - } else { - // Contract for "Iterator". - throw new NoSuchElementException(); - } - } - - /** - * Not applicable. - * - * @throws MathUnsupportedOperationException always - */ - @Override - public void remove() { - throw new MathUnsupportedOperationException(); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/IterationEvent.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/IterationEvent.java deleted file mode 100644 index 5e58b1755..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/IterationEvent.java +++ /dev/null @@ -1,55 +0,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. - */ -package org.apache.commons.math4.util; - -import java.util.EventObject; - -/** - * The root class from which all events occurring while running an - * {@link IterationManager} should be derived. - * - */ -public class IterationEvent extends EventObject { - /** */ - private static final long serialVersionUID = 20120128L; - - /** The number of iterations performed so far. */ - private final int iterations; - - /** - * Creates a new instance of this class. - * - * @param source the iterative algorithm on which the event initially - * occurred - * @param iterations the number of iterations performed at the time - * {@code this} event is created - */ - public IterationEvent(final Object source, final int iterations) { - super(source); - this.iterations = iterations; - } - - /** - * Returns the number of iterations performed at the time {@code this} event - * is created. - * - * @return the number of iterations performed - */ - public int getIterations() { - return iterations; - } - } diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/IterationListener.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/IterationListener.java deleted file mode 100644 index b6c115742..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/IterationListener.java +++ /dev/null @@ -1,57 +0,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. - */ -package org.apache.commons.math4.util; - -import java.util.EventListener; - -/** - * The listener interface for receiving events occurring in an iterative - * algorithm. - * - */ -public interface IterationListener extends EventListener { - /** - * Invoked after completion of the initial phase of the iterative algorithm - * (prior to the main iteration loop). - * - * @param e The {@link IterationEvent} object. - */ - void initializationPerformed(IterationEvent e); - - /** - * Invoked each time an iteration is completed (in the main iteration loop). - * - * @param e The {@link IterationEvent} object. - */ - void iterationPerformed(IterationEvent e); - - /** - * Invoked each time a new iteration is completed (in the main iteration - * loop). - * - * @param e The {@link IterationEvent} object. - */ - void iterationStarted(IterationEvent e); - - /** - * Invoked after completion of the operations which occur after breaking out - * of the main iteration loop. - * - * @param e The {@link IterationEvent} object. - */ - void terminationPerformed(IterationEvent e); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/IterationManager.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/IterationManager.java deleted file mode 100644 index 550bd2582..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/IterationManager.java +++ /dev/null @@ -1,172 +0,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. - */ -package org.apache.commons.math4.util; - -import java.util.Collection; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.apache.commons.math4.exception.MaxCountExceededException; - -/** - * This abstract class provides a general framework for managing iterative - * algorithms. The maximum number of iterations can be set, and methods are - * provided to monitor the current iteration count. A lightweight event - * framework is also provided. - * - */ -public class IterationManager { - - /** Keeps a count of the number of iterations. */ - private final Incrementor iterations; - - /** The collection of all listeners attached to this iterative algorithm. */ - private final Collection listeners; - - /** - * Creates a new instance of this class. - * - * @param maxIterations the maximum number of iterations - */ - public IterationManager(final int maxIterations) { - this.iterations = new Incrementor(maxIterations); - this.listeners = new CopyOnWriteArrayList<>(); - } - - /** - * Creates a new instance of this class. - * - * @param maxIterations the maximum number of iterations - * @param callBack the function to be called when the maximum number of - * iterations has been reached - * @throws org.apache.commons.math4.exception.NullArgumentException if {@code callBack} is {@code null} - * @since 3.1 - */ - public IterationManager(final int maxIterations, - final Incrementor.MaxCountExceededCallback callBack) { - this.iterations = new Incrementor(maxIterations, callBack); - this.listeners = new CopyOnWriteArrayList<>(); - } - - /** - * Attaches a listener to this manager. - * - * @param listener A {@code IterationListener} object. - */ - public void addIterationListener(final IterationListener listener) { - listeners.add(listener); - } - - /** - * Informs all registered listeners that the initial phase (prior to the - * main iteration loop) has been completed. - * - * @param e The {@link IterationEvent} object. - */ - public void fireInitializationEvent(final IterationEvent e) { - for (IterationListener l : listeners) { - l.initializationPerformed(e); - } - } - - /** - * Informs all registered listeners that a new iteration (in the main - * iteration loop) has been performed. - * - * @param e The {@link IterationEvent} object. - */ - public void fireIterationPerformedEvent(final IterationEvent e) { - for (IterationListener l : listeners) { - l.iterationPerformed(e); - } - } - - /** - * Informs all registered listeners that a new iteration (in the main - * iteration loop) has been started. - * - * @param e The {@link IterationEvent} object. - */ - public void fireIterationStartedEvent(final IterationEvent e) { - for (IterationListener l : listeners) { - l.iterationStarted(e); - } - } - - /** - * Informs all registered listeners that the final phase (post-iterations) - * has been completed. - * - * @param e The {@link IterationEvent} object. - */ - public void fireTerminationEvent(final IterationEvent e) { - for (IterationListener l : listeners) { - l.terminationPerformed(e); - } - } - - /** - * Returns the number of iterations of this solver, 0 if no iterations has - * been performed yet. - * - * @return the number of iterations. - */ - public int getIterations() { - return iterations.getCount(); - } - - /** - * Returns the maximum number of iterations. - * - * @return the maximum number of iterations. - */ - public int getMaxIterations() { - return iterations.getMaximalCount(); - } - - /** - * Increments the iteration count by one, and throws an exception if the - * maximum number of iterations is reached. This method should be called at - * the beginning of a new iteration. - * - * @throws MaxCountExceededException if the maximum number of iterations is - * reached. - */ - public void incrementIterationCount() - throws MaxCountExceededException { - iterations.incrementCount(); - } - - /** - * Removes the specified iteration listener from the list of listeners - * currently attached to {@code this} object. Attempting to remove a - * listener which was not previously registered does not cause any - * error. - * - * @param listener The {@link IterationListener} to be removed. - */ - public void removeIterationListener(final IterationListener listener) { - listeners.remove(listener); - } - - /** - * Sets the iteration count to 0. This method must be called during the - * initial phase. - */ - public void resetIterationCount() { - iterations.resetCount(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/KthSelector.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/KthSelector.java deleted file mode 100644 index 2820cbf96..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/KthSelector.java +++ /dev/null @@ -1,157 +0,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. - */ -package org.apache.commons.math4.util; - -import java.io.Serializable; -import java.util.Arrays; - -import org.apache.commons.math4.exception.NullArgumentException; - - -/** - * A Simple Kth selector implementation to pick up the - * Kth ordered element from a work array containing the input - * numbers. - * @since 3.4 - */ -public class KthSelector implements Serializable { - - /** Serializable UID. */ - private static final long serialVersionUID = 20140713L; - - /** Minimum selection size for insertion sort rather than selection. */ - private static final int MIN_SELECT_SIZE = 15; - - /** A {@link PivotingStrategyInterface} used for pivoting */ - private final PivotingStrategyInterface pivotingStrategy; - - /** - * Constructor with default {@link MedianOf3PivotingStrategy median of 3} pivoting strategy - */ - public KthSelector() { - this.pivotingStrategy = new MedianOf3PivotingStrategy(); - } - - /** - * Constructor with specified pivoting strategy - * - * @param pivotingStrategy pivoting strategy to use - * @throws NullArgumentException when pivotingStrategy is null - * @see MedianOf3PivotingStrategy - * @see RandomPivotingStrategy - * @see CentralPivotingStrategy - */ - public KthSelector(final PivotingStrategyInterface pivotingStrategy) - throws NullArgumentException { - MathUtils.checkNotNull(pivotingStrategy); - this.pivotingStrategy = pivotingStrategy; - } - - /** Get the pivotin strategy. - * @return pivoting strategy - */ - public PivotingStrategyInterface getPivotingStrategy() { - return pivotingStrategy; - } - - /** - * Select Kth value in the array. - * - * @param work work array to use to find out the Kth value - * @param pivotsHeap cached pivots heap that can be used for efficient estimation - * @param k the index whose value in the array is of interest - * @return Kth value - */ - public double select(final double[] work, final int[] pivotsHeap, final int k) { - int begin = 0; - int end = work.length; - int node = 0; - final boolean usePivotsHeap = pivotsHeap != null; - while (end - begin > MIN_SELECT_SIZE) { - final int pivot; - - if (usePivotsHeap && node < pivotsHeap.length && - pivotsHeap[node] >= 0) { - // the pivot has already been found in a previous call - // and the array has already been partitioned around it - pivot = pivotsHeap[node]; - } else { - // select a pivot and partition work array around it - pivot = partition(work, begin, end, pivotingStrategy.pivotIndex(work, begin, end)); - if (usePivotsHeap && node < pivotsHeap.length) { - pivotsHeap[node] = pivot; - } - } - - if (k == pivot) { - // the pivot was exactly the element we wanted - return work[k]; - } else if (k < pivot) { - // the element is in the left partition - end = pivot; - node = FastMath.min(2 * node + 1, usePivotsHeap ? pivotsHeap.length : end); - } else { - // the element is in the right partition - begin = pivot + 1; - node = FastMath.min(2 * node + 2, usePivotsHeap ? pivotsHeap.length : end); - } - } - Arrays.sort(work, begin, end); - return work[k]; - } - - /** - * Partition an array slice around a pivot.Partitioning exchanges array - * elements such that all elements smaller than pivot are before it and - * all elements larger than pivot are after it. - * - * @param work work array - * @param begin index of the first element of the slice of work array - * @param end index after the last element of the slice of work array - * @param pivot initial index of the pivot - * @return index of the pivot after partition - */ - private int partition(final double[] work, final int begin, final int end, final int pivot) { - - final double value = work[pivot]; - work[pivot] = work[begin]; - - int i = begin + 1; - int j = end - 1; - while (i < j) { - while (i < j && Double.compare(work[j], value) > 0) { - --j; - } - while (i < j && Double.compare(work[i], value) < 0) { - ++i; - } - - if (i < j) { - final double tmp = work[i]; - work[i++] = work[j]; - work[j--] = tmp; - } - } - - if (i >= end || Double.compare(work[i], value) > 0) { - --i; - } - work[begin] = work[i]; - work[i] = value; - return i; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/MathArrays.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/MathArrays.java deleted file mode 100644 index ce2dce5cc..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/MathArrays.java +++ /dev/null @@ -1,1348 +0,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. - */ - -package org.apache.commons.math4.util; - -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.TreeSet; - -import org.apache.commons.numbers.core.Precision; -import org.apache.commons.math4.Field; -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.MathInternalError; -import org.apache.commons.math4.exception.NoDataException; -import org.apache.commons.math4.exception.NonMonotonicSequenceException; -import org.apache.commons.math4.exception.NotANumberException; -import org.apache.commons.math4.exception.NotPositiveException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooLargeException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Arrays utilities. - * - * @since 3.0 - */ -public class MathArrays { - - /** - * Private constructor. - */ - private MathArrays() {} - - /** - * Real-valued function that operate on an array or a part of it. - * @since 3.1 - */ - public interface Function { - /** - * Operates on an entire array. - * - * @param array Array to operate on. - * @return the result of the operation. - */ - double evaluate(double[] array); - /** - * @param array Array to operate on. - * @param startIndex Index of the first element to take into account. - * @param numElements Number of elements to take into account. - * @return the result of the operation. - */ - double evaluate(double[] array, - int startIndex, - int numElements); - } - - /** - * Create a copy of an array scaled by a value. - * - * @param arr Array to scale. - * @param val Scalar. - * @return scaled copy of array with each entry multiplied by val. - * @since 3.2 - */ - public static double[] scale(double val, final double[] arr) { - double[] newArr = new double[arr.length]; - for (int i = 0; i < arr.length; i++) { - newArr[i] = arr[i] * val; - } - return newArr; - } - - /** - *

Multiply each element of an array by a value.

- * - *

The array is modified in place (no copy is created).

- * - * @param arr Array to scale - * @param val Scalar - * @since 3.2 - */ - public static void scaleInPlace(double val, final double[] arr) { - for (int i = 0; i < arr.length; i++) { - arr[i] *= val; - } - } - - /** - * Creates an array whose contents will be the element-by-element - * addition of the arguments. - * - * @param a First term of the addition. - * @param b Second term of the addition. - * @return a new array {@code r} where {@code r[i] = a[i] + b[i]}. - * @throws DimensionMismatchException if the array lengths differ. - * @since 3.1 - */ - public static double[] ebeAdd(double[] a, double[] b) - throws DimensionMismatchException { - checkEqualLength(a, b); - - final double[] result = a.clone(); - for (int i = 0; i < a.length; i++) { - result[i] += b[i]; - } - return result; - } - /** - * Creates an array whose contents will be the element-by-element - * subtraction of the second argument from the first. - * - * @param a First term. - * @param b Element to be subtracted. - * @return a new array {@code r} where {@code r[i] = a[i] - b[i]}. - * @throws DimensionMismatchException if the array lengths differ. - * @since 3.1 - */ - public static double[] ebeSubtract(double[] a, double[] b) - throws DimensionMismatchException { - checkEqualLength(a, b); - - final double[] result = a.clone(); - for (int i = 0; i < a.length; i++) { - result[i] -= b[i]; - } - return result; - } - /** - * Creates an array whose contents will be the element-by-element - * multiplication of the arguments. - * - * @param a First factor of the multiplication. - * @param b Second factor of the multiplication. - * @return a new array {@code r} where {@code r[i] = a[i] * b[i]}. - * @throws DimensionMismatchException if the array lengths differ. - * @since 3.1 - */ - public static double[] ebeMultiply(double[] a, double[] b) - throws DimensionMismatchException { - checkEqualLength(a, b); - - final double[] result = a.clone(); - for (int i = 0; i < a.length; i++) { - result[i] *= b[i]; - } - return result; - } - /** - * Creates an array whose contents will be the element-by-element - * division of the first argument by the second. - * - * @param a Numerator of the division. - * @param b Denominator of the division. - * @return a new array {@code r} where {@code r[i] = a[i] / b[i]}. - * @throws DimensionMismatchException if the array lengths differ. - * @since 3.1 - */ - public static double[] ebeDivide(double[] a, double[] b) - throws DimensionMismatchException { - checkEqualLength(a, b); - - final double[] result = a.clone(); - for (int i = 0; i < a.length; i++) { - result[i] /= b[i]; - } - return result; - } - - /** - * Calculates the L1 (sum of abs) distance between two points. - * - * @param p1 the first point - * @param p2 the second point - * @return the L1 distance between the two points - * @throws DimensionMismatchException if the array lengths differ. - */ - public static double distance1(double[] p1, double[] p2) - throws DimensionMismatchException { - checkEqualLength(p1, p2); - double sum = 0; - for (int i = 0; i < p1.length; i++) { - sum += FastMath.abs(p1[i] - p2[i]); - } - return sum; - } - - /** - * Calculates the L1 (sum of abs) distance between two points. - * - * @param p1 the first point - * @param p2 the second point - * @return the L1 distance between the two points - * @throws DimensionMismatchException if the array lengths differ. - */ - public static int distance1(int[] p1, int[] p2) - throws DimensionMismatchException { - checkEqualLength(p1, p2); - int sum = 0; - for (int i = 0; i < p1.length; i++) { - sum += FastMath.abs(p1[i] - p2[i]); - } - return sum; - } - - /** - * Calculates the L2 (Euclidean) distance between two points. - * - * @param p1 the first point - * @param p2 the second point - * @return the L2 distance between the two points - * @throws DimensionMismatchException if the array lengths differ. - */ - public static double distance(double[] p1, double[] p2) - throws DimensionMismatchException { - checkEqualLength(p1, p2); - double sum = 0; - for (int i = 0; i < p1.length; i++) { - final double dp = p1[i] - p2[i]; - sum += dp * dp; - } - return FastMath.sqrt(sum); - } - - /** - * Calculates the L2 (Euclidean) distance between two points. - * - * @param p1 the first point - * @param p2 the second point - * @return the L2 distance between the two points - * @throws DimensionMismatchException if the array lengths differ. - */ - public static double distance(int[] p1, int[] p2) - throws DimensionMismatchException { - checkEqualLength(p1, p2); - double sum = 0; - for (int i = 0; i < p1.length; i++) { - final double dp = p1[i] - p2[i]; - sum += dp * dp; - } - return FastMath.sqrt(sum); - } - - /** - * Calculates the L (max of abs) distance between two points. - * - * @param p1 the first point - * @param p2 the second point - * @return the L distance between the two points - * @throws DimensionMismatchException if the array lengths differ. - */ - public static double distanceInf(double[] p1, double[] p2) - throws DimensionMismatchException { - checkEqualLength(p1, p2); - double max = 0; - for (int i = 0; i < p1.length; i++) { - max = FastMath.max(max, FastMath.abs(p1[i] - p2[i])); - } - return max; - } - - /** - * Calculates the L (max of abs) distance between two points. - * - * @param p1 the first point - * @param p2 the second point - * @return the L distance between the two points - * @throws DimensionMismatchException if the array lengths differ. - */ - public static int distanceInf(int[] p1, int[] p2) - throws DimensionMismatchException { - checkEqualLength(p1, p2); - int max = 0; - for (int i = 0; i < p1.length; i++) { - max = FastMath.max(max, FastMath.abs(p1[i] - p2[i])); - } - return max; - } - - /** - * Specification of ordering direction. - */ - public enum OrderDirection { - /** Constant for increasing direction. */ - INCREASING, - /** Constant for decreasing direction. */ - DECREASING - } - - /** - * Check that an array is monotonically increasing or decreasing. - * - * @param the type of the elements in the specified array - * @param val Values. - * @param dir Ordering direction. - * @param strict Whether the order should be strict. - * @return {@code true} if sorted, {@code false} otherwise. - */ - public static > boolean isMonotonic(T[] val, - OrderDirection dir, - boolean strict) { - T previous = val[0]; - final int max = val.length; - for (int i = 1; i < max; i++) { - final int comp; - switch (dir) { - case INCREASING: - comp = previous.compareTo(val[i]); - if (strict) { - if (comp >= 0) { - return false; - } - } else { - if (comp > 0) { - return false; - } - } - break; - case DECREASING: - comp = val[i].compareTo(previous); - if (strict) { - if (comp >= 0) { - return false; - } - } else { - if (comp > 0) { - return false; - } - } - break; - default: - // Should never happen. - throw new MathInternalError(); - } - - previous = val[i]; - } - return true; - } - - /** - * Check that an array is monotonically increasing or decreasing. - * - * @param val Values. - * @param dir Ordering direction. - * @param strict Whether the order should be strict. - * @return {@code true} if sorted, {@code false} otherwise. - */ - public static boolean isMonotonic(double[] val, OrderDirection dir, boolean strict) { - return checkOrder(val, dir, strict, false); - } - - /** - * Check that both arrays have the same length. - * - * @param a Array. - * @param b Array. - * @param abort Whether to throw an exception if the check fails. - * @return {@code true} if the arrays have the same length. - * @throws DimensionMismatchException if the lengths differ and - * {@code abort} is {@code true}. - * @since 3.6 - */ - public static boolean checkEqualLength(double[] a, - double[] b, - boolean abort) { - if (a.length == b.length) { - return true; - } else { - if (abort) { - throw new DimensionMismatchException(a.length, b.length); - } - return false; - } - } - - /** - * Check that both arrays have the same length. - * - * @param a Array. - * @param b Array. - * @throws DimensionMismatchException if the lengths differ. - * @since 3.6 - */ - public static void checkEqualLength(double[] a, - double[] b) { - checkEqualLength(a, b, true); - } - - - /** - * Check that both arrays have the same length. - * - * @param a Array. - * @param b Array. - * @param abort Whether to throw an exception if the check fails. - * @return {@code true} if the arrays have the same length. - * @throws DimensionMismatchException if the lengths differ and - * {@code abort} is {@code true}. - * @since 3.6 - */ - public static boolean checkEqualLength(int[] a, - int[] b, - boolean abort) { - if (a.length == b.length) { - return true; - } else { - if (abort) { - throw new DimensionMismatchException(a.length, b.length); - } - return false; - } - } - - /** - * Check that both arrays have the same length. - * - * @param a Array. - * @param b Array. - * @throws DimensionMismatchException if the lengths differ. - * @since 3.6 - */ - public static void checkEqualLength(int[] a, - int[] b) { - checkEqualLength(a, b, true); - } - - /** - * Check that the given array is sorted. - * - * @param val Values. - * @param dir Ordering direction. - * @param strict Whether the order should be strict. - * @param abort Whether to throw an exception if the check fails. - * @return {@code true} if the array is sorted. - * @throws NonMonotonicSequenceException if the array is not sorted - * and {@code abort} is {@code true}. - */ - public static boolean checkOrder(double[] val, OrderDirection dir, - boolean strict, boolean abort) - throws NonMonotonicSequenceException { - double previous = val[0]; - final int max = val.length; - - int index; - ITEM: - for (index = 1; index < max; index++) { - switch (dir) { - case INCREASING: - if (strict) { - if (val[index] <= previous) { - break ITEM; - } - } else { - if (val[index] < previous) { - break ITEM; - } - } - break; - case DECREASING: - if (strict) { - if (val[index] >= previous) { - break ITEM; - } - } else { - if (val[index] > previous) { - break ITEM; - } - } - break; - default: - // Should never happen. - throw new MathInternalError(); - } - - previous = val[index]; - } - - if (index == max) { - // Loop completed. - return true; - } - - // Loop early exit means wrong ordering. - if (abort) { - throw new NonMonotonicSequenceException(val[index], previous, index, dir, strict); - } else { - return false; - } - } - - /** - * Check that the given array is sorted. - * - * @param val Values. - * @param dir Ordering direction. - * @param strict Whether the order should be strict. - * @throws NonMonotonicSequenceException if the array is not sorted. - * @since 2.2 - */ - public static void checkOrder(double[] val, OrderDirection dir, - boolean strict) throws NonMonotonicSequenceException { - checkOrder(val, dir, strict, true); - } - - /** - * Check that the given array is sorted in strictly increasing order. - * - * @param val Values. - * @throws NonMonotonicSequenceException if the array is not sorted. - * @since 2.2 - */ - public static void checkOrder(double[] val) throws NonMonotonicSequenceException { - checkOrder(val, OrderDirection.INCREASING, true); - } - - /** - * Throws DimensionMismatchException if the input array is not rectangular. - * - * @param in array to be tested - * @throws NullArgumentException if input array is null - * @throws DimensionMismatchException if input array is not rectangular - * @since 3.1 - */ - public static void checkRectangular(final long[][] in) - throws NullArgumentException, DimensionMismatchException { - MathUtils.checkNotNull(in); - for (int i = 1; i < in.length; i++) { - if (in[i].length != in[0].length) { - throw new DimensionMismatchException( - LocalizedFormats.DIFFERENT_ROWS_LENGTHS, - in[i].length, in[0].length); - } - } - } - - /** - * Check that all entries of the input array are strictly positive. - * - * @param in Array to be tested - * @throws NotStrictlyPositiveException if any entries of the array are not - * strictly positive. - * @since 3.1 - */ - public static void checkPositive(final double[] in) - throws NotStrictlyPositiveException { - for (int i = 0; i < in.length; i++) { - if (in[i] <= 0) { - throw new NotStrictlyPositiveException(in[i]); - } - } - } - - /** - * Check that no entry of the input array is {@code NaN}. - * - * @param in Array to be tested. - * @throws NotANumberException if an entry is {@code NaN}. - * @since 3.4 - */ - public static void checkNotNaN(final double[] in) - throws NotANumberException { - for(int i = 0; i < in.length; i++) { - if (Double.isNaN(in[i])) { - throw new NotANumberException(); - } - } - } - - /** - * Check that all entries of the input array are >= 0. - * - * @param in Array to be tested - * @throws NotPositiveException if any array entries are less than 0. - * @since 3.1 - */ - public static void checkNonNegative(final long[] in) - throws NotPositiveException { - for (int i = 0; i < in.length; i++) { - if (in[i] < 0) { - throw new NotPositiveException(in[i]); - } - } - } - - /** - * Check all entries of the input array are >= 0. - * - * @param in Array to be tested - * @throws NotPositiveException if any array entries are less than 0. - * @since 3.1 - */ - public static void checkNonNegative(final long[][] in) - throws NotPositiveException { - for (int i = 0; i < in.length; i ++) { - for (int j = 0; j < in[i].length; j++) { - if (in[i][j] < 0) { - throw new NotPositiveException(in[i][j]); - } - } - } - } - - /** - * Sort an array in ascending order in place and perform the same reordering - * of entries on other arrays. For example, if - * {@code x = [3, 1, 2], y = [1, 2, 3]} and {@code z = [0, 5, 7]}, then - * {@code sortInPlace(x, y, z)} will update {@code x} to {@code [1, 2, 3]}, - * {@code y} to {@code [2, 3, 1]} and {@code z} to {@code [5, 7, 0]}. - * - * @param x Array to be sorted and used as a pattern for permutation - * of the other arrays. - * @param yList Set of arrays whose permutations of entries will follow - * those performed on {@code x}. - * @throws DimensionMismatchException if any {@code y} is not the same - * size as {@code x}. - * @throws NullArgumentException if {@code x} or any {@code y} is null. - * @since 3.0 - */ - public static void sortInPlace(double[] x, double[] ... yList) - throws DimensionMismatchException, NullArgumentException { - sortInPlace(x, OrderDirection.INCREASING, yList); - } - - /** - * Helper data structure holding a (double, integer) pair. - */ - private static class PairDoubleInteger { - /** Key */ - private final double key; - /** Value */ - private final int value; - - /** - * @param key Key. - * @param value Value. - */ - PairDoubleInteger(double key, int value) { - this.key = key; - this.value = value; - } - - /** @return the key. */ - public double getKey() { - return key; - } - - /** @return the value. */ - public int getValue() { - return value; - } - } - - /** - * Sort an array in place and perform the same reordering of entries on - * other arrays. This method works the same as the other - * {@link #sortInPlace(double[], double[][]) sortInPlace} method, but - * allows the order of the sort to be provided in the {@code dir} - * parameter. - * - * @param x Array to be sorted and used as a pattern for permutation - * of the other arrays. - * @param dir Order direction. - * @param yList Set of arrays whose permutations of entries will follow - * those performed on {@code x}. - * @throws DimensionMismatchException if any {@code y} is not the same - * size as {@code x}. - * @throws NullArgumentException if {@code x} or any {@code y} is null - * @since 3.0 - */ - public static void sortInPlace(double[] x, - final OrderDirection dir, - double[] ... yList) - throws NullArgumentException, - DimensionMismatchException { - - // Consistency checks. - if (x == null) { - throw new NullArgumentException(); - } - - final int yListLen = yList.length; - final int len = x.length; - - for (int j = 0; j < yListLen; j++) { - final double[] y = yList[j]; - if (y == null) { - throw new NullArgumentException(); - } - if (y.length != len) { - throw new DimensionMismatchException(y.length, len); - } - } - - // Associate each abscissa "x[i]" with its index "i". - final List list - = new ArrayList<>(len); - for (int i = 0; i < len; i++) { - list.add(new PairDoubleInteger(x[i], i)); - } - - // Create comparators for increasing and decreasing orders. - final Comparator comp - = dir == OrderDirection.INCREASING ? - new Comparator() { - /** {@inheritDoc} */ - @Override - public int compare(PairDoubleInteger o1, - PairDoubleInteger o2) { - return Double.compare(o1.getKey(), o2.getKey()); - } - } : new Comparator() { - /** {@inheritDoc} */ - @Override - public int compare(PairDoubleInteger o1, - PairDoubleInteger o2) { - return Double.compare(o2.getKey(), o1.getKey()); - } - }; - - // Sort. - Collections.sort(list, comp); - - // Modify the original array so that its elements are in - // the prescribed order. - // Retrieve indices of original locations. - final int[] indices = new int[len]; - for (int i = 0; i < len; i++) { - final PairDoubleInteger e = list.get(i); - x[i] = e.getKey(); - indices[i] = e.getValue(); - } - - // In each of the associated arrays, move the - // elements to their new location. - for (int j = 0; j < yListLen; j++) { - // Input array will be modified in place. - final double[] yInPlace = yList[j]; - final double[] yOrig = yInPlace.clone(); - - for (int i = 0; i < len; i++) { - yInPlace[i] = yOrig[indices[i]]; - } - } - } - - /** - * Creates a copy of the {@code source} array. - * - * @param source Array to be copied. - * @return the copied array. - */ - public static int[] copyOf(int[] source) { - return copyOf(source, source.length); - } - - /** - * Creates a copy of the {@code source} array. - * - * @param source Array to be copied. - * @return the copied array. - */ - public static double[] copyOf(double[] source) { - return copyOf(source, source.length); - } - - /** - * Creates a copy of the {@code source} array. - * - * @param source Array to be copied. - * @param len Number of entries to copy. If smaller then the source - * length, the copy will be truncated, if larger it will padded with - * zeroes. - * @return the copied array. - */ - public static int[] copyOf(int[] source, int len) { - final int[] output = new int[len]; - System.arraycopy(source, 0, output, 0, FastMath.min(len, source.length)); - return output; - } - - /** - * Creates a copy of the {@code source} array. - * - * @param source Array to be copied. - * @param len Number of entries to copy. If smaller then the source - * length, the copy will be truncated, if larger it will padded with - * zeroes. - * @return the copied array. - */ - public static double[] copyOf(double[] source, int len) { - final double[] output = new double[len]; - System.arraycopy(source, 0, output, 0, FastMath.min(len, source.length)); - return output; - } - - /** - * Creates a copy of the {@code source} array. - * - * @param source Array to be copied. - * @param from Initial index of the range to be copied, inclusive. - * @param to Final index of the range to be copied, exclusive. (This index may lie outside the array.) - * @return the copied array. - */ - public static double[] copyOfRange(double[] source, int from, int to) { - final int len = to - from; - final double[] output = new double[len]; - System.arraycopy(source, from, output, 0, FastMath.min(len, source.length - from)); - return output; - } - - /** - * Returns true iff both arguments are null or have same dimensions and all - * their elements are equal as defined by - * {@link Precision#equals(float,float)}. - * - * @param x first array - * @param y second array - * @return true if the values are both null or have same dimension - * and equal elements. - */ - public static boolean equals(float[] x, float[] y) { - if ((x == null) || (y == null)) { - return !((x == null) ^ (y == null)); - } - if (x.length != y.length) { - return false; - } - for (int i = 0; i < x.length; ++i) { - if (!Precision.equals(x[i], y[i])) { - return false; - } - } - return true; - } - - /** - * Returns true iff both arguments are null or have same dimensions and all - * their elements are equal as defined by - * {@link Precision#equalsIncludingNaN(double,double) this method}. - * - * @param x first array - * @param y second array - * @return true if the values are both null or have same dimension and - * equal elements - * @since 2.2 - */ - public static boolean equalsIncludingNaN(float[] x, float[] y) { - if ((x == null) || (y == null)) { - return !((x == null) ^ (y == null)); - } - if (x.length != y.length) { - return false; - } - for (int i = 0; i < x.length; ++i) { - if (!Precision.equalsIncludingNaN(x[i], y[i])) { - return false; - } - } - return true; - } - - /** - * Returns {@code true} iff both arguments are {@code null} or have same - * dimensions and all their elements are equal as defined by - * {@link Precision#equals(double,double)}. - * - * @param x First array. - * @param y Second array. - * @return {@code true} if the values are both {@code null} or have same - * dimension and equal elements. - */ - public static boolean equals(double[] x, double[] y) { - if ((x == null) || (y == null)) { - return !((x == null) ^ (y == null)); - } - if (x.length != y.length) { - return false; - } - for (int i = 0; i < x.length; ++i) { - if (!Precision.equals(x[i], y[i])) { - return false; - } - } - return true; - } - - /** - * Returns {@code true} iff both arguments are {@code null} or have same - * dimensions and all their elements are equal as defined by - * {@link Precision#equalsIncludingNaN(double,double) this method}. - * - * @param x First array. - * @param y Second array. - * @return {@code true} if the values are both {@code null} or have same - * dimension and equal elements. - * @since 2.2 - */ - public static boolean equalsIncludingNaN(double[] x, double[] y) { - if ((x == null) || (y == null)) { - return !((x == null) ^ (y == null)); - } - if (x.length != y.length) { - return false; - } - for (int i = 0; i < x.length; ++i) { - if (!Precision.equalsIncludingNaN(x[i], y[i])) { - return false; - } - } - return true; - } - - /** - * Normalizes an array to make it sum to a specified value. - * Returns the result of the transformation - *
-     *    x |-> x * normalizedSum / sum
-     * 
- * applied to each non-NaN element x of the input array, where sum is the - * sum of the non-NaN entries in the input array. - *

- * Throws IllegalArgumentException if {@code normalizedSum} is infinite - * or NaN and ArithmeticException if the input array contains any infinite elements - * or sums to 0. - *

- * Ignores (i.e., copies unchanged to the output array) NaNs in the input array. - * - * @param values Input array to be normalized - * @param normalizedSum Target sum for the normalized array - * @return the normalized array. - * @throws MathArithmeticException if the input array contains infinite - * elements or sums to zero. - * @throws MathIllegalArgumentException if the target sum is infinite or {@code NaN}. - * @since 2.1 - */ - public static double[] normalizeArray(double[] values, double normalizedSum) - throws MathIllegalArgumentException, MathArithmeticException { - if (Double.isInfinite(normalizedSum)) { - throw new MathIllegalArgumentException(LocalizedFormats.NORMALIZE_INFINITE); - } - if (Double.isNaN(normalizedSum)) { - throw new MathIllegalArgumentException(LocalizedFormats.NORMALIZE_NAN); - } - double sum = 0d; - final int len = values.length; - double[] out = new double[len]; - for (int i = 0; i < len; i++) { - if (Double.isInfinite(values[i])) { - throw new MathIllegalArgumentException(LocalizedFormats.INFINITE_ARRAY_ELEMENT, values[i], i); - } - if (!Double.isNaN(values[i])) { - sum += values[i]; - } - } - if (sum == 0) { - throw new MathArithmeticException(LocalizedFormats.ARRAY_SUMS_TO_ZERO); - } - for (int i = 0; i < len; i++) { - if (Double.isNaN(values[i])) { - out[i] = Double.NaN; - } else { - out[i] = values[i] * normalizedSum / sum; - } - } - return out; - } - - /** Build an array of elements. - *

- * Arrays are filled with field.getZero() - * - * @param the type of the field elements - * @param field field to which array elements belong - * @param length of the array - * @return a new array - * @since 3.2 - */ - public static T[] buildArray(final Field field, final int length) { - @SuppressWarnings("unchecked") // OK because field must be correct class - T[] array = (T[]) Array.newInstance(field.getRuntimeClass(), length); - Arrays.fill(array, field.getZero()); - return array; - } - - /** Build a double dimension array of elements. - *

- * Arrays are filled with field.getZero() - * - * @param the type of the field elements - * @param field field to which array elements belong - * @param rows number of rows in the array - * @param columns number of columns (may be negative to build partial - * arrays in the same way new Field[rows][] works) - * @return a new array - * @since 3.2 - */ - @SuppressWarnings("unchecked") - public static T[][] buildArray(final Field field, final int rows, final int columns) { - final T[][] array; - if (columns < 0) { - T[] dummyRow = buildArray(field, 0); - array = (T[][]) Array.newInstance(dummyRow.getClass(), rows); - } else { - array = (T[][]) Array.newInstance(field.getRuntimeClass(), - new int[] { - rows, columns - }); - for (int i = 0; i < rows; ++i) { - Arrays.fill(array[i], field.getZero()); - } - } - return array; - } - - /** - * Calculates the - * convolution between two sequences. - *

- * The solution is obtained via straightforward computation of the - * convolution sum (and not via FFT). Whenever the computation needs - * an element that would be located at an index outside the input arrays, - * the value is assumed to be zero. - * - * @param x First sequence. - * Typically, this sequence will represent an input signal to a system. - * @param h Second sequence. - * Typically, this sequence will represent the impulse response of the system. - * @return the convolution of {@code x} and {@code h}. - * This array's length will be {@code x.length + h.length - 1}. - * @throws NullArgumentException if either {@code x} or {@code h} is {@code null}. - * @throws NoDataException if either {@code x} or {@code h} is empty. - * - * @since 3.3 - */ - public static double[] convolve(double[] x, double[] h) - throws NullArgumentException, - NoDataException { - MathUtils.checkNotNull(x); - MathUtils.checkNotNull(h); - - final int xLen = x.length; - final int hLen = h.length; - - if (xLen == 0 || hLen == 0) { - throw new NoDataException(); - } - - // initialize the output array - final int totalLength = xLen + hLen - 1; - final double[] y = new double[totalLength]; - - // straightforward implementation of the convolution sum - for (int n = 0; n < totalLength; n++) { - double yn = 0; - int k = FastMath.max(0, n + 1 - xLen); - int j = n - k; - while (k < hLen && j >= 0) { - yn += x[j--] * h[k++]; - } - y[n] = yn; - } - - return y; - } - - /** - * Returns an array representing the natural number {@code n}. - * - * @param n Natural number. - * @return an array whose entries are the numbers 0, 1, ..., {@code n}-1. - * If {@code n == 0}, the returned array is empty. - */ - public static int[] natural(int n) { - return sequence(n, 0, 1); - } - /** - * Returns an array of {@code size} integers starting at {@code start}, - * skipping {@code stride} numbers. - * - * @param size Natural number. - * @param start Natural number. - * @param stride Natural number. - * @return an array whose entries are the numbers - * {@code start, start + stride, ..., start + (size - 1) * stride}. - * If {@code size == 0}, the returned array is empty. - * - * @since 3.4 - */ - public static int[] sequence(int size, - int start, - int stride) { - final int[] a = new int[size]; - for (int i = 0; i < size; i++) { - a[i] = start + i * stride; - } - return a; - } - /** - * This method is used - * to verify that the input parameters designate a subarray of positive length. - *

    - *
  • returns true iff the parameters designate a subarray of - * positive length
  • - *
  • throws MathIllegalArgumentException if the array is null or - * or the indices are invalid
  • - *
  • returns false if the array is non-null, but - * length is 0.
  • - *
- * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return true if the parameters are valid and designate a subarray of positive length - * @throws MathIllegalArgumentException if the indices are invalid or the array is null - * @since 3.3 - */ - public static boolean verifyValues(final double[] values, final int begin, final int length) - throws MathIllegalArgumentException { - return verifyValues(values, begin, length, false); - } - - /** - * This method is used - * to verify that the input parameters designate a subarray of positive length. - *
    - *
  • returns true iff the parameters designate a subarray of - * non-negative length
  • - *
  • throws IllegalArgumentException if the array is null or - * or the indices are invalid
  • - *
  • returns false if the array is non-null, but - * length is 0 unless allowEmpty is true
  • - *
- * - * @param values the input array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @param allowEmpty if true then zero length arrays are allowed - * @return true if the parameters are valid - * @throws MathIllegalArgumentException if the indices are invalid or the array is null - * @since 3.3 - */ - public static boolean verifyValues(final double[] values, final int begin, - final int length, final boolean allowEmpty) throws MathIllegalArgumentException { - - if (values == null) { - throw new NullArgumentException(LocalizedFormats.INPUT_ARRAY); - } - - if (begin < 0) { - throw new NotPositiveException(LocalizedFormats.START_POSITION, Integer.valueOf(begin)); - } - - if (length < 0) { - throw new NotPositiveException(LocalizedFormats.LENGTH, Integer.valueOf(length)); - } - - if (begin + length > values.length) { - throw new NumberIsTooLargeException(LocalizedFormats.SUBARRAY_ENDS_AFTER_ARRAY_END, - Integer.valueOf(begin + length), Integer.valueOf(values.length), true); - } - - if (length == 0 && !allowEmpty) { - return false; - } - - return true; - - } - - /** - * This method is used - * to verify that the begin and length parameters designate a subarray of positive length - * and the weights are all non-negative, non-NaN, finite, and not all zero. - *
    - *
  • returns true iff the parameters designate a subarray of - * positive length and the weights array contains legitimate values.
  • - *
  • throws IllegalArgumentException if any of the following are true: - *
    • the values array is null
    • - *
    • the weights array is null
    • - *
    • the weights array does not have the same length as the values array
    • - *
    • the weights array contains one or more infinite values
    • - *
    • the weights array contains one or more NaN values
    • - *
    • the weights array contains negative values
    • - *
    • the start and length arguments do not determine a valid array
    - *
  • - *
  • returns false if the array is non-null, but - * length is 0.
  • - *
- * - * @param values the input array - * @param weights the weights array - * @param begin index of the first array element to include - * @param length the number of elements to include - * @return true if the parameters are valid and designate a subarray of positive length - * @throws MathIllegalArgumentException if the indices are invalid or the array is null - * @since 3.3 - */ - public static boolean verifyValues( - final double[] values, - final double[] weights, - final int begin, - final int length) throws MathIllegalArgumentException { - return verifyValues(values, weights, begin, length, false); - } - - /** - * This method is used - * to verify that the begin and length parameters designate a subarray of positive length - * and the weights are all non-negative, non-NaN, finite, and not all zero. - *
    - *
  • returns true iff the parameters designate a subarray of - * non-negative length and the weights array contains legitimate values.
  • - *
  • throws MathIllegalArgumentException if any of the following are true: - *
    • the values array is null
    • - *
    • the weights array is null
    • - *
    • the weights array does not have the same length as the values array
    • - *
    • the weights array contains one or more infinite values
    • - *
    • the weights array contains one or more NaN values
    • - *
    • the weights array contains negative values
    • - *
    • the start and length arguments do not determine a valid array
    - *
  • - *
  • returns false if the array is non-null, but - * length is 0 unless allowEmpty is true.
  • - *
- * - * @param values the input array. - * @param weights the weights array. - * @param begin index of the first array element to include. - * @param length the number of elements to include. - * @param allowEmpty if {@code true} than allow zero length arrays to pass. - * @return {@code true} if the parameters are valid. - * @throws NullArgumentException if either of the arrays are null - * @throws MathIllegalArgumentException if the array indices are not valid, - * the weights array contains NaN, infinite or negative elements, or there - * are no positive weights. - * @since 3.3 - */ - public static boolean verifyValues(final double[] values, final double[] weights, - final int begin, final int length, final boolean allowEmpty) throws MathIllegalArgumentException { - - if (weights == null || values == null) { - throw new NullArgumentException(LocalizedFormats.INPUT_ARRAY); - } - - checkEqualLength(weights, values); - - boolean containsPositiveWeight = false; - for (int i = begin; i < begin + length; i++) { - final double weight = weights[i]; - if (Double.isNaN(weight)) { - throw new MathIllegalArgumentException(LocalizedFormats.NAN_ELEMENT_AT_INDEX, Integer.valueOf(i)); - } - if (Double.isInfinite(weight)) { - throw new MathIllegalArgumentException(LocalizedFormats.INFINITE_ARRAY_ELEMENT, Double.valueOf(weight), Integer.valueOf(i)); - } - if (weight < 0) { - throw new MathIllegalArgumentException(LocalizedFormats.NEGATIVE_ELEMENT_AT_INDEX, Integer.valueOf(i), Double.valueOf(weight)); - } - if (!containsPositiveWeight && weight > 0.0) { - containsPositiveWeight = true; - } - } - - if (!containsPositiveWeight) { - throw new MathIllegalArgumentException(LocalizedFormats.WEIGHT_AT_LEAST_ONE_NON_ZERO); - } - - return verifyValues(values, begin, length, allowEmpty); - } - - /** - * Concatenates a sequence of arrays. The return array consists of the - * entries of the input arrays concatenated in the order they appear in - * the argument list. Null arrays cause NullPointerExceptions; zero - * length arrays are allowed (contributing nothing to the output array). - * - * @param x list of double[] arrays to concatenate - * @return a new array consisting of the entries of the argument arrays - * @throws NullPointerException if any of the arrays are null - * @since 3.6 - */ - public static double[] concatenate(double[] ...x) { - int combinedLength = 0; - for (double[] a : x) { - combinedLength += a.length; - } - int offset = 0; - int curLength = 0; - final double[] combined = new double[combinedLength]; - for (int i = 0; i < x.length; i++) { - curLength = x[i].length; - System.arraycopy(x[i], 0, combined, offset, curLength); - offset += curLength; - } - return combined; - } - - /** - * Returns an array consisting of the unique values in {@code data}. - * The return array is sorted in descending order. Empty arrays - * are allowed, but null arrays result in NullPointerException. - * Infinities are allowed. NaN values are allowed with maximum - * sort order - i.e., if there are NaN values in {@code data}, - * {@code Double.NaN} will be the first element of the output array, - * even if the array also contains {@code Double.POSITIVE_INFINITY}. - * - * @param data array to scan - * @return descending list of values included in the input array - * @throws NullPointerException if data is null - * @since 3.6 - */ - public static double[] unique(double[] data) { - TreeSet values = new TreeSet<>(); - for (int i = 0; i < data.length; i++) { - values.add(data[i]); - } - final int count = values.size(); - final double[] out = new double[count]; - Iterator iterator = values.descendingIterator(); - int i = 0; - while (iterator.hasNext()) { - out[i++] = iterator.next(); - } - return out; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/MathUtils.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/MathUtils.java deleted file mode 100644 index 303146597..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/MathUtils.java +++ /dev/null @@ -1,284 +0,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. - */ - -package org.apache.commons.math4.util; - -import java.util.Arrays; - -import org.apache.commons.math4.RealFieldElement; -import org.apache.commons.math4.exception.MathArithmeticException; -import org.apache.commons.math4.exception.NotFiniteNumberException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.util.Localizable; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * Miscellaneous utility functions. - * - * @see MathArrays - * - */ -public final class MathUtils { - /** - * \(2\pi\) - * @since 2.1 - */ - public static final double TWO_PI = 2 * FastMath.PI; - - /** - * \(\pi^2\) - * @since 3.4 - */ - public static final double PI_SQUARED = FastMath.PI * FastMath.PI; - - - /** - * Class contains only static methods. - */ - private MathUtils() {} - - - /** - * Returns an integer hash code representing the given double value. - * - * @param value the value to be hashed - * @return the hash code - */ - public static int hash(double value) { - return new Double(value).hashCode(); - } - - /** - * Returns {@code true} if the values are equal according to semantics of - * {@link Double#equals(Object)}. - * - * @param x Value - * @param y Value - * @return {@code new Double(x).equals(new Double(y))} - */ - public static boolean equals(double x, double y) { - return new Double(x).equals(new Double(y)); - } - - /** - * Returns an integer hash code representing the given double array. - * - * @param value the value to be hashed (may be null) - * @return the hash code - * @since 1.2 - */ - public static int hash(double[] value) { - return Arrays.hashCode(value); - } - - /** Find the maximum of two field elements. - * @param the type of the field elements - * @param e1 first element - * @param e2 second element - * @return max(a1, e2) - * @since 3.6 - */ - public static > T max(final T e1, final T e2) { - return e1.subtract(e2).getReal() >= 0 ? e1 : e2; - } - - /** Find the minimum of two field elements. - * @param the type of the field elements - * @param e1 first element - * @param e2 second element - * @return min(a1, e2) - * @since 3.6 - */ - public static > T min(final T e1, final T e2) { - return e1.subtract(e2).getReal() >= 0 ? e2 : e1; - } - - /** - *

Reduce {@code |a - offset|} to the primary interval - * {@code [0, |period|)}.

- * - *

Specifically, the value returned is
- * {@code a - |period| * floor((a - offset) / |period|) - offset}.

- * - *

If any of the parameters are {@code NaN} or infinite, the result is - * {@code NaN}.

- * - * @param a Value to reduce. - * @param period Period. - * @param offset Value that will be mapped to {@code 0}. - * @return the value, within the interval {@code [0 |period|)}, - * that corresponds to {@code a}. - */ - public static double reduce(double a, - double period, - double offset) { - final double p = FastMath.abs(period); - return a - p * FastMath.floor((a - offset) / p) - offset; - } - - /** - * Returns the first argument with the sign of the second argument. - * - * @param magnitude Magnitude of the returned value. - * @param sign Sign of the returned value. - * @return a value with magnitude equal to {@code magnitude} and with the - * same sign as the {@code sign} argument. - * @throws MathArithmeticException if {@code magnitude == Byte.MIN_VALUE} - * and {@code sign >= 0}. - */ - public static byte copySign(byte magnitude, byte sign) - throws MathArithmeticException { - if ((magnitude >= 0 && sign >= 0) || - (magnitude < 0 && sign < 0)) { // Sign is OK. - return magnitude; - } else if (sign >= 0 && - magnitude == Byte.MIN_VALUE) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW); - } else { - return (byte) -magnitude; // Flip sign. - } - } - - /** - * Returns the first argument with the sign of the second argument. - * - * @param magnitude Magnitude of the returned value. - * @param sign Sign of the returned value. - * @return a value with magnitude equal to {@code magnitude} and with the - * same sign as the {@code sign} argument. - * @throws MathArithmeticException if {@code magnitude == Short.MIN_VALUE} - * and {@code sign >= 0}. - */ - public static short copySign(short magnitude, short sign) - throws MathArithmeticException { - if ((magnitude >= 0 && sign >= 0) || - (magnitude < 0 && sign < 0)) { // Sign is OK. - return magnitude; - } else if (sign >= 0 && - magnitude == Short.MIN_VALUE) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW); - } else { - return (short) -magnitude; // Flip sign. - } - } - - /** - * Returns the first argument with the sign of the second argument. - * - * @param magnitude Magnitude of the returned value. - * @param sign Sign of the returned value. - * @return a value with magnitude equal to {@code magnitude} and with the - * same sign as the {@code sign} argument. - * @throws MathArithmeticException if {@code magnitude == Integer.MIN_VALUE} - * and {@code sign >= 0}. - */ - public static int copySign(int magnitude, int sign) - throws MathArithmeticException { - if ((magnitude >= 0 && sign >= 0) || - (magnitude < 0 && sign < 0)) { // Sign is OK. - return magnitude; - } else if (sign >= 0 && - magnitude == Integer.MIN_VALUE) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW); - } else { - return -magnitude; // Flip sign. - } - } - - /** - * Returns the first argument with the sign of the second argument. - * - * @param magnitude Magnitude of the returned value. - * @param sign Sign of the returned value. - * @return a value with magnitude equal to {@code magnitude} and with the - * same sign as the {@code sign} argument. - * @throws MathArithmeticException if {@code magnitude == Long.MIN_VALUE} - * and {@code sign >= 0}. - */ - public static long copySign(long magnitude, long sign) - throws MathArithmeticException { - if ((magnitude >= 0 && sign >= 0) || - (magnitude < 0 && sign < 0)) { // Sign is OK. - return magnitude; - } else if (sign >= 0 && - magnitude == Long.MIN_VALUE) { - throw new MathArithmeticException(LocalizedFormats.OVERFLOW); - } else { - return -magnitude; // Flip sign. - } - } - /** - * Check that the argument is a real number. - * - * @param x Argument. - * @throws NotFiniteNumberException if {@code x} is not a - * finite real number. - */ - public static void checkFinite(final double x) - throws NotFiniteNumberException { - if (Double.isInfinite(x) || Double.isNaN(x)) { - throw new NotFiniteNumberException(x); - } - } - - /** - * Check that all the elements are real numbers. - * - * @param val Arguments. - * @throws NotFiniteNumberException if any values of the array is not a - * finite real number. - */ - public static void checkFinite(final double[] val) - throws NotFiniteNumberException { - for (int i = 0; i < val.length; i++) { - final double x = val[i]; - if (Double.isInfinite(x) || Double.isNaN(x)) { - throw new NotFiniteNumberException(LocalizedFormats.ARRAY_ELEMENT, x, i); - } - } - } - - /** - * Checks that an object is not null. - * - * @param o Object to be checked. - * @param pattern Message pattern. - * @param args Arguments to replace the placeholders in {@code pattern}. - * @throws NullArgumentException if {@code o} is {@code null}. - */ - public static void checkNotNull(Object o, - Localizable pattern, - Object ... args) - throws NullArgumentException { - if (o == null) { - throw new NullArgumentException(pattern, args); - } - } - - /** - * Checks that an object is not null. - * - * @param o Object to be checked. - * @throws NullArgumentException if {@code o} is {@code null}. - */ - public static void checkNotNull(Object o) - throws NullArgumentException { - if (o == null) { - throw new NullArgumentException(); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/MedianOf3PivotingStrategy.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/MedianOf3PivotingStrategy.java deleted file mode 100644 index e8499dc4e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/MedianOf3PivotingStrategy.java +++ /dev/null @@ -1,64 +0,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. - */ -package org.apache.commons.math4.util; - -import java.io.Serializable; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; - - -/** - * Classic median of 3 strategy given begin and end indices. - * @since 3.4 - */ -public class MedianOf3PivotingStrategy implements PivotingStrategyInterface, Serializable { - - /** Serializable UID. */ - private static final long serialVersionUID = 20140713L; - - /**{@inheritDoc} - * This in specific makes use of median of 3 pivoting. - * @return The index corresponding to a pivot chosen between the - * first, middle and the last indices of the array slice - * @throws MathIllegalArgumentException when indices exceeds range - */ - @Override - public int pivotIndex(final double[] work, final int begin, final int end) - throws MathIllegalArgumentException { - MathArrays.verifyValues(work, begin, end-begin); - final int inclusiveEnd = end - 1; - final int middle = begin + (inclusiveEnd - begin) / 2; - final double wBegin = work[begin]; - final double wMiddle = work[middle]; - final double wEnd = work[inclusiveEnd]; - - if (wBegin < wMiddle) { - if (wMiddle < wEnd) { - return middle; - } else { - return wBegin < wEnd ? inclusiveEnd : begin; - } - } else { - if (wBegin < wEnd) { - return begin; - } else { - return wMiddle < wEnd ? inclusiveEnd : middle; - } - } - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/MultidimensionalCounter.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/MultidimensionalCounter.java deleted file mode 100644 index 861fcd965..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/MultidimensionalCounter.java +++ /dev/null @@ -1,308 +0,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. - */ - -package org.apache.commons.math4.util; - -import java.util.NoSuchElementException; - -import org.apache.commons.math4.exception.DimensionMismatchException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.OutOfRangeException; - -/** - * Converter between unidimensional storage structure and multidimensional - * conceptual structure. - * This utility will convert from indices in a multidimensional structure - * to the corresponding index in a one-dimensional array. For example, - * assuming that the ranges (in 3 dimensions) of indices are 2, 4 and 3, - * the following correspondences, between 3-tuples indices and unidimensional - * indices, will hold: - *
    - *
  • (0, 0, 0) corresponds to 0
  • - *
  • (0, 0, 1) corresponds to 1
  • - *
  • (0, 0, 2) corresponds to 2
  • - *
  • (0, 1, 0) corresponds to 3
  • - *
  • ...
  • - *
  • (1, 0, 0) corresponds to 12
  • - *
  • ...
  • - *
  • (1, 3, 2) corresponds to 23
  • - *
- * - * @since 2.2 - */ -public class MultidimensionalCounter implements Iterable { - /** - * Number of dimensions. - */ - private final int dimension; - /** - * Offset for each dimension. - */ - private final int[] uniCounterOffset; - /** - * Counter sizes. - */ - private final int[] size; - /** - * Total number of (one-dimensional) slots. - */ - private final int totalSize; - /** - * Index of last dimension. - */ - private final int last; - - /** - * Perform iteration over the multidimensional counter. - */ - public class Iterator implements java.util.Iterator { - /** - * Multidimensional counter. - */ - private final int[] counter = new int[dimension]; - /** - * Unidimensional counter. - */ - private int count = -1; - /** - * Maximum value for {@link #count}. - */ - private final int maxCount = totalSize - 1; - - /** - * Create an iterator - * @see #iterator() - */ - Iterator() { - counter[last] = -1; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean hasNext() { - return count < maxCount; - } - - /** - * @return the unidimensional count after the counter has been - * incremented by {@code 1}. - * @throws NoSuchElementException if {@link #hasNext()} would have - * returned {@code false}. - */ - @Override - public Integer next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - - for (int i = last; i >= 0; i--) { - if (counter[i] == size[i] - 1) { - counter[i] = 0; - } else { - ++counter[i]; - break; - } - } - - return ++count; - } - - /** - * Get the current unidimensional counter slot. - * - * @return the index within the unidimensionl counter. - */ - public int getCount() { - return count; - } - /** - * Get the current multidimensional counter slots. - * - * @return the indices within the multidimensional counter. - */ - public int[] getCounts() { - return MathArrays.copyOf(counter); - } - - /** - * Get the current count in the selected dimension. - * - * @param dim Dimension index. - * @return the count at the corresponding index for the current state - * of the iterator. - * @throws IndexOutOfBoundsException if {@code index} is not in the - * correct interval (as defined by the length of the argument in the - * {@link MultidimensionalCounter#MultidimensionalCounter(int[]) - * constructor of the enclosing class}). - */ - public int getCount(int dim) { - return counter[dim]; - } - - /** - * @throws UnsupportedOperationException always - */ - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - } - - /** - * Create a counter. - * - * @param size Counter sizes (number of slots in each dimension). - * @throws NotStrictlyPositiveException if one of the sizes is - * negative or zero. - */ - public MultidimensionalCounter(int ... size) throws NotStrictlyPositiveException { - dimension = size.length; - this.size = MathArrays.copyOf(size); - - uniCounterOffset = new int[dimension]; - - last = dimension - 1; - int tS = size[last]; - for (int i = 0; i < last; i++) { - int count = 1; - for (int j = i + 1; j < dimension; j++) { - count *= size[j]; - } - uniCounterOffset[i] = count; - tS *= size[i]; - } - uniCounterOffset[last] = 0; - - if (tS <= 0) { - throw new NotStrictlyPositiveException(tS); - } - - totalSize = tS; - } - - /** - * Create an iterator over this counter. - * - * @return the iterator. - */ - @Override - public Iterator iterator() { - return new Iterator(); - } - - /** - * Get the number of dimensions of the multidimensional counter. - * - * @return the number of dimensions. - */ - public int getDimension() { - return dimension; - } - - /** - * Convert to multidimensional counter. - * - * @param index Index in unidimensional counter. - * @return the multidimensional counts. - * @throws OutOfRangeException if {@code index} is not between - * {@code 0} and the value returned by {@link #getSize()} (excluded). - */ - public int[] getCounts(int index) throws OutOfRangeException { - if (index < 0 || - index >= totalSize) { - throw new OutOfRangeException(index, 0, totalSize); - } - - final int[] indices = new int[dimension]; - - int count = 0; - for (int i = 0; i < last; i++) { - int idx = 0; - final int offset = uniCounterOffset[i]; - while (count <= index) { - count += offset; - ++idx; - } - --idx; - count -= offset; - indices[i] = idx; - } - - indices[last] = index - count; - - return indices; - } - - /** - * Convert to unidimensional counter. - * - * @param c Indices in multidimensional counter. - * @return the index within the unidimensionl counter. - * @throws DimensionMismatchException if the size of {@code c} - * does not match the size of the array given in the constructor. - * @throws OutOfRangeException if a value of {@code c} is not in - * the range of the corresponding dimension, as defined in the - * {@link MultidimensionalCounter#MultidimensionalCounter(int...) constructor}. - */ - public int getCount(int ... c) - throws OutOfRangeException, DimensionMismatchException { - if (c.length != dimension) { - throw new DimensionMismatchException(c.length, dimension); - } - int count = 0; - for (int i = 0; i < dimension; i++) { - final int index = c[i]; - if (index < 0 || - index >= size[i]) { - throw new OutOfRangeException(index, 0, size[i] - 1); - } - count += uniCounterOffset[i] * c[i]; - } - return count + c[last]; - } - - /** - * Get the total number of elements. - * - * @return the total size of the unidimensional counter. - */ - public int getSize() { - return totalSize; - } - /** - * Get the number of multidimensional counter slots in each dimension. - * - * @return the sizes of the multidimensional counter in each dimension. - */ - public int[] getSizes() { - return MathArrays.copyOf(size); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - for (int i = 0; i < dimension; i++) { - sb.append("[").append(getCount(i)).append("]"); - } - return sb.toString(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/NumberTransformer.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/NumberTransformer.java deleted file mode 100644 index 8c411abe6..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/NumberTransformer.java +++ /dev/null @@ -1,38 +0,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. - */ -package org.apache.commons.math4.util; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; - -/** - * Subclasses implementing this interface can transform Objects to doubles. - * - * No longer extends Serializable since 2.0 - * - */ -public interface NumberTransformer { - - /** - * Implementing this interface provides a facility to transform - * from Object to Double. - * - * @param o the Object to be transformed. - * @return the double value of the Object. - * @throws MathIllegalArgumentException if the Object can not be transformed into a Double. - */ - double transform(Object o) throws MathIllegalArgumentException; -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/OpenIntToDoubleHashMap.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/OpenIntToDoubleHashMap.java deleted file mode 100644 index b03ca95b9..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/OpenIntToDoubleHashMap.java +++ /dev/null @@ -1,596 +0,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. - */ - -package org.apache.commons.math4.util; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.Serializable; -import java.util.ConcurrentModificationException; -import java.util.NoSuchElementException; - -/** - * Open addressed map from int to double. - *

This class provides a dedicated map from integers to doubles with a - * much smaller memory overhead than standard java.util.Map.

- *

This class is not synchronized. The specialized iterators returned by - * {@link #iterator()} are fail-fast: they throw a - * ConcurrentModificationException when they detect the map has been - * modified during iteration.

- * @since 2.0 - */ -public class OpenIntToDoubleHashMap implements Serializable { - - /** Status indicator for free table entries. */ - protected static final byte FREE = 0; - - /** Status indicator for full table entries. */ - protected static final byte FULL = 1; - - /** Status indicator for removed table entries. */ - protected static final byte REMOVED = 2; - - /** Serializable version identifier */ - private static final long serialVersionUID = -3646337053166149105L; - - /** Load factor for the map. */ - private static final float LOAD_FACTOR = 0.5f; - - /** Default starting size. - *

This must be a power of two for bit mask to work properly.

- */ - private static final int DEFAULT_EXPECTED_SIZE = 16; - - /** Multiplier for size growth when map fills up. - *

This must be a power of two for bit mask to work properly.

- */ - private static final int RESIZE_MULTIPLIER = 2; - - /** Number of bits to perturb the index when probing for collision resolution. */ - private static final int PERTURB_SHIFT = 5; - - /** Keys table. */ - private int[] keys; - - /** Values table. */ - private double[] values; - - /** States table. */ - private byte[] states; - - /** Return value for missing entries. */ - private final double missingEntries; - - /** Current size of the map. */ - private int size; - - /** Bit mask for hash values. */ - private int mask; - - /** Modifications count. */ - private transient int count; - - /** - * Build an empty map with default size and using NaN for missing entries. - */ - public OpenIntToDoubleHashMap() { - this(DEFAULT_EXPECTED_SIZE, Double.NaN); - } - - /** - * Build an empty map with default size - * @param missingEntries value to return when a missing entry is fetched - */ - public OpenIntToDoubleHashMap(final double missingEntries) { - this(DEFAULT_EXPECTED_SIZE, missingEntries); - } - - /** - * Build an empty map with specified size and using NaN for missing entries. - * @param expectedSize expected number of elements in the map - */ - public OpenIntToDoubleHashMap(final int expectedSize) { - this(expectedSize, Double.NaN); - } - - /** - * Build an empty map with specified size. - * @param expectedSize expected number of elements in the map - * @param missingEntries value to return when a missing entry is fetched - */ - public OpenIntToDoubleHashMap(final int expectedSize, - final double missingEntries) { - final int capacity = computeCapacity(expectedSize); - keys = new int[capacity]; - values = new double[capacity]; - states = new byte[capacity]; - this.missingEntries = missingEntries; - mask = capacity - 1; - } - - /** - * Copy constructor. - * @param source map to copy - */ - public OpenIntToDoubleHashMap(final OpenIntToDoubleHashMap source) { - final int length = source.keys.length; - keys = new int[length]; - System.arraycopy(source.keys, 0, keys, 0, length); - values = new double[length]; - System.arraycopy(source.values, 0, values, 0, length); - states = new byte[length]; - System.arraycopy(source.states, 0, states, 0, length); - missingEntries = source.missingEntries; - size = source.size; - mask = source.mask; - count = source.count; - } - - /** - * Compute the capacity needed for a given size. - * @param expectedSize expected size of the map - * @return capacity to use for the specified size - */ - private static int computeCapacity(final int expectedSize) { - if (expectedSize == 0) { - return 1; - } - final int capacity = (int) FastMath.ceil(expectedSize / LOAD_FACTOR); - final int powerOfTwo = Integer.highestOneBit(capacity); - if (powerOfTwo == capacity) { - return capacity; - } - return nextPowerOfTwo(capacity); - } - - /** - * Find the smallest power of two greater than the input value - * @param i input value - * @return smallest power of two greater than the input value - */ - private static int nextPowerOfTwo(final int i) { - return Integer.highestOneBit(i) << 1; - } - - /** - * Get the stored value associated with the given key - * @param key key associated with the data - * @return data associated with the key - */ - public double get(final int key) { - - final int hash = hashOf(key); - int index = hash & mask; - if (containsKey(key, index)) { - return values[index]; - } - - if (states[index] == FREE) { - return missingEntries; - } - - int j = index; - for (int perturb = perturb(hash); states[index] != FREE; perturb >>= PERTURB_SHIFT) { - j = probe(perturb, j); - index = j & mask; - if (containsKey(key, index)) { - return values[index]; - } - } - - return missingEntries; - - } - - /** - * Check if a value is associated with a key. - * @param key key to check - * @return true if a value is associated with key - */ - public boolean containsKey(final int key) { - - final int hash = hashOf(key); - int index = hash & mask; - if (containsKey(key, index)) { - return true; - } - - if (states[index] == FREE) { - return false; - } - - int j = index; - for (int perturb = perturb(hash); states[index] != FREE; perturb >>= PERTURB_SHIFT) { - j = probe(perturb, j); - index = j & mask; - if (containsKey(key, index)) { - return true; - } - } - - return false; - - } - - /** - * Get an iterator over map elements. - *

The specialized iterators returned are fail-fast: they throw a - * ConcurrentModificationException when they detect the map - * has been modified during iteration.

- * @return iterator over the map elements - */ - public Iterator iterator() { - return new Iterator(); - } - - /** - * Perturb the hash for starting probing. - * @param hash initial hash - * @return perturbed hash - */ - private static int perturb(final int hash) { - return hash & 0x7fffffff; - } - - /** - * Find the index at which a key should be inserted - * @param key key to lookup - * @return index at which key should be inserted - */ - private int findInsertionIndex(final int key) { - return findInsertionIndex(keys, states, key, mask); - } - - /** - * Find the index at which a key should be inserted - * @param keys keys table - * @param states states table - * @param key key to lookup - * @param mask bit mask for hash values - * @return index at which key should be inserted - */ - private static int findInsertionIndex(final int[] keys, final byte[] states, - final int key, final int mask) { - final int hash = hashOf(key); - int index = hash & mask; - if (states[index] == FREE) { - return index; - } else if (states[index] == FULL && keys[index] == key) { - return changeIndexSign(index); - } - - int perturb = perturb(hash); - int j = index; - if (states[index] == FULL) { - while (true) { - j = probe(perturb, j); - index = j & mask; - perturb >>= PERTURB_SHIFT; - - if (states[index] != FULL || keys[index] == key) { - break; - } - } - } - - if (states[index] == FREE) { - return index; - } else if (states[index] == FULL) { - // due to the loop exit condition, - // if (states[index] == FULL) then keys[index] == key - return changeIndexSign(index); - } - - final int firstRemoved = index; - while (true) { - j = probe(perturb, j); - index = j & mask; - - if (states[index] == FREE) { - return firstRemoved; - } else if (states[index] == FULL && keys[index] == key) { - return changeIndexSign(index); - } - - perturb >>= PERTURB_SHIFT; - - } - - } - - /** - * Compute next probe for collision resolution - * @param perturb perturbed hash - * @param j previous probe - * @return next probe - */ - private static int probe(final int perturb, final int j) { - return (j << 2) + j + perturb + 1; - } - - /** - * Change the index sign - * @param index initial index - * @return changed index - */ - private static int changeIndexSign(final int index) { - return -index - 1; - } - - /** - * Get the number of elements stored in the map. - * @return number of elements stored in the map - */ - public int size() { - return size; - } - - - /** - * Remove the value associated with a key. - * @param key key to which the value is associated - * @return removed value - */ - public double remove(final int key) { - - final int hash = hashOf(key); - int index = hash & mask; - if (containsKey(key, index)) { - return doRemove(index); - } - - if (states[index] == FREE) { - return missingEntries; - } - - int j = index; - for (int perturb = perturb(hash); states[index] != FREE; perturb >>= PERTURB_SHIFT) { - j = probe(perturb, j); - index = j & mask; - if (containsKey(key, index)) { - return doRemove(index); - } - } - - return missingEntries; - - } - - /** - * Check if the tables contain an element associated with specified key - * at specified index. - * @param key key to check - * @param index index to check - * @return true if an element is associated with key at index - */ - private boolean containsKey(final int key, final int index) { - return (key != 0 || states[index] == FULL) && keys[index] == key; - } - - /** - * Remove an element at specified index. - * @param index index of the element to remove - * @return removed value - */ - private double doRemove(int index) { - keys[index] = 0; - states[index] = REMOVED; - final double previous = values[index]; - values[index] = missingEntries; - --size; - ++count; - return previous; - } - - /** - * Put a value associated with a key in the map. - * @param key key to which value is associated - * @param value value to put in the map - * @return previous value associated with the key - */ - public double put(final int key, final double value) { - int index = findInsertionIndex(key); - double previous = missingEntries; - boolean newMapping = true; - if (index < 0) { - index = changeIndexSign(index); - previous = values[index]; - newMapping = false; - } - keys[index] = key; - states[index] = FULL; - values[index] = value; - if (newMapping) { - ++size; - if (shouldGrowTable()) { - growTable(); - } - ++count; - } - return previous; - - } - - /** - * Grow the tables. - */ - private void growTable() { - - final int oldLength = states.length; - final int[] oldKeys = keys; - final double[] oldValues = values; - final byte[] oldStates = states; - - final int newLength = RESIZE_MULTIPLIER * oldLength; - final int[] newKeys = new int[newLength]; - final double[] newValues = new double[newLength]; - final byte[] newStates = new byte[newLength]; - final int newMask = newLength - 1; - for (int i = 0; i < oldLength; ++i) { - if (oldStates[i] == FULL) { - final int key = oldKeys[i]; - final int index = findInsertionIndex(newKeys, newStates, key, newMask); - newKeys[index] = key; - newValues[index] = oldValues[i]; - newStates[index] = FULL; - } - } - - mask = newMask; - keys = newKeys; - values = newValues; - states = newStates; - - } - - /** - * Check if tables should grow due to increased size. - * @return true if tables should grow - */ - private boolean shouldGrowTable() { - return size > (mask + 1) * LOAD_FACTOR; - } - - /** - * Compute the hash value of a key - * @param key key to hash - * @return hash value of the key - */ - private static int hashOf(final int key) { - final int h = key ^ ((key >>> 20) ^ (key >>> 12)); - return h ^ (h >>> 7) ^ (h >>> 4); - } - - - /** Iterator class for the map. */ - public class Iterator { - - /** Reference modification count. */ - private final int referenceCount; - - /** Index of current element. */ - private int current; - - /** Index of next element. */ - private int next; - - /** - * Simple constructor. - */ - private Iterator() { - - // preserve the modification count of the map to detect concurrent modifications later - referenceCount = count; - - // initialize current index - next = -1; - try { - advance(); - } catch (NoSuchElementException nsee) { // NOPMD - // ignored - } - - } - - /** - * Check if there is a next element in the map. - * @return true if there is a next element - */ - public boolean hasNext() { - return next >= 0; - } - - /** - * Get the key of current entry. - * @return key of current entry - * @exception ConcurrentModificationException if the map is modified during iteration - * @exception NoSuchElementException if there is no element left in the map - */ - public int key() - throws ConcurrentModificationException, NoSuchElementException { - if (referenceCount != count) { - throw new ConcurrentModificationException(); - } - if (current < 0) { - throw new NoSuchElementException(); - } - return keys[current]; - } - - /** - * Get the value of current entry. - * @return value of current entry - * @exception ConcurrentModificationException if the map is modified during iteration - * @exception NoSuchElementException if there is no element left in the map - */ - public double value() - throws ConcurrentModificationException, NoSuchElementException { - if (referenceCount != count) { - throw new ConcurrentModificationException(); - } - if (current < 0) { - throw new NoSuchElementException(); - } - return values[current]; - } - - /** - * Advance iterator one step further. - * @exception ConcurrentModificationException if the map is modified during iteration - * @exception NoSuchElementException if there is no element left in the map - */ - public void advance() - throws ConcurrentModificationException, NoSuchElementException { - - if (referenceCount != count) { - throw new ConcurrentModificationException(); - } - - // advance on step - current = next; - - // prepare next step - try { - while (states[++next] != FULL) { // NOPMD - // nothing to do - } - } catch (ArrayIndexOutOfBoundsException e) { - next = -2; - if (current < 0) { - throw new NoSuchElementException(); - } - } - - } - - } - - /** - * Read a serialized object. - * @param stream input stream - * @throws IOException if object cannot be read - * @throws ClassNotFoundException if the class corresponding - * to the serialized object cannot be found - */ - private void readObject(final ObjectInputStream stream) - throws IOException, ClassNotFoundException { - stream.defaultReadObject(); - count = 0; - } - - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/OpenIntToFieldHashMap.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/OpenIntToFieldHashMap.java deleted file mode 100644 index 1fb034adc..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/OpenIntToFieldHashMap.java +++ /dev/null @@ -1,617 +0,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. - */ -package org.apache.commons.math4.util; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.Serializable; -import java.lang.reflect.Array; -import java.util.ConcurrentModificationException; -import java.util.NoSuchElementException; - -import org.apache.commons.math4.Field; -import org.apache.commons.math4.FieldElement; - -/** - * Open addressed map from int to FieldElement. - *

This class provides a dedicated map from integers to FieldElements with a - * much smaller memory overhead than standard java.util.Map.

- *

This class is not synchronized. The specialized iterators returned by - * {@link #iterator()} are fail-fast: they throw a - * ConcurrentModificationException when they detect the map has been - * modified during iteration.

- * @param the type of the field elements - * @since 2.0 - */ -public class OpenIntToFieldHashMap> implements Serializable { - - /** Status indicator for free table entries. */ - protected static final byte FREE = 0; - - /** Status indicator for full table entries. */ - protected static final byte FULL = 1; - - /** Status indicator for removed table entries. */ - protected static final byte REMOVED = 2; - - /** Serializable version identifier. */ - private static final long serialVersionUID = -9179080286849120720L; - - /** Load factor for the map. */ - private static final float LOAD_FACTOR = 0.5f; - - /** Default starting size. - *

This must be a power of two for bit mask to work properly.

- */ - private static final int DEFAULT_EXPECTED_SIZE = 16; - - /** Multiplier for size growth when map fills up. - *

This must be a power of two for bit mask to work properly.

- */ - private static final int RESIZE_MULTIPLIER = 2; - - /** Number of bits to perturb the index when probing for collision resolution. */ - private static final int PERTURB_SHIFT = 5; - - /** Field to which the elements belong. */ - private final Field field; - - /** Keys table. */ - private int[] keys; - - /** Values table. */ - private T[] values; - - /** States table. */ - private byte[] states; - - /** Return value for missing entries. */ - private final T missingEntries; - - /** Current size of the map. */ - private int size; - - /** Bit mask for hash values. */ - private int mask; - - /** Modifications count. */ - private transient int count; - - /** - * Build an empty map with default size and using zero for missing entries. - * @param field field to which the elements belong - */ - public OpenIntToFieldHashMap(final Fieldfield) { - this(field, DEFAULT_EXPECTED_SIZE, field.getZero()); - } - - /** - * Build an empty map with default size - * @param field field to which the elements belong - * @param missingEntries value to return when a missing entry is fetched - */ - public OpenIntToFieldHashMap(final Fieldfield, final T missingEntries) { - this(field,DEFAULT_EXPECTED_SIZE, missingEntries); - } - - /** - * Build an empty map with specified size and using zero for missing entries. - * @param field field to which the elements belong - * @param expectedSize expected number of elements in the map - */ - public OpenIntToFieldHashMap(final Field field,final int expectedSize) { - this(field,expectedSize, field.getZero()); - } - - /** - * Build an empty map with specified size. - * @param field field to which the elements belong - * @param expectedSize expected number of elements in the map - * @param missingEntries value to return when a missing entry is fetched - */ - public OpenIntToFieldHashMap(final Field field,final int expectedSize, - final T missingEntries) { - this.field = field; - final int capacity = computeCapacity(expectedSize); - keys = new int[capacity]; - values = buildArray(capacity); - states = new byte[capacity]; - this.missingEntries = missingEntries; - mask = capacity - 1; - } - - /** - * Copy constructor. - * @param source map to copy - */ - public OpenIntToFieldHashMap(final OpenIntToFieldHashMap source) { - field = source.field; - final int length = source.keys.length; - keys = new int[length]; - System.arraycopy(source.keys, 0, keys, 0, length); - values = buildArray(length); - System.arraycopy(source.values, 0, values, 0, length); - states = new byte[length]; - System.arraycopy(source.states, 0, states, 0, length); - missingEntries = source.missingEntries; - size = source.size; - mask = source.mask; - count = source.count; - } - - /** - * Compute the capacity needed for a given size. - * @param expectedSize expected size of the map - * @return capacity to use for the specified size - */ - private static int computeCapacity(final int expectedSize) { - if (expectedSize == 0) { - return 1; - } - final int capacity = (int) FastMath.ceil(expectedSize / LOAD_FACTOR); - final int powerOfTwo = Integer.highestOneBit(capacity); - if (powerOfTwo == capacity) { - return capacity; - } - return nextPowerOfTwo(capacity); - } - - /** - * Find the smallest power of two greater than the input value - * @param i input value - * @return smallest power of two greater than the input value - */ - private static int nextPowerOfTwo(final int i) { - return Integer.highestOneBit(i) << 1; - } - - /** - * Get the stored value associated with the given key - * @param key key associated with the data - * @return data associated with the key - */ - public T get(final int key) { - - final int hash = hashOf(key); - int index = hash & mask; - if (containsKey(key, index)) { - return values[index]; - } - - if (states[index] == FREE) { - return missingEntries; - } - - int j = index; - for (int perturb = perturb(hash); states[index] != FREE; perturb >>= PERTURB_SHIFT) { - j = probe(perturb, j); - index = j & mask; - if (containsKey(key, index)) { - return values[index]; - } - } - - return missingEntries; - - } - - /** - * Check if a value is associated with a key. - * @param key key to check - * @return true if a value is associated with key - */ - public boolean containsKey(final int key) { - - final int hash = hashOf(key); - int index = hash & mask; - if (containsKey(key, index)) { - return true; - } - - if (states[index] == FREE) { - return false; - } - - int j = index; - for (int perturb = perturb(hash); states[index] != FREE; perturb >>= PERTURB_SHIFT) { - j = probe(perturb, j); - index = j & mask; - if (containsKey(key, index)) { - return true; - } - } - - return false; - - } - - /** - * Get an iterator over map elements. - *

The specialized iterators returned are fail-fast: they throw a - * ConcurrentModificationException when they detect the map - * has been modified during iteration.

- * @return iterator over the map elements - */ - public Iterator iterator() { - return new Iterator(); - } - - /** - * Perturb the hash for starting probing. - * @param hash initial hash - * @return perturbed hash - */ - private static int perturb(final int hash) { - return hash & 0x7fffffff; - } - - /** - * Find the index at which a key should be inserted - * @param key key to lookup - * @return index at which key should be inserted - */ - private int findInsertionIndex(final int key) { - return findInsertionIndex(keys, states, key, mask); - } - - /** - * Find the index at which a key should be inserted - * @param keys keys table - * @param states states table - * @param key key to lookup - * @param mask bit mask for hash values - * @return index at which key should be inserted - */ - private static int findInsertionIndex(final int[] keys, final byte[] states, - final int key, final int mask) { - final int hash = hashOf(key); - int index = hash & mask; - if (states[index] == FREE) { - return index; - } else if (states[index] == FULL && keys[index] == key) { - return changeIndexSign(index); - } - - int perturb = perturb(hash); - int j = index; - if (states[index] == FULL) { - while (true) { - j = probe(perturb, j); - index = j & mask; - perturb >>= PERTURB_SHIFT; - - if (states[index] != FULL || keys[index] == key) { - break; - } - } - } - - if (states[index] == FREE) { - return index; - } else if (states[index] == FULL) { - // due to the loop exit condition, - // if (states[index] == FULL) then keys[index] == key - return changeIndexSign(index); - } - - final int firstRemoved = index; - while (true) { - j = probe(perturb, j); - index = j & mask; - - if (states[index] == FREE) { - return firstRemoved; - } else if (states[index] == FULL && keys[index] == key) { - return changeIndexSign(index); - } - - perturb >>= PERTURB_SHIFT; - - } - - } - - /** - * Compute next probe for collision resolution - * @param perturb perturbed hash - * @param j previous probe - * @return next probe - */ - private static int probe(final int perturb, final int j) { - return (j << 2) + j + perturb + 1; - } - - /** - * Change the index sign - * @param index initial index - * @return changed index - */ - private static int changeIndexSign(final int index) { - return -index - 1; - } - - /** - * Get the number of elements stored in the map. - * @return number of elements stored in the map - */ - public int size() { - return size; - } - - - /** - * Remove the value associated with a key. - * @param key key to which the value is associated - * @return removed value - */ - public T remove(final int key) { - - final int hash = hashOf(key); - int index = hash & mask; - if (containsKey(key, index)) { - return doRemove(index); - } - - if (states[index] == FREE) { - return missingEntries; - } - - int j = index; - for (int perturb = perturb(hash); states[index] != FREE; perturb >>= PERTURB_SHIFT) { - j = probe(perturb, j); - index = j & mask; - if (containsKey(key, index)) { - return doRemove(index); - } - } - - return missingEntries; - - } - - /** - * Check if the tables contain an element associated with specified key - * at specified index. - * @param key key to check - * @param index index to check - * @return true if an element is associated with key at index - */ - private boolean containsKey(final int key, final int index) { - return (key != 0 || states[index] == FULL) && keys[index] == key; - } - - /** - * Remove an element at specified index. - * @param index index of the element to remove - * @return removed value - */ - private T doRemove(int index) { - keys[index] = 0; - states[index] = REMOVED; - final T previous = values[index]; - values[index] = missingEntries; - --size; - ++count; - return previous; - } - - /** - * Put a value associated with a key in the map. - * @param key key to which value is associated - * @param value value to put in the map - * @return previous value associated with the key - */ - public T put(final int key, final T value) { - int index = findInsertionIndex(key); - T previous = missingEntries; - boolean newMapping = true; - if (index < 0) { - index = changeIndexSign(index); - previous = values[index]; - newMapping = false; - } - keys[index] = key; - states[index] = FULL; - values[index] = value; - if (newMapping) { - ++size; - if (shouldGrowTable()) { - growTable(); - } - ++count; - } - return previous; - - } - - /** - * Grow the tables. - */ - private void growTable() { - - final int oldLength = states.length; - final int[] oldKeys = keys; - final T[] oldValues = values; - final byte[] oldStates = states; - - final int newLength = RESIZE_MULTIPLIER * oldLength; - final int[] newKeys = new int[newLength]; - final T[] newValues = buildArray(newLength); - final byte[] newStates = new byte[newLength]; - final int newMask = newLength - 1; - for (int i = 0; i < oldLength; ++i) { - if (oldStates[i] == FULL) { - final int key = oldKeys[i]; - final int index = findInsertionIndex(newKeys, newStates, key, newMask); - newKeys[index] = key; - newValues[index] = oldValues[i]; - newStates[index] = FULL; - } - } - - mask = newMask; - keys = newKeys; - values = newValues; - states = newStates; - - } - - /** - * Check if tables should grow due to increased size. - * @return true if tables should grow - */ - private boolean shouldGrowTable() { - return size > (mask + 1) * LOAD_FACTOR; - } - - /** - * Compute the hash value of a key - * @param key key to hash - * @return hash value of the key - */ - private static int hashOf(final int key) { - final int h = key ^ ((key >>> 20) ^ (key >>> 12)); - return h ^ (h >>> 7) ^ (h >>> 4); - } - - - /** Iterator class for the map. */ - public class Iterator { - - /** Reference modification count. */ - private final int referenceCount; - - /** Index of current element. */ - private int current; - - /** Index of next element. */ - private int next; - - /** - * Simple constructor. - */ - private Iterator() { - - // preserve the modification count of the map to detect concurrent modifications later - referenceCount = count; - - // initialize current index - next = -1; - try { - advance(); - } catch (NoSuchElementException nsee) { // NOPMD - // ignored - } - - } - - /** - * Check if there is a next element in the map. - * @return true if there is a next element - */ - public boolean hasNext() { - return next >= 0; - } - - /** - * Get the key of current entry. - * @return key of current entry - * @exception ConcurrentModificationException if the map is modified during iteration - * @exception NoSuchElementException if there is no element left in the map - */ - public int key() - throws ConcurrentModificationException, NoSuchElementException { - if (referenceCount != count) { - throw new ConcurrentModificationException(); - } - if (current < 0) { - throw new NoSuchElementException(); - } - return keys[current]; - } - - /** - * Get the value of current entry. - * @return value of current entry - * @exception ConcurrentModificationException if the map is modified during iteration - * @exception NoSuchElementException if there is no element left in the map - */ - public T value() - throws ConcurrentModificationException, NoSuchElementException { - if (referenceCount != count) { - throw new ConcurrentModificationException(); - } - if (current < 0) { - throw new NoSuchElementException(); - } - return values[current]; - } - - /** - * Advance iterator one step further. - * @exception ConcurrentModificationException if the map is modified during iteration - * @exception NoSuchElementException if there is no element left in the map - */ - public void advance() - throws ConcurrentModificationException, NoSuchElementException { - - if (referenceCount != count) { - throw new ConcurrentModificationException(); - } - - // advance on step - current = next; - - // prepare next step - try { - while (states[++next] != FULL) { // NOPMD - // nothing to do - } - } catch (ArrayIndexOutOfBoundsException e) { - next = -2; - if (current < 0) { - throw new NoSuchElementException(); - } - } - - } - - } - - /** - * Read a serialized object. - * @param stream input stream - * @throws IOException if object cannot be read - * @throws ClassNotFoundException if the class corresponding - * to the serialized object cannot be found - */ - private void readObject(final ObjectInputStream stream) - throws IOException, ClassNotFoundException { - stream.defaultReadObject(); - count = 0; - } - - /** Build an array of elements. - * @param length size of the array to build - * @return a new array - */ - @SuppressWarnings("unchecked") // field is of type T - private T[] buildArray(final int length) { - return (T[]) Array.newInstance(field.getRuntimeClass(), length); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/Pair.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/Pair.java deleted file mode 100644 index 6a9ad86bf..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/Pair.java +++ /dev/null @@ -1,156 +0,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. - */ -package org.apache.commons.math4.util; - -/** - * Generic pair. - *
- * Although the instances of this class are immutable, it is impossible - * to ensure that the references passed to the constructor will not be - * modified by the caller. - * - * @param Key type. - * @param Value type. - * - * @since 3.0 - */ -public class Pair { - /** Key. */ - private final K key; - /** Value. */ - private final V value; - - /** - * Create an entry representing a mapping from the specified key to the - * specified value. - * - * @param k Key (first element of the pair). - * @param v Value (second element of the pair). - */ - public Pair(K k, V v) { - key = k; - value = v; - } - - /** - * Create an entry representing the same mapping as the specified entry. - * - * @param entry Entry to copy. - */ - public Pair(Pair entry) { - this(entry.getKey(), entry.getValue()); - } - - /** - * Get the key. - * - * @return the key (first element of the pair). - */ - public K getKey() { - return key; - } - - /** - * Get the value. - * - * @return the value (second element of the pair). - */ - public V getValue() { - return value; - } - - /** - * Get the first element of the pair. - * - * @return the first element of the pair. - * @since 3.1 - */ - public K getFirst() { - return key; - } - - /** - * Get the second element of the pair. - * - * @return the second element of the pair. - * @since 3.1 - */ - public V getSecond() { - return value; - } - - /** - * Compare the specified object with this entry for equality. - * - * @param o Object. - * @return {@code true} if the given object is also a map entry and - * the two entries represent the same mapping. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof Pair)) { - return false; - } else { - Pair oP = (Pair) o; - return (key == null ? - oP.key == null : - key.equals(oP.key)) && - (value == null ? - oP.value == null : - value.equals(oP.value)); - } - } - - /** - * Compute a hash code. - * - * @return the hash code value. - */ - @Override - public int hashCode() { - int result = key == null ? 0 : key.hashCode(); - - final int h = value == null ? 0 : value.hashCode(); - result = 37 * result + h ^ (h >>> 16); - - return result; - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "[" + getKey() + ", " + getValue() + "]"; - } - - /** - * Convenience factory method that calls the - * {@link #Pair(Object, Object) constructor}. - * - * @param the key type - * @param the value type - * @param k First element of the pair. - * @param v Second element of the pair. - * @return a new {@code Pair} containing {@code k} and {@code v}. - * @since 3.3 - */ - public static Pair create(K k, V v) { - return new Pair<>(k, v); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/PivotingStrategyInterface.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/PivotingStrategyInterface.java deleted file mode 100644 index 36a3bcbaa..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/PivotingStrategyInterface.java +++ /dev/null @@ -1,44 +0,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. - */ -package org.apache.commons.math4.util; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; - - -/** - * A strategy to pick a pivoting index of an array for doing partitioning. - * @see MedianOf3PivotingStrategy - * @see RandomPivotingStrategy - * @see CentralPivotingStrategy - * @since 3.4 - */ -public interface PivotingStrategyInterface { - - /** - * Find pivot index of the array so that partition and Kth - * element selection can be made - * @param work data array - * @param begin index of the first element of the slice - * @param end index after the last element of the slice - * @return the index of the pivot element chosen between the - * first and the last element of the array slice - * @throws MathIllegalArgumentException when indices exceeds range - */ - int pivotIndex(double[] work, int begin, int end) - throws MathIllegalArgumentException; - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/RandomPivotingStrategy.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/RandomPivotingStrategy.java deleted file mode 100644 index f8b0ac760..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/RandomPivotingStrategy.java +++ /dev/null @@ -1,101 +0,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. - */ -package org.apache.commons.math4.util; - -import java.io.Serializable; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.io.ObjectInputStream; -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.rng.RestorableUniformRandomProvider; -import org.apache.commons.rng.simple.RandomSource; -import org.apache.commons.rng.core.RandomProviderDefaultState; - -/** - * A strategy of selecting random index between begin and end indices. - * - * @since 3.4 - */ -public class RandomPivotingStrategy implements PivotingStrategyInterface, Serializable { - /** Serializable UID. */ - private static final long serialVersionUID = 20160517L; - /** Source of randomness. */ - private final RandomSource randomSource; - /** Random generator to use for selecting pivot. */ - private transient RestorableUniformRandomProvider random; - - /** - * Simple constructor. - * - * @param randomSource RNG to use for selecting pivot. - * @param seed Seed for initializing the RNG. - * - * @since 4.0 - */ - public RandomPivotingStrategy(RandomSource randomSource, - long seed) { - this.randomSource = randomSource; - random = RandomSource.create(randomSource, seed); - } - - /** - * {@inheritDoc} - * - * A uniform random pivot selection between begin and end indices. - * - * @return The index corresponding to a random uniformly selected - * value between first and the last indices of the array slice - * @throws MathIllegalArgumentException when indices exceeds range - */ - @Override - public int pivotIndex(final double[] work, final int begin, final int end) - throws MathIllegalArgumentException { - MathArrays.verifyValues(work, begin, end-begin); - return begin + random.nextInt(end - begin - 1); - } - - /** - * @param out Output stream. - * @throws IOException if an error occurs. - */ - private void writeObject(ObjectOutputStream out) - throws IOException { - // Write non-transient fields. - out.defaultWriteObject(); - - // Save current state. - out.writeObject(((RandomProviderDefaultState) random.saveState()).getState()); - } - - /** - * @param in Input stream. - * @throws IOException if an error occurs. - * @throws ClassNotFoundException if an error occurs. - */ - private void readObject(ObjectInputStream in) - throws IOException, - ClassNotFoundException { - // Read non-transient fields. - in.defaultReadObject(); - - // Recreate the "delegate" from serialized info. - random = RandomSource.create(randomSource); - // And restore its state. - final RandomProviderDefaultState state = new RandomProviderDefaultState((byte[]) in.readObject()); - random.restoreState(state); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/ResizableDoubleArray.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/ResizableDoubleArray.java deleted file mode 100644 index f4105125f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/ResizableDoubleArray.java +++ /dev/null @@ -1,849 +0,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. - */ -package org.apache.commons.math4.util; - -import java.io.Serializable; -import java.util.Arrays; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; -import org.apache.commons.math4.exception.MathIllegalStateException; -import org.apache.commons.math4.exception.NotStrictlyPositiveException; -import org.apache.commons.math4.exception.NullArgumentException; -import org.apache.commons.math4.exception.NumberIsTooSmallException; -import org.apache.commons.math4.exception.util.LocalizedFormats; - -/** - * A variable length {@link DoubleArray} implementation that automatically - * handles expanding and contracting its internal storage array as elements - * are added and removed. - *

- * The internal storage array starts with capacity determined by the - * {@code initialCapacity} property, which can be set by the constructor. - * The default initial capacity is 16. Adding elements using - * {@link #addElement(double)} appends elements to the end of the array. - * When there are no open entries at the end of the internal storage array, - * the array is expanded. The size of the expanded array depends on the - * {@code expansionMode} and {@code expansionFactor} properties. - * The {@code expansionMode} determines whether the size of the array is - * multiplied by the {@code expansionFactor} - * ({@link ExpansionMode#MULTIPLICATIVE}) or if the expansion is additive - * ({@link ExpansionMode#ADDITIVE} -- {@code expansionFactor} storage - * locations added). - * The default {@code expansionMode} is {@code MULTIPLICATIVE} and the default - * {@code expansionFactor} is 2. - *

- * The {@link #addElementRolling(double)} method adds a new element to the end - * of the internal storage array and adjusts the "usable window" of the - * internal array forward by one position (effectively making what was the - * second element the first, and so on). Repeated activations of this method - * (or activation of {@link #discardFrontElements(int)}) will effectively orphan - * the storage locations at the beginning of the internal storage array. To - * reclaim this storage, each time one of these methods is activated, the size - * of the internal storage array is compared to the number of addressable - * elements (the {@code numElements} property) and if the difference - * is too large, the internal array is contracted to size - * {@code numElements + 1}. The determination of when the internal - * storage array is "too large" depends on the {@code expansionMode} and - * {@code contractionFactor} properties. If the {@code expansionMode} - * is {@code MULTIPLICATIVE}, contraction is triggered when the - * ratio between storage array length and {@code numElements} exceeds - * {@code contractionFactor.} If the {@code expansionMode} - * is {@code ADDITIVE}, the number of excess storage locations - * is compared to {@code contractionFactor}. - *

- * To avoid cycles of expansions and contractions, the - * {@code expansionFactor} must not exceed the {@code contractionFactor}. - * Constructors and mutators for both of these properties enforce this - * requirement, throwing a {@code MathIllegalArgumentException} if it is - * violated. - *

- * Note: this class is NOT thread-safe. - */ -public class ResizableDoubleArray implements DoubleArray, Serializable { - /** Serializable version identifier. */ - private static final long serialVersionUID = -3485529955529426875L; - - /** Default value for initial capacity. */ - private static final int DEFAULT_INITIAL_CAPACITY = 16; - /** Default value for array size modifier. */ - private static final double DEFAULT_EXPANSION_FACTOR = 2.0; - /** Default value for expansion mode. */ - private static final ExpansionMode DEFAULT_EXPANSION_MODE = ExpansionMode.MULTIPLICATIVE; - /** - * Default value for the difference between {@link #contractionCriterion} - * and {@link #expansionFactor}. - */ - private static final double DEFAULT_CONTRACTION_DELTA = 0.5; - - /** - * The contraction criteria determines when the internal array will be - * contracted to fit the number of elements contained in the element - * array + 1. - */ - private final double contractionCriterion; - - /** - * The expansion factor of the array. When the array needs to be expanded, - * the new array size will be {@code internalArray.length * expansionFactor} - * if {@code expansionMode} is set to MULTIPLICATIVE, or - * {@code internalArray.length + expansionFactor} if - * {@code expansionMode} is set to ADDITIVE. - */ - private final double expansionFactor; - - /** - * Determines whether array expansion by {@code expansionFactor} - * is additive or multiplicative. - */ - private final ExpansionMode expansionMode; - - /** - * The internal storage array. - */ - private double[] internalArray; - - /** - * The number of addressable elements in the array. Note that this - * has nothing to do with the length of the internal storage array. - */ - private int numElements = 0; - - /** - * The position of the first addressable element in the internal storage - * array. The addressable elements in the array are - * {@code internalArray[startIndex],...,internalArray[startIndex + numElements - 1]}. - */ - private int startIndex = 0; - - /** - * Specification of expansion algorithm. - * @since 3.1 - */ - public enum ExpansionMode { - /** Multiplicative expansion mode. */ - MULTIPLICATIVE, - /** Additive expansion mode. */ - ADDITIVE - } - - /** - * Creates an instance with default properties. - *

    - *
  • {@code initialCapacity = 16}
  • - *
  • {@code expansionMode = MULTIPLICATIVE}
  • - *
  • {@code expansionFactor = 2.0}
  • - *
  • {@code contractionCriterion = 2.5}
  • - *
- */ - public ResizableDoubleArray() { - this(DEFAULT_INITIAL_CAPACITY); - } - - /** - * Creates an instance with the specified initial capacity. - *

- * Other properties take default values: - *

    - *
  • {@code expansionMode = MULTIPLICATIVE}
  • - *
  • {@code expansionFactor = 2.0}
  • - *
  • {@code contractionCriterion = 2.5}
  • - *
- * @param initialCapacity Initial size of the internal storage array. - * @throws MathIllegalArgumentException if {@code initialCapacity <= 0}. - */ - public ResizableDoubleArray(int initialCapacity) throws MathIllegalArgumentException { - this(initialCapacity, DEFAULT_EXPANSION_FACTOR); - } - - /** - * Creates an instance from an existing {@code double[]} with the - * initial capacity and numElements corresponding to the size of - * the supplied {@code double[]} array. - *

- * If the supplied array is null, a new empty array with the default - * initial capacity will be created. - * The input array is copied, not referenced. - * Other properties take default values: - *

    - *
  • {@code expansionMode = MULTIPLICATIVE}
  • - *
  • {@code expansionFactor = 2.0}
  • - *
  • {@code contractionCriterion = 2.5}
  • - *
- * - * @param initialArray initial array - * @since 2.2 - */ - public ResizableDoubleArray(double[] initialArray) { - this(initialArray == null || initialArray.length == 0 ? - DEFAULT_INITIAL_CAPACITY : - initialArray.length, - DEFAULT_EXPANSION_FACTOR, - DEFAULT_CONTRACTION_DELTA + DEFAULT_EXPANSION_FACTOR, - DEFAULT_EXPANSION_MODE, - initialArray); - } - - /** - * Creates an instance with the specified initial capacity - * and expansion factor. - *

- * The remaining properties take default values: - *

    - *
  • {@code expansionMode = MULTIPLICATIVE}
  • - *
  • {@code contractionCriterion = 0.5 + expansionFactor}
  • - *
- *

- * Throws MathIllegalArgumentException if the following conditions - * are not met: - *

    - *
  • {@code initialCapacity > 0}
  • - *
  • {@code expansionFactor > 1}
  • - *
- * - * @param initialCapacity Initial size of the internal storage array. - * @param expansionFactor The array will be expanded based on this parameter. - * @throws MathIllegalArgumentException if parameters are not valid. - * @since 3.1 - */ - public ResizableDoubleArray(int initialCapacity, double expansionFactor) throws MathIllegalArgumentException { - this(initialCapacity, expansionFactor, DEFAULT_CONTRACTION_DELTA + expansionFactor); - } - - /** - * Creates an instance with the specified initial capacity, - * expansion factor, and contraction criteria. - *

- * The expansion mode will default to {@code MULTIPLICATIVE}. - *

- * Throws MathIllegalArgumentException if the following conditions - * are not met: - *

    - *
  • {@code initialCapacity > 0}
  • - *
  • {@code expansionFactor > 1}
  • - *
  • {@code contractionCriterion >= expansionFactor}
  • - *
- * - * @param initialCapacity Initial size of the internal storage array. - * @param expansionFactor The array will be expanded based on this parameter. - * @param contractionCriterion Contraction criterion. - * @throws MathIllegalArgumentException if the parameters are not valid. - * @since 3.1 - */ - public ResizableDoubleArray(int initialCapacity, double expansionFactor, double contractionCriterion) - throws MathIllegalArgumentException { - this(initialCapacity, expansionFactor, contractionCriterion, DEFAULT_EXPANSION_MODE, null); - } - - /** - * Creates an instance with the specified properties. - *
- * Throws MathIllegalArgumentException if the following conditions - * are not met: - *
    - *
  • {@code initialCapacity > 0}
  • - *
  • {@code expansionFactor > 1}
  • - *
  • {@code contractionCriterion >= expansionFactor}
  • - *
- * - * @param initialCapacity Initial size of the internal storage array. - * @param expansionFactor The array will be expanded based on this parameter. - * @param contractionCriterion Contraction criteria. - * @param expansionMode Expansion mode. - * @param data Initial contents of the array. - * @throws MathIllegalArgumentException if the parameters are not valid. - * @throws NullArgumentException if expansionMode is null - */ - public ResizableDoubleArray(int initialCapacity, - double expansionFactor, - double contractionCriterion, - ExpansionMode expansionMode, - double ... data) - throws MathIllegalArgumentException { - if (initialCapacity <= 0) { - throw new NotStrictlyPositiveException(LocalizedFormats.INITIAL_CAPACITY_NOT_POSITIVE, - initialCapacity); - } - checkContractExpand(contractionCriterion, expansionFactor); - MathUtils.checkNotNull(expansionMode); - - this.expansionFactor = expansionFactor; - this.contractionCriterion = contractionCriterion; - this.expansionMode = expansionMode; - internalArray = new double[initialCapacity]; - numElements = 0; - startIndex = 0; - - if (data != null && data.length > 0) { - addElements(data); - } - } - - /** - * Copy constructor. - *

- * Creates a new ResizableDoubleArray that is a deep, fresh copy of the original. - * Original may not be null; otherwise a {@link NullArgumentException} is thrown. - * - * @param original array to copy - * @exception NullArgumentException if original is null - * @since 2.0 - */ - public ResizableDoubleArray(final ResizableDoubleArray original) - throws NullArgumentException { - MathUtils.checkNotNull(original); - this.contractionCriterion = original.contractionCriterion; - this.expansionFactor = original.expansionFactor; - this.expansionMode = original.expansionMode; - this.internalArray = new double[original.internalArray.length]; - System.arraycopy(original.internalArray, 0, this.internalArray, 0, this.internalArray.length); - this.numElements = original.numElements; - this.startIndex = original.startIndex; - } - - /** - * Adds an element to the end of this expandable array. - * - * @param value Value to be added to end of array. - */ - @Override - public void addElement(final double value) { - if (internalArray.length <= startIndex + numElements) { - expand(); - } - internalArray[startIndex + numElements++] = value; - } - - /** - * Adds several element to the end of this expandable array. - * - * @param values Values to be added to end of array. - * @since 2.2 - */ - @Override - public void addElements(final double[] values) { - final double[] tempArray = new double[numElements + values.length + 1]; - System.arraycopy(internalArray, startIndex, tempArray, 0, numElements); - System.arraycopy(values, 0, tempArray, numElements, values.length); - internalArray = tempArray; - startIndex = 0; - numElements += values.length; - } - - /** - * Adds an element to the end of the array and removes the first - * element in the array. Returns the discarded first element. - *

- * The effect is similar to a push operation in a FIFO queue. - *

- * Example: If the array contains the elements 1, 2, 3, 4 (in that order) - * and addElementRolling(5) is invoked, the result is an array containing - * the entries 2, 3, 4, 5 and the value returned is 1. - * - * @param value Value to be added to the array. - * @return the value which has been discarded or "pushed" out of the array - * by this rolling insert. - */ - @Override - public double addElementRolling(double value) { - double discarded = internalArray[startIndex]; - - if ((startIndex + (numElements + 1)) > internalArray.length) { - expand(); - } - // Increment the start index - startIndex += 1; - - // Add the new value - internalArray[startIndex + (numElements - 1)] = value; - - // Check the contraction criterion. - if (shouldContract()) { - contract(); - } - return discarded; - } - - /** - * Substitutes {@code value} for the most recently added value. - *

- * Returns the value that has been replaced. If the array is empty (i.e. - * if {@link #numElements} is zero), an MathIllegalStateException is thrown. - * - * @param value New value to substitute for the most recently added value - * @return the value that has been replaced in the array. - * @throws MathIllegalStateException if the array is empty - * @since 2.0 - */ - public double substituteMostRecentElement(double value) throws MathIllegalStateException { - if (numElements < 1) { - throw new MathIllegalStateException(LocalizedFormats.CANNOT_SUBSTITUTE_ELEMENT_FROM_EMPTY_ARRAY); - } - - final int substIndex = startIndex + (numElements - 1); - final double discarded = internalArray[substIndex]; - - internalArray[substIndex] = value; - - return discarded; - } - - /** - * Checks the expansion factor and the contraction criterion and raises - * an exception if the contraction criterion is smaller than the - * expansion criterion. - * - * @param contraction Criterion to be checked. - * @param expansion Factor to be checked. - * @throws NumberIsTooSmallException if {@code contraction < expansion}. - * @throws NumberIsTooSmallException if {@code contraction <= 1}. - * @throws NumberIsTooSmallException if {@code expansion <= 1 }. - * @since 3.1 - */ - protected void checkContractExpand(double contraction, double expansion) throws NumberIsTooSmallException { - if (contraction < expansion) { - final NumberIsTooSmallException e = new NumberIsTooSmallException(contraction, 1, true); - e.getContext().addMessage(LocalizedFormats.CONTRACTION_CRITERIA_SMALLER_THAN_EXPANSION_FACTOR, - contraction, expansion); - throw e; - } - - if (contraction <= 1) { - final NumberIsTooSmallException e = new NumberIsTooSmallException(contraction, 1, false); - e.getContext().addMessage(LocalizedFormats.CONTRACTION_CRITERIA_SMALLER_THAN_ONE, - contraction); - throw e; - } - - if (expansion <= 1) { - final NumberIsTooSmallException e = new NumberIsTooSmallException(contraction, 1, false); - e.getContext().addMessage(LocalizedFormats.EXPANSION_FACTOR_SMALLER_THAN_ONE, - expansion); - throw e; - } - } - - /** - * Clear the array contents, resetting the number of elements to zero. - */ - @Override - public void clear() { - numElements = 0; - startIndex = 0; - } - - /** - * Contracts the storage array to the (size of the element set) + 1 - to avoid - * a zero length array. This function also resets the startIndex to zero. - */ - public void contract() { - final double[] tempArray = new double[numElements + 1]; - - // Copy and swap - copy only the element array from the src array. - System.arraycopy(internalArray, startIndex, tempArray, 0, numElements); - internalArray = tempArray; - - // Reset the start index to zero - startIndex = 0; - } - - /** - * Discards the {@code i} initial elements of the array. - *

- * For example, if the array contains the elements 1,2,3,4, invoking - * {@code discardFrontElements(2)} will cause the first two elements - * to be discarded, leaving 3,4 in the array. - * - * @param i the number of elements to discard from the front of the array - * @throws MathIllegalArgumentException if i is greater than numElements. - * @since 2.0 - */ - public void discardFrontElements(int i) throws MathIllegalArgumentException { - discardExtremeElements(i,true); - } - - /** - * Discards the {@code i} last elements of the array. - *

- * For example, if the array contains the elements 1,2,3,4, invoking - * {@code discardMostRecentElements(2)} will cause the last two elements - * to be discarded, leaving 1,2 in the array. - * - * @param i the number of elements to discard from the end of the array - * @throws MathIllegalArgumentException if i is greater than numElements. - * @since 2.0 - */ - public void discardMostRecentElements(int i) throws MathIllegalArgumentException { - discardExtremeElements(i,false); - } - - /** - * Discards the {@code i} first or last elements of the array, - * depending on the value of {@code front}. - *

- * For example, if the array contains the elements 1,2,3,4, invoking - * {@code discardExtremeElements(2,false)} will cause the last two elements - * to be discarded, leaving 1,2 in the array. - * For example, if the array contains the elements 1,2,3,4, invoking - * {@code discardExtremeElements(2,true)} will cause the first two elements - * to be discarded, leaving 3,4 in the array. - * - * @param i the number of elements to discard from the front/end of the array - * @param front true if elements are to be discarded from the front - * of the array, false if elements are to be discarded from the end - * of the array - * @throws MathIllegalArgumentException if i is greater than numElements. - * @since 2.0 - */ - private void discardExtremeElements(int i, boolean front) throws MathIllegalArgumentException { - if (i > numElements) { - throw new MathIllegalArgumentException( - LocalizedFormats.TOO_MANY_ELEMENTS_TO_DISCARD_FROM_ARRAY, - i, numElements); - } else if (i < 0) { - throw new MathIllegalArgumentException( - LocalizedFormats.CANNOT_DISCARD_NEGATIVE_NUMBER_OF_ELEMENTS, - i); - } else { - // "Subtract" this number of discarded from numElements - numElements -= i; - if (front) { - startIndex += i; - } - } - if (shouldContract()) { - contract(); - } - } - - /** - * Expands the internal storage array using the expansion factor. - *

- * If {@code expansionMode} is set to MULTIPLICATIVE, - * the new array size will be {@code internalArray.length * expansionFactor}. - * If {@code expansionMode} is set to ADDITIVE, the length - * after expansion will be {@code internalArray.length + expansionFactor}. - */ - protected void expand() { - // notice the use of FastMath.ceil(), this guarantees that we will always - // have an array of at least currentSize + 1. Assume that the - // current initial capacity is 1 and the expansion factor - // is 1.000000000000000001. The newly calculated size will be - // rounded up to 2 after the multiplication is performed. - int newSize = 0; - if (expansionMode == ExpansionMode.MULTIPLICATIVE) { - newSize = (int) FastMath.ceil(internalArray.length * expansionFactor); - } else { - newSize = (int) (internalArray.length + FastMath.round(expansionFactor)); - } - final double[] tempArray = new double[newSize]; - - // Copy and swap - System.arraycopy(internalArray, 0, tempArray, 0, internalArray.length); - internalArray = tempArray; - } - - /** - * Expands the internal storage array to the specified size. - * - * @param size Size of the new internal storage array. - */ - private void expandTo(int size) { - final double[] tempArray = new double[size]; - // Copy and swap - System.arraycopy(internalArray, 0, tempArray, 0, internalArray.length); - internalArray = tempArray; - } - - /** - * The contraction criterion defines when the internal array will contract - * to store only the number of elements in the element array. - *

- * If the {@code expansionMode} is {@code MULTIPLICATIVE}, - * contraction is triggered when the ratio between storage array length - * and {@code numElements} exceeds {@code contractionFactor}. - * If the {@code expansionMode} is {@code ADDITIVE}, the - * number of excess storage locations is compared to {@code contractionFactor}. - * - * @return the contraction criterion used to reclaim memory. - * @since 3.1 - */ - public double getContractionCriterion() { - return contractionCriterion; - } - - /** - * Returns the element at the specified index. - * - * @param index index to fetch a value from - * @return value stored at the specified index - * @throws ArrayIndexOutOfBoundsException if {@code index} is less than - * zero or is greater than {@code getNumElements() - 1}. - */ - @Override - public double getElement(int index) { - if (index >= numElements) { - throw new ArrayIndexOutOfBoundsException(index); - } else if (index >= 0) { - return internalArray[startIndex + index]; - } else { - throw new ArrayIndexOutOfBoundsException(index); - } - } - - /** - * Returns a double array containing the elements of this ResizableArray. - *

- * This method returns a copy, not a reference to the underlying array, - * so that changes made to the returned array have no effect on this ResizableArray. - * - * @return the double array. - */ - @Override - public double[] getElements() { - final double[] elementArray = new double[numElements]; - System.arraycopy(internalArray, startIndex, elementArray, 0, numElements); - return elementArray; - } - - /** - * The expansion factor controls the size of a new array when an array - * needs to be expanded. - *

- * The {@code expansionMode} determines whether the size of the array - * is multiplied by the {@code expansionFactor} (MULTIPLICATIVE) or if - * the expansion is additive (ADDITIVE -- {@code expansionFactor} - * storage locations added). The default {@code expansionMode} is - * MULTIPLICATIVE and the default {@code expansionFactor} is 2.0. - * - * @return the expansion factor of this expandable double array - */ - public double getExpansionFactor() { - return expansionFactor; - } - - /** - * The expansion mode determines whether the internal storage - * array grows additively or multiplicatively when it is expanded. - * - * @return the expansion mode. - */ - public ExpansionMode getExpansionMode() { - return expansionMode; - } - - /** - * Gets the currently allocated size of the internal data structure used - * for storing elements. - * This is not to be confused with {@link #getNumElements() the number of - * elements actually stored}. - * - * @return the length of the internal array. - * @since 3.1 - */ - public int getCapacity() { - return internalArray.length; - } - - /** - * Returns the number of elements currently in the array. Please note - * that this is different from the length of the internal storage array. - * - * @return the number of elements. - */ - @Override - public int getNumElements() { - return numElements; - } - - /** - * Provides direct access to the internal storage array. - * Please note that this method returns a reference to this object's - * storage array, not a copy. - *

- * To correctly address elements of the array, the "start index" is - * required (available via the {@link #getStartIndex() getStartIndex} - * method. - *

- * This method should only be used to avoid copying the internal array. - * The returned value must be used for reading only; other - * uses could lead to this object becoming inconsistent. - *

- * The {@link #getElements} method has no such limitation since it - * returns a copy of this array's addressable elements. - * - * @return the internal storage array used by this object. - * @since 3.1 - */ - protected double[] getArrayRef() { - return internalArray; - } - - /** - * Returns the "start index" of the internal array. - * This index is the position of the first addressable element in the - * internal storage array. - *

- * The addressable elements in the array are at indices contained in - * the interval [{@link #getStartIndex()}, - * {@link #getStartIndex()} + {@link #getNumElements()} - 1]. - * - * @return the start index. - * @since 3.1 - */ - protected int getStartIndex() { - return startIndex; - } - - /** - * Performs an operation on the addressable elements of the array. - * - * @param f Function to be applied on this array. - * @return the result. - * @since 3.1 - */ - public double compute(MathArrays.Function f) { - return f.evaluate(internalArray, startIndex, numElements); - } - - /** - * Sets the element at the specified index. - *

- * If the specified index is greater than {@code getNumElements() - 1}, - * the {@code numElements} property is increased to {@code index +1} - * and additional storage is allocated (if necessary) for the new element and - * all (uninitialized) elements between the new element and the previous end - * of the array). - * - * @param index index to store a value in - * @param value value to store at the specified index - * @throws ArrayIndexOutOfBoundsException if {@code index < 0}. - */ - @Override - public void setElement(int index, double value) { - if (index < 0) { - throw new ArrayIndexOutOfBoundsException(index); - } - if (index + 1 > numElements) { - numElements = index + 1; - } - if ((startIndex + index) >= internalArray.length) { - expandTo(startIndex + (index + 1)); - } - internalArray[startIndex + index] = value; - } - - /** - * This function allows you to control the number of elements contained - * in this array, and can be used to "throw out" the last n values in an - * array. This function will also expand the internal array as needed. - * - * @param i a new number of elements - * @throws MathIllegalArgumentException if {@code i} is negative. - */ - public void setNumElements(int i) throws MathIllegalArgumentException { - // If index is negative thrown an error. - if (i < 0) { - throw new MathIllegalArgumentException(LocalizedFormats.INDEX_NOT_POSITIVE, i); - } - - // Test the new num elements, check to see if the array needs to be - // expanded to accommodate this new number of elements. - final int newSize = startIndex + i; - if (newSize > internalArray.length) { - expandTo(newSize); - } - - // Set the new number of elements to new value. - numElements = i; - } - - /** - * Returns true if the internal storage array has too many unused - * storage positions. - * - * @return true if array satisfies the contraction criteria - */ - private boolean shouldContract() { - if (expansionMode == ExpansionMode.MULTIPLICATIVE) { - return (internalArray.length / ((float) numElements)) > contractionCriterion; - } else { - return (internalArray.length - numElements) > contractionCriterion; - } - } - - /** - * Returns a copy of the ResizableDoubleArray. Does not contract before - * the copy, so the returned object is an exact copy of this. - * - * @return a new ResizableDoubleArray with the same data and configuration - * properties as this - * @since 2.0 - */ - public ResizableDoubleArray copy() { - return new ResizableDoubleArray(this); - } - - /** - * Returns true iff object is a ResizableDoubleArray with the same properties - * as this and an identical internal storage array. - * - * @param object object to be compared for equality with this - * @return true iff object is a ResizableDoubleArray with the same data and - * properties as this - * @since 2.0 - */ - @Override - public boolean equals(Object object) { - if (object == this ) { - return true; - } - if (object instanceof ResizableDoubleArray == false) { - return false; - } - boolean result = true; - final ResizableDoubleArray other = (ResizableDoubleArray) object; - result = result && (other.contractionCriterion == contractionCriterion); - result = result && (other.expansionFactor == expansionFactor); - result = result && (other.expansionMode == expansionMode); - result = result && (other.numElements == numElements); - result = result && (other.startIndex == startIndex); - if (!result) { - return false; - } else { - return Arrays.equals(internalArray, other.internalArray); - } - } - - /** - * Returns a hash code consistent with equals. - * - * @return the hash code representing this {@code ResizableDoubleArray}. - * @since 2.0 - */ - @Override - public int hashCode() { - final int[] hashData = new int[6]; - hashData[0] = Double.valueOf(expansionFactor).hashCode(); - hashData[1] = Double.valueOf(contractionCriterion).hashCode(); - hashData[2] = expansionMode.hashCode(); - hashData[3] = Arrays.hashCode(internalArray); - hashData[4] = numElements; - hashData[5] = startIndex; - return Arrays.hashCode(hashData); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/TransformerMap.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/TransformerMap.java deleted file mode 100644 index 9ea3ccb7f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/TransformerMap.java +++ /dev/null @@ -1,190 +0,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. - */ -package org.apache.commons.math4.util; - -import java.io.Serializable; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.math4.exception.MathIllegalArgumentException; - -/** - * This TansformerMap automates the transformation of mixed object types. - * It provides a means to set NumberTransformers that will be selected - * based on the Class of the object handed to the Maps - * double transform(Object o) method. - */ -public class TransformerMap implements NumberTransformer, Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = 4605318041528645258L; - - /** - * A default Number Transformer for Numbers and numeric Strings. - */ - private NumberTransformer defaultTransformer = null; - - /** - * The internal Map. - */ - private Map, NumberTransformer> map = null; - - /** - * Build a map containing only the default transformer. - */ - public TransformerMap() { - map = new HashMap<>(); - defaultTransformer = new DefaultTransformer(); - } - - /** - * Tests if a Class is present in the TransformerMap. - * @param key Class to check - * @return true|false - */ - public boolean containsClass(Class key) { - return map.containsKey(key); - } - - /** - * Tests if a NumberTransformer is present in the TransformerMap. - * @param value NumberTransformer to check - * @return true|false - */ - public boolean containsTransformer(NumberTransformer value) { - return map.containsValue(value); - } - - /** - * Returns the Transformer that is mapped to a class - * if mapping is not present, this returns null. - * @param key The Class of the object - * @return the mapped NumberTransformer or null. - */ - public NumberTransformer getTransformer(Class key) { - return map.get(key); - } - - /** - * Sets a Class to Transformer Mapping in the Map. If - * the Class is already present, this overwrites that - * mapping. - * @param key The Class - * @param transformer The NumberTransformer - * @return the replaced transformer if one is present - */ - public NumberTransformer putTransformer(Class key, NumberTransformer transformer) { - return map.put(key, transformer); - } - - /** - * Removes a Class to Transformer Mapping in the Map. - * @param key The Class - * @return the removed transformer if one is present or - * null if none was present. - */ - public NumberTransformer removeTransformer(Class key) { - return map.remove(key); - } - - /** - * Clears all the Class to Transformer mappings. - */ - public void clear() { - map.clear(); - } - - /** - * Returns the Set of Classes used as keys in the map. - * @return Set of Classes - */ - public Set> classes() { - return map.keySet(); - } - - /** - * Returns the Set of NumberTransformers used as values - * in the map. - * @return Set of NumberTransformers - */ - public Collection transformers() { - return map.values(); - } - - /** - * Attempts to transform the Object against the map of - * NumberTransformers. Otherwise it returns Double.NaN. - * - * @param o the Object to be transformed. - * @return the double value of the Object. - * @throws MathIllegalArgumentException if the Object can not be - * transformed into a Double. - * @see org.apache.commons.math4.util.NumberTransformer#transform(Object) - */ - @Override - public double transform(Object o) throws MathIllegalArgumentException { - double value = Double.NaN; - - if (o instanceof Number || o instanceof String) { - value = defaultTransformer.transform(o); - } else { - NumberTransformer trans = getTransformer(o.getClass()); - if (trans != null) { - value = trans.transform(o); - } - } - - return value; - } - - /** {@inheritDoc} */ - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other instanceof TransformerMap) { - TransformerMap rhs = (TransformerMap) other; - if (! defaultTransformer.equals(rhs.defaultTransformer)) { - return false; - } - if (map.size() != rhs.map.size()) { - return false; - } - for (Map.Entry, NumberTransformer> entry : map.entrySet()) { - if (! entry.getValue().equals(rhs.map.get(entry.getKey()))) { - return false; - } - } - return true; - } - return false; - } - - /** {@inheritDoc} */ - @Override - public int hashCode() { - int hash = defaultTransformer.hashCode(); - for (NumberTransformer t : map.values()) { - hash = hash * 31 + t.hashCode(); - } - return hash; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/package-info.java deleted file mode 100644 index 80f385b39..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/math4/util/package-info.java +++ /dev/null @@ -1,20 +0,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. - */ -/** - * Convenience routines and common data structures used throughout the commons-math library. - */ -package org.apache.commons.math4.util; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/arrays/CosAngle.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/arrays/CosAngle.java deleted file mode 100644 index 58e5f51c1..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/arrays/CosAngle.java +++ /dev/null @@ -1,35 +0,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. - */ -package org.apache.commons.numbers.arrays; - -/** - * Computes the cosine of the angle between two vectors. - */ -public class CosAngle { - /** - * Computes the cosine of the angle between {@code v1} and {@code v2}. - * - * @param v1 Cartesian coordinates of the first vector. - * @param v2 Cartesian coordinates of the second vector. - * @return the cosine of the angle between the vectors. - */ - public static double value(double[] v1, - double[] v2) { - return LinearCombination.value(v1, v2) / SafeNorm.value(v1) / SafeNorm.value(v2); - } -} - diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/arrays/LinearCombination.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/arrays/LinearCombination.java deleted file mode 100644 index f28a3d81e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/arrays/LinearCombination.java +++ /dev/null @@ -1,341 +0,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. - */ -package org.apache.commons.numbers.arrays; - -/** - * Computes linear combinations accurately. - * This method computes the sum of the products - * ai bi to high accuracy. - * It does so by using specific multiplication and addition algorithms to - * preserve accuracy and reduce cancellation effects. - * - * It is based on the 2005 paper - * - * Accurate Sum and Dot Product by Takeshi Ogita, Siegfried M. Rump, - * and Shin'ichi Oishi published in SIAM J. Sci. Comput. - */ -public class LinearCombination { - /* - * Caveat: - * - * The code below is split in many additions/subtractions that may - * appear redundant. However, they should NOT be simplified, as they - * do use IEEE754 floating point arithmetic rounding properties. - * The variables naming conventions are that xyzHigh contains the most significant - * bits of xyz and xyzLow contains its least significant bits. So theoretically - * xyz is the sum xyzHigh + xyzLow, but in many cases below, this sum cannot - * be represented in only one double precision number so we preserve two numbers - * to hold it as long as we can, combining the high and low order bits together - * only at the end, after cancellation may have occurred on high order bits - */ - - /** - * @param a Factors. - * @param b Factors. - * @return \( \sum_i a_i b_i \). - * @throws IllegalArgumentException if the sizes of the arrays are different. - */ - public static double value(double[] a, - double[] b) { - if (a.length != b.length) { - throw new IllegalArgumentException("Dimension mismatch: " + a.length + " != " + b.length); - } - - final int len = a.length; - - if (len == 1) { - // Revert to scalar multiplication. - return a[0] * b[0]; - } - - final double[] prodHigh = new double[len]; - double prodLowSum = 0; - - for (int i = 0; i < len; i++) { - final double ai = a[i]; - final double aHigh = highPart(ai); - final double aLow = ai - aHigh; - - final double bi = b[i]; - final double bHigh = highPart(bi); - final double bLow = bi - bHigh; - prodHigh[i] = ai * bi; - final double prodLow = prodLow(aLow, bLow, prodHigh[i], aHigh, bHigh); - prodLowSum += prodLow; - } - - - final double prodHighCur = prodHigh[0]; - double prodHighNext = prodHigh[1]; - double sHighPrev = prodHighCur + prodHighNext; - double sPrime = sHighPrev - prodHighNext; - double sLowSum = (prodHighNext - (sHighPrev - sPrime)) + (prodHighCur - sPrime); - - final int lenMinusOne = len - 1; - for (int i = 1; i < lenMinusOne; i++) { - prodHighNext = prodHigh[i + 1]; - final double sHighCur = sHighPrev + prodHighNext; - sPrime = sHighCur - prodHighNext; - sLowSum += (prodHighNext - (sHighCur - sPrime)) + (sHighPrev - sPrime); - sHighPrev = sHighCur; - } - - double result = sHighPrev + (prodLowSum + sLowSum); - - if (Double.isNaN(result)) { - // either we have split infinite numbers or some coefficients were NaNs, - // just rely on the naive implementation and let IEEE754 handle this - result = 0; - for (int i = 0; i < len; ++i) { - result += a[i] * b[i]; - } - } - - return result; - } - - /** - * @param a1 First factor of the first term. - * @param b1 Second factor of the first term. - * @param a2 First factor of the second term. - * @param b2 Second factor of the second term. - * @return \( a_1 b_1 + a_2 b_2 \) - * - * @see #value(double, double, double, double, double, double) - * @see #value(double, double, double, double, double, double, double, double) - * @see #value(double[], double[]) - */ - public static double value(double a1, double b1, - double a2, double b2) { - // split a1 and b1 as one 26 bits number and one 27 bits number - final double a1High = highPart(a1); - final double a1Low = a1 - a1High; - final double b1High = highPart(b1); - final double b1Low = b1 - b1High; - - // accurate multiplication a1 * b1 - final double prod1High = a1 * b1; - final double prod1Low = prodLow(a1Low, b1Low, prod1High, a1High, b1High); - - // split a2 and b2 as one 26 bits number and one 27 bits number - final double a2High = highPart(a2); - final double a2Low = a2 - a2High; - final double b2High = highPart(b2); - final double b2Low = b2 - b2High; - - // accurate multiplication a2 * b2 - final double prod2High = a2 * b2; - final double prod2Low = prodLow(a2Low, b2Low, prod2High, a2High, b2High); - - // accurate addition a1 * b1 + a2 * b2 - final double s12High = prod1High + prod2High; - final double s12Prime = s12High - prod2High; - final double s12Low = (prod2High - (s12High - s12Prime)) + (prod1High - s12Prime); - - // final rounding, s12 may have suffered many cancellations, we try - // to recover some bits from the extra words we have saved up to now - double result = s12High + (prod1Low + prod2Low + s12Low); - - if (Double.isNaN(result)) { - // either we have split infinite numbers or some coefficients were NaNs, - // just rely on the naive implementation and let IEEE754 handle this - result = a1 * b1 + a2 * b2; - } - - return result; - } - - /** - * @param a1 First factor of the first term. - * @param b1 Second factor of the first term. - * @param a2 First factor of the second term. - * @param b2 Second factor of the second term. - * @param a3 First factor of the third term. - * @param b3 Second factor of the third term. - * @return \( a_1 b_1 + a_2 b_2 + a_3 b_3 \) - * - * @see #value(double, double, double, double) - * @see #value(double, double, double, double, double, double, double, double) - * @see #value(double[], double[]) - */ - public static double value(double a1, double b1, - double a2, double b2, - double a3, double b3) { - // split a1 and b1 as one 26 bits number and one 27 bits number - final double a1High = highPart(a1); - final double a1Low = a1 - a1High; - final double b1High = highPart(b1); - final double b1Low = b1 - b1High; - - // accurate multiplication a1 * b1 - final double prod1High = a1 * b1; - final double prod1Low = prodLow(a1Low, b1Low, prod1High, a1High, b1High); - - // split a2 and b2 as one 26 bits number and one 27 bits number - final double a2High = highPart(a2); - final double a2Low = a2 - a2High; - final double b2High = highPart(b2); - final double b2Low = b2 - b2High; - - // accurate multiplication a2 * b2 - final double prod2High = a2 * b2; - final double prod2Low = prodLow(a2Low, b2Low, prod2High, a2High, b2High); - - // split a3 and b3 as one 26 bits number and one 27 bits number - final double a3High = highPart(a3); - final double a3Low = a3 - a3High; - final double b3High = highPart(b3); - final double b3Low = b3 - b3High; - - // accurate multiplication a3 * b3 - final double prod3High = a3 * b3; - final double prod3Low = prodLow(a3Low, b3Low, prod3High, a3High, b3High); - - // accurate addition a1 * b1 + a2 * b2 - final double s12High = prod1High + prod2High; - final double s12Prime = s12High - prod2High; - final double s12Low = (prod2High - (s12High - s12Prime)) + (prod1High - s12Prime); - - // accurate addition a1 * b1 + a2 * b2 + a3 * b3 - final double s123High = s12High + prod3High; - final double s123Prime = s123High - prod3High; - final double s123Low = (prod3High - (s123High - s123Prime)) + (s12High - s123Prime); - - // final rounding, s123 may have suffered many cancellations, we try - // to recover some bits from the extra words we have saved up to now - double result = s123High + (prod1Low + prod2Low + prod3Low + s12Low + s123Low); - - if (Double.isNaN(result)) { - // either we have split infinite numbers or some coefficients were NaNs, - // just rely on the naive implementation and let IEEE754 handle this - result = a1 * b1 + a2 * b2 + a3 * b3; - } - - return result; - } - - /** - * @param a1 First factor of the first term. - * @param b1 Second factor of the first term. - * @param a2 First factor of the second term. - * @param b2 Second factor of the second term. - * @param a3 First factor of the third term. - * @param b3 Second factor of the third term. - * @param a4 First factor of the fourth term. - * @param b4 Second factor of the fourth term. - * @return \( a_1 b_1 + a_2 b_2 + a_3 b_3 + a_4 b_4 \) - * - * @see #value(double, double, double, double) - * @see #value(double, double, double, double, double, double) - * @see #value(double[], double[]) - */ - public static double value(double a1, double b1, - double a2, double b2, - double a3, double b3, - double a4, double b4) { - // split a1 and b1 as one 26 bits number and one 27 bits number - final double a1High = highPart(a1); - final double a1Low = a1 - a1High; - final double b1High = highPart(b1); - final double b1Low = b1 - b1High; - - // accurate multiplication a1 * b1 - final double prod1High = a1 * b1; - final double prod1Low = prodLow(a1Low, b1Low, prod1High, a1High, b1High); - - // split a2 and b2 as one 26 bits number and one 27 bits number - final double a2High = highPart(a2); - final double a2Low = a2 - a2High; - final double b2High = highPart(b2); - final double b2Low = b2 - b2High; - - // accurate multiplication a2 * b2 - final double prod2High = a2 * b2; - final double prod2Low = prodLow(a2Low, b2Low, prod2High, a2High, b2High); - - // split a3 and b3 as one 26 bits number and one 27 bits number - final double a3High = highPart(a3); - final double a3Low = a3 - a3High; - final double b3High = highPart(b3); - final double b3Low = b3 - b3High; - - // accurate multiplication a3 * b3 - final double prod3High = a3 * b3; - final double prod3Low = prodLow(a3Low, b3Low, prod3High, a3High, b3High); - - // split a4 and b4 as one 26 bits number and one 27 bits number - final double a4High = highPart(a4); - final double a4Low = a4 - a4High; - final double b4High = highPart(b4); - final double b4Low = b4 - b4High; - - // accurate multiplication a4 * b4 - final double prod4High = a4 * b4; - final double prod4Low = prodLow(a4Low, b4Low, prod4High, a4High, b4High); - - // accurate addition a1 * b1 + a2 * b2 - final double s12High = prod1High + prod2High; - final double s12Prime = s12High - prod2High; - final double s12Low = (prod2High - (s12High - s12Prime)) + (prod1High - s12Prime); - - // accurate addition a1 * b1 + a2 * b2 + a3 * b3 - final double s123High = s12High + prod3High; - final double s123Prime = s123High - prod3High; - final double s123Low = (prod3High - (s123High - s123Prime)) + (s12High - s123Prime); - - // accurate addition a1 * b1 + a2 * b2 + a3 * b3 + a4 * b4 - final double s1234High = s123High + prod4High; - final double s1234Prime = s1234High - prod4High; - final double s1234Low = (prod4High - (s1234High - s1234Prime)) + (s123High - s1234Prime); - - // final rounding, s1234 may have suffered many cancellations, we try - // to recover some bits from the extra words we have saved up to now - double result = s1234High + (prod1Low + prod2Low + prod3Low + prod4Low + s12Low + s123Low + s1234Low); - - if (Double.isNaN(result)) { - // either we have split infinite numbers or some coefficients were NaNs, - // just rely on the naive implementation and let IEEE754 handle this - result = a1 * b1 + a2 * b2 + a3 * b3 + a4 * b4; - } - - return result; - } - - /** - * @param value Value. - * @return the high part of the value. - */ - private static double highPart(double value) { - return Double.longBitsToDouble(Double.doubleToRawLongBits(value) & ((-1L) << 27)); - } - - /** - * @param aLow Low part of first factor. - * @param bLow Low part of second factor. - * @param prodHigh Product of the factors. - * @param aHigh High part of first factor. - * @param bHigh High part of second factor. - * @return aLow * bLow - (((prodHigh - aHigh * bHigh) - aLow * bHigh) - aHigh * bLow) - */ - private static double prodLow(double aLow, - double bLow, - double prodHigh, - double aHigh, - double bHigh) { - return aLow * bLow - (((prodHigh - aHigh * bHigh) - aLow * bHigh) - aHigh * bLow); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/arrays/SafeNorm.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/arrays/SafeNorm.java deleted file mode 100644 index a04fb4d1a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/arrays/SafeNorm.java +++ /dev/null @@ -1,86 +0,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. - */ -package org.apache.commons.numbers.arrays; - -/** - * Computes the Cartesian norm (2-norm), handling both overflow and underflow. - * Translation of the minpack - * "enorm" subroutine. - */ -public class SafeNorm { - /** Constant. */ - private static final double R_DWARF = 3.834e-20; - /** Constant. */ - private static final double R_GIANT = 1.304e+19; - - /** - * @param v Cartesian coordinates. - * @return the 2-norm of the vector. - */ - public static double value(double[] v) { - double s1 = 0; - double s2 = 0; - double s3 = 0; - double x1max = 0; - double x3max = 0; - double floatn = v.length; - double agiant = R_GIANT / floatn; - for (int i = 0; i < v.length; i++) { - double xabs = Math.abs(v[i]); - if (xabs < R_DWARF || xabs > agiant) { - if (xabs > R_DWARF) { - if (xabs > x1max) { - double r = x1max / xabs; - s1 = 1 + s1 * r * r; - x1max = xabs; - } else { - double r = xabs / x1max; - s1 += r * r; - } - } else { - if (xabs > x3max) { - double r = x3max / xabs; - s3 = 1 + s3 * r * r; - x3max = xabs; - } else { - if (xabs != 0) { - double r = xabs / x3max; - s3 += r * r; - } - } - } - } else { - s2 += xabs * xabs; - } - } - double norm; - if (s1 != 0) { - norm = x1max * Math.sqrt(s1 + (s2 / x1max) / x1max); - } else { - if (s2 == 0) { - norm = x3max * Math.sqrt(s3); - } else { - if (s2 >= x3max) { - norm = Math.sqrt(s2 * (1 + (x3max / s2) * (x3max * s3))); - } else { - norm = Math.sqrt(x3max * ((s2 / x3max) + (x3max * s3))); - } - } - } - return norm; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/arrays/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/arrays/package-info.java deleted file mode 100644 index be18674ed..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/arrays/package-info.java +++ /dev/null @@ -1,20 +0,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. - */ -/** - * Array utilities. - */ -package org.apache.commons.numbers.arrays; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/BinomialCoefficient.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/BinomialCoefficient.java deleted file mode 100644 index 6da5a7df5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/BinomialCoefficient.java +++ /dev/null @@ -1,119 +0,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. - */ - -package org.apache.commons.numbers.combinatorics; - -import org.apache.commons.numbers.core.ArithmeticUtils; - -/** - * Representation of the - * binomial coefficient. - * It is "{@code n choose k}", the number of {@code k}-element subsets that - * can be selected from an {@code n}-element set. - */ -public class BinomialCoefficient { - /** - * Computes de binomial coefficient. - * The largest value of {@code n} for which all coefficients can - * fit into a {@code long} is 66. - * - * @param n Size of the set. - * @param k Size of the subsets to be counted. - * @return {@code n choose k}. - * @throws IllegalArgumentException if {@code n < 0}. - * @throws IllegalArgumentException if {@code k > n}. - * @throws ArithmeticException if the result is too large to be - * represented by a {@code long}. - */ - public static long value(int n, int k) { - checkBinomial(n, k); - - if (n == k || - k == 0) { - return 1; - } - if (k == 1 || - k == n - 1) { - return n; - } - // Use symmetry for large k. - if (k > n / 2) { - return value(n, n - k); - } - - // We use the formulae: - // (n choose k) = n! / (n-k)! / k! - // (n choose k) = ((n-k+1)*...*n) / (1*...*k) - // which can be written - // (n choose k) = (n-1 choose k-1) * n / k - long result = 1; - if (n <= 61) { - // For n <= 61, the naive implementation cannot overflow. - int i = n - k + 1; - for (int j = 1; j <= k; j++) { - result = result * i / j; - i++; - } - } else if (n <= 66) { - // For n > 61 but n <= 66, the result cannot overflow, - // but we must take care not to overflow intermediate values. - int i = n - k + 1; - for (int j = 1; j <= k; j++) { - // We know that (result * i) is divisible by j, - // but (result * i) may overflow, so we split j: - // Filter out the gcd, d, so j/d and i/d are integer. - // result is divisible by (j/d) because (j/d) - // is relative prime to (i/d) and is a divisor of - // result * (i/d). - final long d = ArithmeticUtils.gcd(i, j); - result = (result / (j / d)) * (i / d); - ++i; - } - } else { - // For n > 66, a result overflow might occur, so we check - // the multiplication, taking care to not overflow - // unnecessary. - int i = n - k + 1; - for (int j = 1; j <= k; j++) { - final long d = ArithmeticUtils.gcd(i, j); - result = ArithmeticUtils.mulAndCheck(result / (j / d), i / d); - ++i; - } - } - - return result; - } - - /** - * Check binomial preconditions. - * - * @param n Size of the set. - * @param k Size of the subsets to be counted. - * @throws IllegalArgumentException if {@code n < 0}. - * @throws IllegalArgumentException if {@code k > n} or {@code k < 0}. - */ - static void checkBinomial(int n, - int k) { - if (n < 0) { - throw new CombinatoricsException(CombinatoricsException.NEGATIVE, n); - } - if (k > n || - k < 0) { - throw new CombinatoricsException(CombinatoricsException.OUT_OF_RANGE, k, 0, n); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/BinomialCoefficientDouble.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/BinomialCoefficientDouble.java deleted file mode 100644 index 609b13e95..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/BinomialCoefficientDouble.java +++ /dev/null @@ -1,66 +0,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. - */ - -package org.apache.commons.numbers.combinatorics; - -/** - * Representation of the - * binomial coefficient, as a {@code double}. - * It is "{@code n choose k}", the number of {@code k}-element subsets that - * can be selected from an {@code n}-element set. - */ -public class BinomialCoefficientDouble { - /** - * Computes de binomial coefficient. - * The largest value of {@code n} for which all coefficients can - * fit into a {@code long} is 66. - * - * @param n Size of the set. - * @param k Size of the subsets to be counted. - * @return {@code n choose k}. - * @throws IllegalArgumentException if {@code n < 0}. - * @throws IllegalArgumentException if {@code k > n}. - * @throws IllegalArgumentException if the result is too large to be - * represented by a {@code long}. - */ - public static double value(int n, int k) { - BinomialCoefficient.checkBinomial(n, k); - - if (n == k || - k == 0) { - return 1; - } - if (k == 1 || - k == n - 1) { - return n; - } - if (k > n / 2) { - return value(n, n - k); - } - if (n < 67) { - return BinomialCoefficient.value(n, k); - } - - double result = 1; - for (int i = 1; i <= k; i++) { - result *= n - k + i; - result /= i; - } - - return Math.floor(result + 0.5); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/Combinations.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/Combinations.java deleted file mode 100644 index 691b2c1bc..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/Combinations.java +++ /dev/null @@ -1,434 +0,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. - */ - -package org.apache.commons.numbers.combinatorics; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.NoSuchElementException; -import java.util.Iterator; -import java.util.Comparator; - -import org.apache.commons.numbers.core.ArithmeticUtils; - -/** - * Utility to create - * combinations {@code (n, k)} of {@code k} elements in a set of - * {@code n} elements. - */ -public class Combinations implements Iterable { - /** Size of the set from which combinations are drawn. */ - private final int n; - /** Number of elements in each combination. */ - private final int k; - /** Iteration order. */ - private final IterationOrder iterationOrder; - - /** - * Describes the type of iteration performed by the - * {@link #iterator() iterator}. - */ - private enum IterationOrder { - /** Lexicographic order. */ - LEXICOGRAPHIC - } - - /** - * Creates an instance whose range is the k-element subsets of - * {0, ..., n - 1} represented as {@code int[]} arrays. - *

- * The iteration order is lexicographic: the arrays returned by the - * {@link #iterator() iterator} are sorted in descending order and - * they are visited in lexicographic order with significance from - * right to left. - * For example, {@code new Combinations(4, 2).iterator()} returns - * an iterator that will generate the following sequence of arrays - * on successive calls to - * {@code next()}:
- * {@code [0, 1], [0, 2], [1, 2], [0, 3], [1, 3], [2, 3]} - *

- * If {@code k == 0} an iterator containing an empty array is returned; - * if {@code k == n} an iterator containing [0, ..., n - 1] is returned. - * - * @param n Size of the set from which subsets are selected. - * @param k Size of the subsets to be enumerated. - * @throws IllegalArgumentException if {@code n < 0}. - * @throws IllegalArgumentException if {@code k > n} or {@code k < 0}. - */ - public Combinations(int n, - int k) { - this(n, k, IterationOrder.LEXICOGRAPHIC); - } - - /** - * Creates an instance whose range is the k-element subsets of - * {0, ..., n - 1} represented as {@code int[]} arrays. - *

- * If the {@code iterationOrder} argument is set to - * {@link IterationOrder#LEXICOGRAPHIC}, the arrays returned by the - * {@link #iterator() iterator} are sorted in descending order and - * they are visited in lexicographic order with significance from - * right to left. - * For example, {@code new Combinations(4, 2).iterator()} returns - * an iterator that will generate the following sequence of arrays - * on successive calls to - * {@code next()}:
- * {@code [0, 1], [0, 2], [1, 2], [0, 3], [1, 3], [2, 3]} - *

- * If {@code k == 0} an iterator containing an empty array is returned; - * if {@code k == n} an iterator containing [0, ..., n - 1] is returned. - * - * @param n Size of the set from which subsets are selected. - * @param k Size of the subsets to be enumerated. - * @param iterationOrder Specifies the {@link #iterator() iteration order}. - * @throws IllegalArgumentException if {@code n < 0}. - * @throws IllegalArgumentException if {@code k > n} or {@code k < 0}. - */ - private Combinations(int n, - int k, - IterationOrder iterationOrder) { - BinomialCoefficient.checkBinomial(n, k); - this.n = n; - this.k = k; - this.iterationOrder = iterationOrder; - } - - /** - * Gets the size of the set from which combinations are drawn. - * - * @return the size of the universe. - */ - public int getN() { - return n; - } - - /** - * Gets the number of elements in each combination. - * - * @return the size of the subsets to be enumerated. - */ - public int getK() { - return k; - } - - /** {@inheritDoc} */ - @Override - public Iterator iterator() { - if (k == 0 || - k == n) { - return new SingletonIterator(k); - } - - switch (iterationOrder) { - case LEXICOGRAPHIC: - return new LexicographicIterator(n, k); - default: - // Should never happen. - throw new UnsupportedOperationException("Please file a bug report"); - } - } - - /** - * Lexicographic combinations iterator. - *

- * Implementation follows Algorithm T in The Art of Computer Programming - * Internet Draft (PRE-FASCICLE 3A), "A Draft of Section 7.2.1.3 Generating All - * Combinations, D. Knuth, 2004.

- *

- * The degenerate cases {@code k == 0} and {@code k == n} are NOT handled by this - * implementation. If constructor arguments satisfy {@code k == 0} - * or {@code k >= n}, no exception is generated, but the iterator is empty. - *

- * - */ - private static class LexicographicIterator implements Iterator { - /** Size of subsets returned by the iterator. */ - private final int k; - - /** - * c[1], ..., c[k] stores the next combination; c[k + 1], c[k + 2] are - * sentinels. - *

- * Note that c[0] is "wasted" but this makes it a little easier to - * follow the code. - *

- */ - private final int[] c; - - /** Return value for {@link #hasNext()} */ - private boolean more = true; - - /** Marker: smallest index such that {@code c[j + 1] > j}. */ - private int j; - - /** - * Construct a CombinationIterator to enumerate {@code k}-sets from a set - * of size {@code n}. - *

- * NOTE: If {@code k === 0} or {@code k >= n}, the Iterator will be empty - * (that is, {@link #hasNext()} will return {@code false} immediately. - *

- * - * @param n Size of the set from which subsets are enumerated. - * @param k Size of the subsets to enumerate. - */ - LexicographicIterator(int n, int k) { - this.k = k; - c = new int[k + 3]; - if (k == 0 || k >= n) { - more = false; - return; - } - // Initialize c to start with lexicographically first k-set - for (int i = 1; i <= k; i++) { - c[i] = i - 1; - } - // Initialize sentinels - c[k + 1] = n; - c[k + 2] = 0; - j = k; // Set up invariant: j is smallest index such that c[j + 1] > j - } - - /** - * {@inheritDoc} - */ - @Override - public boolean hasNext() { - return more; - } - - /** - * {@inheritDoc} - */ - @Override - public int[] next() { - if (!more) { - throw new NoSuchElementException(); - } - // Copy return value (prepared by last activation) - final int[] ret = new int[k]; - System.arraycopy(c, 1, ret, 0, k); - - // Prepare next iteration - // T2 and T6 loop - int x = 0; - if (j > 0) { - x = j; - c[j] = x; - j--; - return ret; - } - // T3 - if (c[1] + 1 < c[2]) { - c[1]++; - return ret; - } else { - j = 2; - } - // T4 - boolean stepDone = false; - while (!stepDone) { - c[j - 1] = j - 2; - x = c[j] + 1; - if (x == c[j + 1]) { - j++; - } else { - stepDone = true; - } - } - // T5 - if (j > k) { - more = false; - return ret; - } - // T6 - c[j] = x; - j--; - return ret; - } - - /** - * Not supported. - */ - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - } - - /** - * Iterator with just one element to handle degenerate cases (full array, - * empty array) for combination iterator. - */ - private static class SingletonIterator implements Iterator { - /** Number of elements of the singleton array. */ - private final int n; - /** True on initialization, false after first call to next */ - private boolean more = true; - /** - * Create a singleton iterator providing the given array. - * - * @param n Size of the singleton array returned by the iterator. - */ - SingletonIterator(final int n) { - this.n = n; - } - /** - * @return {@code true} until next is called the first time, - * then {@code false}. - **/ - @Override - public boolean hasNext() { - return more; - } - /** - * @return the singleton at the first activation. - * @throws NoSuchElementException after the first activation. - */ - @Override - public int[] next() { - if (more) { - more = false; - // Create singleton. - final int[] s = new int[n]; - for (int i = 0; i < n; i++) { - s[i] = i; - } - return s; - } else { - throw new NoSuchElementException(); - } - } - /** - * Unsupported. - * - * @throws UnsupportedOperationException - */ - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - } - - /** - * Defines a lexicographic ordering of the combinations. - * - * The comparison is based on the value (in base 10) represented - * by the digit (interpreted in base {@code n}) in the input array, - * in reverse order. - * For example if {@code c} is {@code {3, 2, 1}}, and {@code n} - * is 3, the method will return 18. - */ - public static class LexicographicComparator - implements Comparator, - Serializable { - /** Serializable version identifier. */ - private static final long serialVersionUID = 20170520L; - /** Size of the set from which combinations are drawn. */ - private final int n; - /** Number of elements in each combination. */ - private final int k; - - /** - * @param n Size of the set from which subsets are selected. - * @param k Size of the subsets to be enumerated. - */ - public LexicographicComparator(int n, - int k) { - this.n = n; - this.k = k; - } - - /** - * Gets the size of the set from which combinations are drawn. - * - * @return the size of the universe. - */ - public int getN() { - return n; - } - - /** - * Gets the number of elements in each combination. - * - * @return the size of the subsets. - */ - public int getK() { - return k; - } - - /** - * {@inheritDoc} - * - * @throws IllegalArgumentException if the array lengths are not - * equal to {@code k}. - * @throws IllegalArgumentException if an element of the array is not - * within the interval [0, {@code n}). - */ - @Override - public int compare(int[] c1, - int[] c2) { - if (c1.length != k) { - throw new CombinatoricsException(CombinatoricsException.MISMATCH, c1.length, k); - } - if (c2.length != k) { - throw new CombinatoricsException(CombinatoricsException.MISMATCH, c2.length, k); - } - - // Method "lexNorm" works with ordered arrays. - final int[] c1s = Arrays.copyOf(c1, k); - final int[] c2s = Arrays.copyOf(c2, k); - Arrays.sort(c1s); - Arrays.sort(c2s); - - final long v1 = lexNorm(c1s); - final long v2 = lexNorm(c2s); - - if (v1 < v2) { - return -1; - } else if (v1 > v2) { - return 1; - } else { - return 0; - } - } - - /** - * Computes the value (in base 10) represented by the digit - * (interpreted in base {@code n}) in the input array in reverse - * order. - * - * @param c Input array. - * @return the lexicographic norm. - * @throws IllegalArgumentException if an element of the array is not - * within the interval [0, {@code n}). - */ - private long lexNorm(int[] c) { - long ret = 0; - for (int i = 0; i < c.length; i++) { - final int digit = c[i]; - if (digit < 0 || - digit >= n) { - throw new CombinatoricsException(CombinatoricsException.OUT_OF_RANGE, digit, 0, n - 1); - } - - ret += c[i] * ArithmeticUtils.pow(n, i); - } - return ret; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/CombinatoricsException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/CombinatoricsException.java deleted file mode 100644 index 651429358..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/CombinatoricsException.java +++ /dev/null @@ -1,55 +0,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. - */ -package org.apache.commons.numbers.combinatorics; - -import java.text.MessageFormat; - -/** - * Package private exception class with constants for frequently used messages. - */ -class CombinatoricsException extends IllegalArgumentException { - /** Error message for "out of range" condition. */ - static final String OUT_OF_RANGE = "Number {0} is out of range [{1}, {2}]"; - /** Error message for "out of range" condition. */ - static final String NEGATIVE = "Number {0} is negative"; - /** Error message for "mismatch" condition. */ - static final String MISMATCH = "Expected {1} but was {0}"; - - /** Serializable version identifier. */ - private static final long serialVersionUID = 20170515L; - - /** Arguments for formatting the message. */ - protected Object[] formatArguments; - - /** - * Create an exception where the message is constructed by applying - * the {@code format()} method from {@code java.text.MessageFormat}. - * - * @param message the exception message with replaceable parameters - * @param formatArguments the arguments for formatting the message - */ - CombinatoricsException(String message, Object... formatArguments) { - super(message); - this.formatArguments = formatArguments; - } - - /** {@inheritDoc} */ - @Override - public String getMessage() { - return MessageFormat.format(super.getMessage(), formatArguments); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/Factorial.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/Factorial.java deleted file mode 100644 index 714830e8c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/Factorial.java +++ /dev/null @@ -1,53 +0,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. - */ - -package org.apache.commons.numbers.combinatorics; - -/** - * Factorial of a number. - */ -public class Factorial { - /** All long-representable factorials */ - static final long[] FACTORIALS = new long[] { - 1L, 1L, 2L, - 6L, 24L, 120L, - 720L, 5040L, 40320L, - 362880L, 3628800L, 39916800L, - 479001600L, 6227020800L, 87178291200L, - 1307674368000L, 20922789888000L, 355687428096000L, - 6402373705728000L, 121645100408832000L, 2432902008176640000L - }; - - /** - * Computes the factorial of {@code n}. - * - * @param n Argument. - * @return {@code n!} - * @throws IllegalArgumentException if {@code n < 0}. - * @throws IllegalArgumentException if {@code n > 20} (the factorial - * value is too large to fit in a {@code long}). - */ - public static long value(int n) { - if (n < 0 || - n > 20) { - throw new CombinatoricsException(CombinatoricsException.OUT_OF_RANGE, - n, 0, 20); - } - - return FACTORIALS[n]; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/FactorialDouble.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/FactorialDouble.java deleted file mode 100644 index df6942f98..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/FactorialDouble.java +++ /dev/null @@ -1,134 +0,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. - */ - -package org.apache.commons.numbers.combinatorics; - -/** - * Class for computing the natural logarithm of the - * factorial of a number. - * It allows to allocate a cache of precomputed values. - */ -public class FactorialDouble { - /** - * Size of precomputed factorials. - * @see Factorial - */ - private static final int FACTORIALS_LONG_CACHE_SIZE = 21; - /** - * Precomputed values of the function: {@code factorialsDouble[i] = i!}. - */ - private final double[] factorialsDouble; - - /** - * Creates an instance, reusing the already computed values if available. - * - * @param numValues Number of values of the function to compute. - * @param cache Cached values. - * @throw IllegalArgumentException if {@code n < 0}. - */ - private FactorialDouble(int numValues, - double[] cache) { - if (numValues < 0) { - throw new CombinatoricsException(CombinatoricsException.NEGATIVE, numValues); - } - - factorialsDouble = new double[numValues]; - // Initialize first two entries. - for (int i = 0, max = numValues < 2 ? numValues : 2; - i < max; i++) { - factorialsDouble [i] = 1; - } - - final int beginCopy = 2; - final int endCopy = cache == null || cache.length <= beginCopy ? - beginCopy : cache.length <= numValues ? - cache.length : numValues; - - // Copy available values. - for (int i = beginCopy; i < endCopy; i++) { - factorialsDouble[i] = cache[i]; - } - - // Precompute. - for (int i = endCopy; i < numValues; i++) { - factorialsDouble[i] = i * factorialsDouble[i - 1]; - } - } - - /** - * Creates an instance with no precomputed values. - * @return instance with no precomputed values - */ - public static FactorialDouble create() { - return new FactorialDouble(0, null); - } - - /** - * Creates an instance with the specified cache size. - * - * @param cacheSize Number of precomputed values of the function. - * @return a new instance where {@code cacheSize} values have been - * precomputed. - * @throws IllegalArgumentException if {@code cacheSize < 0}. - */ - public FactorialDouble withCache(final int cacheSize) { - return new FactorialDouble(cacheSize, - factorialsDouble); - } - - /** - * Computes the factorial of {@code n}. - * The result should be small enough to fit into a {@code double}: The - * largest {@code n} for which {@code n!} does not exceed - * {@code Double.MAX_VALUE} is 170. {@code Double.POSITIVE_INFINITY} is - * returned for {@code n > 170}. - * - * @param n Argument. - * @return {@code n!} - * @throws IllegalArgumentException if {@code n < 0}. - */ - public double value(int n) { - if (n < FACTORIALS_LONG_CACHE_SIZE) { - return Factorial.value(n); - } - - if (n < factorialsDouble.length) { - // Use cache of precomputed values. - return factorialsDouble[n]; - } - - return compute(n); - } - - /** - * @param n Argument. - * @return {@code n!} (approximated as a {@code double}). - */ - private double compute(int n) { - int start = 2; - double result = 1; - - if (factorialsDouble.length > 2) { - result = factorialsDouble[factorialsDouble.length - 1]; - start = factorialsDouble.length; - } - for (int i = start; i <= n; i++) { - result *= i; - } - return result; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/LogBinomialCoefficient.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/LogBinomialCoefficient.java deleted file mode 100644 index d943fae80..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/LogBinomialCoefficient.java +++ /dev/null @@ -1,83 +0,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. - */ - -package org.apache.commons.numbers.combinatorics; - -/** - * Natural logarithm of the - * binomial coefficient. - * It is "{@code n choose k}", the number of {@code k}-element subsets that - * can be selected from an {@code n}-element set. - */ -public class LogBinomialCoefficient { - /** - * Computes the logarithm of the binomial coefficient. - * The largest value of {@code n} for which all coefficients can - * fit into a {@code long} is 66. - * - * @param n Size of the set. - * @param k Size of the subsets to be counted. - * @return {@code log(n choose k)}. - * @throws IllegalArgumentException if {@code n < 0}. - * @throws IllegalArgumentException if {@code k > n}. - * @throws IllegalArgumentException if the result is too large to be - * represented by a {@code long}. - */ - public static double value(int n, int k) { - BinomialCoefficient.checkBinomial(n, k); - - if (n == k || - k == 0) { - return 0; - } - if (k == 1 || - k == n - 1) { - return Math.log(n); - } - - // For values small enough to do exact integer computation, - // return the log of the exact value. - if (n < 67) { - return Math.log(BinomialCoefficient.value(n, k)); - } - - // Logarithm of "BinomialCoefficientDouble" for values that - // will not overflow. - if (n < 1030) { - return Math.log(BinomialCoefficientDouble.value(n, k)); - } - - if (k > n / 2) { - return value(n, n - k); - } - - // Sum for values that could overflow. - double logSum = 0; - - // n! / (n - k)! - for (int i = n - k + 1; i <= n; i++) { - logSum += Math.log(i); - } - - // Divide by k! - for (int i = 2; i <= k; i++) { - logSum -= Math.log(i); - } - - return logSum; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/LogFactorial.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/LogFactorial.java deleted file mode 100644 index db2c1ddc7..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/LogFactorial.java +++ /dev/null @@ -1,115 +0,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. - */ - -package org.apache.commons.numbers.combinatorics; - -import org.apache.commons.numbers.gamma.LogGamma; - -/** - * Class for computing the natural logarithm of the factorial of a number. - * It allows to allocate a cache of precomputed values. - * In case of cache miss, computation is performed by a call to - * {@link LogGamma#value(double)}. - */ -public class LogFactorial { - /** - * Size of precomputed factorials. - * @see Factorial - */ - private static final int FACTORIALS_CACHE_SIZE = 21; - /** - * Precomputed values of the function: {@code logFactorials[i] = Math.log(i!)}. - */ - private final double[] logFactorials; - - /** - * Creates an instance, reusing the already computed values if available. - * - * @param numValues Number of values of the function to compute. - * @param cache Cached values. - * @throw IllegalArgumentException if {@code n < 0}. - */ - private LogFactorial(int numValues, - double[] cache) { - if (numValues < 0) { - throw new CombinatoricsException(CombinatoricsException.NEGATIVE, numValues); - } - - logFactorials = new double[numValues]; - - final int beginCopy = 2; - final int endCopy = cache == null || cache.length <= beginCopy ? - beginCopy : cache.length <= numValues ? - cache.length : numValues; - - // Copy available values. - for (int i = beginCopy; i < endCopy; i++) { - logFactorials[i] = cache[i]; - } - - // Precompute. - for (int i = endCopy; i < numValues; i++) { - logFactorials[i] = logFactorials[i - 1] + Math.log(i); - } - } - - /** - * Creates an instance with no precomputed values. - * @return instance with no precomputed values - */ - public static LogFactorial create() { - return new LogFactorial(0, null); - } - - /** - * Creates an instance with the specified cache size. - * - * @param cacheSize Number of precomputed values of the function. - * @return a new instance where {@code cacheSize} values have been - * precomputed. - * @throws IllegalArgumentException if {@code cacheSize < 0}. - */ - public LogFactorial withCache(final int cacheSize) { - return new LogFactorial(cacheSize, logFactorials); - } - - /** - * Computes \( log_e(n!) \). - * - * @param n Argument. - * @return {@code log(n!)}. - * @throws IllegalArgumentException if {@code n < 0}. - */ - public double value(int n) { - if (n < 0) { - throw new CombinatoricsException(CombinatoricsException.NEGATIVE, n); - } - - // Use cache of precomputed values. - if (n < logFactorials.length) { - return logFactorials[n]; - } - - // Use cache of precomputed factorial values. - if (n < FACTORIALS_CACHE_SIZE) { - return Math.log(Factorial.value(n)); - } - - // Delegate. - return LogGamma.value(n + 1); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/package-info.java deleted file mode 100644 index 9fdc00dde..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/combinatorics/package-info.java +++ /dev/null @@ -1,21 +0,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. - */ - -/** - * Combinatorics. - */ -package org.apache.commons.numbers.combinatorics; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/complex/Complex.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/complex/Complex.java deleted file mode 100644 index 5a80e5959..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/complex/Complex.java +++ /dev/null @@ -1,1400 +0,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. - */ - -package org.apache.commons.numbers.complex; - -import org.apache.commons.numbers.core.Precision; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -/** - * Representation of a Complex number, i.e. a number which has both a - * real and imaginary part. - *

- * Implementations of arithmetic operations handle {@code NaN} and - * infinite values according to the rules for {@link Double}, i.e. - * {@link #equals} is an equivalence relation for all instances that have - * a {@code NaN} in either real or imaginary part, e.g. the following are - * considered equal: - *

    - *
  • {@code 1 + NaNi}
  • - *
  • {@code NaN + i}
  • - *
  • {@code NaN + NaNi}
  • - *

- * Note that this contradicts the IEEE-754 standard for floating - * point numbers (according to which the test {@code x == x} must fail if - * {@code x} is {@code NaN}). The method - * {@link Precision#equals(double,double,int) - * equals for primitive double} in class {@code Precision} conforms with - * IEEE-754 while this class conforms with the standard behavior for Java - * object types.

- * - */ -public final class Complex implements Serializable { - /** The square root of -1, a.k.a. "i". */ - public static final Complex I = new Complex(0, 1); - /** A complex number representing "+INF + INF i" */ - public static final Complex INF = new Complex(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); - /** A complex number representing one. */ - public static final Complex ONE = new Complex(1, 0); - /** A complex number representing zero. */ - public static final Complex ZERO = new Complex(0, 0); - /** A complex number representing "NaN + NaN i" */ - private static final Complex NAN = new Complex(Double.NaN, Double.NaN); - - /** Serializable version identifier. */ - private static final long serialVersionUID = 20180201L; - - /** {@link #toString() String representation}. */ - private static final String FORMAT_START = "("; - /** {@link #toString() String representation}. */ - private static final String FORMAT_END = ")"; - /** {@link #toString() String representation}. */ - private static final String FORMAT_SEP = ","; - - /** The imaginary part. */ - private final double imaginary; - /** The real part. */ - private final double real; - - /** - * Private default constructor. - * - * @param real Real part. - * @param imaginary Imaginary part. - */ - private Complex(double real, double imaginary) { - this.real = real; - this.imaginary = imaginary; - } - - /** - * Create a complex number given the real and imaginary parts. - * - * @param real Real part. - * @param imaginary Imaginary part. - * @return {@code Complex} object - */ - public static Complex ofCartesian(double real, double imaginary) { - return new Complex(real, imaginary); - } - - /** - * Create a complex number given the real part. - * - * @param real Real part. - * @return {@code Complex} object - */ - public static Complex ofReal(double real) { - return new Complex(real, 0); - } - - /** - * Creates a Complex from its polar representation. - * - * If {@code r} is infinite and {@code theta} is finite, infinite or NaN - * values may be returned in parts of the result, following the rules for - * double arithmetic. - * - *
-     * Examples:
-     * {@code
-     * polar2Complex(INFINITY, \(\pi\)) = INFINITY + INFINITY i
-     * polar2Complex(INFINITY, 0) = INFINITY + NaN i
-     * polar2Complex(INFINITY, \(-\frac{\pi}{4}\)) = INFINITY - INFINITY i
-     * polar2Complex(INFINITY, \(5\frac{\pi}{4}\)) = -INFINITY - INFINITY i }
-     * 
- * - * @param r the modulus of the complex number to create - * @param theta the argument of the complex number to create - * @return {@code Complex} - */ - public static Complex ofPolar(double r, double theta) { - checkNotNegative(r); - return new Complex(r * Math.cos(theta), r * Math.sin(theta)); - } - - /** - * For a real constructor argument x, returns a new Complex object c - * where {@code c = cos(x) + i sin (x)} - * - * @param x {@code double} to build the cis number - * @return {@code Complex} - */ - public static Complex ofCis(double x) { - return new Complex(Math.cos(x), Math.sin(x)); - } - - /** - * Parses a string that would be produced by {@link #toString()} - * and instantiates the corresponding object. - * - * @param s String representation. - * @return an instance. - * @throws IllegalArgumentException if the string does not - * conform to the specification. - */ - public static Complex parse(String s) { - final int len = s.length(); - final int startParen = s.indexOf(FORMAT_START); - if (startParen != 0) { - throw new ComplexParsingException("Expected start string: " + FORMAT_START); - } - final int endParen = s.indexOf(FORMAT_END); - if (endParen != len - 1) { - throw new ComplexParsingException("Expected end string: " + FORMAT_END); - } - final String[] elements = s.substring(1, s.length() - 1).split(FORMAT_SEP); - if (elements.length != 2) { - throw new ComplexParsingException("Incorrect number of parts: Expected 2 but was " + - elements.length + - " (separator is '" + FORMAT_SEP + "')"); - } - - final double re; - try { - re = Double.parseDouble(elements[0]); - } catch (NumberFormatException ex) { - throw new ComplexParsingException("Could not parse real part" + elements[0]); - } - final double im; - try { - im = Double.parseDouble(elements[1]); - } catch (NumberFormatException ex) { - throw new ComplexParsingException("Could not parse imaginary part" + elements[1]); - } - - return ofCartesian(re, im); - } - - /** - * Returns true if either real or imaginary component of the Complex - * is NaN - * - * @return {@code boolean} - */ - public boolean isNaN() { - if (Double.isNaN(real) || - Double.isNaN(imaginary)) { - return true; - } else { - return false; - } - } - - /** - * Returns true if either real or imaginary component of the Complex - * is Infinite - * - * @return {@code boolean} - */ - public boolean isInfinite() { - if (Double.isInfinite(real) || - Double.isInfinite(imaginary)) { - return true; - } else { - return false; - } - } - - /** - * Returns projection of this complex number onto the Riemann sphere, - * i.e. all infinities (including those with an NaN component) - * project onto real infinity, as described in the - * - * IEEE and ISO C standards. - *

- * - * - * @return {@code Complex} projected onto the Riemann sphere. - */ - public Complex proj() { - if (Double.isInfinite(real) || - Double.isInfinite(imaginary)) { - return new Complex(Double.POSITIVE_INFINITY, 0); - } else { - return this; - } - } - - /** - * Return the absolute value of this complex number. - * This code follows the ISO C Standard, Annex G, - * in calculating the returned value (i.e. the hypot(x,y) method) - * and in handling of NaNs. - * - * @return the absolute value. - */ - public double abs() { - if (Math.abs(real) < Math.abs(imaginary)) { - final double q = real / imaginary; - return Math.abs(imaginary) * Math.sqrt(1 + q * q); - } else { - if (real == 0) { - return Math.abs(imaginary); - } - final double q = imaginary / real; - return Math.abs(real) * Math.sqrt(1 + q * q); - } - } - - /** - * Returns a {@code Complex} whose value is - * {@code (this + addend)}. - * Uses the definitional formula - *

- * {@code (a + bi) + (c + di) = (a+c) + (b+d)i} - *

- * - * @param addend Value to be added to this {@code Complex}. - * @return {@code this + addend}. - */ - public Complex add(Complex addend) { - return new Complex(real + addend.real, - imaginary + addend.imaginary); - } - - /** - * Returns a {@code Complex} whose value is {@code (this + addend)}, - * with {@code addend} interpreted as a real number. - * - * @param addend Value to be added to this {@code Complex}. - * @return {@code this + addend}. - * @see #add(Complex) - */ - public Complex add(double addend) { - return new Complex(real + addend, imaginary); - } - - /** - * Returns the conjugate of this complex number. - * The conjugate of {@code a + bi} is {@code a - bi}. - * - * @return the conjugate of this complex object. - */ - public Complex conjugate() { - return new Complex(real, -imaginary); - } - - /** - * Returns the conjugate of this complex number. - * C++11 grammar. - * @return the conjugate of this complex object. - */ - public Complex conj() { - return conjugate(); - } - - - /** - * Returns a {@code Complex} whose value is - * {@code (this / divisor)}. - * Implements the definitional formula - *
-     *  
-     *    a + bi          ac + bd + (bc - ad)i
-     *    ----------- = -------------------------
-     *    c + di         c2 + d2
-     *  
-     * 
- * - * - * Recalculates to recover infinities as specified in C.99 - * standard G.5.1. Method is fully in accordance with - * C++11 standards for complex numbers. - * - * @param divisor Value by which this {@code Complex} is to be divided. - * @return {@code this / divisor}. - */ - public Complex divide(Complex divisor) { - - double a = real; - double b = imaginary; - double c = divisor.getReal(); - double d = divisor.getImaginary(); - int ilogbw = 0; - double logbw = Math.log(Math.max(Math.abs(c), Math.abs(d))) / Math.log(2); - if (!Double.isInfinite(logbw)) { - ilogbw = (int)logbw; - c = Math.scalb(c, -ilogbw); - d = Math.scalb(d, -ilogbw); - } - double denom = c*c + d*d; - double x = Math.scalb( (a*c + b*d) / denom, -ilogbw); - double y = Math.scalb( (b*c - a*d) / denom, -ilogbw); - if (Double.isNaN(x) && Double.isNaN(y)) { - if ((denom == 0.0) && - (!Double.isNaN(a) || !Double.isNaN(b))) { - x = Math.copySign(Double.POSITIVE_INFINITY, c) * a; - y = Math.copySign(Double.POSITIVE_INFINITY, c) * b; - } else if ((Double.isInfinite(a) && Double.isInfinite(b)) && - !Double.isInfinite(c) && !Double.isInfinite(d)) { - a = Math.copySign(Double.isInfinite(a) ? 1.0 : 0.0, a); - b = Math.copySign(Double.isInfinite(b) ? 1.0 : 0.0, b); - x = Double.POSITIVE_INFINITY * (a*c + b*d); - y = Double.POSITIVE_INFINITY * (b*c - a*d); - } else if (Double.isInfinite(logbw) && - !Double.isInfinite(a) && !Double.isInfinite(b)) { - c = Math.copySign(Double.isInfinite(c) ? 1.0 : 0.0, c); - d = Math.copySign(Double.isInfinite(d) ? 1.0 : 0.0, d); - x = 0.0 * (a*c + b*d); - y = 0.0 * (b*c - a*d); - } - } - return new Complex(x, y); - - - } - - /** - * Returns a {@code Complex} whose value is {@code (this / divisor)}, - * with {@code divisor} interpreted as a real number. - * - * @param divisor Value by which this {@code Complex} is to be divided. - * @return {@code this / divisor}. - * @see #divide(Complex) - */ - public Complex divide(double divisor) { - return divide(new Complex(divisor, 0)); - } - - /** - * Returns the multiplicative inverse of this instance. - * - * @return {@code 1 / this}. - * @see #divide(Complex) - */ - public Complex reciprocal() { - if (Math.abs(real) < Math.abs(imaginary)) { - final double q = real / imaginary; - final double scale = 1. / (real * q + imaginary); - double scaleQ = 0; - if (q != 0 && - scale != 0) { - scaleQ = scale * q; - } - return new Complex(scaleQ, -scale); - } else { - final double q = imaginary / real; - final double scale = 1. / (imaginary * q + real); - double scaleQ = 0; - if (q != 0 && - scale != 0) { - scaleQ = scale * q; - } - return new Complex(scale, -scaleQ); - } - } - - /** - * Test for equality with another object. - * If both the real and imaginary parts of two complex numbers - * are exactly the same, and neither is {@code Double.NaN}, the two - * Complex objects are considered to be equal. - * The behavior is the same as for JDK's {@link Double#equals(Object) - * Double}: - *
    - *
  • All {@code NaN} values are considered to be equal, - * i.e, if either (or both) real and imaginary parts of the complex - * number are equal to {@code Double.NaN}, the complex number is equal - * to {@code NaN}. - *
  • - *
  • - * Instances constructed with different representations of zero (i.e. - * either "0" or "-0") are not considered to be equal. - *
  • - *
- * - * @param other Object to test for equality with this instance. - * @return {@code true} if the objects are equal, {@code false} if object - * is {@code null}, not an instance of {@code Complex}, or not equal to - * this instance. - */ - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other instanceof Complex){ - Complex c = (Complex) other; - return equals(real, c.real) && - equals(imaginary, c.imaginary); - } - return false; - } - - /** - * Test for the floating-point equality between Complex objects. - * It returns {@code true} if both arguments are equal or within the - * range of allowed error (inclusive). - * - * @param x First value (cannot be {@code null}). - * @param y Second value (cannot be {@code null}). - * @param maxUlps {@code (maxUlps - 1)} is the number of floating point - * values between the real (resp. imaginary) parts of {@code x} and - * {@code y}. - * @return {@code true} if there are fewer than {@code maxUlps} floating - * point values between the real (resp. imaginary) parts of {@code x} - * and {@code y}. - * - * @see Precision#equals(double,double,int) - */ - public static boolean equals(Complex x, - Complex y, - int maxUlps) { - return Precision.equals(x.real, y.real, maxUlps) && - Precision.equals(x.imaginary, y.imaginary, maxUlps); - } - - /** - * Returns {@code true} iff the values are equal as defined by - * {@link #equals(Complex,Complex,int) equals(x, y, 1)}. - * - * @param x First value (cannot be {@code null}). - * @param y Second value (cannot be {@code null}). - * @return {@code true} if the values are equal. - */ - public static boolean equals(Complex x, - Complex y) { - return equals(x, y, 1); - } - - /** - * Returns {@code true} if, both for the real part and for the imaginary - * part, there is no double value strictly between the arguments or the - * difference between them is within the range of allowed error - * (inclusive). Returns {@code false} if either of the arguments is NaN. - * - * @param x First value (cannot be {@code null}). - * @param y Second value (cannot be {@code null}). - * @param eps Amount of allowed absolute error. - * @return {@code true} if the values are two adjacent floating point - * numbers or they are within range of each other. - * - * @see Precision#equals(double,double,double) - */ - public static boolean equals(Complex x, - Complex y, - double eps) { - return Precision.equals(x.real, y.real, eps) && - Precision.equals(x.imaginary, y.imaginary, eps); - } - - /** - * Returns {@code true} if, both for the real part and for the imaginary - * part, there is no double value strictly between the arguments or the - * relative difference between them is smaller or equal to the given - * tolerance. Returns {@code false} if either of the arguments is NaN. - * - * @param x First value (cannot be {@code null}). - * @param y Second value (cannot be {@code null}). - * @param eps Amount of allowed relative error. - * @return {@code true} if the values are two adjacent floating point - * numbers or they are within range of each other. - * - * @see Precision#equalsWithRelativeTolerance(double,double,double) - */ - public static boolean equalsWithRelativeTolerance(Complex x, Complex y, - double eps) { - return Precision.equalsWithRelativeTolerance(x.real, y.real, eps) && - Precision.equalsWithRelativeTolerance(x.imaginary, y.imaginary, eps); - } - - /** - * Get a hash code for the complex number. - * Any {@code Double.NaN} value in real or imaginary part produces - * the same hash code {@code 7}. - * - * @return a hash code value for this object. - */ - @Override - public int hashCode() { - if (Double.isNaN(real) || - Double.isNaN(imaginary)) { - return 7; - } - return 37 * (17 * hash(imaginary) + hash(real)); - } - - /** - * @param d Value. - * @return a hash code for the given value. - */ - private int hash(double d) { - final long v = Double.doubleToLongBits(d); - return (int) (v ^ (v >>> 32)); - //return new Double(d).hashCode(); - } - - /** - * Access the imaginary part. - * - * @return the imaginary part. - */ - public double getImaginary() { - return imaginary; - } - /** - * Access the imaginary part (C++ grammar) - * - * @return the imaginary part. - */ - public double imag() { - return imaginary; - } - - /** - * Access the real part. - * - * @return the real part. - */ - public double getReal() { - return real; - } - - /** - * Access the real part (C++ grammar) - * - * @return the real part. - */ - public double real() { - return real; - } - - /** - * Returns a {@code Complex} whose value is {@code this * factor}. - * Implements the definitional formula: - * - * {@code (a + bi)(c + di) = (ac - bd) + (ad + bc)i} - * - * Recalculates to recover infinities as specified in C.99 - * standard G.5.1. Method is fully in accordance with - * C++11 standards for complex numbers. - * - * @param factor value to be multiplied by this {@code Complex}. - * @return {@code this * factor}. - */ - public Complex multiply(Complex factor) { - double a = real; - double b = imaginary; - double c = factor.getReal(); - double d = factor.getImaginary(); - final double ac = a*c; - final double bd = b*d; - final double ad = a*d; - final double bc = b*c; - double x = ac - bd; - double y = ad + bc; - if (Double.isNaN(a) && Double.isNaN(b)) { - boolean recalc = false; - if (Double.isInfinite(a) || Double.isInfinite(b)) { - a = Math.copySign(Double.isInfinite(a) ? 1.0 : 0.0, a); - b = Math.copySign(Double.isInfinite(a) ? 1.0 : 0.0, a); - if (Double.isNaN(c)) { - c = Math.copySign(0.0, c); - } - if (Double.isNaN(d)) { - d = Math.copySign(0.0, d); - } - recalc = true; - } - if (Double.isInfinite(c) || Double.isInfinite(d)) { - c = Math.copySign(Double.isInfinite(c) ? 1.0 : 0.0, c); - d = Math.copySign(Double.isInfinite(d) ? 1.0 : 0.0, d); - if (Double.isNaN(a)) { - a = Math.copySign(0.0, a); - } - if (Double.isNaN(b)) { - b = Math.copySign(0.0, b); - } - recalc = true; - } - if (!recalc && (Double.isInfinite(ac) || Double.isInfinite(bd) || - Double.isInfinite(ad) || Double.isInfinite(bc))) { - if (Double.isNaN(a)) { - a = Math.copySign(0.0, a); - } - if (Double.isNaN(b)) { - b = Math.copySign(0.0, b); - } - if (Double.isNaN(c)) { - c = Math.copySign(0.0, c); - } - if (Double.isNaN(d)) { - d = Math.copySign(0.0, d); - } - recalc = true; - } - if (recalc) { - x = Double.POSITIVE_INFINITY * (a*c - b*d); - y = Double.POSITIVE_INFINITY * (a*d + b*c); - } - } - return new Complex(x, y); - } - - /** - * Returns a {@code Complex} whose value is {@code this * factor}, with {@code factor} - * interpreted as a integer number. - * - * @param factor value to be multiplied by this {@code Complex}. - * @return {@code this * factor}. - * @see #multiply(Complex) - */ - public Complex multiply(final int factor) { - return new Complex(real * factor, imaginary * factor); - } - - /** - * Returns a {@code Complex} whose value is {@code this * factor}, with {@code factor} - * interpreted as a real number. - * - * @param factor value to be multiplied by this {@code Complex}. - * @return {@code this * factor}. - * @see #multiply(Complex) - */ - public Complex multiply(double factor) { - return new Complex(real * factor, imaginary * factor); - } - - /** - * Returns a {@code Complex} whose value is {@code (-this)}. - * - * @return {@code -this}. - */ - public Complex negate() { - return new Complex(-real, -imaginary); - } - - /** - * Returns a {@code Complex} whose value is - * {@code (this - subtrahend)}. - * Uses the definitional formula - *

- * {@code (a + bi) - (c + di) = (a-c) + (b-d)i} - *

- * - * @param subtrahend value to be subtracted from this {@code Complex}. - * @return {@code this - subtrahend}. - */ - public Complex subtract(Complex subtrahend) { - return new Complex(real - subtrahend.real, - imaginary - subtrahend.imaginary); - } - - /** - * Returns a {@code Complex} whose value is - * {@code (this - subtrahend)}. - * - * @param subtrahend value to be subtracted from this {@code Complex}. - * @return {@code this - subtrahend}. - * @see #subtract(Complex) - */ - public Complex subtract(double subtrahend) { - return new Complex(real - subtrahend, imaginary); - } - - /** - * Compute the - * - * inverse cosine of this complex number. - * Implements the formula: - *

- * {@code acos(z) = -i (log(z + i (sqrt(1 - z2))))} - *

- * - * @return the inverse cosine of this complex number. - */ - public Complex acos() { - if (real == 0 && - Double.isNaN(imaginary)) { - return new Complex(Math.PI * 0.5, Double.NaN); - } else if (neitherInfiniteNorZeroNorNaN(real) && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(Math.PI * 0.5, Double.NEGATIVE_INFINITY); - } else if (real == Double.NEGATIVE_INFINITY && - imaginary == 1) { - return new Complex(Math.PI, Double.NEGATIVE_INFINITY); - } else if (real == Double.POSITIVE_INFINITY && - imaginary == 1) { - return new Complex(0, Double.NEGATIVE_INFINITY); - } else if (real == Double.NEGATIVE_INFINITY && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(Math.PI * 0.75, Double.NEGATIVE_INFINITY); - } else if (real == Double.POSITIVE_INFINITY && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(Math.PI * 0.25, Double.NEGATIVE_INFINITY); - } else if (real == Double.POSITIVE_INFINITY && - Double.isNaN(imaginary)) { - return new Complex(Double.NaN , Double.POSITIVE_INFINITY); - } else if (real == Double.NEGATIVE_INFINITY && - Double.isNaN(imaginary)) { - return new Complex(Double.NaN, Double.NEGATIVE_INFINITY); - } else if (Double.isNaN(real) && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(Double.NaN, Double.NEGATIVE_INFINITY); - } - return add(sqrt1z().multiply(I)).log().multiply(I.negate()); - } - /** - * Compute the - * - * inverse sine of this complex number. - *

- * {@code asin(z) = -i (log(sqrt(1 - z2) + iz))} - *

- * @return the inverse sine of this complex number - */ - public Complex asin() { - return sqrt1z().add(multiply(I)).log().multiply(I.negate()); - } - /** - * Compute the - * - * inverse tangent of this complex number. - * Implements the formula: - *

- * {@code atan(z) = (i/2) log((i + z)/(i - z))} - *

- * @return the inverse tangent of this complex number - */ - public Complex atan() { - return add(I).divide(I.subtract(this)).log().multiply(I.multiply(0.5)); - } - - /** - * Compute the - * - * inverse hyperbolic sine of this complex number. - * Implements the formula: - *

- * {@code asinh(z) = log(z+sqrt(z^2+1))} - *

- * @return the inverse hyperbolic cosine of this complex number - */ - public Complex asinh(){ - if (neitherInfiniteNorZeroNorNaN(real) && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(Double.POSITIVE_INFINITY, Math.PI * 0.5); - } else if (real == Double.POSITIVE_INFINITY && - !Double.isInfinite(imaginary) && !Double.isNaN(imaginary)) { - return new Complex(Double.POSITIVE_INFINITY, 0); - } else if (real == Double.POSITIVE_INFINITY && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(Double.POSITIVE_INFINITY, Math.PI * 0.25); - } else if (real == Double.POSITIVE_INFINITY && - Double.isNaN(imaginary)) { - return new Complex(Double.POSITIVE_INFINITY, Double.NaN); - } else if (Double.isNaN(real) && - imaginary == 0) { - return new Complex(Double.NaN, 0); - } else if (Double.isNaN(real) && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(Double.POSITIVE_INFINITY, Double.NaN); - } - return square().add(ONE).sqrt().add(this).log(); - } - - /** - * Compute the - * - * inverse hyperbolic tangent of this complex number. - * Implements the formula: - *

- * {@code atanh(z) = log((1+z)/(1-z))/2} - *

- * @return the inverse hyperbolic cosine of this complex number - */ - public Complex atanh(){ - if (real == 0 && - Double.isNaN(imaginary)) { - return new Complex(0, Double.NaN); - } else if (neitherInfiniteNorZeroNorNaN(real) && - imaginary == 0) { - return new Complex(Double.POSITIVE_INFINITY, 0); - } else if (neitherInfiniteNorZeroNorNaN(real) && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(0, Math.PI * 0.5); - } else if (real == Double.POSITIVE_INFINITY && - neitherInfiniteNorZeroNorNaN(imaginary)) { - return new Complex(0, Math.PI * 0.5); - } else if (real == Double.POSITIVE_INFINITY && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(0, Math.PI * 0.5); - } else if (real == Double.POSITIVE_INFINITY && - Double.isNaN(imaginary)) { - return new Complex(0, Double.NaN); - } else if (Double.isNaN(real) && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(0, Math.PI * 0.5); - } - return add(ONE).divide(ONE.subtract(this)).log().multiply(0.5); - } - /** - * Compute the - * - * inverse hyperbolic cosine of this complex number. - * Implements the formula: - *

- * {@code acosh(z) = log(z+sqrt(z^2-1))} - *

- * @return the inverse hyperbolic cosine of this complex number - */ - public Complex acosh() { - return square().subtract(ONE).sqrt().add(this).log(); - } - - /** - * Compute the square of this complex number. - * - * @return square of this complex number - */ - public Complex square() { - return multiply(this); - } - - /** - * Compute the - * - * cosine of this complex number. - * Implements the formula: - *

- * {@code cos(a + bi) = cos(a)cosh(b) - sin(a)sinh(b)i} - *

- * where the (real) functions on the right-hand side are - * {@link Math#sin}, {@link Math#cos}, - * {@link Math#cosh} and {@link Math#sinh}. - *

- * - * @return the cosine of this complex number. - */ - public Complex cos() { - return new Complex(Math.cos(real) * Math.cosh(imaginary), - -Math.sin(real) * Math.sinh(imaginary)); - } - - /** - * Compute the - * - * hyperbolic cosine of this complex number. - * Implements the formula: - *

-     *  
-     *   cosh(a + bi) = cosh(a)cos(b) + sinh(a)sin(b)i
-     *  
-     * 
- * where the (real) functions on the right-hand side are - * {@link Math#sin}, {@link Math#cos}, - * {@link Math#cosh} and {@link Math#sinh}. - *

- * - * @return the hyperbolic cosine of this complex number. - */ - public Complex cosh() { - if (real == 0 && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(Double.NaN, 0); - } else if (real == 0 && - Double.isNaN(imaginary)) { - return new Complex(Double.NaN, 0); - } else if (real == Double.POSITIVE_INFINITY && - imaginary == 0) { - return new Complex(Double.POSITIVE_INFINITY, 0); - } else if (real == Double.POSITIVE_INFINITY && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(Double.POSITIVE_INFINITY, Double.NaN); - } else if (real == Double.POSITIVE_INFINITY && - Double.isNaN(imaginary)) { - return new Complex(Double.POSITIVE_INFINITY, Double.NaN); - } else if (Double.isNaN(real) && - imaginary == 0) { - return new Complex(Double.NaN, 0); - } - - return new Complex(Math.cosh(real) * Math.cos(imaginary), - Math.sinh(real) * Math.sin(imaginary)); - } - - /** - * Compute the - * - * exponential function of this complex number. - * Implements the formula: - *

-     *  
-     *   exp(a + bi) = exp(a)cos(b) + exp(a)sin(b)i
-     *  
-     * 
- * where the (real) functions on the right-hand side are - * {@link Math#exp}, {@link Math#cos}, and - * {@link Math#sin}. - * - * @return ethis. - */ - public Complex exp() { - if (real == Double.POSITIVE_INFINITY && - imaginary == 0) { - return new Complex(Double.POSITIVE_INFINITY, 0); - } else if (real == Double.NEGATIVE_INFINITY && - imaginary == Double.POSITIVE_INFINITY) { - return Complex.ZERO; - } else if (real == Double.POSITIVE_INFINITY && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(Double.POSITIVE_INFINITY, Double.NaN); - } else if (real == Double.NEGATIVE_INFINITY && - Double.isNaN(imaginary)) { - return Complex.ZERO; - } else if (real == Double.POSITIVE_INFINITY && - Double.isNaN(imaginary)) { - return new Complex(Double.POSITIVE_INFINITY, Double.NaN); - } else if (Double.isNaN(real) && - imaginary == 0) { - return new Complex(Double.NaN, 0); - } - double expReal = Math.exp(real); - return new Complex(expReal * Math.cos(imaginary), - expReal * Math.sin(imaginary)); - } - - /** - * Compute the - * - * natural logarithm of this complex number. - * Implements the formula: - *
-     *  
-     *   log(a + bi) = ln(|a + bi|) + arg(a + bi)i
-     *  
-     * 
- * where ln on the right hand side is {@link Math#log}, - * {@code |a + bi|} is the modulus, {@link Complex#abs}, and - * {@code arg(a + bi) = }{@link Math#atan2}(b, a). - * - * @return the value ln   this, the natural logarithm - * of {@code this}. - */ - public Complex log() { - if (real == Double.POSITIVE_INFINITY && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(Double.POSITIVE_INFINITY, Math.PI * 0.25); - } else if (real == Double.POSITIVE_INFINITY && - Double.isNaN(imaginary)) { - return new Complex(Double.POSITIVE_INFINITY, Double.NaN); - } else if (Double.isNaN(real) && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(Double.POSITIVE_INFINITY, Double.NaN); - } - return new Complex(Math.log(abs()), - Math.atan2(imaginary, real)); - } - - /** - * Compute the base 10 or - * - * common logarithm of this complex number. - * - * @return the base 10 logarithm of this. - */ - public Complex log10() { - return new Complex(Math.log(abs()) / Math.log(10), - Math.atan2(imaginary, real)); - } - - /** - * Returns of value of this complex number raised to the power of {@code x}. - * Implements the formula: - *
-     *  
-     *   yx = exp(x·log(y))
-     *  
-     * 
- * where {@code exp} and {@code log} are {@link #exp} and - * {@link #log}, respectively. - * - * @param x exponent to which this {@code Complex} is to be raised. - * @return thisx. - */ - public Complex pow(Complex x) { - if (real == 0 && - imaginary == 0) { - if (x.real > 0 && - x.imaginary == 0) { - // 0 raised to positive number is 0 - return ZERO; - } else { - // 0 raised to anything else is NaN - return NAN; - } - } - return log().multiply(x).exp(); - } - - /** - * Returns of value of this complex number raised to the power of {@code x}. - * - * @param x exponent to which this {@code Complex} is to be raised. - * @return thisx. - * @see #pow(Complex) - */ - public Complex pow(double x) { - if (real == 0 && - imaginary == 0) { - if (x > 0) { - // 0 raised to positive number is 0 - return ZERO; - } else { - // 0 raised to anything else is NaN - return NAN; - } - } - return log().multiply(x).exp(); - } - - /** - * Compute the - * - * sine - * of this complex number. - * Implements the formula: - *
-     *  
-     *   sin(a + bi) = sin(a)cosh(b) - cos(a)sinh(b)i
-     *  
-     * 
- * where the (real) functions on the right-hand side are - * {@link Math#sin}, {@link Math#cos}, - * {@link Math#cosh} and {@link Math#sinh}. - * - * @return the sine of this complex number. - */ - public Complex sin() { - return new Complex(Math.sin(real) * Math.cosh(imaginary), - Math.cos(real) * Math.sinh(imaginary)); - } - - /** - * Compute the - * - * hyperbolic sine of this complex number. - * Implements the formula: - *
-     *  
-     *   sinh(a + bi) = sinh(a)cos(b)) + cosh(a)sin(b)i
-     *  
-     * 
- * where the (real) functions on the right-hand side are - * {@link Math#sin}, {@link Math#cos}, - * {@link Math#cosh} and {@link Math#sinh}. - * - * @return the hyperbolic sine of {@code this}. - */ - public Complex sinh() { - if (real == 0 && - imaginary == 0) { - return Complex.ZERO; - } else if (real == 0 && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(0, Double.NaN); - } else if (real == 0 && - Double.isNaN(imaginary)) { - return new Complex(0, Double.NaN); - } else if (real == Double.POSITIVE_INFINITY && - imaginary == 0) { - return new Complex(Double.POSITIVE_INFINITY, 0); - } else if (real == Double.POSITIVE_INFINITY && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(Double.POSITIVE_INFINITY, Double.NaN); - } else if (real == Double.POSITIVE_INFINITY && - Double.isNaN(imaginary)) { - return new Complex(Double.POSITIVE_INFINITY, Double.NaN); - } else if (Double.isNaN(real) && - imaginary == 0) { - return new Complex(Double.NaN, 0); - } - return new Complex(Math.sinh(real) * Math.cos(imaginary), - Math.cosh(real) * Math.sin(imaginary)); - } - - /** - * Compute the - * - * square root of this complex number. - * Implements the following algorithm to compute {@code sqrt(a + bi)}: - *
  1. Let {@code t = sqrt((|a| + |a + bi|) / 2)}
  2. - *
  3. if {@code  a ≥ 0} return {@code t + (b/2t)i}
    -     *  else return {@code |b|/2t + sign(b)t i }
  4. - *
- * where
    - *
  • {@code |a| = }{@link Math#abs}(a)
  • - *
  • {@code |a + bi| = }{@link Complex#abs}(a + bi)
  • - *
  • {@code sign(b) = }{@link Math#copySign(double,double) copySign(1d, b)} - *
- * - * @return the square root of {@code this}. - */ - public Complex sqrt() { - if (real == 0 && - imaginary == 0) { - return ZERO; - } else if (neitherInfiniteNorZeroNorNaN(real) && - imaginary == Double.POSITIVE_INFINITY) { - return new Complex(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); - } else if (real == Double.NEGATIVE_INFINITY && - neitherInfiniteNorZeroNorNaN(imaginary)) { - return new Complex(0, Double.NaN); - } else if (real == Double.NEGATIVE_INFINITY && - Double.isNaN(imaginary)) { - return new Complex(Double.NaN, Double.POSITIVE_INFINITY); - } else if (real == Double.POSITIVE_INFINITY && - Double.isNaN(imaginary)) { - return new Complex(Double.POSITIVE_INFINITY, Double.NaN); - } - - final double t = Math.sqrt((Math.abs(real) + abs()) / 2); - if (real >= 0) { - return new Complex(t, imaginary / (2 * t)); - } else { - return new Complex(Math.abs(imaginary) / (2 * t), - Math.copySign(1d, imaginary) * t); - } - } - - /** - * Compute the - * - * square root of 1 - this2 for this complex - * number. - * Computes the result directly as - * {@code sqrt(ONE.subtract(z.multiply(z)))}. - * - * @return the square root of 1 - this2. - */ - private Complex sqrt1z() { - return ONE.subtract(square()).sqrt(); - } - - /** - * Compute the - * - * tangent of this complex number. - * Implements the formula: - *
-     *  
-     *   tan(a + bi) = sin(2a)/(cos(2a)+cosh(2b)) + [sinh(2b)/(cos(2a)+cosh(2b))]i
-     *  
-     * 
- * where the (real) functions on the right-hand side are - * {@link Math#sin}, {@link Math#cos}, {@link Math#cosh} and - * {@link Math#sinh}. - * - * @return the tangent of {@code this}. - */ - public Complex tan() { - if (imaginary > 20) { - return ONE; - } - if (imaginary < -20) { - return new Complex(0, -1); - } - - final double real2 = 2 * real; - final double imaginary2 = 2 * imaginary; - final double d = Math.cos(real2) + Math.cosh(imaginary2); - - return new Complex(Math.sin(real2) / d, - Math.sinh(imaginary2) / d); - } - - /** - * Compute the - * - * hyperbolic tangent of this complex number. - * Implements the formula: - *
-     *  
-     *   tan(a + bi) = sinh(2a)/(cosh(2a)+cos(2b)) + [sin(2b)/(cosh(2a)+cos(2b))]i
-     *  
-     * 
- * where the (real) functions on the right-hand side are - * {@link Math#sin}, {@link Math#cos}, {@link Math#cosh} and - * {@link Math#sinh}. - * - * @return the hyperbolic tangent of {@code this}. - */ - public Complex tanh() { - if (real == Double.POSITIVE_INFINITY && - imaginary == Double.POSITIVE_INFINITY) { - return ONE; - } else if (real == Double.POSITIVE_INFINITY && - Double.isNaN(imaginary)) { - return ONE; - } else if (Double.isNaN(real) && - imaginary == 0) { - return new Complex(Double.NaN, 0); - } - final double real2 = 2 * real; - final double imaginary2 = 2 * imaginary; - final double d = Math.cosh(real2) + Math.cos(imaginary2); - - return new Complex(Math.sinh(real2) / d, - Math.sin(imaginary2) / d); - } - - /** - * Compute the argument of this complex number. - * The argument is the angle phi between the positive real axis and - * the point representing this number in the complex plane. - * The value returned is between -PI (not inclusive) - * and PI (inclusive), with negative values returned for numbers with - * negative imaginary parts. - *

- * If either real or imaginary part (or both) is NaN, NaN is returned. - * Infinite parts are handled as {@code Math.atan2} handles them, - * essentially treating finite parts as zero in the presence of an - * infinite coordinate and returning a multiple of pi/4 depending on - * the signs of the infinite parts. - * See the javadoc for {@code Math.atan2} for full details. - * - * @return the argument of {@code this}. - */ - public double getArgument() { - return Math.atan2(imaginary, real); - } - - /** - * Compute the argument of this complex number. - * C++11 syntax - * - * @return the argument of {@code this}. - */ - public double arg() { - return getArgument(); - } - - /** - * Computes the n-th roots of this complex number. - * The nth roots are defined by the formula: - *

-     *  
-     *   zk = abs1/n (cos(phi + 2πk/n) + i (sin(phi + 2πk/n))
-     *  
-     * 
- * for {@code k=0, 1, ..., n-1}, where {@code abs} and {@code phi} - * are respectively the {@link #abs() modulus} and - * {@link #getArgument() argument} of this complex number. - *

- * If one or both parts of this complex number is NaN, a list with just - * one element, {@code NaN + NaN i} is returned. - * if neither part is NaN, but at least one part is infinite, the result - * is a one-element list containing {@link #INF}. - * - * @param n Degree of root. - * @return a List of all {@code n}-th roots of {@code this}. - */ - public List nthRoot(int n) { - if (n == 0) { - throw new IllegalArgumentException("cannot compute zeroth root"); - } - - final List result = new ArrayList(); - - // nth root of abs -- faster / more accurate to use a solver here? - final double nthRootOfAbs = Math.pow(abs(), 1d / n); - - // Compute nth roots of complex number with k = 0, 1, ... n-1 - final double nthPhi = getArgument() / n; - final double slice = 2 * Math.PI / n; - double innerPart = nthPhi; - for (int k = 0; k < Math.abs(n) ; k++) { - // inner part - final double realPart = nthRootOfAbs * Math.cos(innerPart); - final double imaginaryPart = nthRootOfAbs * Math.sin(innerPart); - result.add(new Complex(realPart, imaginaryPart)); - innerPart += slice; - } - - return result; - } - - /** {@inheritDoc} */ - @Override - public String toString() { - final StringBuilder s = new StringBuilder(); - s.append(FORMAT_START) - .append(real).append(FORMAT_SEP) - .append(imaginary) - .append(FORMAT_END); - - return s.toString(); - } - - /** - * Check that the argument is positive and throw a RuntimeException - * if it is not. - * @param arg {@code double} to check - */ - private static void checkNotNegative(double arg) { - if (arg <= 0) { - throw new IllegalArgumentException("Complex: Non-positive argument"); - } - } - - /** - * Returns {@code true} if the values are equal according to semantics of - * {@link Double#equals(Object)}. - * - * @param x Value - * @param y Value - * @return {@code Double.valueof(x).equals(Double.valueOf(y))} - */ - private static boolean equals(double x, double y) { - return Double.doubleToLongBits(x) == Double.doubleToLongBits(y); - } - - /** - * Check that a value meets all the following conditions: - *

    - *
  • it is not {@code NaN},
  • - *
  • it is not infinite,
  • - *
  • it is not zero,
  • - *
- * - * @param d Value. - * @return {@code true} if {@code d} meets all the conditions and - * {@code false} otherwise. - */ - private static boolean neitherInfiniteNorZeroNorNaN(double d) { - return !Double.isNaN(d) && - !Double.isInfinite(d) && - d != 0; - } - - /** See {@link #parse(String)}. */ - private static class ComplexParsingException extends IllegalArgumentException { - /** Serializable version identifier. */ - private static final long serialVersionUID = 20180430L; - - /** - * @param msg Error message. - */ - ComplexParsingException(String msg) { - super(msg); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/complex/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/complex/package-info.java deleted file mode 100644 index 152d08f8c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/complex/package-info.java +++ /dev/null @@ -1,20 +0,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. - */ -/** - * Complex numbers. - */ -package org.apache.commons.numbers.complex; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/complex/streams/ComplexUtils.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/complex/streams/ComplexUtils.java deleted file mode 100644 index 66d72b5fd..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/complex/streams/ComplexUtils.java +++ /dev/null @@ -1,1602 +0,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. - */ - -package org.apache.commons.numbers.complex.streams; - -import org.apache.commons.numbers.complex.Complex; - -/** - * Static implementations of common {@link Complex} utilities functions. - */ -public class ComplexUtils { - - /** - * Utility class. - */ - private ComplexUtils() {} - - /** - * Creates a complex number from the given polar representation. - *

- * If either {@code r} or {@code theta} is NaN, or {@code theta} is - * infinite, {@link Complex#NAN} is returned. - *

- * If {@code r} is infinite and {@code theta} is finite, infinite or NaN - * values may be returned in parts of the result, following the rules for - * double arithmetic. - * - * Examples: - *

-     * {@code
-     * polar2Complex(INFINITY, \(\pi\)) = INFINITY + INFINITY i
-     * polar2Complex(INFINITY, 0) = INFINITY + NaN i
-     * polar2Complex(INFINITY, \(-\frac{\pi}{4}\)) = INFINITY - INFINITY i
-     * polar2Complex(INFINITY, \(5\frac{\pi}{4}\)) = -INFINITY - INFINITY i }
-     * 
- * - * @param r the modulus of the complex number to create - * @param theta the argument of the complex number to create - * @return {@code Complex} - */ - public static Complex polar2Complex(double r, double theta) { - if (r < 0) { - throw new NegativeModulusException(r); - } - return Complex.ofCartesian(r * Math.cos(theta), r * Math.sin(theta)); - } - - /** - * Creates {@code Complex[]} array given {@code double[]} arrays of r and - * theta. - * - * @param r {@code double[]} of moduli - * @param theta {@code double[]} of arguments - * @return {@code Complex[]} - */ - public static Complex[] polar2Complex(double[] r, double[] theta) { - final int length = r.length; - final Complex[] c = new Complex[length]; - for (int x = 0; x < length; x++) { - if (r[x] < 0) { - throw new NegativeModulusException(r[x]); - } - c[x] = Complex.ofCartesian(r[x] * Math.cos(theta[x]), r[x] * Math.sin(theta[x])); - } - return c; - } - - /** - * Creates {@code Complex[][]} array given {@code double[][]} arrays of r - * and theta. - * - * @param r {@code double[]} of moduli - * @param theta {@code double[]} of arguments - * @return {@code Complex[][]} - */ - public static Complex[][] polar2Complex(double[][] r, double[][] theta) { - final int length = r.length; - final Complex[][] c = new Complex[length][]; - for (int x = 0; x < length; x++) { - c[x] = polar2Complex(r[x], theta[x]); - } - return c; - } - - /** - * Creates {@code Complex[][][]} array given {@code double[][][]} arrays of - * r and theta. - * - * @param r array of moduli - * @param theta array of arguments - * @return {@code Complex} - */ - public static Complex[][][] polar2Complex(double[][][] r, double[][][] theta) { - final int length = r.length; - final Complex[][][] c = new Complex[length][][]; - for (int x = 0; x < length; x++) { - c[x] = polar2Complex(r[x], theta[x]); - } - return c; - } - - /** - * Returns double from array {@code real[]} at entry {@code index} as a - * {@code Complex}. - * - * @param real array of real numbers - * @param index location in the array - * @return {@code Complex}. - */ - public static Complex extractComplexFromRealArray(double[] real, int index) { - return Complex.ofReal(real[index]); - } - - /** - * Returns float from array {@code real[]} at entry {@code index} as a - * {@code Complex}. - * - * @param real array of real numbers - * @param index location in the array - * @return {@code Complex} array - */ - public static Complex extractComplexFromRealArray(float[] real, int index) { - return Complex.ofReal(real[index]); - } - - /** - * Returns double from array {@code imaginary[]} at entry {@code index} as a - * {@code Complex}. - * - * @param imaginary array of imaginary numbers - * @param index location in the array - * @return {@code Complex} array - */ - public static Complex extractComplexFromImaginaryArray(double[] imaginary, int index) { - return Complex.ofCartesian(0, imaginary[index]); - } - - /** - * Returns float from array {@code imaginary[]} at entry {@code index} as a - * {@code Complex}. - * - * @param imaginary array of imaginary numbers - * @param index location in the array - * @return {@code Complex} array - */ - public static Complex extractComplexFromImaginaryArray(float[] imaginary, int index) { - return Complex.ofCartesian(0, imaginary[index]); - } - - /** - * Returns real component of Complex from array {@code Complex[]} at entry - * {@code index} as a {@code double}. - * - * @param complex array of complex numbers - * @param index location in the array - * @return {@code double}. - */ - public static double extractRealFromComplexArray(Complex[] complex, int index) { - return complex[index].getReal(); - } - - /** - * Returns real component of array {@code Complex[]} at entry {@code index} - * as a {@code float}. - * - * @param complex array of complex numbers - * @param index location in the array - * @return {@code float}. - */ - public static float extractRealFloatFromComplexArray(Complex[] complex, int index) { - return (float) complex[index].getReal(); - } - - /** - * Returns imaginary component of Complex from array {@code Complex[]} at - * entry {@code index} as a {@code double}. - * - * @param complex array of complex numbers - * @param index location in the array - * @return {@code double}. - */ - public static double extractImaginaryFromComplexArray(Complex[] complex, int index) { - return complex[index].getImaginary(); - } - - /** - * Returns imaginary component of array {@code Complex[]} at entry - * {@code index} as a {@code float}. - * - * @param complex array of complex numbers - * @param index location in the array - * @return {@code float}. - */ - public static float extractImaginaryFloatFromComplexArray(Complex[] complex, int index) { - return (float) complex[index].getImaginary(); - } - - /** - * Returns a Complex object from interleaved {@code double[]} array at entry - * {@code index}. - * - * @param d array of interleaved complex numbers alternating real and imaginary values - * @param index location in the array This is the location by complex number, e.g. index number 5 in the array will return {@code Complex.ofCartesian(d[10], d[11])} - * @return {@code Complex}. - */ - public static Complex extractComplexFromInterleavedArray(double[] d, int index) { - return Complex.ofCartesian(d[index * 2], d[index * 2 + 1]); - } - - /** - * Returns a Complex object from interleaved {@code float[]} array at entry - * {@code index}. - * - * @param f float array of interleaved complex numbers alternating real and imaginary values - * @param index location in the array This is the location by complex number, e.g. index number 5 in the {@code float[]} array will return new {@code Complex(d[10], d[11])} - * @return {@code Complex}. - */ - public static Complex extractComplexFromInterleavedArray(float[] f, int index) { - return Complex.ofCartesian(f[index * 2], f[index * 2 + 1]); - } - - /** - * Returns values of Complex object from array {@code Complex[]} at entry - * {@code index} as a size 2 {@code double} of the form {real, imag}. - * - * @param complex array of complex numbers - * @param index location in the array - * @return size 2 array. - */ - public static double[] extractInterleavedFromComplexArray(Complex[] complex, int index) { - return new double[] { complex[index].getReal(), complex[index].getImaginary() }; - } - - /** - * Returns Complex object from array {@code Complex[]} at entry - * {@code index} as a size 2 {@code float} of the form {real, imag}. - * - * @param complex {@code Complex} array - * @param index location in the array - * @return size 2 {@code float[]}. - */ - public static float[] extractInterleavedFloatFromComplexArray(Complex[] complex, int index) { - return new float[] { (float) complex[index].getReal(), (float) complex[index].getImaginary() }; - } - - /** - * Converts a {@code double[]} array to a {@code Complex[]} array. - * - * @param real array of numbers to be converted to their {@code Complex} equivalent - * @return {@code Complex} array - */ - public static Complex[] real2Complex(double[] real) { - int index = 0; - final Complex[] c = new Complex[real.length]; - for (double d : real) { - c[index] = Complex.ofReal(d); - index++; - } - return c; - } - - /** - * Converts a {@code float[]} array to a {@code Complex[]} array. - * - * @param real array of numbers to be converted to their {@code Complex} equivalent - * @return {@code Complex} array - */ - public static Complex[] real2Complex(float[] real) { - int index = 0; - final Complex[] c = new Complex[real.length]; - for (float d : real) { - c[index] = Complex.ofReal(d); - index++; - } - return c; - } - - /** - * Converts a 2D real {@code double[][]} array to a 2D {@code Complex[][]} - * array. - * - * @param d 2D array - * @return 2D {@code Complex} array - */ - public static Complex[][] real2Complex(double[][] d) { - final int w = d.length; - final Complex[][] c = new Complex[w][]; - for (int n = 0; n < w; n++) { - c[n] = ComplexUtils.real2Complex(d[n]); - } - return c; - } - - /** - * Converts a 2D real {@code float[][]} array to a 2D {@code Complex[][]} - * array. - * - * @param d 2D array - * @return 2D {@code Complex} array - */ - public static Complex[][] real2Complex(float[][] d) { - final int w = d.length; - final Complex[][] c = new Complex[w][]; - for (int n = 0; n < w; n++) { - c[n] = ComplexUtils.real2Complex(d[n]); - } - return c; - } - - /** - * Converts a 3D real {@code double[][][]} array to a {@code Complex [][][]} - * array. - * - * @param d 3D complex interleaved array - * @return 3D {@code Complex} array - */ - public static Complex[][][] real2Complex(double[][][] d) { - final int w = d.length; - final Complex[][][] c = new Complex[w][][]; - for (int x = 0; x < w; x++) { - c[x] = ComplexUtils.real2Complex(d[x]); - } - return c; - } - - /** - * Converts a 3D real {@code float[][][]} array to a {@code Complex [][][]} - * array. - * - * @param d 3D complex interleaved array - * @return 3D {@code Complex} array - */ - public static Complex[][][] real2Complex(float[][][] d) { - final int w = d.length; - final Complex[][][] c = new Complex[w][][]; - for (int x = 0; x < w; x++) { - c[x] = ComplexUtils.real2Complex(d[x]); - } - return c; - } - - /** - * Converts a 4D real {@code double[][][][]} array to a {@code Complex [][][][]} - * array. - * - * @param d 4D complex interleaved array - * @return 4D {@code Complex} array - */ - public static Complex[][][][] real2Complex(double[][][][] d) { - final int w = d.length; - final Complex[][][][] c = new Complex[w][][][]; - for (int x = 0; x < w; x++) { - c[x] = ComplexUtils.real2Complex(d[x]); - } - return c; - } - - /** - * Converts real component of {@code Complex[]} array to a {@code double[]} - * array. - * - * @param c {@code Complex} array - * @return array of the real component - */ - public static double[] complex2Real(Complex[] c) { - int index = 0; - final double[] d = new double[c.length]; - for (Complex cc : c) { - d[index] = cc.getReal(); - index++; - } - return d; - } - - /** - * Converts real component of {@code Complex[]} array to a {@code float[]} - * array. - * - * @param c {@code Complex} array - * @return {@code float[]} array of the real component - */ - public static float[] complex2RealFloat(Complex[] c) { - int index = 0; - final float[] f = new float[c.length]; - for (Complex cc : c) { - f[index] = (float) cc.getReal(); - index++; - } - return f; - } - - /** - * Converts real component of a 2D {@code Complex[][]} array to a 2D - * {@code double[][]} array. - * - * @param c 2D {@code Complex} array - * @return {@code double[][]} of real component - */ - public static double[][] complex2Real(Complex[][] c) { - final int length = c.length; - double[][] d = new double[length][]; - for (int n = 0; n < length; n++) { - d[n] = complex2Real(c[n]); - } - return d; - } - - /** - * Converts real component of a 2D {@code Complex[][]} array to a 2D - * {@code float[][]} array. - * - * @param c 2D {@code Complex} array - * @return {@code float[][]} of real component - */ - public static float[][] complex2RealFloat(Complex[][] c) { - final int length = c.length; - float[][] f = new float[length][]; - for (int n = 0; n < length; n++) { - f[n] = complex2RealFloat(c[n]); - } - return f; - } - - /** - * Converts real component of a 3D {@code Complex[][][]} array to a 3D - * {@code double[][][]} array. - * - * @param c 3D complex interleaved array - * @return array of real component - */ - public static double[][][] complex2Real(Complex[][][] c) { - final int length = c.length; - double[][][] d = new double[length][][]; - for (int n = 0; n < length; n++) { - d[n] = complex2Real(c[n]); - } - return d; - } - - /** - * Converts real component of a 3D {@code Complex[][][]} array to a 3D - * {@code float[][][]} array. - * - * @param c 3D {@code Complex} array - * @return {@code float[][][]} of real component - */ - public static float[][][] complex2RealFloat(Complex[][][] c) { - final int length = c.length; - float[][][] f = new float[length][][]; - for (int n = 0; n < length; n++) { - f[n] = complex2RealFloat(c[n]); - } - return f; - } - - /** - * Converts real component of a 4D {@code Complex[][][][]} array to a 4D - * {@code double[][][][]} array. - * - * @param c 4D complex interleaved array - * @return array of real component - */ - public static double[][][][] complex2Real(Complex[][][][] c) { - final int length = c.length; - double[][][][] d = new double[length][][][]; - for (int n = 0; n < length; n++) { - d[n] = complex2Real(c[n]); - } - return d; - } - - /** - * Converts real component of a 4D {@code Complex[][][][]} array to a 4D - * {@code float[][][][]} array. - * - * @param c 4D {@code Complex} array - * @return {@code float[][][][]} of real component - */ - public static float[][][][] complex2RealFloat(Complex[][][][] c) { - final int length = c.length; - float[][][][] f = new float[length][][][]; - for (int n = 0; n < length; n++) { - f[n] = complex2RealFloat(c[n]); - } - return f; - } - - /** - * Converts a {@code double[]} array to an imaginary {@code Complex[]} - * array. - * - * @param imaginary array of numbers to be converted to their {@code Complex} equivalent - * @return {@code Complex} array - */ - public static Complex[] imaginary2Complex(double[] imaginary) { - int index = 0; - final Complex[] c = new Complex[imaginary.length]; - for (double d : imaginary) { - c[index] = Complex.ofCartesian(0, d); - index++; - } - return c; - } - - /** - * Converts a {@code float[]} array to an imaginary {@code Complex[]} array. - * - * @param imaginary array of numbers to be converted to their {@code Complex} equivalent - * @return {@code Complex} array - */ - public static Complex[] imaginary2Complex(float[] imaginary) { - int index = 0; - final Complex[] c = new Complex[imaginary.length]; - for (float d : imaginary) { - c[index] = Complex.ofCartesian(0, d); - index++; - } - return c; - } - - /** - * Converts a 2D imaginary array {@code double[][]} to a 2D - * {@code Complex[][]} array. - * - * @param i 2D array - * @return 2D {@code Complex} array - */ - public static Complex[][] imaginary2Complex(double[][] i) { - int w = i.length; - Complex[][] c = new Complex[w][]; - for (int n = 0; n < w; n++) { - c[n] = ComplexUtils.imaginary2Complex(i[n]); - } - return c; - } - - /** - * Converts a 3D imaginary array {@code double[][][]} to a {@code Complex[]} - * array. - * - * @param i 3D complex imaginary array - * @return 3D {@code Complex} array - */ - public static Complex[][][] imaginary2Complex(double[][][] i) { - int w = i.length; - Complex[][][] c = new Complex[w][][]; - for (int n = 0; n < w; n++) { - c[n] = ComplexUtils.imaginary2Complex(i[n]); - } - return c; - } - - /** - * Converts a 4D imaginary array {@code double[][][][]} to a 4D {@code Complex[][][][]} - * array. - * - * @param i 4D complex imaginary array - * @return 4D {@code Complex} array - */ - public static Complex[][][][] imaginary2Complex(double[][][][] i) { - int w = i.length; - Complex[][][][] c = new Complex[w][][][]; - for (int n = 0; n < w; n++) { - c[n] = ComplexUtils.imaginary2Complex(i[n]); - } - return c; - } - - /** - * Converts imaginary part of a {@code Complex[]} array to a - * {@code double[]} array. - * - * @param c {@code Complex} array. - * @return array of the imaginary component - */ - public static double[] complex2Imaginary(Complex[] c) { - int index = 0; - final double[] i = new double[c.length]; - for (Complex cc : c) { - i[index] = cc.getImaginary(); - index++; - } - return i; - } - - /** - * Converts imaginary component of a {@code Complex[]} array to a - * {@code float[]} array. - * - * @param c {@code Complex} array. - * @return {@code float[]} array of the imaginary component - */ - public static float[] complex2ImaginaryFloat(Complex[] c) { - int index = 0; - final float[] f = new float[c.length]; - for (Complex cc : c) { - f[index] = (float) cc.getImaginary(); - index++; - } - return f; - } - - /** - * Converts imaginary component of a 2D {@code Complex[][]} array to a 2D - * {@code double[][]} array. - * - * @param c 2D {@code Complex} array - * @return {@code double[][]} of imaginary component - */ - public static double[][] complex2Imaginary(Complex[][] c) { - final int length = c.length; - double[][] i = new double[length][]; - for (int n = 0; n < length; n++) { - i[n] = complex2Imaginary(c[n]); - } - return i; - } - - /** - * Converts imaginary component of a 2D {@code Complex[][]} array to a 2D - * {@code float[][]} array. - * - * @param c 2D {@code Complex} array - * @return {@code float[][]} of imaginary component - */ - public static float[][] complex2ImaginaryFloat(Complex[][] c) { - final int length = c.length; - float[][] f = new float[length][]; - for (int n = 0; n < length; n++) { - f[n] = complex2ImaginaryFloat(c[n]); - } - return f; - } - - /** - * Converts imaginary component of a 3D {@code Complex[][][]} array to a 3D - * {@code double[][][]} array. - * - * @param c 3D complex interleaved array - * @return 3D {@code Complex} array - */ - public static double[][][] complex2Imaginary(Complex[][][] c) { - final int length = c.length; - double[][][] i = new double[length][][]; - for (int n = 0; n < length; n++) { - i[n] = complex2Imaginary(c[n]); - } - return i; - } - - /** - * Converts imaginary component of a 3D {@code Complex[][][]} array to a 3D - * {@code float[][][]} array. - * - * @param c 3D {@code Complex} array - * @return {@code float[][][]} of imaginary component - */ - public static float[][][] complex2ImaginaryFloat(Complex[][][] c) { - final int length = c.length; - float[][][] f = new float[length][][]; - for (int n = 0; n < length; n++) { - f[n] = complex2ImaginaryFloat(c[n]); - } - return f; - } - - /** - * Converts imaginary component of a 4D {@code Complex[][][][]} array to a 4D - * {@code double[][][][]} array. - * - * @param c 4D complex interleaved array - * @return 4D {@code Complex} array - */ - public static double[][][][] complex2Imaginary(Complex[][][][] c) { - final int length = c.length; - double[][][][] i = new double[length][][][]; - for (int n = 0; n < length; n++) { - i[n] = complex2Imaginary(c[n]); - } - return i; - } - - /** - * Converts imaginary component of a 4D {@code Complex[][][][]} array to a 4D - * {@code float[][][][]} array. - * - * @param c 4D {@code Complex} array - * @return {@code float[][][][]} of imaginary component - */ - public static float[][][][] complex2ImaginaryFloat(Complex[][][][] c) { - final int length = c.length; - float[][][][] f = new float[length][][][]; - for (int n = 0; n < length; n++) { - f[n] = complex2ImaginaryFloat(c[n]); - } - return f; - } - - // INTERLEAVED METHODS - - /** - * Converts a complex interleaved {@code double[]} array to a - * {@code Complex[]} array - * - * @param interleaved array of numbers to be converted to their {@code Complex} equivalent - * @return {@code Complex} array - */ - public static Complex[] interleaved2Complex(double[] interleaved) { - final int length = interleaved.length / 2; - final Complex[] c = new Complex[length]; - for (int n = 0; n < length; n++) { - c[n] = Complex.ofCartesian(interleaved[n * 2], interleaved[n * 2 + 1]); - } - return c; - } - - /** - * Converts a complex interleaved {@code float[]} array to a - * {@code Complex[]} array - * - * @param interleaved float[] array of numbers to be converted to their {@code Complex} equivalent - * @return {@code Complex} array - */ - public static Complex[] interleaved2Complex(float[] interleaved) { - final int length = interleaved.length / 2; - final Complex[] c = new Complex[length]; - for (int n = 0; n < length; n++) { - c[n] = Complex.ofCartesian(interleaved[n * 2], interleaved[n * 2 + 1]); - } - return c; - } - - /** - * Converts a {@code Complex[]} array to an interleaved complex - * {@code double[]} array - * - * @param c Complex array - * @return complex interleaved array alternating real and - * imaginary values - */ - public static double[] complex2Interleaved(Complex[] c) { - int index = 0; - final double[] i = new double[c.length * 2]; - for (Complex cc : c) { - int real = index * 2; - int imag = index * 2 + 1; - i[real] = cc.getReal(); - i[imag] = cc.getImaginary(); - index++; - } - return i; - } - - /** - * Converts a {@code Complex[]} array to an interleaved complex - * {@code float[]} array - * - * @param c Complex array - * @return complex interleaved {@code float[]} alternating real and - * imaginary values - */ - public static float[] complex2InterleavedFloat(Complex[] c) { - int index = 0; - final float[] f = new float[c.length * 2]; - for (Complex cc : c) { - int real = index * 2; - int imag = index * 2 + 1; - f[real] = (float) cc.getReal(); - f[imag] = (float) cc.getImaginary(); - index++; - } - return f; - } - - /** - * Converts a 2D {@code Complex[][]} array to an interleaved complex - * {@code double[][]} array. - * - * @param c 2D Complex array - * @param interleavedDim Depth level of the array to interleave - * @return complex interleaved array alternating real and - * imaginary values - */ - public static double[][] complex2Interleaved(Complex[][] c, int interleavedDim) { - if (interleavedDim > 1 || interleavedDim < 0) { - throw new IndexOutOfRangeException(interleavedDim); - } - final int w = c.length; - final int h = c[0].length; - double[][] i; - if (interleavedDim == 0) { - i = new double[2 * w][h]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - i[x * 2][y] = c[x][y].getReal(); - i[x * 2 + 1][y] = c[x][y].getImaginary(); - } - } - } else { - i = new double[w][2 * h]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - i[x][y * 2] = c[x][y].getReal(); - i[x][y * 2 + 1] = c[x][y].getImaginary(); - } - } - } - return i; - } - - /** - * Converts a 2D {@code Complex[][]} array to an interleaved complex - * {@code double[][]} array. The second d level of the array is assumed - * to be interleaved. - * - * @param c 2D Complex array - * @return complex interleaved array alternating real and - * imaginary values - */ - public static double[][] complex2Interleaved(Complex[][] c) { - return complex2Interleaved(c, 1); - } - - /** - * Converts a 3D {@code Complex[][][]} array to an interleaved complex - * {@code double[][][]} array. - * - * @param c 3D Complex array - * @param interleavedDim Depth level of the array to interleave - * @return complex interleaved array alternating real and - * imaginary values - */ - public static double[][][] complex2Interleaved(Complex[][][] c, int interleavedDim) { - if (interleavedDim > 2 || interleavedDim < 0) { - throw new IndexOutOfRangeException(interleavedDim); - } - int w = c.length; - int h = c[0].length; - int d = c[0][0].length; - double[][][] i; - if (interleavedDim == 0) { - i = new double[2 * w][h][d]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - for (int z = 0; z < d; z++) { - i[x * 2][y][z] = c[x][y][z].getReal(); - i[x * 2 + 1][y][z] = c[x][y][z].getImaginary(); - } - } - } - } else if (interleavedDim == 1) { - i = new double[w][2 * h][d]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - for (int z = 0; z < d; z++) { - i[x][y * 2][z] = c[x][y][z].getReal(); - i[x][y * 2 + 1][z] = c[x][y][z].getImaginary(); - } - } - } - } else { - i = new double[w][h][2 * d]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - for (int z = 0; z < d; z++) { - i[x][y][z * 2] = c[x][y][z].getReal(); - i[x][y][z * 2 + 1] = c[x][y][z].getImaginary(); - } - } - } - } - return i; - } - - /** - * Converts a 4D {@code Complex[][][][]} array to an interleaved complex - * {@code double[][][][]} array. - * - * @param c 4D Complex array - * @param interleavedDim Depth level of the array to interleave - * @return complex interleaved array alternating real and - * imaginary values - */ - public static double[][][][] complex2Interleaved(Complex[][][][] c, int interleavedDim) { - if (interleavedDim > 3 || interleavedDim < 0) { - throw new IndexOutOfRangeException(interleavedDim); - } - int w = c.length; - int h = c[0].length; - int d = c[0][0].length; - int v = c[0][0][0].length; - double[][][][] i; - if (interleavedDim == 0) { - i = new double[2 * w][h][d][v]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - for (int z = 0; z < d; z++) { - for (int t = 0; t < v; t++) { - i[x * 2][y][z][t] = c[x][y][z][t].getReal(); - i[x * 2 + 1][y][z][t] = c[x][y][z][t].getImaginary(); - } - } - } - } - } else if (interleavedDim == 1) { - i = new double[w][2 * h][d][v]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - for (int z = 0; z < d; z++) { - for (int t = 0; t < v; t++) { - i[x][y * 2][z][t] = c[x][y][z][t].getReal(); - i[x][y * 2 + 1][z][t] = c[x][y][z][t].getImaginary(); - } - } - } - } - } else if (interleavedDim == 2) { - i = new double[w][h][2 * d][v]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - for (int z = 0; z < d; z++) { - for (int t = 0; t < v; t++) { - i[x][y][z * 2][t] = c[x][y][z][t].getReal(); - i[x][y][z * 2 + 1][t] = c[x][y][z][t].getImaginary(); - } - } - } - } - } else { - i = new double[w][h][d][2 * v]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - for (int z = 0; z < d; z++) { - for (int t = 0; t < v; t++) { - i[x][y][z][t * 2] = c[x][y][z][t].getReal(); - i[x][y][z][t * 2 + 1] = c[x][y][z][t].getImaginary(); - } - } - } - } - } - return i; - } - - /** - * Converts a 3D {@code Complex[][][]} array to an interleaved complex - * {@code double[][][]} array. The third level of the array is - * interleaved. - * - * @param c 3D Complex array - * @return complex interleaved array alternating real and - * imaginary values - */ - public static double[][][] complex2Interleaved(Complex[][][] c) { - return complex2Interleaved(c, 2); - } - - /** - * Converts a 4D {@code Complex[][][][]} array to an interleaved complex - * {@code double[][][][]} array. The fourth level of the array is - * interleaved. - * - * @param c 4D Complex array - * @return complex interleaved array alternating real and - * imaginary values - */ - public static double[][][][] complex2Interleaved(Complex[][][][] c) { - return complex2Interleaved(c, 3); - } - - /** - * Converts a 2D {@code Complex[][]} array to an interleaved complex - * {@code float[][]} array. - * - * @param c 2D Complex array - * @param interleavedDim Depth level of the array to interleave - * @return complex interleaved {@code float[][]} alternating real and - * imaginary values - */ - public static float[][] complex2InterleavedFloat(Complex[][] c, int interleavedDim) { - if (interleavedDim > 1 || interleavedDim < 0) { - throw new IndexOutOfRangeException(interleavedDim); - } - final int w = c.length; - final int h = c[0].length; - float[][] i; - if (interleavedDim == 0) { - i = new float[2 * w][h]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - i[x * 2][y] = (float) c[x][y].getReal(); - i[x * 2 + 1][y] = (float) c[x][y].getImaginary(); - } - } - } else { - i = new float[w][2 * h]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - i[x][y * 2] = (float) c[x][y].getReal(); - i[x][y * 2 + 1] = (float) c[x][y].getImaginary(); - } - } - } - return i; - } - - /** - * Converts a 2D {@code Complex[][]} array to an interleaved complex - * {@code float[][]} array. The second d level of the array is assumed - * to be interleaved. - * - * @param c 2D Complex array - * - * @return complex interleaved {@code float[][]} alternating real and - * imaginary values - */ - public static float[][] complex2InterleavedFloat(Complex[][] c) { - return complex2InterleavedFloat(c, 1); - } - - /** - * Converts a 3D {@code Complex[][][]} array to an interleaved complex - * {@code float[][][]} array. - * - * @param c 3D Complex array - * @param interleavedDim Depth level of the array to interleave - * @return complex interleaved {@code float[][][]} alternating real and - * imaginary values - */ - public static float[][][] complex2InterleavedFloat(Complex[][][] c, int interleavedDim) { - if (interleavedDim > 2 || interleavedDim < 0) { - throw new IndexOutOfRangeException(interleavedDim); - } - final int w = c.length; - final int h = c[0].length; - final int d = c[0][0].length; - float[][][] i; - if (interleavedDim == 0) { - i = new float[2 * w][h][d]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - for (int z = 0; z < d; z++) { - i[x * 2][y][z] = (float) c[x][y][z].getReal(); - i[x * 2 + 1][y][z] = (float) c[x][y][z].getImaginary(); - } - } - } - } else if (interleavedDim == 1) { - i = new float[w][2 * h][d]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - for (int z = 0; z < d; z++) { - i[x][y * 2][z] = (float) c[x][y][z].getReal(); - i[x][y * 2 + 1][z] = (float) c[x][y][z].getImaginary(); - } - } - } - } else { - i = new float[w][h][2 * d]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - for (int z = 0; z < d; z++) { - i[x][y][z * 2] = (float) c[x][y][z].getReal(); - i[x][y][z * 2 + 1] = (float) c[x][y][z].getImaginary(); - } - } - } - } - return i; - } - - /** - * Converts a 3D {@code Complex[][][]} array to an interleaved complex - * {@code float[][][]} array. The third d level of the array is - * interleaved. - * - * @param c 2D Complex array - * - * @return complex interleaved {@code float[][][]} alternating real and - * imaginary values - */ - public static float[][][] complex2InterleavedFloat(Complex[][][] c) { - return complex2InterleavedFloat(c, 2); - } - - /** - * Converts a 2D interleaved complex {@code double[][]} array to a - * {@code Complex[][]} array. - * - * @param i 2D complex interleaved array - * @param interleavedDim Depth level of the array to interleave - * @return 2D {@code Complex} array - */ - public static Complex[][] interleaved2Complex(double[][] i, int interleavedDim) { - if (interleavedDim > 1 || interleavedDim < 0) { - throw new IndexOutOfRangeException(interleavedDim); - } - final int w = i.length; - final int h = i[0].length; - Complex[][] c; - if (interleavedDim == 0) { - c = new Complex[w / 2][h]; - for (int x = 0; x < w / 2; x++) { - for (int y = 0; y < h; y++) { - c[x][y] = Complex.ofCartesian(i[x * 2][y], i[x * 2 + 1][y]); - } - } - } else { - c = new Complex[w][h / 2]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h / 2; y++) { - c[x][y] = Complex.ofCartesian(i[x][y * 2], i[x][y * 2 + 1]); - } - } - } - return c; - } - - /** - * Converts a 2D interleaved complex {@code double[][]} array to a - * {@code Complex[][]} array. The second d level of the array is assumed - * to be interleaved. - * - * @param d 2D complex interleaved array - * @return 2D {@code Complex} array - */ - public static Complex[][] interleaved2Complex(double[][] d) { - return interleaved2Complex(d, 1); - } - - /** - * Converts a 3D interleaved complex {@code double[][][]} array to a - * {@code Complex[][][]} array. - * - * @param i 3D complex interleaved array - * @param interleavedDim Depth level of the array to interleave - * @return 3D {@code Complex} array - */ - public static Complex[][][] interleaved2Complex(double[][][] i, int interleavedDim) { - if (interleavedDim > 2 || interleavedDim < 0) { - throw new IndexOutOfRangeException(interleavedDim); - } - final int w = i.length; - final int h = i[0].length; - final int d = i[0][0].length; - Complex[][][] c; - if (interleavedDim == 0) { - c = new Complex[w / 2][h][d]; - for (int x = 0; x < w / 2; x++) { - for (int y = 0; y < h; y++) { - for (int z = 0; z < d; z++) { - c[x][y][z] = Complex.ofCartesian(i[x * 2][y][z], i[x * 2 + 1][y][z]); - } - } - } - } else if (interleavedDim == 1) { - c = new Complex[w][h / 2][d]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h / 2; y++) { - for (int z = 0; z < d; z++) { - c[x][y][z] = Complex.ofCartesian(i[x][y * 2][z], i[x][y * 2 + 1][z]); - } - } - } - } else { - c = new Complex[w][h][d / 2]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - for (int z = 0; z < d / 2; z++) { - c[x][y][z] = Complex.ofCartesian(i[x][y][z * 2], i[x][y][z * 2 + 1]); - } - } - } - } - return c; - } - - /** - * Converts a 4D interleaved complex {@code double[][][][]} array to a - * {@code Complex[][][][]} array. - * - * @param i 4D complex interleaved array - * @param interleavedDim Depth level of the array to interleave - * @return 4D {@code Complex} array - */ - public static Complex[][][][] interleaved2Complex(double[][][][] i, int interleavedDim) { - if (interleavedDim > 3 || interleavedDim < 0) { - throw new IndexOutOfRangeException(interleavedDim); - } - final int w = i.length; - final int h = i[0].length; - final int d = i[0][0].length; - final int v = i[0][0][0].length; - Complex[][][][] c; - if (interleavedDim == 0) { - c = new Complex[w / 2][h][d][v]; - for (int x = 0; x < w / 2; x++) { - for (int y = 0; y < h; y++) { - for (int z = 0; z < d; z++) { - for (int t = 0; t < v; t++) { - c[x][y][z][t] = Complex.ofCartesian(i[x * 2][y][z][t], i[x * 2 + 1][y][z][t]); - } - } - } - } - } else if (interleavedDim == 1) { - c = new Complex[w][h / 2][d][v]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h / 2; y++) { - for (int z = 0; z < d; z++) { - for (int t = 0; t < v; t++) { - c[x][y][z][t] = Complex.ofCartesian(i[x][y * 2][z][t], i[x][y * 2 + 1][z][t]); - } - } - } - } - } else if (interleavedDim == 2) { - c = new Complex[w][h][d / 2][v]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - for (int z = 0; z < d / 2; z++) { - for (int t = 0; t < v; t++) { - c[x][y][z][t] = Complex.ofCartesian(i[x][y][z * 2][t], i[x][y][z * 2 + 1][t]); - } - } - } - } - } else { - c = new Complex[w][h][d][v / 2]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - for (int z = 0; z < d; z++) { - for (int t = 0; t < v / 2; t++) { - c[x][y][z][t] = Complex.ofCartesian(i[x][y][z][t * 2], i[x][y][z][t * 2 + 1]); - } - } - } - } - } - return c; - } - - /** - * Converts a 3D interleaved complex {@code double[][][]} array to a - * {@code Complex[][][]} array. The third d level is assumed to be - * interleaved. - * - * @param d 3D complex interleaved array - * @return 3D {@code Complex} array - */ - public static Complex[][][] interleaved2Complex(double[][][] d) { - return interleaved2Complex(d, 2); - } - - /** - * Converts a 2D interleaved complex {@code float[][]} array to a - * {@code Complex[][]} array. - * - * @param i 2D complex interleaved float array - * @param interleavedDim Depth level of the array to interleave - * @return 2D {@code Complex} array - */ - public static Complex[][] interleaved2Complex(float[][] i, int interleavedDim) { - if (interleavedDim > 1 || interleavedDim < 0) { - throw new IndexOutOfRangeException(interleavedDim); - } - final int w = i.length; - final int h = i[0].length; - Complex[][] c; - if (interleavedDim == 0) { - c = new Complex[w / 2][h]; - for (int x = 0; x < w / 2; x++) { - for (int y = 0; y < h; y++) { - c[x][y] = Complex.ofCartesian(i[x * 2][y], i[x * 2 + 1][y]); - } - } - } else { - c = new Complex[w][h / 2]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h / 2; y++) { - c[x][y] = Complex.ofCartesian(i[x][y * 2], i[x][y * 2 + 1]); - } - } - } - return c; - } - - /** - * Converts a 2D interleaved complex {@code float[][]} array to a - * {@code Complex[][]} array. The second d level of the array is assumed - * to be interleaved. - * - * @param d 2D complex interleaved float array - * @return 2D {@code Complex} array - */ - public static Complex[][] interleaved2Complex(float[][] d) { - return interleaved2Complex(d, 1); - } - - /** - * Converts a 3D interleaved complex {@code float[][][]} array to a - * {@code Complex[][][]} array. - * - * @param i 3D complex interleaved float array - * @param interleavedDim Depth level of the array to interleave - * @return 3D {@code Complex} array - */ - public static Complex[][][] interleaved2Complex(float[][][] i, int interleavedDim) { - if (interleavedDim > 2 || interleavedDim < 0) { - throw new IndexOutOfRangeException(interleavedDim); - } - final int w = i.length; - final int h = i[0].length; - final int d = i[0][0].length; - Complex[][][] c; - if (interleavedDim == 0) { - c = new Complex[w / 2][h][d]; - for (int x = 0; x < w/2; x ++) { - for (int y = 0; y < h; y++) { - for (int z = 0; z < d; z++) { - c[x][y][z] = Complex.ofCartesian(i[x * 2][y][z], i[x * 2 + 1][y][z]); - } - } - } - } else if (interleavedDim == 1) { - c = new Complex[w][h / 2][d]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h/2; y ++) { - for (int z = 0; z < d; z++) { - c[x][y][z] = Complex.ofCartesian(i[x][y * 2][z], i[x][y * 2 + 1][z]); - } - } - } - } else { - c = new Complex[w][h][d / 2]; - for (int x = 0; x < w; x++) { - for (int y = 0; y < h; y++) { - for (int z = 0; z < d/2; z++) { - c[x][y][z] = Complex.ofCartesian(i[x][y][z * 2], i[x][y][z * 2 + 1]); - } - } - } - } - return c; - } - - /** - * Converts a 3D interleaved complex {@code float[][][]} array to a - * {@code Complex[]} array. The third level of the array is assumed to - * be interleaved. - * - * @param d 3D complex interleaved float array - * @return 3D {@code Complex} array - */ - public static Complex[][][] interleaved2Complex(float[][][] d) { - return interleaved2Complex(d, 2); - } - - // SPLIT METHODS - - /** - * Converts a split complex array {@code double[] r, double[] i} to a - * {@code Complex[]} array. - * - * @param real real component - * @param imag imaginary component - * @return {@code Complex} array - */ - public static Complex[] split2Complex(double[] real, double[] imag) { - final int length = real.length; - final Complex[] c = new Complex[length]; - for (int n = 0; n < length; n++) { - c[n] = Complex.ofCartesian(real[n], imag[n]); - } - return c; - } - - /** - * Converts a 2D split complex array {@code double[][] r, double[][] i} to a - * 2D {@code Complex[][]} array. - * - * @param real real component - * @param imag imaginary component - * @return 2D {@code Complex} array - */ - public static Complex[][] split2Complex(double[][] real, double[][] imag) { - final int length = real.length; - Complex[][] c = new Complex[length][]; - for (int x = 0; x < length; x++) { - c[x] = split2Complex(real[x], imag[x]); - } - return c; - } - - /** - * Converts a 3D split complex array {@code double[][][] r, double[][][] i} - * to a 3D {@code Complex[][][]} array. - * - * @param real real component - * @param imag imaginary component - * @return 3D {@code Complex} array - */ - public static Complex[][][] split2Complex(double[][][] real, double[][][] imag) { - final int length = real.length; - Complex[][][] c = new Complex[length][][]; - for (int x = 0; x < length; x++) { - c[x] = split2Complex(real[x], imag[x]); - } - return c; - } - - /** - * Converts a 4D split complex array {@code double[][][][] r, double[][][][] i} - * to a 4D {@code Complex[][][][]} array. - * - * @param real real component - * @param imag imaginary component - * @return 4D {@code Complex} array - */ - public static Complex[][][][] split2Complex(double[][][][] real, double[][][][] imag) { - final int length = real.length; - Complex[][][][] c = new Complex[length][][][]; - for (int x = 0; x < length; x++) { - c[x] = split2Complex(real[x], imag[x]); - } - return c; - } - - /** - * Converts a split complex array {@code float[] r, float[] i} to a - * {@code Complex[]} array. - * - * @param real real component - * @param imag imaginary component - * @return {@code Complex} array - */ - public static Complex[] split2Complex(float[] real, float[] imag) { - final int length = real.length; - final Complex[] c = new Complex[length]; - for (int n = 0; n < length; n++) { - c[n] = Complex.ofCartesian(real[n], imag[n]); - } - return c; - } - - /** - * Converts a 2D split complex array {@code float[][] r, float[][] i} to a - * 2D {@code Complex[][]} array. - * - * @param real real component - * @param imag imaginary component - * @return 2D {@code Complex} array - */ - public static Complex[][] split2Complex(float[][] real, float[][] imag) { - final int length = real.length; - Complex[][] c = new Complex[length][]; - for (int x = 0; x < length; x++) { - c[x] = split2Complex(real[x], imag[x]); - } - return c; - } - - /** - * Converts a 3D split complex array {@code float[][][] r, float[][][] i} to - * a 3D {@code Complex[][][]} array. - * - * @param real real component - * @param imag imaginary component - * @return 3D {@code Complex} array - */ - public static Complex[][][] split2Complex(float[][][] real, float[][][] imag) { - final int length = real.length; - Complex[][][] c = new Complex[length][][]; - for (int x = 0; x < length; x++) { - c[x] = split2Complex(real[x], imag[x]); - } - return c; - } - - // MISC - - /** - * Initializes a {@code Complex[]} array to zero, to avoid - * NullPointerExceptions. - * - * @param c Complex array - * @return c - */ - public static Complex[] initialize(Complex[] c) { - final int length = c.length; - for (int x = 0; x < length; x++) { - c[x] = Complex.ZERO; - } - return c; - } - - /** - * Initializes a {@code Complex[][]} array to zero, to avoid - * NullPointerExceptions. - * - * @param c {@code Complex} array - * @return c - */ - public static Complex[][] initialize(Complex[][] c) { - final int length = c.length; - for (int x = 0; x < length; x++) { - c[x] = initialize(c[x]); - } - return c; - } - - /** - * Initializes a {@code Complex[][][]} array to zero, to avoid - * NullPointerExceptions. - * - * @param c {@code Complex} array - * @return c - */ - public static Complex[][][] initialize(Complex[][][] c) { - final int length = c.length; - for (int x = 0; x < length; x++) { - c[x] = initialize(c[x]); - } - return c; - } - - /** - * Returns {@code double[]} containing absolute values (magnitudes) of a - * {@code Complex[]} array. - * - * @param c {@code Complex} array - * @return {@code double[]} - */ - public static double[] abs(Complex[] c) { - final int length = c.length; - final double[] i = new double[length]; - for (int x = 0; x < length; x++) { - i[x] = c[x].abs(); - } - return i; - } - - /** - * Returns {@code double[]} containing arguments (phase angles) of a - * {@code Complex[]} array. - * - * @param c {@code Complex} array - * @return {@code double[]} array - */ - public static double[] arg(Complex[] c) { - final int length = c.length; - final double[] i = new double[length]; - for (int x = 0; x < length; x++) { - i[x] = c[x].getArgument(); - } - return i; - } - - /** - * Exception to be throw when a negative value is passed as the modulus. - */ - private static class NegativeModulusException extends IllegalArgumentException { - /** Serializable version identifier. */ - private static final long serialVersionUID = 20181205L; - - /** - * @param r Wrong modulus. - */ - NegativeModulusException(double r) { - super("Modulus is negative: " + r); - } - } - - /** - * Exception to be throw when an out-of-range index value is passed. - */ - private static class IndexOutOfRangeException extends IllegalArgumentException { - /** Serializable version identifier. */ - private static final long serialVersionUID = 20181205L; - - /** - * @param i Wrong index. - */ - IndexOutOfRangeException(int i) { - super("Out of range: " + i); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/complex/streams/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/complex/streams/package-info.java deleted file mode 100644 index 0b7c1cd98..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/complex/streams/package-info.java +++ /dev/null @@ -1,20 +0,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. - */ -/** - * Complex numbers collections. - */ -package org.apache.commons.numbers.complex.streams; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/Addition.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/Addition.java deleted file mode 100644 index 1e3197994..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/Addition.java +++ /dev/null @@ -1,47 +0,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. - */ -package org.apache.commons.numbers.core; - -/** - * Addition. - * - * @param Type of elements. - */ -public interface Addition { - /** - * Binary addition. - * - * @param a Element. - * @return {@code this + a}. - */ - T add(T a); - - /** - * Identity element. - * - * @return the field element such that for all {@code a}, - * {@code zero().add(a).equals(a)} is {@code true}. - */ - T zero(); - - /** - * Additive inverse. - * - * @return {@code -this}. - */ - T negate(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/ArithmeticUtils.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/ArithmeticUtils.java deleted file mode 100644 index 36a84f520..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/ArithmeticUtils.java +++ /dev/null @@ -1,785 +0,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. - */ -package org.apache.commons.numbers.core; - -import java.math.BigInteger; -import java.text.MessageFormat; - -/** - * Some useful, arithmetics related, additions to the built-in functions in - * {@link Math}. - * - */ -public final class ArithmeticUtils { - - /** Private constructor. */ - private ArithmeticUtils() { - super(); - } - - /** - * Add two integers, checking for overflow. - * - * @param x an addend - * @param y an addend - * @return the sum {@code x+y} - * @throws ArithmeticException if the result can not be represented - * as an {@code int}. - */ - public static int addAndCheck(int x, int y) { - long s = (long)x + (long)y; - if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) { - throw new NumbersArithmeticException("overflow in addition: {0} + {1}", x, y); - } - return (int)s; - } - - /** - * Add two long integers, checking for overflow. - * - * @param a an addend - * @param b an addend - * @return the sum {@code a+b} - * @throws ArithmeticException if the result can not be represented as an long - */ - public static long addAndCheck(long a, long b) { - return addAndCheck(a, b, "overflow in addition: {0} + {1}"); - } - - /** - * Computes the greatest common divisor of the absolute value of two - * numbers, using a modified version of the "binary gcd" method. - * See Knuth 4.5.2 algorithm B. - * The algorithm is due to Josef Stein (1961). - *
- * Special cases: - *
    - *
  • The invocations - * {@code gcd(Integer.MIN_VALUE, Integer.MIN_VALUE)}, - * {@code gcd(Integer.MIN_VALUE, 0)} and - * {@code gcd(0, Integer.MIN_VALUE)} throw an - * {@code ArithmeticException}, because the result would be 2^31, which - * is too large for an int value.
  • - *
  • The result of {@code gcd(x, x)}, {@code gcd(0, x)} and - * {@code gcd(x, 0)} is the absolute value of {@code x}, except - * for the special cases above.
  • - *
  • The invocation {@code gcd(0, 0)} is the only one which returns - * {@code 0}.
  • - *
- * - * @param p Number. - * @param q Number. - * @return the greatest common divisor (never negative). - * @throws ArithmeticException if the result cannot be represented as - * a non-negative {@code int} value. - */ - public static int gcd(int p, int q) { - int a = p; - int b = q; - if (a == 0 || - b == 0) { - if (a == Integer.MIN_VALUE || - b == Integer.MIN_VALUE) { - throw new NumbersArithmeticException("overflow: gcd({0}, {1}) is 2^31", - p, q); - } - return Math.abs(a + b); - } - - long al = a; - long bl = b; - boolean useLong = false; - if (a < 0) { - if(Integer.MIN_VALUE == a) { - useLong = true; - } else { - a = -a; - } - al = -al; - } - if (b < 0) { - if (Integer.MIN_VALUE == b) { - useLong = true; - } else { - b = -b; - } - bl = -bl; - } - if (useLong) { - if(al == bl) { - throw new NumbersArithmeticException("overflow: gcd({0}, {1}) is 2^31", - p, q); - } - long blbu = bl; - bl = al; - al = blbu % al; - if (al == 0) { - if (bl > Integer.MAX_VALUE) { - throw new NumbersArithmeticException("overflow: gcd({0}, {1}) is 2^31", - p, q); - } - return (int) bl; - } - blbu = bl; - - // Now "al" and "bl" fit in an "int". - b = (int) al; - a = (int) (blbu % al); - } - - return gcdPositive(a, b); - } - - /** - * Computes the greatest common divisor of two positive numbers - * (this precondition is not checked and the result is undefined - * if not fulfilled) using the "binary gcd" method which avoids division - * and modulo operations. - * See Knuth 4.5.2 algorithm B. - * The algorithm is due to Josef Stein (1961). - *
- * Special cases: - *
    - *
  • The result of {@code gcd(x, x)}, {@code gcd(0, x)} and - * {@code gcd(x, 0)} is the value of {@code x}.
  • - *
  • The invocation {@code gcd(0, 0)} is the only one which returns - * {@code 0}.
  • - *
- * - * @param a Positive number. - * @param b Positive number. - * @return the greatest common divisor. - */ - private static int gcdPositive(int a, int b) { - if (a == 0) { - return b; - } - else if (b == 0) { - return a; - } - - // Make "a" and "b" odd, keeping track of common power of 2. - final int aTwos = Integer.numberOfTrailingZeros(a); - a >>= aTwos; - final int bTwos = Integer.numberOfTrailingZeros(b); - b >>= bTwos; - final int shift = Math.min(aTwos, bTwos); - - // "a" and "b" are positive. - // If a > b then "gdc(a, b)" is equal to "gcd(a - b, b)". - // If a < b then "gcd(a, b)" is equal to "gcd(b - a, a)". - // Hence, in the successive iterations: - // "a" becomes the absolute difference of the current values, - // "b" becomes the minimum of the current values. - while (a != b) { - final int delta = a - b; - b = Math.min(a, b); - a = Math.abs(delta); - - // Remove any power of 2 in "a" ("b" is guaranteed to be odd). - a >>= Integer.numberOfTrailingZeros(a); - } - - // Recover the common power of 2. - return a << shift; - } - - /** - *

- * Gets the greatest common divisor of the absolute value of two numbers, - * using the "binary gcd" method which avoids division and modulo - * operations. See Knuth 4.5.2 algorithm B. This algorithm is due to Josef - * Stein (1961). - *

- * Special cases: - *
    - *
  • The invocations - * {@code gcd(Long.MIN_VALUE, Long.MIN_VALUE)}, - * {@code gcd(Long.MIN_VALUE, 0L)} and - * {@code gcd(0L, Long.MIN_VALUE)} throw an - * {@code ArithmeticException}, because the result would be 2^63, which - * is too large for a long value.
  • - *
  • The result of {@code gcd(x, x)}, {@code gcd(0L, x)} and - * {@code gcd(x, 0L)} is the absolute value of {@code x}, except - * for the special cases above. - *
  • The invocation {@code gcd(0L, 0L)} is the only one which returns - * {@code 0L}.
  • - *
- * - * @param p Number. - * @param q Number. - * @return the greatest common divisor, never negative. - * @throws ArithmeticException if the result cannot be represented as - * a non-negative {@code long} value. - */ - public static long gcd(final long p, final long q) { - long u = p; - long v = q; - if ((u == 0) || (v == 0)) { - if ((u == Long.MIN_VALUE) || (v == Long.MIN_VALUE)){ - throw new NumbersArithmeticException("overflow: gcd({0}, {1}) is 2^63", - p, q); - } - return Math.abs(u) + Math.abs(v); - } - // keep u and v negative, as negative integers range down to - // -2^63, while positive numbers can only be as large as 2^63-1 - // (i.e. we can't necessarily negate a negative number without - // overflow) - /* assert u!=0 && v!=0; */ - if (u > 0) { - u = -u; - } // make u negative - if (v > 0) { - v = -v; - } // make v negative - // B1. [Find power of 2] - int k = 0; - while ((u & 1) == 0 && (v & 1) == 0 && k < 63) { // while u and v are - // both even... - u /= 2; - v /= 2; - k++; // cast out twos. - } - if (k == 63) { - throw new NumbersArithmeticException("overflow: gcd({0}, {1}) is 2^63", - p, q); - } - // B2. Initialize: u and v have been divided by 2^k and at least - // one is odd. - long t = ((u & 1) == 1) ? v : -(u / 2)/* B3 */; - // t negative: u was odd, v may be even (t replaces v) - // t positive: u was even, v is odd (t replaces u) - do { - /* assert u<0 && v<0; */ - // B4/B3: cast out twos from t. - while ((t & 1) == 0) { // while t is even.. - t /= 2; // cast out twos - } - // B5 [reset max(u,v)] - if (t > 0) { - u = -t; - } else { - v = t; - } - // B6/B3. at this point both u and v should be odd. - t = (v - u) / 2; - // |u| larger: t positive (replace u) - // |v| larger: t negative (replace v) - } while (t != 0); - return -u * (1L << k); // gcd is u*2^k - } - - /** - *

- * Returns the least common multiple of the absolute value of two numbers, - * using the formula {@code lcm(a,b) = (a / gcd(a,b)) * b}. - *

- * Special cases: - *
    - *
  • The invocations {@code lcm(Integer.MIN_VALUE, n)} and - * {@code lcm(n, Integer.MIN_VALUE)}, where {@code abs(n)} is a - * power of 2, throw an {@code ArithmeticException}, because the result - * would be 2^31, which is too large for an int value.
  • - *
  • The result of {@code lcm(0, x)} and {@code lcm(x, 0)} is - * {@code 0} for any {@code x}. - *
- * - * @param a Number. - * @param b Number. - * @return the least common multiple, never negative. - * @throws ArithmeticException if the result cannot be represented as - * a non-negative {@code int} value. - */ - public static int lcm(int a, int b) { - if (a == 0 || b == 0){ - return 0; - } - int lcm = Math.abs(ArithmeticUtils.mulAndCheck(a / gcd(a, b), b)); - if (lcm == Integer.MIN_VALUE) { - throw new NumbersArithmeticException("overflow: lcm({0}, {1}) is 2^31", - a, b); - } - return lcm; - } - - /** - *

- * Returns the least common multiple of the absolute value of two numbers, - * using the formula {@code lcm(a,b) = (a / gcd(a,b)) * b}. - *

- * Special cases: - *
    - *
  • The invocations {@code lcm(Long.MIN_VALUE, n)} and - * {@code lcm(n, Long.MIN_VALUE)}, where {@code abs(n)} is a - * power of 2, throw an {@code ArithmeticException}, because the result - * would be 2^63, which is too large for an int value.
  • - *
  • The result of {@code lcm(0L, x)} and {@code lcm(x, 0L)} is - * {@code 0L} for any {@code x}. - *
- * - * @param a Number. - * @param b Number. - * @return the least common multiple, never negative. - * @throws ArithmeticException if the result cannot be represented - * as a non-negative {@code long} value. - */ - public static long lcm(long a, long b) { - if (a == 0 || b == 0){ - return 0; - } - long lcm = Math.abs(ArithmeticUtils.mulAndCheck(a / gcd(a, b), b)); - if (lcm == Long.MIN_VALUE){ - throw new NumbersArithmeticException("overflow: lcm({0}, {1}) is 2^63", - a, b); - } - return lcm; - } - - /** - * Multiply two integers, checking for overflow. - * - * @param x Factor. - * @param y Factor. - * @return the product {@code x * y}. - * @throws ArithmeticException if the result can not be - * represented as an {@code int}. - */ - public static int mulAndCheck(int x, int y) { - long m = ((long)x) * ((long)y); - if (m < Integer.MIN_VALUE || m > Integer.MAX_VALUE) { - throw new NumbersArithmeticException(); - } - return (int)m; - } - - /** - * Multiply two long integers, checking for overflow. - * - * @param a Factor. - * @param b Factor. - * @return the product {@code a * b}. - * @throws ArithmeticException if the result can not be represented - * as a {@code long}. - */ - public static long mulAndCheck(long a, long b) { - long ret; - if (a > b) { - // use symmetry to reduce boundary cases - ret = mulAndCheck(b, a); - } else { - if (a < 0) { - if (b < 0) { - // check for positive overflow with negative a, negative b - if (a >= Long.MAX_VALUE / b) { - ret = a * b; - } else { - throw new NumbersArithmeticException(); - } - } else if (b > 0) { - // check for negative overflow with negative a, positive b - if (Long.MIN_VALUE / b <= a) { - ret = a * b; - } else { - throw new NumbersArithmeticException(); - - } - } else { - // assert b == 0 - ret = 0; - } - } else if (a > 0) { - // assert a > 0 - // assert b > 0 - - // check for positive overflow with positive a, positive b - if (a <= Long.MAX_VALUE / b) { - ret = a * b; - } else { - throw new NumbersArithmeticException(); - } - } else { - // assert a == 0 - ret = 0; - } - } - return ret; - } - - /** - * Subtract two integers, checking for overflow. - * - * @param x Minuend. - * @param y Subtrahend. - * @return the difference {@code x - y}. - * @throws ArithmeticException if the result can not be represented - * as an {@code int}. - */ - public static int subAndCheck(int x, int y) { - long s = (long)x - (long)y; - if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) { - throw new NumbersArithmeticException("overflow in subtraction: {0} - {1}", x, y); - } - return (int)s; - } - - /** - * Subtract two long integers, checking for overflow. - * - * @param a Value. - * @param b Value. - * @return the difference {@code a - b}. - * @throws ArithmeticException if the result can not be represented as a - * {@code long}. - */ - public static long subAndCheck(long a, long b) { - long ret; - if (b == Long.MIN_VALUE) { - if (a < 0) { - ret = a - b; - } else { - throw new NumbersArithmeticException("overflow in subtraction: {0} + {1}", a, -b); - } - } else { - // use additive inverse - ret = addAndCheck(a, -b, "overflow in subtraction: {0} + {1}"); - } - return ret; - } - - /** - * Raise an int to an int power. - * - * @param k Number to raise. - * @param e Exponent (must be positive or zero). - * @return \( k^e \) - * @throws IllegalArgumentException if {@code e < 0}. - * @throws ArithmeticException if the result would overflow. - */ - public static int pow(final int k, - final int e) { - if (e < 0) { - throw new IllegalArgumentException("negative exponent ({" + e + "})"); - } - - int exp = e; - int result = 1; - int k2p = k; - while (true) { - if ((exp & 0x1) != 0) { - result = mulAndCheck(result, k2p); - } - - exp >>= 1; - if (exp == 0) { - break; - } - - k2p = mulAndCheck(k2p, k2p); - } - - return result; - } - - /** - * Raise a long to an int power. - * - * @param k Number to raise. - * @param e Exponent (must be positive or zero). - * @return \( k^e \) - * @throws IllegalArgumentException if {@code e < 0}. - * @throws ArithmeticException if the result would overflow. - */ - public static long pow(final long k, - final int e) { - if (e < 0) { - throw new IllegalArgumentException("negative exponent ({" + e + "})"); - } - - int exp = e; - long result = 1; - long k2p = k; - while (true) { - if ((exp & 0x1) != 0) { - result = mulAndCheck(result, k2p); - } - - exp >>= 1; - if (exp == 0) { - break; - } - - k2p = mulAndCheck(k2p, k2p); - } - - return result; - } - - /** - * Raise a BigInteger to an int power. - * - * @param k Number to raise. - * @param e Exponent (must be positive or zero). - * @return ke - * @throws IllegalArgumentException if {@code e < 0}. - */ - public static BigInteger pow(final BigInteger k, int e) { - if (e < 0) { - throw new IllegalArgumentException("negative exponent ({" + e + "})"); - } - - return k.pow(e); - } - - /** - * Raise a BigInteger to a long power. - * - * @param k Number to raise. - * @param e Exponent (must be positive or zero). - * @return ke - * @throws IllegalArgumentException if {@code e < 0}. - */ - public static BigInteger pow(final BigInteger k, long e) { - if (e < 0) { - throw new IllegalArgumentException("negative exponent ({" + e + "})"); - } - - BigInteger result = BigInteger.ONE; - BigInteger k2p = k; - while (e != 0) { - if ((e & 0x1) != 0) { - result = result.multiply(k2p); - } - k2p = k2p.multiply(k2p); - e >>= 1; - } - - return result; - - } - - /** - * Raise a BigInteger to a BigInteger power. - * - * @param k Number to raise. - * @param e Exponent (must be positive or zero). - * @return ke - * @throws IllegalArgumentException if {@code e < 0}. - */ - public static BigInteger pow(final BigInteger k, BigInteger e) { - if (e.compareTo(BigInteger.ZERO) < 0) { - throw new IllegalArgumentException("negative exponent ({" + e + "})"); - } - - BigInteger result = BigInteger.ONE; - BigInteger k2p = k; - while (!BigInteger.ZERO.equals(e)) { - if (e.testBit(0)) { - result = result.multiply(k2p); - } - k2p = k2p.multiply(k2p); - e = e.shiftRight(1); - } - - return result; - } - - /** - * Add two long integers, checking for overflow. - * - * @param a Addend. - * @param b Addend. - * @param message Pattern to use for any thrown exception. - * @return the sum {@code a + b}. - * @throws ArithmeticException if the result cannot be represented - * as a {@code long}. - */ - private static long addAndCheck(long a, long b, String message) { - final long result = a + b; - if (!((a ^ b) < 0 || (a ^ result) >= 0)) { - throw new NumbersArithmeticException(message, a, b); - } - return result; - } - - /** - * Returns true if the argument is a power of two. - * - * @param n the number to test - * @return true if the argument is a power of two - */ - public static boolean isPowerOfTwo(long n) { - return (n > 0) && ((n & (n - 1)) == 0); - } - - /** - * Returns the unsigned remainder from dividing the first argument - * by the second where each argument and the result is interpreted - * as an unsigned value. - *

This method does not use the {@code long} datatype.

- * - * @param dividend the value to be divided - * @param divisor the value doing the dividing - * @return the unsigned remainder of the first argument divided by - * the second argument. - */ - public static int remainderUnsigned(int dividend, int divisor) { - if (divisor >= 0) { - if (dividend >= 0) { - return dividend % divisor; - } - // The implementation is a Java port of algorithm described in the book - // "Hacker's Delight" (section "Unsigned short division from signed division"). - int q = ((dividend >>> 1) / divisor) << 1; - dividend -= q * divisor; - if (dividend < 0 || dividend >= divisor) { - dividend -= divisor; - } - return dividend; - } - return dividend >= 0 || dividend < divisor ? dividend : dividend - divisor; - } - - /** - * Returns the unsigned remainder from dividing the first argument - * by the second where each argument and the result is interpreted - * as an unsigned value. - *

This method does not use the {@code BigInteger} datatype.

- * - * @param dividend the value to be divided - * @param divisor the value doing the dividing - * @return the unsigned remainder of the first argument divided by - * the second argument. - */ - public static long remainderUnsigned(long dividend, long divisor) { - if (divisor >= 0L) { - if (dividend >= 0L) { - return dividend % divisor; - } - // The implementation is a Java port of algorithm described in the book - // "Hacker's Delight" (section "Unsigned short division from signed division"). - long q = ((dividend >>> 1) / divisor) << 1; - dividend -= q * divisor; - if (dividend < 0L || dividend >= divisor) { - dividend -= divisor; - } - return dividend; - } - return dividend >= 0L || dividend < divisor ? dividend : dividend - divisor; - } - - /** - * Returns the unsigned quotient of dividing the first argument by - * the second where each argument and the result is interpreted as - * an unsigned value. - *

Note that in two's complement arithmetic, the three other - * basic arithmetic operations of add, subtract, and multiply are - * bit-wise identical if the two operands are regarded as both - * being signed or both being unsigned. Therefore separate {@code - * addUnsigned}, etc. methods are not provided.

- *

This method does not use the {@code long} datatype.

- * - * @param dividend the value to be divided - * @param divisor the value doing the dividing - * @return the unsigned quotient of the first argument divided by - * the second argument - */ - public static int divideUnsigned(int dividend, int divisor) { - if (divisor >= 0) { - if (dividend >= 0) { - return dividend / divisor; - } - // The implementation is a Java port of algorithm described in the book - // "Hacker's Delight" (section "Unsigned short division from signed division"). - int q = ((dividend >>> 1) / divisor) << 1; - dividend -= q * divisor; - if (dividend < 0L || dividend >= divisor) { - q++; - } - return q; - } - return dividend >= 0 || dividend < divisor ? 0 : 1; - } - - /** - * Returns the unsigned quotient of dividing the first argument by - * the second where each argument and the result is interpreted as - * an unsigned value. - *

Note that in two's complement arithmetic, the three other - * basic arithmetic operations of add, subtract, and multiply are - * bit-wise identical if the two operands are regarded as both - * being signed or both being unsigned. Therefore separate {@code - * addUnsigned}, etc. methods are not provided.

- *

This method does not use the {@code BigInteger} datatype.

- * - * @param dividend the value to be divided - * @param divisor the value doing the dividing - * @return the unsigned quotient of the first argument divided by - * the second argument. - */ - public static long divideUnsigned(long dividend, long divisor) { - if (divisor >= 0L) { - if (dividend >= 0L) { - return dividend / divisor; - } - // The implementation is a Java port of algorithm described in the book - // "Hacker's Delight" (section "Unsigned short division from signed division"). - long q = ((dividend >>> 1) / divisor) << 1; - dividend -= q * divisor; - if (dividend < 0L || dividend >= divisor) { - q++; - } - return q; - } - return dividend >= 0L || dividend < divisor ? 0L : 1L; - } - - /** - * Exception. - */ - private static class NumbersArithmeticException extends ArithmeticException { - /** Serializable version Id. */ - private static final long serialVersionUID = 20180130L; - /** Argument to construct a message. */ - private final Object[] formatArguments; - - /** - * Default constructor. - */ - NumbersArithmeticException() { - this("arithmetic exception"); - } - - /** - * Constructor with a specific message. - * - * @param message Message pattern providing the specific context of - * the error. - * @param args Arguments. - */ - NumbersArithmeticException(String message, Object ... args) { - super(message); - this.formatArguments = args; - } - - /** {@inheritDoc} */ - @Override - public String getMessage() { - return MessageFormat.format(super.getMessage(), formatArguments); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/Multiplication.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/Multiplication.java deleted file mode 100644 index e94ed860a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/Multiplication.java +++ /dev/null @@ -1,47 +0,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. - */ -package org.apache.commons.numbers.core; - -/** - * Multiplication. - * - * @param Type of elements. - */ -public interface Multiplication { - /** - * Binary multiplication. - * - * @param a Element. - * @return {@code this * a}. - */ - T multiply(T a); - - /** - * Identity element. - * - * @return the field element such that for all {@code a}, - * {@code one().multiply(a).equals(a)} is {@code true}. - */ - T one(); - - /** - * Multiplicative inverse. - * - * @return this-1. - */ - T reciprocal(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/NativeOperators.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/NativeOperators.java deleted file mode 100644 index 483dba2a9..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/NativeOperators.java +++ /dev/null @@ -1,59 +0,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. - */ -package org.apache.commons.numbers.core; - -/** - * Operators that can be implemented in a more performant way - * using the language constructs. - * - * @param Type of elements. - */ -public interface NativeOperators - extends Addition, - Multiplication { - /** - * Binary subtraction. - * - * @param a Element. - * @return {@code this - a}. - */ - T subtract(T a); - - /** - * Binary division. - * - * @param a Element. - * @return {@code this / a}. - */ - T divide(T a); - - /** - * Repeated addition. - * - * @param n Number of times to add {@code this} to itself. - * @return {@code n * this}. - */ - T multiply(int n); - - /** - * Repeated multiplication. - * - * @param n Number of times to multiply {@code this} with itself. - * @return {@code this^n}. - */ - T pow(int n); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/Precision.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/Precision.java deleted file mode 100644 index 3503cf29c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/Precision.java +++ /dev/null @@ -1,483 +0,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. - */ - -package org.apache.commons.numbers.core; - -import java.math.BigDecimal; -import java.math.RoundingMode; - -/** - * Utilities for comparing numbers. - */ -public class Precision { - /** - *

- * Largest double-precision floating-point number such that - * {@code 1 + EPSILON} is numerically equal to 1. This value is an upper - * bound on the relative error due to rounding real numbers to double - * precision floating-point numbers. - *

- *

- * In IEEE 754 arithmetic, this is 2-53. - *

- * - * @see Machine epsilon - */ - public static final double EPSILON; - - /** - * Safe minimum, such that {@code 1 / SAFE_MIN} does not overflow. - * In IEEE 754 arithmetic, this is also the smallest normalized - * number 2-1022. - */ - public static final double SAFE_MIN; - - /** Exponent offset in IEEE754 representation. */ - private static final long EXPONENT_OFFSET = 1023l; - - /** Offset to order signed double numbers lexicographically. */ - private static final long SGN_MASK = 0x8000000000000000L; - /** Offset to order signed double numbers lexicographically. */ - private static final int SGN_MASK_FLOAT = 0x80000000; - /** Positive zero. */ - private static final double POSITIVE_ZERO = 0d; - /** Positive zero bits. */ - private static final long POSITIVE_ZERO_DOUBLE_BITS = Double.doubleToRawLongBits(+0.0); - /** Negative zero bits. */ - private static final long NEGATIVE_ZERO_DOUBLE_BITS = Double.doubleToRawLongBits(-0.0); - /** Positive zero bits. */ - private static final int POSITIVE_ZERO_FLOAT_BITS = Float.floatToRawIntBits(+0.0f); - /** Negative zero bits. */ - private static final int NEGATIVE_ZERO_FLOAT_BITS = Float.floatToRawIntBits(-0.0f); - - static { - /* - * This was previously expressed as = 0x1.0p-53; - * However, OpenJDK (Sparc Solaris) cannot handle such small - * constants: MATH-721 - */ - EPSILON = Double.longBitsToDouble((EXPONENT_OFFSET - 53l) << 52); - - /* - * This was previously expressed as = 0x1.0p-1022; - * However, OpenJDK (Sparc Solaris) cannot handle such small - * constants: MATH-721 - */ - SAFE_MIN = Double.longBitsToDouble((EXPONENT_OFFSET - 1022l) << 52); - } - - /** - * Private constructor. - */ - private Precision() {} - - /** - * Compares two numbers given some amount of allowed error. - * The returned value is - *
    - *
  • - * 0 if {@link #equals(double,double,double) equals(x, y, eps)}, - *
  • - *
  • - * negative if !{@link #equals(double,double,double) equals(x, y, eps)} and {@code x < y}, - *
  • - *
  • - * positive if !{@link #equals(double,double,double) equals(x, y, eps)} and {@code x > y} or - * either argument is {@code NaN}. - *
  • - *
- * - * @param x First value. - * @param y Second value. - * @param eps Allowed error when checking for equality. - * @return 0 if the value are considered equal, -1 if the first is smaller than - * the second, 1 is the first is larger than the second. - */ - public static int compareTo(double x, double y, double eps) { - if (equals(x, y, eps)) { - return 0; - } else if (x < y) { - return -1; - } - return 1; - } - - /** - * Compares two numbers given some amount of allowed error. - * Two float numbers are considered equal if there are {@code (maxUlps - 1)} - * (or fewer) floating point numbers between them, i.e. two adjacent floating - * point numbers are considered equal. - * Adapted from - * - * Bruce Dawson. Returns {@code false} if either of the arguments is NaN. - * The returned value is - *
    - *
  • - * zero if {@link #equals(double,double,int) equals(x, y, maxUlps)}, - *
  • - *
  • - * negative if !{@link #equals(double,double,int) equals(x, y, maxUlps)} and {@code x < y}, - *
  • - *
  • - * positive if !{@link #equals(double,double,int) equals(x, y, maxUlps)} and {@code x > y} - * or either argument is {@code NaN}. - *
  • - *
- * - * @param x First value. - * @param y Second value. - * @param maxUlps {@code (maxUlps - 1)} is the number of floating point - * values between {@code x} and {@code y}. - * @return 0 if the value are considered equal, -1 if the first is smaller than - * the second, 1 is the first is larger than the second. - */ - public static int compareTo(final double x, final double y, final int maxUlps) { - if (equals(x, y, maxUlps)) { - return 0; - } else if (x < y) { - return -1; - } - return 1; - } - - /** - * Returns true iff they are equal as defined by - * {@link #equals(float,float,int) equals(x, y, 1)}. - * - * @param x first value - * @param y second value - * @return {@code true} if the values are equal. - */ - public static boolean equals(float x, float y) { - return equals(x, y, 1); - } - - /** - * Returns true if both arguments are NaN or they are - * equal as defined by {@link #equals(float,float) equals(x, y, 1)}. - * - * @param x first value - * @param y second value - * @return {@code true} if the values are equal or both are NaN. - */ - public static boolean equalsIncludingNaN(float x, float y) { - return (x != x || y != y) ? !(x != x ^ y != y) : equals(x, y, 1); - } - - /** - * Returns true if the arguments are equal or within the range of allowed - * error (inclusive). Returns {@code false} if either of the arguments - * is NaN. - * - * @param x first value - * @param y second value - * @param eps the amount of absolute error to allow. - * @return {@code true} if the values are equal or within range of each other. - */ - public static boolean equals(float x, float y, float eps) { - return equals(x, y, 1) || Math.abs(y - x) <= eps; - } - - /** - * Returns true if the arguments are both NaN, are equal, or are within the range - * of allowed error (inclusive). - * - * @param x first value - * @param y second value - * @param eps the amount of absolute error to allow. - * @return {@code true} if the values are equal or within range of each other, - * or both are NaN. - */ - public static boolean equalsIncludingNaN(float x, float y, float eps) { - return equalsIncludingNaN(x, y) || (Math.abs(y - x) <= eps); - } - - /** - * Returns true if the arguments are equal or within the range of allowed - * error (inclusive). - * Two float numbers are considered equal if there are {@code (maxUlps - 1)} - * (or fewer) floating point numbers between them, i.e. two adjacent floating - * point numbers are considered equal. - * Adapted from - * Bruce Dawson. Returns {@code false} if either of the arguments is NaN. - * - * @param x first value - * @param y second value - * @param maxUlps {@code (maxUlps - 1)} is the number of floating point - * values between {@code x} and {@code y}. - * @return {@code true} if there are fewer than {@code maxUlps} floating - * point values between {@code x} and {@code y}. - */ - public static boolean equals(final float x, final float y, final int maxUlps) { - - final int xInt = Float.floatToRawIntBits(x); - final int yInt = Float.floatToRawIntBits(y); - - final boolean isEqual; - if (((xInt ^ yInt) & SGN_MASK_FLOAT) == 0) { - // number have same sign, there is no risk of overflow - isEqual = Math.abs(xInt - yInt) <= maxUlps; - } else { - // number have opposite signs, take care of overflow - final int deltaPlus; - final int deltaMinus; - if (xInt < yInt) { - deltaPlus = yInt - POSITIVE_ZERO_FLOAT_BITS; - deltaMinus = xInt - NEGATIVE_ZERO_FLOAT_BITS; - } else { - deltaPlus = xInt - POSITIVE_ZERO_FLOAT_BITS; - deltaMinus = yInt - NEGATIVE_ZERO_FLOAT_BITS; - } - - if (deltaPlus > maxUlps) { - isEqual = false; - } else { - isEqual = deltaMinus <= (maxUlps - deltaPlus); - } - - } - - return isEqual && !Float.isNaN(x) && !Float.isNaN(y); - - } - - /** - * Returns true if the arguments are both NaN or if they are equal as defined - * by {@link #equals(float,float,int) equals(x, y, maxUlps)}. - * - * @param x first value - * @param y second value - * @param maxUlps {@code (maxUlps - 1)} is the number of floating point - * values between {@code x} and {@code y}. - * @return {@code true} if both arguments are NaN or if there are less than - * {@code maxUlps} floating point values between {@code x} and {@code y}. - */ - public static boolean equalsIncludingNaN(float x, float y, int maxUlps) { - return (x != x || y != y) ? !(x != x ^ y != y) : equals(x, y, maxUlps); - } - - /** - * Returns true iff they are equal as defined by - * {@link #equals(double,double,int) equals(x, y, 1)}. - * - * @param x first value - * @param y second value - * @return {@code true} if the values are equal. - */ - public static boolean equals(double x, double y) { - return equals(x, y, 1); - } - - /** - * Returns true if the arguments are both NaN or they are - * equal as defined by {@link #equals(double,double) equals(x, y, 1)}. - * - * @param x first value - * @param y second value - * @return {@code true} if the values are equal or both are NaN. - */ - public static boolean equalsIncludingNaN(double x, double y) { - return (x != x || y != y) ? !(x != x ^ y != y) : equals(x, y, 1); - } - - /** - * Returns {@code true} if there is no double value strictly between the - * arguments or the difference between them is within the range of allowed - * error (inclusive). Returns {@code false} if either of the arguments - * is NaN. - * - * @param x First value. - * @param y Second value. - * @param eps Amount of allowed absolute error. - * @return {@code true} if the values are two adjacent floating point - * numbers or they are within range of each other. - */ - public static boolean equals(double x, double y, double eps) { - return equals(x, y, 1) || Math.abs(y - x) <= eps; - } - - /** - * Returns {@code true} if there is no double value strictly between the - * arguments or the relative difference between them is less than or equal - * to the given tolerance. Returns {@code false} if either of the arguments - * is NaN. - * - * @param x First value. - * @param y Second value. - * @param eps Amount of allowed relative error. - * @return {@code true} if the values are two adjacent floating point - * numbers or they are within range of each other. - */ - public static boolean equalsWithRelativeTolerance(double x, double y, double eps) { - if (equals(x, y, 1)) { - return true; - } - - final double absoluteMax = Math.max(Math.abs(x), Math.abs(y)); - final double relativeDifference = Math.abs((x - y) / absoluteMax); - - return relativeDifference <= eps; - } - - /** - * Returns true if the arguments are both NaN, are equal or are within the range - * of allowed error (inclusive). - * - * @param x first value - * @param y second value - * @param eps the amount of absolute error to allow. - * @return {@code true} if the values are equal or within range of each other, - * or both are NaN. - */ - public static boolean equalsIncludingNaN(double x, double y, double eps) { - return equalsIncludingNaN(x, y) || (Math.abs(y - x) <= eps); - } - - /** - * Returns true if the arguments are equal or within the range of allowed - * error (inclusive). - *

- * Two float numbers are considered equal if there are {@code (maxUlps - 1)} - * (or fewer) floating point numbers between them, i.e. two adjacent - * floating point numbers are considered equal. - *

- *

- * Adapted from - * Bruce Dawson. Returns {@code false} if either of the arguments is NaN. - *

- * - * @param x first value - * @param y second value - * @param maxUlps {@code (maxUlps - 1)} is the number of floating point - * values between {@code x} and {@code y}. - * @return {@code true} if there are fewer than {@code maxUlps} floating - * point values between {@code x} and {@code y}. - */ - public static boolean equals(final double x, final double y, final int maxUlps) { - - final long xInt = Double.doubleToRawLongBits(x); - final long yInt = Double.doubleToRawLongBits(y); - - final boolean isEqual; - if (((xInt ^ yInt) & SGN_MASK) == 0l) { - // number have same sign, there is no risk of overflow - isEqual = Math.abs(xInt - yInt) <= maxUlps; - } else { - // number have opposite signs, take care of overflow - final long deltaPlus; - final long deltaMinus; - if (xInt < yInt) { - deltaPlus = yInt - POSITIVE_ZERO_DOUBLE_BITS; - deltaMinus = xInt - NEGATIVE_ZERO_DOUBLE_BITS; - } else { - deltaPlus = xInt - POSITIVE_ZERO_DOUBLE_BITS; - deltaMinus = yInt - NEGATIVE_ZERO_DOUBLE_BITS; - } - - if (deltaPlus > maxUlps) { - isEqual = false; - } else { - isEqual = deltaMinus <= (maxUlps - deltaPlus); - } - - } - - return isEqual && !Double.isNaN(x) && !Double.isNaN(y); - - } - - /** - * Returns true if both arguments are NaN or if they are equal as defined - * by {@link #equals(double,double,int) equals(x, y, maxUlps)}. - * - * @param x first value - * @param y second value - * @param maxUlps {@code (maxUlps - 1)} is the number of floating point - * values between {@code x} and {@code y}. - * @return {@code true} if both arguments are NaN or if there are less than - * {@code maxUlps} floating point values between {@code x} and {@code y}. - */ - public static boolean equalsIncludingNaN(double x, double y, int maxUlps) { - return (x != x || y != y) ? !(x != x ^ y != y) : equals(x, y, maxUlps); - } - - /** - * Rounds the given value to the specified number of decimal places. - * The value is rounded using the {@link BigDecimal#ROUND_HALF_UP} method. - * - * @param x Value to round. - * @param scale Number of digits to the right of the decimal point. - * @return the rounded value. - */ - public static double round(double x, int scale) { - return round(x, scale, RoundingMode.HALF_UP); - } - - /** - * Rounds the given value to the specified number of decimal places. - * The value is rounded using the given method which is any method defined - * in {@link BigDecimal}. - * If {@code x} is infinite or {@code NaN}, then the value of {@code x} is - * returned unchanged, regardless of the other parameters. - * - * @param x Value to round. - * @param scale Number of digits to the right of the decimal point. - * @param roundingMethod Rounding method as defined in {@link BigDecimal}. - * @return the rounded value. - * @throws ArithmeticException if {@code roundingMethod} is - * {@link RoundingMode#UNNECESSARY} and the specified scaling operation - * would require rounding. - */ - public static double round(double x, - int scale, - RoundingMode roundingMethod) { - try { - final double rounded = (new BigDecimal(Double.toString(x)) - .setScale(scale, roundingMethod)) - .doubleValue(); - // MATH-1089: negative values rounded to zero should result in negative zero - return rounded == POSITIVE_ZERO ? POSITIVE_ZERO * x : rounded; - } catch (NumberFormatException ex) { - if (Double.isInfinite(x)) { - return x; - } else { - return Double.NaN; - } - } - } - - /** - * Computes a number {@code delta} close to {@code originalDelta} with - * the property that

-     *   x + delta - x
-     * 
- * is exactly machine-representable. - * This is useful when computing numerical derivatives, in order to reduce - * roundoff errors. - * - * @param x Value. - * @param originalDelta Offset value. - * @return a number {@code delta} so that {@code x + delta} and {@code x} - * differ by a representable floating number. - */ - public static double representableDelta(double x, - double originalDelta) { - return x + originalDelta - x; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/package-info.java deleted file mode 100644 index 60a7c18d7..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/core/package-info.java +++ /dev/null @@ -1,20 +0,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. - */ -/** - * Basic utilities. - */ -package org.apache.commons.numbers.core; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/AbstractFormat.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/AbstractFormat.java deleted file mode 100644 index 687b24fa6..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/AbstractFormat.java +++ /dev/null @@ -1,205 +0,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. - */ - -package org.apache.commons.numbers.fraction; - -import java.io.Serializable; -import java.text.FieldPosition; -import java.text.NumberFormat; -import java.text.ParsePosition; -import java.util.Locale; - -/** - * Common part shared by both {@link FractionFormat} and {@link BigFractionFormat}. - */ -public abstract class AbstractFormat extends NumberFormat implements Serializable { - - /** Serializable version identifier. */ - private static final long serialVersionUID = -6981118387974191891L; - - /** The format used for the denominator. */ - private NumberFormat denominatorFormat; - - /** The format used for the numerator. */ - private NumberFormat numeratorFormat; - - /** - * Create an improper formatting instance with the default number format - * for the numerator and denominator. - */ - protected AbstractFormat() { - this(getDefaultNumberFormat()); - } - - /** - * Create an improper formatting instance with a custom number format for - * both the numerator and denominator. - * @param format the custom format for both the numerator and denominator. - */ - protected AbstractFormat(final NumberFormat format) { - this(format, (NumberFormat) format.clone()); - } - - /** - * Create an improper formatting instance with a custom number format for - * the numerator and a custom number format for the denominator. - * @param numeratorFormat the custom format for the numerator. - * @param denominatorFormat the custom format for the denominator. - */ - protected AbstractFormat(final NumberFormat numeratorFormat, - final NumberFormat denominatorFormat) { - this.numeratorFormat = numeratorFormat; - this.denominatorFormat = denominatorFormat; - } - - /** - * Create a default number format. The default number format is based on - * {@link NumberFormat#getNumberInstance(Locale)}. The only - * customization is the maximum number of BigFraction digits, which is set to 0. - * @return the default number format. - */ - protected static NumberFormat getDefaultNumberFormat() { - return getDefaultNumberFormat(Locale.getDefault()); - } - - /** - * Create a default number format. The default number format is based on - * {@link NumberFormat#getNumberInstance(Locale)}. The only - * customization is the maximum number of BigFraction digits, which is set to 0. - * @param locale the specific locale used by the format. - * @return the default number format specific to the given locale. - */ - protected static NumberFormat getDefaultNumberFormat(final Locale locale) { - final NumberFormat nf = NumberFormat.getNumberInstance(locale); - nf.setMaximumFractionDigits(0); - nf.setParseIntegerOnly(true); - return nf; - } - - /** - * Access the denominator format. - * @return the denominator format. - */ - public NumberFormat getDenominatorFormat() { - return denominatorFormat; - } - - /** - * Access the numerator format. - * @return the numerator format. - */ - public NumberFormat getNumeratorFormat() { - return numeratorFormat; - } - - /** - * Modify the denominator format. - * @param format the new denominator format value. - * @throws NullPointerException if {@code format} is {@code null}. - */ - public void setDenominatorFormat(final NumberFormat format) { - if (format == null) { - throw new NullPointerException("denominator format"); - } - this.denominatorFormat = format; - } - - /** - * Modify the numerator format. - * @param format the new numerator format value. - * @throws NullPointerException if {@code format} is {@code null}. - */ - public void setNumeratorFormat(final NumberFormat format) { - if (format == null) { - throw new NullPointerException("numerator format"); - } - this.numeratorFormat = format; - } - - /** - * Parses source until a non-whitespace character is found. - * @param source the string to parse - * @param pos input/output parsing parameter. On output, pos - * holds the index of the next non-whitespace character. - */ - protected static void parseAndIgnoreWhitespace(final String source, - final ParsePosition pos) { - parseNextCharacter(source, pos); - pos.setIndex(pos.getIndex() - 1); - } - - /** - * Parses source until a non-whitespace character is found. - * @param source the string to parse - * @param pos input/output parsing parameter. - * @return the first non-whitespace character. - */ - protected static char parseNextCharacter(final String source, - final ParsePosition pos) { - int index = pos.getIndex(); - final int n = source.length(); - char ret = 0; - - if (index < n) { - char c; - do { - c = source.charAt(index++); - } while (Character.isWhitespace(c) && index < n); - pos.setIndex(index); - - if (index < n) { - ret = c; - } - } - - return ret; - } - - /** - * Formats a double value as a fraction and appends the result to a StringBuffer. - * - * @param value the double value to format - * @param buffer StringBuffer to append to - * @param position On input: an alignment field, if desired. On output: the - * offsets of the alignment field - * @return a reference to the appended buffer - * @see #format(Object, StringBuffer, FieldPosition) - */ - @Override - public StringBuffer format(final double value, - final StringBuffer buffer, final FieldPosition position) { - return format(Double.valueOf(value), buffer, position); - } - - - /** - * Formats a long value as a fraction and appends the result to a StringBuffer. - * - * @param value the long value to format - * @param buffer StringBuffer to append to - * @param position On input: an alignment field, if desired. On output: the - * offsets of the alignment field - * @return a reference to the appended buffer - * @see #format(Object, StringBuffer, FieldPosition) - */ - @Override - public StringBuffer format(final long value, - final StringBuffer buffer, final FieldPosition position) { - return format(Long.valueOf(value), buffer, position); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java deleted file mode 100644 index 9b49b7ad0..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java +++ /dev/null @@ -1,1204 +0,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. - */ -package org.apache.commons.numbers.fraction; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.math.RoundingMode; -import org.apache.commons.numbers.core.ArithmeticUtils; - -/** - * Representation of a rational number without any overflow. This class is - * immutable. - */ -public class BigFraction - extends Number - implements Comparable, Serializable { - - /** A fraction representing "2 / 1". */ - public static final BigFraction TWO = new BigFraction(2); - - /** A fraction representing "1". */ - public static final BigFraction ONE = new BigFraction(1); - - /** A fraction representing "0". */ - public static final BigFraction ZERO = new BigFraction(0); - - /** A fraction representing "-1 / 1". */ - public static final BigFraction MINUS_ONE = new BigFraction(-1); - - /** A fraction representing "4/5". */ - public static final BigFraction FOUR_FIFTHS = new BigFraction(4, 5); - - /** A fraction representing "1/5". */ - public static final BigFraction ONE_FIFTH = new BigFraction(1, 5); - - /** A fraction representing "1/2". */ - public static final BigFraction ONE_HALF = new BigFraction(1, 2); - - /** A fraction representing "1/4". */ - public static final BigFraction ONE_QUARTER = new BigFraction(1, 4); - - /** A fraction representing "1/3". */ - public static final BigFraction ONE_THIRD = new BigFraction(1, 3); - - /** A fraction representing "3/5". */ - public static final BigFraction THREE_FIFTHS = new BigFraction(3, 5); - - /** A fraction representing "3/4". */ - public static final BigFraction THREE_QUARTERS = new BigFraction(3, 4); - - /** A fraction representing "2/5". */ - public static final BigFraction TWO_FIFTHS = new BigFraction(2, 5); - - /** A fraction representing "2/4". */ - public static final BigFraction TWO_QUARTERS = new BigFraction(2, 4); - - /** A fraction representing "2/3". */ - public static final BigFraction TWO_THIRDS = new BigFraction(2, 3); - - /** Serializable version identifier. */ - private static final long serialVersionUID = -5630213147331578515L; - - /** BigInteger representation of 100. */ - private static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100); - - /** Parameter name for fraction (to satisfy checkstyle). */ - private static final String PARAM_NAME_FRACTION = "fraction"; - - /** Parameter name for BigIntegers (to satisfy checkstyle). */ - private static final String PARAM_NAME_BG = "bg"; - - /** The numerator. */ - private final BigInteger numerator; - - /** The denominator. */ - private final BigInteger denominator; - - /** - *

- * Create a {@link BigFraction} equivalent to the passed {@code BigInteger}, ie - * "num / 1". - *

- * - * @param num - * the numerator. - */ - public BigFraction(final BigInteger num) { - this(num, BigInteger.ONE); - } - - /** - * Create a {@link BigFraction} given the numerator and denominator as - * {@code BigInteger}. The {@link BigFraction} is reduced to lowest terms. - * - * @param num the numerator, must not be {@code null}. - * @param den the denominator, must not be {@code null}. - * @throws ArithmeticException if the denominator is zero. - */ - public BigFraction(BigInteger num, BigInteger den) { - checkNotNull(num, "numerator"); - checkNotNull(den, "denominator"); - if (den.signum() == 0) { - throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR); - } - if (num.signum() == 0) { - numerator = BigInteger.ZERO; - denominator = BigInteger.ONE; - } else { - - // reduce numerator and denominator by greatest common denominator - final BigInteger gcd = num.gcd(den); - if (BigInteger.ONE.compareTo(gcd) < 0) { - num = num.divide(gcd); - den = den.divide(gcd); - } - - // move sign to numerator - if (den.signum() == -1) { - num = num.negate(); - den = den.negate(); - } - - // store the values in the final fields - numerator = num; - denominator = den; - - } - } - - /** - * Create a fraction given the double value. - *

- * This constructor behaves differently from - * {@link #BigFraction(double, double, int)}. It converts the double value - * exactly, considering its internal bits representation. This works for all - * values except NaN and infinities and does not requires any loop or - * convergence threshold. - *

- *

- * Since this conversion is exact and since double numbers are sometimes - * approximated, the fraction created may seem strange in some cases. For example, - * calling new BigFraction(1.0 / 3.0) does not create - * the fraction 1/3, but the fraction 6004799503160661 / 18014398509481984 - * because the double number passed to the constructor is not exactly 1/3 - * (this number cannot be stored exactly in IEEE754). - *

- * @see #BigFraction(double, double, int) - * @param value the double value to convert to a fraction. - * @exception IllegalArgumentException if value is NaN or infinite - */ - public BigFraction(final double value) throws IllegalArgumentException { - if (Double.isNaN(value)) { - throw new IllegalArgumentException("cannot convert NaN value"); - } - if (Double.isInfinite(value)) { - throw new IllegalArgumentException("cannot convert infinite value"); - } - - // compute m and k such that value = m * 2^k - final long bits = Double.doubleToLongBits(value); - final long sign = bits & 0x8000000000000000L; - final long exponent = bits & 0x7ff0000000000000L; - long m = bits & 0x000fffffffffffffL; - if (exponent != 0) { - // this was a normalized number, add the implicit most significant bit - m |= 0x0010000000000000L; - } - if (sign != 0) { - m = -m; - } - int k = ((int) (exponent >> 52)) - 1075; - while (((m & 0x001ffffffffffffeL) != 0) && ((m & 0x1) == 0)) { - m >>= 1; - ++k; - } - - if (k < 0) { - numerator = BigInteger.valueOf(m); - denominator = BigInteger.ZERO.flipBit(-k); - } else { - numerator = BigInteger.valueOf(m).multiply(BigInteger.ZERO.flipBit(k)); - denominator = BigInteger.ONE; - } - - } - - /** - * Create a fraction given the double value and maximum error allowed. - *

- * References: - *

- * - * @param value - * the double value to convert to a fraction. - * @param epsilon - * maximum error allowed. The resulting fraction is within - * epsilon of value, in absolute terms. - * @param maxIterations - * maximum number of convergents. - * @throws ArithmeticException - * if the continued fraction failed to converge. - * @see #BigFraction(double) - */ - public BigFraction(final double value, final double epsilon, - final int maxIterations) { - this(value, epsilon, Integer.MAX_VALUE, maxIterations); - } - - /** - * Create a fraction given the double value and either the maximum error - * allowed or the maximum number of denominator digits. - *

- * - * NOTE: This constructor is called with EITHER - a valid epsilon value and - * the maxDenominator set to Integer.MAX_VALUE (that way the maxDenominator - * has no effect). OR - a valid maxDenominator value and the epsilon value - * set to zero (that way epsilon only has effect if there is an exact match - * before the maxDenominator value is reached). - *

- *

- * - * It has been done this way so that the same code can be (re)used for both - * scenarios. However this could be confusing to users if it were part of - * the public API and this constructor should therefore remain PRIVATE. - *

- * - * See JIRA issue ticket MATH-181 for more details: - * - * https://issues.apache.org/jira/browse/MATH-181 - * - * @param value - * the double value to convert to a fraction. - * @param epsilon - * maximum error allowed. The resulting fraction is within - * epsilon of value, in absolute terms. - * @param maxDenominator - * maximum denominator value allowed. - * @param maxIterations - * maximum number of convergents. - * @throws ArithmeticException - * if the continued fraction failed to converge. - */ - private BigFraction(final double value, final double epsilon, - final int maxDenominator, int maxIterations) { - long overflow = Integer.MAX_VALUE; - double r0 = value; - long a0 = (long) Math.floor(r0); - - if (Math.abs(a0) > overflow) { - throw new FractionException(FractionException.ERROR_CONVERSION_OVERFLOW, value, a0, 1l); - } - - // check for (almost) integer arguments, which should not go - // to iterations. - if (Math.abs(a0 - value) < epsilon) { - numerator = BigInteger.valueOf(a0); - denominator = BigInteger.ONE; - return; - } - - long p0 = 1; - long q0 = 0; - long p1 = a0; - long q1 = 1; - - long p2 = 0; - long q2 = 1; - - int n = 0; - boolean stop = false; - do { - ++n; - final double r1 = 1.0 / (r0 - a0); - final long a1 = (long) Math.floor(r1); - p2 = (a1 * p1) + p0; - q2 = (a1 * q1) + q0; - if ((p2 > overflow) || (q2 > overflow)) { - // in maxDenominator mode, if the last fraction was very close to the actual value - // q2 may overflow in the next iteration; in this case return the last one. - if (epsilon == 0.0 && Math.abs(q1) < maxDenominator) { - break; - } - throw new FractionException(FractionException.ERROR_CONVERSION_OVERFLOW, value, p2, q2); - } - - final double convergent = (double) p2 / (double) q2; - if ((n < maxIterations) && - (Math.abs(convergent - value) > epsilon) && - (q2 < maxDenominator)) { - p0 = p1; - p1 = p2; - q0 = q1; - q1 = q2; - a0 = a1; - r0 = r1; - } else { - stop = true; - } - } while (!stop); - - if (n >= maxIterations) { - throw new FractionException(FractionException.ERROR_CONVERSION, value, maxIterations); - } - - if (q2 < maxDenominator) { - numerator = BigInteger.valueOf(p2); - denominator = BigInteger.valueOf(q2); - } else { - numerator = BigInteger.valueOf(p1); - denominator = BigInteger.valueOf(q1); - } - } - - /** - * Create a fraction given the double value and maximum denominator. - *

- * References: - *

- * - * @param value - * the double value to convert to a fraction. - * @param maxDenominator - * The maximum allowed value for denominator. - * @throws ArithmeticException - * if the continued fraction failed to converge. - */ - public BigFraction(final double value, final int maxDenominator) { - this(value, 0, maxDenominator, 100); - } - - /** - *

- * Create a {@link BigFraction} equivalent to the passed {@code int}, ie - * "num / 1". - *

- * - * @param num - * the numerator. - */ - public BigFraction(final int num) { - this(BigInteger.valueOf(num), BigInteger.ONE); - } - - /** - *

- * Create a {@link BigFraction} given the numerator and denominator as simple - * {@code int}. The {@link BigFraction} is reduced to lowest terms. - *

- * - * @param num - * the numerator. - * @param den - * the denominator. - */ - public BigFraction(final int num, final int den) { - this(BigInteger.valueOf(num), BigInteger.valueOf(den)); - } - - /** - *

- * Create a {@link BigFraction} equivalent to the passed long, ie "num / 1". - *

- * - * @param num - * the numerator. - */ - public BigFraction(final long num) { - this(BigInteger.valueOf(num), BigInteger.ONE); - } - - /** - *

- * Create a {@link BigFraction} given the numerator and denominator as simple - * {@code long}. The {@link BigFraction} is reduced to lowest terms. - *

- * - * @param num - * the numerator. - * @param den - * the denominator. - */ - public BigFraction(final long num, final long den) { - this(BigInteger.valueOf(num), BigInteger.valueOf(den)); - } - - /** - *

- * Creates a BigFraction instance with the 2 parts of a fraction - * Y/Z. - *

- * - *

- * Any negative signs are resolved to be on the numerator. - *

- * - * @param numerator - * the numerator, for example the three in 'three sevenths'. - * @param denominator - * the denominator, for example the seven in 'three sevenths'. - * @return a new fraction instance, with the numerator and denominator - * reduced. - * @throws ArithmeticException - * if the denominator is zero. - */ - public static BigFraction getReducedFraction(final int numerator, - final int denominator) { - if (numerator == 0) { - return ZERO; // normalize zero. - } - - return new BigFraction(numerator, denominator); - } - - /** - *

- * Returns the absolute value of this {@link BigFraction}. - *

- * - * @return the absolute value as a {@link BigFraction}. - */ - public BigFraction abs() { - return (numerator.signum() == 1) ? this : negate(); - } - - /** - *

- * Adds the value of this fraction to the passed {@link BigInteger}, - * returning the result in reduced form. - *

- * - * @param bg - * the {@link BigInteger} to add, must'nt be null. - * @return a BigFraction instance with the resulting values. - */ - public BigFraction add(final BigInteger bg) { - checkNotNull(bg, PARAM_NAME_BG); - - if (numerator.signum() == 0) { - return new BigFraction(bg); - } - if (bg.signum() == 0) { - return this; - } - - return new BigFraction(numerator.add(denominator.multiply(bg)), denominator); - } - - /** - *

- * Adds the value of this fraction to the passed {@code integer}, returning - * the result in reduced form. - *

- * - * @param i - * the {@code integer} to add. - * @return a BigFraction instance with the resulting values. - */ - public BigFraction add(final int i) { - return add(BigInteger.valueOf(i)); - } - - /** - *

- * Adds the value of this fraction to the passed {@code long}, returning - * the result in reduced form. - *

- * - * @param l - * the {@code long} to add. - * @return a BigFraction instance with the resulting values. - */ - public BigFraction add(final long l) { - return add(BigInteger.valueOf(l)); - } - - /** - *

- * Adds the value of this fraction to another, returning the result in - * reduced form. - *

- * - * @param fraction - * the {@link BigFraction} to add, must not be null. - * @return a {@link BigFraction} instance with the resulting values. - */ - public BigFraction add(final BigFraction fraction) { - checkNotNull(fraction, PARAM_NAME_FRACTION); - if (fraction.numerator.signum() == 0) { - return this; - } - if (numerator.signum() == 0) { - return fraction; - } - - final BigInteger num; - final BigInteger den; - - if (denominator.equals(fraction.denominator)) { - num = numerator.add(fraction.numerator); - den = denominator; - } else { - num = (numerator.multiply(fraction.denominator)).add((fraction.numerator).multiply(denominator)); - den = denominator.multiply(fraction.denominator); - } - - if (num.signum() == 0) { - return ZERO; - } - - return new BigFraction(num, den); - - } - - /** - *

- * Gets the fraction as a BigDecimal. This calculates the - * fraction as the numerator divided by denominator. - *

- * - * @return the fraction as a BigDecimal. - * @throws ArithmeticException - * if the exact quotient does not have a terminating decimal - * expansion. - * @see BigDecimal - */ - public BigDecimal bigDecimalValue() { - return new BigDecimal(numerator).divide(new BigDecimal(denominator)); - } - - /** - *

- * Gets the fraction as a BigDecimal following the passed - * rounding mode. This calculates the fraction as the numerator divided by - * denominator. - *

- * - * @param roundingMode Rounding mode to apply. - * @return the fraction as a BigDecimal. - * @see BigDecimal - */ - public BigDecimal bigDecimalValue(RoundingMode roundingMode) { - return new BigDecimal(numerator).divide(new BigDecimal(denominator), roundingMode); - } - - /** - *

- * Gets the fraction as a BigDecimal following the passed scale - * and rounding mode. This calculates the fraction as the numerator divided - * by denominator. - *

- * - * @param scale - * scale of the BigDecimal quotient to be returned. - * see {@link BigDecimal} for more information. - * @param roundingMode Rounding mode to apply. - * @return the fraction as a BigDecimal. - * @see BigDecimal - */ - public BigDecimal bigDecimalValue(final int scale, RoundingMode roundingMode) { - return new BigDecimal(numerator).divide(new BigDecimal(denominator), scale, roundingMode); - } - - /** - *

- * Compares this object to another based on size. - *

- * - * @param object - * the object to compare to, must not be null. - * @return -1 if this is less than {@code object}, +1 if this is greater - * than {@code object}, 0 if they are equal. - * @see Comparable#compareTo(Object) - */ - @Override - public int compareTo(final BigFraction object) { - int lhsSigNum = numerator.signum(); - int rhsSigNum = object.numerator.signum(); - - if (lhsSigNum != rhsSigNum) { - return (lhsSigNum > rhsSigNum) ? 1 : -1; - } - if (lhsSigNum == 0) { - return 0; - } - - BigInteger nOd = numerator.multiply(object.denominator); - BigInteger dOn = denominator.multiply(object.numerator); - return nOd.compareTo(dOn); - } - - /** - *

- * Divide the value of this fraction by the passed {@code BigInteger}, - * ie {@code this * 1 / bg}, returning the result in reduced form. - *

- * - * @param bg the {@code BigInteger} to divide by, must not be {@code null} - * @return a {@link BigFraction} instance with the resulting values - * @throws ArithmeticException if the fraction to divide by is zero - */ - public BigFraction divide(final BigInteger bg) { - checkNotNull(bg, PARAM_NAME_BG); - if (bg.signum() == 0) { - throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR); - } - if (numerator.signum() == 0) { - return ZERO; - } - return new BigFraction(numerator, denominator.multiply(bg)); - } - - /** - *

- * Divide the value of this fraction by the passed {@code int}, ie - * {@code this * 1 / i}, returning the result in reduced form. - *

- * - * @param i the {@code int} to divide by - * @return a {@link BigFraction} instance with the resulting values - * @throws ArithmeticException if the fraction to divide by is zero - */ - public BigFraction divide(final int i) { - return divide(BigInteger.valueOf(i)); - } - - /** - *

- * Divide the value of this fraction by the passed {@code long}, ie - * {@code this * 1 / l}, returning the result in reduced form. - *

- * - * @param l the {@code long} to divide by - * @return a {@link BigFraction} instance with the resulting values - * @throws ArithmeticException if the fraction to divide by is zero - */ - public BigFraction divide(final long l) { - return divide(BigInteger.valueOf(l)); - } - - /** - *

- * Divide the value of this fraction by another, returning the result in - * reduced form. - *

- * - * @param fraction Fraction to divide by, must not be {@code null}. - * @return a {@link BigFraction} instance with the resulting values. - * @throws ArithmeticException if the fraction to divide by is zero - */ - public BigFraction divide(final BigFraction fraction) { - checkNotNull(fraction, PARAM_NAME_FRACTION); - if (fraction.numerator.signum() == 0) { - throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR); - } - if (numerator.signum() == 0) { - return ZERO; - } - - return multiply(fraction.reciprocal()); - } - - /** - *

- * Gets the fraction as a {@code double}. This calculates the fraction as - * the numerator divided by denominator. - *

- * - * @return the fraction as a {@code double} - * @see Number#doubleValue() - */ - @Override - public double doubleValue() { - double doubleNum = numerator.doubleValue(); - double doubleDen = denominator.doubleValue(); - double result = doubleNum / doubleDen; - if (Double.isInfinite(doubleNum) || - Double.isInfinite(doubleDen) || - Double.isNaN(result)) { - // Numerator and/or denominator must be out of range: - // Calculate how far to shift them to put them in range. - int shift = Math.max(numerator.bitLength(), - denominator.bitLength()) - Math.getExponent(Double.MAX_VALUE); - result = numerator.shiftRight(shift).doubleValue() / - denominator.shiftRight(shift).doubleValue(); - } - return result; - } - - /** - *

- * Test for the equality of two fractions. If the lowest term numerator and - * denominators are the same for both fractions, the two fractions are - * considered to be equal. - *

- * - * @param other - * fraction to test for equality to this fraction, can be - * null. - * @return true if two fractions are equal, false if object is - * null, not an instance of {@link BigFraction}, or not - * equal to this fraction instance. - * @see Object#equals(Object) - */ - @Override - public boolean equals(final Object other) { - boolean ret = false; - - if (this == other) { - ret = true; - } else if (other instanceof BigFraction) { - BigFraction rhs = ((BigFraction) other).reduce(); - BigFraction thisOne = this.reduce(); - ret = thisOne.numerator.equals(rhs.numerator) && thisOne.denominator.equals(rhs.denominator); - } - - return ret; - } - - /** - *

- * Gets the fraction as a {@code float}. This calculates the fraction as - * the numerator divided by denominator. - *

- * - * @return the fraction as a {@code float}. - * @see Number#floatValue() - */ - @Override - public float floatValue() { - float floatNum = numerator.floatValue(); - float floatDen = denominator.floatValue(); - float result = floatNum / floatDen; - if (Float.isInfinite(floatNum) || - Float.isInfinite(floatDen) || - Float.isNaN(result)) { - // Numerator and/or denominator must be out of range: - // Calculate how far to shift them to put them in range. - int shift = Math.max(numerator.bitLength(), - denominator.bitLength()) - Math.getExponent(Float.MAX_VALUE); - result = numerator.shiftRight(shift).floatValue() / - denominator.shiftRight(shift).floatValue(); - } - return result; - } - - /** - *

- * Access the denominator as a BigInteger. - *

- * - * @return the denominator as a BigInteger. - */ - public BigInteger getDenominator() { - return denominator; - } - - /** - *

- * Access the denominator as a {@code int}. - *

- * - * @return the denominator as a {@code int}. - */ - public int getDenominatorAsInt() { - return denominator.intValue(); - } - - /** - *

- * Access the denominator as a {@code long}. - *

- * - * @return the denominator as a {@code long}. - */ - public long getDenominatorAsLong() { - return denominator.longValue(); - } - - /** - *

- * Access the numerator as a BigInteger. - *

- * - * @return the numerator as a BigInteger. - */ - public BigInteger getNumerator() { - return numerator; - } - - /** - *

- * Access the numerator as a {@code int}. - *

- * - * @return the numerator as a {@code int}. - */ - public int getNumeratorAsInt() { - return numerator.intValue(); - } - - /** - *

- * Access the numerator as a {@code long}. - *

- * - * @return the numerator as a {@code long}. - */ - public long getNumeratorAsLong() { - return numerator.longValue(); - } - - /** - *

- * Gets a hashCode for the fraction. - *

- * - * @return a hash code value for this object. - * @see Object#hashCode() - */ - @Override - public int hashCode() { - return 37 * (37 * 17 + numerator.hashCode()) + denominator.hashCode(); - } - - /** - *

- * Gets the fraction as an {@code int}. This returns the whole number part - * of the fraction. - *

- * - * @return the whole number fraction part. - * @see Number#intValue() - */ - @Override - public int intValue() { - return numerator.divide(denominator).intValue(); - } - - /** - *

- * Gets the fraction as a {@code long}. This returns the whole number part - * of the fraction. - *

- * - * @return the whole number fraction part. - * @see Number#longValue() - */ - @Override - public long longValue() { - return numerator.divide(denominator).longValue(); - } - - /** - *

- * Multiplies the value of this fraction by the passed - * BigInteger, returning the result in reduced form. - *

- * - * @param bg the {@code BigInteger} to multiply by. - * @return a {@code BigFraction} instance with the resulting values. - */ - public BigFraction multiply(final BigInteger bg) { - checkNotNull(bg, PARAM_NAME_BG); - if (numerator.signum() == 0 || bg.signum() == 0) { - return ZERO; - } - return new BigFraction(bg.multiply(numerator), denominator); - } - - /** - *

- * Multiply the value of this fraction by the passed {@code int}, returning - * the result in reduced form. - *

- * - * @param i - * the {@code int} to multiply by. - * @return a {@link BigFraction} instance with the resulting values. - */ - public BigFraction multiply(final int i) { - if (i == 0 || numerator.signum() == 0) { - return ZERO; - } - - return multiply(BigInteger.valueOf(i)); - } - - /** - *

- * Multiply the value of this fraction by the passed {@code long}, - * returning the result in reduced form. - *

- * - * @param l - * the {@code long} to multiply by. - * @return a {@link BigFraction} instance with the resulting values. - */ - public BigFraction multiply(final long l) { - if (l == 0 || numerator.signum() == 0) { - return ZERO; - } - - return multiply(BigInteger.valueOf(l)); - } - - /** - *

- * Multiplies the value of this fraction by another, returning the result in - * reduced form. - *

- * - * @param fraction Fraction to multiply by, must not be {@code null}. - * @return a {@link BigFraction} instance with the resulting values. - */ - public BigFraction multiply(final BigFraction fraction) { - checkNotNull(fraction, PARAM_NAME_FRACTION); - if (numerator.signum() == 0 || - fraction.numerator.signum() == 0) { - return ZERO; - } - return new BigFraction(numerator.multiply(fraction.numerator), - denominator.multiply(fraction.denominator)); - } - - /** - *

- * Return the additive inverse of this fraction, returning the result in - * reduced form. - *

- * - * @return the negation of this fraction. - */ - public BigFraction negate() { - return new BigFraction(numerator.negate(), denominator); - } - - /** - *

- * Gets the fraction percentage as a {@code double}. This calculates the - * fraction as the numerator divided by denominator multiplied by 100. - *

- * - * @return the fraction percentage as a {@code double}. - */ - public double percentageValue() { - return multiply(ONE_HUNDRED).doubleValue(); - } - - /** - *

- * Returns a {@code BigFraction} whose value is - * {@code (thisexponent)}, returning the result in reduced form. - *

- * - * @param exponent - * exponent to which this {@code BigFraction} is to be - * raised. - * @return thisexponent. - */ - public BigFraction pow(final int exponent) { - if (exponent == 0) { - return ONE; - } - if (numerator.signum() == 0) { - return this; - } - - if (exponent < 0) { - return new BigFraction(denominator.pow(-exponent), numerator.pow(-exponent)); - } - return new BigFraction(numerator.pow(exponent), denominator.pow(exponent)); - } - - /** - *

- * Returns a BigFraction whose value is - * (thisexponent), returning the result in reduced form. - *

- * - * @param exponent - * exponent to which this BigFraction is to be raised. - * @return thisexponent as a BigFraction. - */ - public BigFraction pow(final long exponent) { - if (exponent == 0) { - return ONE; - } - if (numerator.signum() == 0) { - return this; - } - - if (exponent < 0) { - return new BigFraction(ArithmeticUtils.pow(denominator, -exponent), - ArithmeticUtils.pow(numerator, -exponent)); - } - return new BigFraction(ArithmeticUtils.pow(numerator, exponent), - ArithmeticUtils.pow(denominator, exponent)); - } - - /** - *

- * Returns a BigFraction whose value is - * (thisexponent), returning the result in reduced form. - *

- * - * @param exponent - * exponent to which this BigFraction is to be raised. - * @return thisexponent as a BigFraction. - */ - public BigFraction pow(final BigInteger exponent) { - if (exponent.signum() == 0) { - return ONE; - } - if (numerator.signum() == 0) { - return this; - } - - if (exponent.signum() == -1) { - final BigInteger eNeg = exponent.negate(); - return new BigFraction(ArithmeticUtils.pow(denominator, eNeg), - ArithmeticUtils.pow(numerator, eNeg)); - } - return new BigFraction(ArithmeticUtils.pow(numerator, exponent), - ArithmeticUtils.pow(denominator, exponent)); - } - - /** - *

- * Returns a double whose value is - * (thisexponent), returning the result in reduced form. - *

- * - * @param exponent - * exponent to which this BigFraction is to be raised. - * @return thisexponent. - */ - public double pow(final double exponent) { - return Math.pow(numerator.doubleValue(), exponent) / - Math.pow(denominator.doubleValue(), exponent); - } - - /** - *

- * Return the multiplicative inverse of this fraction. - *

- * - * @return the reciprocal fraction. - */ - public BigFraction reciprocal() { - return new BigFraction(denominator, numerator); - } - - /** - *

- * Reduce this BigFraction to its lowest terms. - *

- * - * @return the reduced BigFraction. It doesn't change anything if - * the fraction can be reduced. - */ - public BigFraction reduce() { - final BigInteger gcd = numerator.gcd(denominator); - - if (BigInteger.ONE.compareTo(gcd) < 0) { - return new BigFraction(numerator.divide(gcd), denominator.divide(gcd)); - } else { - return this; - } - } - - /** - *

- * Subtracts the value of an {@link BigInteger} from the value of this - * {@code BigFraction}, returning the result in reduced form. - *

- * - * @param bg the {@link BigInteger} to subtract, cannot be {@code null}. - * @return a {@code BigFraction} instance with the resulting values. - */ - public BigFraction subtract(final BigInteger bg) { - checkNotNull(bg, PARAM_NAME_BG); - if (bg.signum() == 0) { - return this; - } - if (numerator.signum() == 0) { - return new BigFraction(bg.negate()); - } - - return new BigFraction(numerator.subtract(denominator.multiply(bg)), denominator); - } - - /** - *

- * Subtracts the value of an {@code integer} from the value of this - * {@code BigFraction}, returning the result in reduced form. - *

- * - * @param i the {@code integer} to subtract. - * @return a {@code BigFraction} instance with the resulting values. - */ - public BigFraction subtract(final int i) { - return subtract(BigInteger.valueOf(i)); - } - - /** - *

- * Subtracts the value of a {@code long} from the value of this - * {@code BigFraction}, returning the result in reduced form. - *

- * - * @param l the {@code long} to subtract. - * @return a {@code BigFraction} instance with the resulting values. - */ - public BigFraction subtract(final long l) { - return subtract(BigInteger.valueOf(l)); - } - - /** - *

- * Subtracts the value of another fraction from the value of this one, - * returning the result in reduced form. - *

- * - * @param fraction {@link BigFraction} to subtract, must not be {@code null}. - * @return a {@link BigFraction} instance with the resulting values - */ - public BigFraction subtract(final BigFraction fraction) { - checkNotNull(fraction, PARAM_NAME_FRACTION); - if (fraction.numerator.signum() == 0) { - return this; - } - if (numerator.signum() == 0) { - return fraction.negate(); - } - - final BigInteger num; - final BigInteger den; - if (denominator.equals(fraction.denominator)) { - num = numerator.subtract(fraction.numerator); - den = denominator; - } else { - num = (numerator.multiply(fraction.denominator)).subtract((fraction.numerator).multiply(denominator)); - den = denominator.multiply(fraction.denominator); - } - return new BigFraction(num, den); - - } - - /** - *

- * Returns the String representing this fraction, ie - * "num / dem" or just "num" if the denominator is one. - *

- * - * @return a string representation of the fraction. - * @see Object#toString() - */ - @Override - public String toString() { - final String str; - if (BigInteger.ONE.equals(denominator)) { - str = numerator.toString(); - } else if (BigInteger.ZERO.equals(numerator)) { - str = "0"; - } else { - str = numerator + " / " + denominator; - } - return str; - } - - /** - * Check that the argument is not null and throw a NullPointerException - * if it is. - * @param arg the argument to check - * @param argName the name of the argument - */ - private static void checkNotNull(Object arg, String argName) { - if (arg == null) { - throw new NullPointerException(argName); - } - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/BigFractionFormat.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/BigFractionFormat.java deleted file mode 100644 index b8bf1d3dc..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/BigFractionFormat.java +++ /dev/null @@ -1,282 +0,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. - */ - -package org.apache.commons.numbers.fraction; - -import java.io.Serializable; -import java.math.BigInteger; -import java.text.FieldPosition; -import java.text.NumberFormat; -import java.text.ParseException; -import java.text.ParsePosition; -import java.util.Locale; - -/** - * Formats a BigFraction number in proper format or improper format. - *

- * The number format for each of the whole number, numerator and, - * denominator can be configured. - *

- */ -public class BigFractionFormat extends AbstractFormat implements Serializable { - - /** Serializable version identifier */ - private static final long serialVersionUID = -2932167925527338976L; - - /** - * Create an improper formatting instance with the default number format - * for the numerator and denominator. - */ - public BigFractionFormat() { - } - - /** - * Create an improper formatting instance with a custom number format for - * both the numerator and denominator. - * @param format the custom format for both the numerator and denominator. - */ - public BigFractionFormat(final NumberFormat format) { - super(format); - } - - /** - * Create an improper formatting instance with a custom number format for - * the numerator and a custom number format for the denominator. - * @param numeratorFormat the custom format for the numerator. - * @param denominatorFormat the custom format for the denominator. - */ - public BigFractionFormat(final NumberFormat numeratorFormat, - final NumberFormat denominatorFormat) { - super(numeratorFormat, denominatorFormat); - } - - /** - * Get the set of locales for which complex formats are available. This - * is the same set as the {@link NumberFormat} set. - * @return available complex format locales. - */ - public static Locale[] getAvailableLocales() { - return NumberFormat.getAvailableLocales(); - } - - /** - * This static method calls formatBigFraction() on a default instance of - * BigFractionFormat. - * - * @param f BigFraction object to format - * @return A formatted BigFraction in proper form. - */ - public static String formatBigFraction(final BigFraction f) { - return getImproperInstance().format(f); - } - - /** - * Returns the default complex format for the current locale. - * @return the default complex format. - */ - public static BigFractionFormat getImproperInstance() { - return getImproperInstance(Locale.getDefault()); - } - - /** - * Returns the default complex format for the given locale. - * @param locale the specific locale used by the format. - * @return the complex format specific to the given locale. - */ - public static BigFractionFormat getImproperInstance(final Locale locale) { - return new BigFractionFormat(getDefaultNumberFormat(locale)); - } - - /** - * Returns the default complex format for the current locale. - * @return the default complex format. - */ - public static BigFractionFormat getProperInstance() { - return getProperInstance(Locale.getDefault()); - } - - /** - * Returns the default complex format for the given locale. - * @param locale the specific locale used by the format. - * @return the complex format specific to the given locale. - */ - public static BigFractionFormat getProperInstance(final Locale locale) { - return new ProperBigFractionFormat(getDefaultNumberFormat(locale)); - } - - /** - * Formats a {@link BigFraction} object to produce a string. The BigFraction is - * output in improper format. - * - * @param BigFraction the object to format. - * @param toAppendTo where the text is to be appended - * @param pos On input: an alignment field, if desired. On output: the - * offsets of the alignment field - * @return the value passed in as toAppendTo. - */ - public StringBuffer format(final BigFraction BigFraction, - final StringBuffer toAppendTo, final FieldPosition pos) { - - pos.setBeginIndex(0); - pos.setEndIndex(0); - - getNumeratorFormat().format(BigFraction.getNumerator(), toAppendTo, pos); - toAppendTo.append(" / "); - getDenominatorFormat().format(BigFraction.getDenominator(), toAppendTo, pos); - - return toAppendTo; - } - - /** - * Formats an object and appends the result to a StringBuffer. - * obj must be either a {@link BigFraction} object or a - * {@link BigInteger} object or a {@link Number} object. Any other type of - * object will result in an {@link IllegalArgumentException} being thrown. - * - * @param obj the object to format. - * @param toAppendTo where the text is to be appended - * @param pos On input: an alignment field, if desired. On output: the - * offsets of the alignment field - * @return the value passed in as toAppendTo. - * @see java.text.Format#format(Object, StringBuffer, FieldPosition) - * @throws IllegalArgumentException if obj is not a valid type. - */ - @Override - public StringBuffer format(final Object obj, - final StringBuffer toAppendTo, final FieldPosition pos) { - - final StringBuffer ret; - if (obj instanceof BigFraction) { - ret = format((BigFraction) obj, toAppendTo, pos); - } else if (obj instanceof BigInteger) { - ret = format(new BigFraction((BigInteger) obj), toAppendTo, pos); - } else if (obj instanceof Number) { - ret = format(new BigFraction(((Number) obj).doubleValue()), - toAppendTo, pos); - } else { - throw new IllegalArgumentException("cannot format given object as a fraction number"); - } - - return ret; - } - - /** - * Parses a string to produce a {@link BigFraction} object. - * @param source the string to parse - * @return the parsed {@link BigFraction} object. - * @exception ParseException if the beginning of the specified string - * cannot be parsed. - */ - @Override - public BigFraction parse(final String source) throws ParseException { - final ParsePosition parsePosition = new ParsePosition(0); - final BigFraction result = parse(source, parsePosition); - if (parsePosition.getIndex() == 0) { - throw new FractionParseException(source, parsePosition.getErrorIndex(), BigFraction.class); - } - return result; - } - - /** - * Parses a string to produce a {@link BigFraction} object. - * This method expects the string to be formatted as an improper BigFraction. - * @param source the string to parse - * @param pos input/output parsing parameter. - * @return the parsed {@link BigFraction} object. - */ - @Override - public BigFraction parse(final String source, final ParsePosition pos) { - final int initialIndex = pos.getIndex(); - - // parse whitespace - parseAndIgnoreWhitespace(source, pos); - - // parse numerator - final BigInteger num = parseNextBigInteger(source, pos); - if (num == null) { - // invalid integer number - // set index back to initial, error index should already be set - // character examined. - pos.setIndex(initialIndex); - return null; - } - - // parse '/' - final int startIndex = pos.getIndex(); - final char c = parseNextCharacter(source, pos); - switch (c) { - case 0 : - // no '/' - // return num as a BigFraction - return new BigFraction(num); - case '/' : - // found '/', continue parsing denominator - break; - default : - // invalid '/' - // set index back to initial, error index should be the last - // character examined. - pos.setIndex(initialIndex); - pos.setErrorIndex(startIndex); - return null; - } - - // parse whitespace - parseAndIgnoreWhitespace(source, pos); - - // parse denominator - final BigInteger den = parseNextBigInteger(source, pos); - if (den == null) { - // invalid integer number - // set index back to initial, error index should already be set - // character examined. - pos.setIndex(initialIndex); - return null; - } - - return new BigFraction(num, den); - } - - /** - * Parses a string to produce a BigInteger. - * @param source the string to parse - * @param pos input/output parsing parameter. - * @return a parsed BigInteger or null if string does not - * contain a BigInteger at the specified position - */ - protected BigInteger parseNextBigInteger(final String source, - final ParsePosition pos) { - - final int start = pos.getIndex(); - int end = (source.charAt(start) == '-') ? (start + 1) : start; - while((end < source.length()) && - Character.isDigit(source.charAt(end))) { - ++end; - } - - try { - BigInteger n = new BigInteger(source.substring(start, end)); - pos.setIndex(end); - return n; - } catch (NumberFormatException nfe) { - pos.setErrorIndex(start); - return null; - } - - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/ContinuedFraction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/ContinuedFraction.java deleted file mode 100644 index 121b5731b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/ContinuedFraction.java +++ /dev/null @@ -1,172 +0,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. - */ -package org.apache.commons.numbers.fraction; - -import org.apache.commons.numbers.core.Precision; - -/** - * Provides a generic means to evaluate - * continued fractions. - * Subclasses must provide the {@link #getA(int,double) a} and {@link #getB(int,double) b} - * coefficients to evaluate the continued fraction. - */ -public abstract class ContinuedFraction { - /** Maximum allowed numerical error. */ - private static final double DEFAULT_EPSILON = 1e-9; - - /** - * Defines the - * {@code n}-th "a" coefficient of the continued fraction. - * - * @param n Index of the coefficient to retrieve. - * @param x Evaluation point. - * @return the coefficient an. - */ - protected abstract double getA(int n, double x); - - /** - * Defines the - * {@code n}-th "b" coefficient of the continued fraction. - * - * @param n Index of the coefficient to retrieve. - * @param x Evaluation point. - * @return the coefficient bn. - */ - protected abstract double getB(int n, double x); - - /** - * Evaluates the continued fraction. - * - * @param x Point at which to evaluate the continued fraction. - * @return the value of the continued fraction evaluated at {@code x}. - * @throws ArithmeticException if the algorithm fails to converge. - * @throws ArithmeticException if the maximal number of iterations is reached - * before the expected convergence is achieved. - * - * @see #evaluate(double,double,int) - */ - public double evaluate(double x) { - return evaluate(x, DEFAULT_EPSILON, Integer.MAX_VALUE); - } - - /** - * Evaluates the continued fraction. - * - * @param x the evaluation point. - * @param epsilon Maximum error allowed. - * @return the value of the continued fraction evaluated at {@code x}. - * @throws ArithmeticException if the algorithm fails to converge. - * @throws ArithmeticException if the maximal number of iterations is reached - * before the expected convergence is achieved. - * - * @see #evaluate(double,double,int) - */ - public double evaluate(double x, double epsilon) { - return evaluate(x, epsilon, Integer.MAX_VALUE); - } - - /** - * Evaluates the continued fraction at the value x. - * @param x the evaluation point. - * @param maxIterations Maximum number of iterations. - * @return the value of the continued fraction evaluated at {@code x}. - * @throws ArithmeticException if the algorithm fails to converge. - * @throws ArithmeticException if the maximal number of iterations is reached - * before the expected convergence is achieved. - * - * @see #evaluate(double,double,int) - */ - public double evaluate(double x, int maxIterations) { - return evaluate(x, DEFAULT_EPSILON, maxIterations); - } - - /** - * Evaluates the continued fraction. - *

- * The implementation of this method is based on the modified Lentz algorithm as described - * on page 18 ff. in: - *

- * - * - * - * @param x Point at which to evaluate the continued fraction. - * @param epsilon Maximum error allowed. - * @param maxIterations Maximum number of iterations. - * @return the value of the continued fraction evaluated at {@code x}. - * @throws ArithmeticException if the algorithm fails to converge. - * @throws ArithmeticException if the maximal number of iterations is reached - * before the expected convergence is achieved. - */ - public double evaluate(double x, double epsilon, int maxIterations) { - final double small = 1e-50; - double hPrev = getA(0, x); - - // use the value of small as epsilon criteria for zero checks - if (Precision.equals(hPrev, 0.0, small)) { - hPrev = small; - } - - int n = 1; - double dPrev = 0.0; - double cPrev = hPrev; - double hN = hPrev; - - while (n <= maxIterations) { - final double a = getA(n, x); - final double b = getB(n, x); - - double dN = a + b * dPrev; - if (Precision.equals(dN, 0.0, small)) { - dN = small; - } - double cN = a + b / cPrev; - if (Precision.equals(cN, 0.0, small)) { - cN = small; - } - - dN = 1 / dN; - final double deltaN = cN * dN; - hN = hPrev * deltaN; - - if (Double.isInfinite(hN)) { - throw new FractionException("Continued fraction convergents diverged to +/- infinity for value {0}", - x); - } - if (Double.isNaN(hN)) { - throw new FractionException("Continued fraction diverged to NaN for value {0}", - x); - } - - if (Math.abs(deltaN - 1) < epsilon) { - return hN; - } - - dPrev = dN; - cPrev = cN; - hPrev = hN; - ++n; - } - - throw new FractionException("maximal count ({0}) exceeded", maxIterations); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/Fraction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/Fraction.java deleted file mode 100644 index a9a070141..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/Fraction.java +++ /dev/null @@ -1,689 +0,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. - */ -package org.apache.commons.numbers.fraction; - -import org.apache.commons.numbers.core.ArithmeticUtils; -import org.apache.commons.numbers.core.NativeOperators; - -import java.io.Serializable; -import java.math.BigInteger; - -/** - * Representation of a rational number. - */ -public class Fraction - extends Number - implements Comparable, - Serializable, - NativeOperators { - - /** A fraction representing "2 / 1". */ - public static final Fraction TWO = new Fraction(2, 1); - - /** A fraction representing "1". */ - public static final Fraction ONE = new Fraction(1, 1); - - /** A fraction representing "0". */ - public static final Fraction ZERO = new Fraction(0, 1); - - /** A fraction representing "4/5". */ - public static final Fraction FOUR_FIFTHS = new Fraction(4, 5); - - /** A fraction representing "1/5". */ - public static final Fraction ONE_FIFTH = new Fraction(1, 5); - - /** A fraction representing "1/2". */ - public static final Fraction ONE_HALF = new Fraction(1, 2); - - /** A fraction representing "1/4". */ - public static final Fraction ONE_QUARTER = new Fraction(1, 4); - - /** A fraction representing "1/3". */ - public static final Fraction ONE_THIRD = new Fraction(1, 3); - - /** A fraction representing "3/5". */ - public static final Fraction THREE_FIFTHS = new Fraction(3, 5); - - /** A fraction representing "3/4". */ - public static final Fraction THREE_QUARTERS = new Fraction(3, 4); - - /** A fraction representing "2/5". */ - public static final Fraction TWO_FIFTHS = new Fraction(2, 5); - - /** A fraction representing "2/4". */ - public static final Fraction TWO_QUARTERS = new Fraction(2, 4); - - /** A fraction representing "2/3". */ - public static final Fraction TWO_THIRDS = new Fraction(2, 3); - - /** A fraction representing "-1 / 1". */ - public static final Fraction MINUS_ONE = new Fraction(-1, 1); - - /** Serializable version identifier */ - private static final long serialVersionUID = 3698073679419233275L; - - /** Parameter name for fraction (to satisfy checkstyle). */ - private static final String PARAM_NAME_FRACTION = "fraction"; - - /** The default epsilon used for convergence. */ - private static final double DEFAULT_EPSILON = 1e-5; - - /** The denominator. */ - private final int denominator; - - /** The numerator. */ - private final int numerator; - - /** - * Create a fraction given the double value. - * @param value the double value to convert to a fraction. - * @throws IllegalArgumentException if the continued fraction failed to - * converge. - */ - public Fraction(double value) { - this(value, DEFAULT_EPSILON, 100); - } - - /** - * Create a fraction given the double value and maximum error allowed. - *

- * References: - *

- * - * @param value the double value to convert to a fraction. - * @param epsilon maximum error allowed. The resulting fraction is within - * {@code epsilon} of {@code value}, in absolute terms. - * @param maxIterations maximum number of convergents - * @throws IllegalArgumentException if the continued fraction failed to - * converge. - */ - public Fraction(double value, double epsilon, int maxIterations) - { - this(value, epsilon, Integer.MAX_VALUE, maxIterations); - } - - /** - * Create a fraction given the double value and maximum denominator. - *

- * References: - *

- * - * @param value the double value to convert to a fraction. - * @param maxDenominator The maximum allowed value for denominator - * @throws IllegalArgumentException if the continued fraction failed to - * converge - */ - public Fraction(double value, int maxDenominator) - { - this(value, 0, maxDenominator, 100); - } - - /** - * Create a fraction given the double value and either the maximum error - * allowed or the maximum number of denominator digits. - *

- * - * NOTE: This constructor is called with EITHER - * - a valid epsilon value and the maxDenominator set to Integer.MAX_VALUE - * (that way the maxDenominator has no effect). - * OR - * - a valid maxDenominator value and the epsilon value set to zero - * (that way epsilon only has effect if there is an exact match before - * the maxDenominator value is reached). - *

- * - * It has been done this way so that the same code can be (re)used for both - * scenarios. However this could be confusing to users if it were part of - * the public API and this constructor should therefore remain PRIVATE. - *

- * - * See JIRA issue ticket MATH-181 for more details: - * - * https://issues.apache.org/jira/browse/MATH-181 - * - * @param value the double value to convert to a fraction. - * @param epsilon maximum error allowed. The resulting fraction is within - * {@code epsilon} of {@code value}, in absolute terms. - * @param maxDenominator maximum denominator value allowed. - * @param maxIterations maximum number of convergents - * @throws IllegalArgumentException if the continued fraction failed to - * converge. - */ - private Fraction(double value, double epsilon, int maxDenominator, int maxIterations) - { - long overflow = Integer.MAX_VALUE; - double r0 = value; - long a0 = (long)Math.floor(r0); - if (Math.abs(a0) > overflow) { - throw new FractionException(FractionException.ERROR_CONVERSION, value, a0, 1l); - } - - // check for (almost) integer arguments, which should not go to iterations. - if (Math.abs(a0 - value) < epsilon) { - this.numerator = (int) a0; - this.denominator = 1; - return; - } - - long p0 = 1; - long q0 = 0; - long p1 = a0; - long q1 = 1; - - long p2 = 0; - long q2 = 1; - - int n = 0; - boolean stop = false; - do { - ++n; - double r1 = 1.0 / (r0 - a0); - long a1 = (long)Math.floor(r1); - p2 = (a1 * p1) + p0; - q2 = (a1 * q1) + q0; - - if ((Math.abs(p2) > overflow) || (Math.abs(q2) > overflow)) { - // in maxDenominator mode, if the last fraction was very close to the actual value - // q2 may overflow in the next iteration; in this case return the last one. - if (epsilon == 0.0 && Math.abs(q1) < maxDenominator) { - break; - } - throw new FractionException(FractionException.ERROR_CONVERSION, value, p2, q2); - } - - double convergent = (double)p2 / (double)q2; - if (n < maxIterations && Math.abs(convergent - value) > epsilon && q2 < maxDenominator) { - p0 = p1; - p1 = p2; - q0 = q1; - q1 = q2; - a0 = a1; - r0 = r1; - } else { - stop = true; - } - } while (!stop); - - if (n >= maxIterations) { - throw new FractionException(FractionException.ERROR_CONVERSION, value, maxIterations); - } - - if (q2 < maxDenominator) { - this.numerator = (int) p2; - this.denominator = (int) q2; - } else { - this.numerator = (int) p1; - this.denominator = (int) q1; - } - - } - - /** - * Create a fraction from an int. - * The fraction is num / 1. - * @param num the numerator. - */ - public Fraction(int num) { - this(num, 1); - } - - /** - * Create a fraction given the numerator and denominator. The fraction is - * reduced to lowest terms. - * @param num the numerator. - * @param den the denominator. - * @throws ArithmeticException if the denominator is {@code zero} - * or if integer overflow occurs - */ - public Fraction(int num, int den) { - if (den == 0) { - throw new ArithmeticException("division by zero"); - } - if (den < 0) { - if (num == Integer.MIN_VALUE || - den == Integer.MIN_VALUE) { - throw new FractionException(FractionException.ERROR_NEGATION_OVERFLOW, num, den); - } - num = -num; - den = -den; - } - // reduce numerator and denominator by greatest common denominator. - final int d = ArithmeticUtils.gcd(num, den); - if (d > 1) { - num /= d; - den /= d; - } - - // move sign to numerator. - if (den < 0) { - num = -num; - den = -den; - } - this.numerator = num; - this.denominator = den; - } - - /** - * Returns the absolute value of this fraction. - * @return the absolute value. - */ - public Fraction abs() { - Fraction ret; - if (numerator >= 0) { - ret = this; - } else { - ret = negate(); - } - return ret; - } - - /** - * Compares this object to another based on size. - * @param object the object to compare to - * @return -1 if this is less than {@code object}, +1 if this is greater - * than {@code object}, 0 if they are equal. - */ - @Override - public int compareTo(Fraction object) { - long nOd = ((long) numerator) * object.denominator; - long dOn = ((long) denominator) * object.numerator; - return (nOd < dOn) ? -1 : ((nOd > dOn) ? +1 : 0); - } - - /** - * Gets the fraction as a {@code double}. This calculates the fraction as - * the numerator divided by denominator. - * @return the fraction as a {@code double} - */ - @Override - public double doubleValue() { - return (double)numerator / (double)denominator; - } - - /** - * Test for the equality of two fractions. If the lowest term - * numerator and denominators are the same for both fractions, the two - * fractions are considered to be equal. - * @param other fraction to test for equality to this fraction - * @return true if two fractions are equal, false if object is - * {@code null}, not an instance of {@link Fraction}, or not equal - * to this fraction instance. - */ - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other instanceof Fraction) { - // since fractions are always in lowest terms, numerators and - // denominators can be compared directly for equality. - Fraction rhs = (Fraction)other; - return (numerator == rhs.numerator) && - (denominator == rhs.denominator); - } - return false; - } - - /** - * Gets the fraction as a {@code float}. This calculates the fraction as - * the numerator divided by denominator. - * @return the fraction as a {@code float} - */ - @Override - public float floatValue() { - return (float)doubleValue(); - } - - /** - * Access the denominator. - * @return the denominator. - */ - public int getDenominator() { - return denominator; - } - - /** - * Access the numerator. - * @return the numerator. - */ - public int getNumerator() { - return numerator; - } - - /** - * Gets a hashCode for the fraction. - * @return a hash code value for this object - */ - @Override - public int hashCode() { - return 37 * (37 * 17 + numerator) + denominator; - } - - /** - * Gets the fraction as an {@code int}. This returns the whole number part - * of the fraction. - * @return the whole number fraction part - */ - @Override - public int intValue() { - return (int)doubleValue(); - } - - /** - * Gets the fraction as a {@code long}. This returns the whole number part - * of the fraction. - * @return the whole number fraction part - */ - @Override - public long longValue() { - return (long)doubleValue(); - } - - /** {@inheritDoc} */ - @Override - public Fraction zero() { - return ZERO; - } - - /** {@inheritDoc} */ - @Override - public Fraction one() { - return ONE; - } - - /** - * Return the additive inverse of this fraction. - * @return the negation of this fraction. - */ - public Fraction negate() { - if (numerator==Integer.MIN_VALUE) { - throw new FractionException(FractionException.ERROR_NEGATION_OVERFLOW, numerator, denominator); - } - return new Fraction(-numerator, denominator); - } - - /** - * Return the multiplicative inverse of this fraction. - * @return the reciprocal fraction - */ - public Fraction reciprocal() { - return new Fraction(denominator, numerator); - } - - /** - *

Adds the value of this fraction to another, returning the result in reduced form. - * The algorithm follows Knuth, 4.5.1.

- * - * @param fraction the fraction to add, must not be {@code null} - * @return a {@code Fraction} instance with the resulting values - * @throws NullPointerException if the fraction is {@code null} - * @throws ArithmeticException if the resulting numerator or denominator exceeds - * {@code Integer.MAX_VALUE} - */ - public Fraction add(Fraction fraction) { - return addSub(fraction, true /* add */); - } - - /** - * Add an integer to the fraction. - * @param i the {@code integer} to add. - * @return this + i - */ - public Fraction add(final int i) { - return new Fraction(numerator + i * denominator, denominator); - } - - /** - *

Subtracts the value of another fraction from the value of this one, - * returning the result in reduced form.

- * - * @param fraction the fraction to subtract, must not be {@code null} - * @return a {@code Fraction} instance with the resulting values - * @throws NullPointerException if the fraction is {@code null} - * @throws ArithmeticException if the resulting numerator or denominator - * cannot be represented in an {@code int}. - */ - public Fraction subtract(Fraction fraction) { - return addSub(fraction, false /* subtract */); - } - - /** - * Subtract an integer from the fraction. - * @param i the {@code integer} to subtract. - * @return this - i - */ - public Fraction subtract(final int i) { - return new Fraction(numerator - i * denominator, denominator); - } - - /** - * Implement add and subtract using algorithm described in Knuth 4.5.1. - * - * @param fraction the fraction to subtract, must not be {@code null} - * @param isAdd true to add, false to subtract - * @return a {@code Fraction} instance with the resulting values - * @throws NullPointerException if the fraction is {@code null} - * @throws ArithmeticException if the resulting numerator or denominator - * cannot be represented in an {@code int}. - */ - private Fraction addSub(Fraction fraction, boolean isAdd) { - if (fraction == null) { - throw new NullPointerException(PARAM_NAME_FRACTION); - } - // zero is identity for addition. - if (numerator == 0) { - return isAdd ? fraction : fraction.negate(); - } - if (fraction.numerator == 0) { - return this; - } - // if denominators are randomly distributed, d1 will be 1 about 61% - // of the time. - int d1 = ArithmeticUtils.gcd(denominator, fraction.denominator); - if (d1==1) { - // result is ( (u*v' +/- u'v) / u'v') - int uvp = ArithmeticUtils.mulAndCheck(numerator, fraction.denominator); - int upv = ArithmeticUtils.mulAndCheck(fraction.numerator, denominator); - return new Fraction - (isAdd ? ArithmeticUtils.addAndCheck(uvp, upv) : - ArithmeticUtils.subAndCheck(uvp, upv), - ArithmeticUtils.mulAndCheck(denominator, fraction.denominator)); - } - // the quantity 't' requires 65 bits of precision; see knuth 4.5.1 - // exercise 7. we're going to use a BigInteger. - // t = u(v'/d1) +/- v(u'/d1) - BigInteger uvp = BigInteger.valueOf(numerator) - .multiply(BigInteger.valueOf(fraction.denominator/d1)); - BigInteger upv = BigInteger.valueOf(fraction.numerator) - .multiply(BigInteger.valueOf(denominator/d1)); - BigInteger t = isAdd ? uvp.add(upv) : uvp.subtract(upv); - // but d2 doesn't need extra precision because - // d2 = gcd(t,d1) = gcd(t mod d1, d1) - int tmodd1 = t.mod(BigInteger.valueOf(d1)).intValue(); - int d2 = (tmodd1==0)?d1:ArithmeticUtils.gcd(tmodd1, d1); - - // result is (t/d2) / (u'/d1)(v'/d2) - BigInteger w = t.divide(BigInteger.valueOf(d2)); - if (w.bitLength() > 31) { - throw new FractionException( - "overflow, numerator too large after multiply: {0}", w.toString(), ""); - } - return new Fraction (w.intValue(), - ArithmeticUtils.mulAndCheck(denominator/d1, - fraction.denominator/d2)); - } - - /** - *

Multiplies the value of this fraction by another, returning the - * result in reduced form.

- * - * @param fraction the fraction to multiply by, must not be {@code null} - * @return a {@code Fraction} instance with the resulting values - * @throws NullPointerException if the fraction is {@code null} - * @throws ArithmeticException if the resulting numerator or denominator exceeds - * {@code Integer.MAX_VALUE} - */ - public Fraction multiply(Fraction fraction) { - if (fraction == null) { - throw new NullPointerException(PARAM_NAME_FRACTION); - } - if (numerator == 0 || fraction.numerator == 0) { - return ZERO; - } - // knuth 4.5.1 - // make sure we don't overflow unless the result *must* overflow. - int d1 = ArithmeticUtils.gcd(numerator, fraction.denominator); - int d2 = ArithmeticUtils.gcd(fraction.numerator, denominator); - return getReducedFraction - (ArithmeticUtils.mulAndCheck(numerator/d1, fraction.numerator/d2), - ArithmeticUtils.mulAndCheck(denominator/d2, fraction.denominator/d1)); - } - - /** - * Multiply the fraction by an integer. - * @param i the {@code integer} to multiply by. - * @return this * i - */ - public Fraction multiply(final int i) { - return multiply(new Fraction(i)); - } - - /** - * @param n Power. - * @return {@code this^n} - */ - public Fraction pow(final int n) { - if (n == 0) { - return ONE; - } - if (numerator == 0) { - return this; - } - - return n < 0 ? - new Fraction(ArithmeticUtils.pow(denominator, -n), - ArithmeticUtils.pow(numerator, -n)) : - new Fraction(ArithmeticUtils.pow(numerator, n), - ArithmeticUtils.pow(denominator, n)); - } - - /** - *

Divide the value of this fraction by another.

- * - * @param fraction the fraction to divide by, must not be {@code null} - * @return a {@code Fraction} instance with the resulting values - * @throws ArithmeticException if the fraction to divide by is zero - * or if the resulting numerator or denominator - * exceeds {@code Integer.MAX_VALUE} - */ - public Fraction divide(Fraction fraction) { - if (fraction == null) { - throw new NullPointerException(PARAM_NAME_FRACTION); - } - if (fraction.numerator == 0) { - throw new FractionException("the fraction to divide by must not be zero: {0}/{1}", - fraction.numerator, fraction.denominator); - } - return multiply(fraction.reciprocal()); - } - - /** - * Divide the fraction by an integer. - * @param i the {@code integer} to divide by. - * @return this * i - */ - public Fraction divide(final int i) { - return divide(new Fraction(i)); - } - - /** - *

- * Gets the fraction percentage as a {@code double}. This calculates the - * fraction as the numerator divided by denominator multiplied by 100. - *

- * - * @return the fraction percentage as a {@code double}. - */ - public double percentageValue() { - return 100 * doubleValue(); - } - - /** - *

Creates a {@code Fraction} instance with the 2 parts - * of a fraction Y/Z.

- * - *

Any negative signs are resolved to be on the numerator.

- * - * @param numerator the numerator, for example the three in 'three sevenths' - * @param denominator the denominator, for example the seven in 'three sevenths' - * @return a new fraction instance, with the numerator and denominator reduced - * @throws ArithmeticException if the denominator is {@code zero} - */ - public static Fraction getReducedFraction(int numerator, int denominator) { - if (denominator == 0) { - throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR); - } - if (numerator==0) { - return ZERO; // normalize zero. - } - // allow 2^k/-2^31 as a valid fraction (where k>0) - if (denominator==Integer.MIN_VALUE && (numerator&1)==0) { - numerator/=2; denominator/=2; - } - if (denominator < 0) { - if (numerator==Integer.MIN_VALUE || - denominator==Integer.MIN_VALUE) { - throw new FractionException(FractionException.ERROR_NEGATION_OVERFLOW, numerator, denominator); - } - numerator = -numerator; - denominator = -denominator; - } - // simplify fraction. - int gcd = ArithmeticUtils.gcd(numerator, denominator); - numerator /= gcd; - denominator /= gcd; - return new Fraction(numerator, denominator); - } - - /** - *

- * Returns the {@code String} representing this fraction, ie - * "num / dem" or just "num" if the denominator is one. - *

- * - * @return a string representation of the fraction. - * @see Object#toString() - */ - @Override - public String toString() { - final String str; - if (denominator == 1) { - str = Integer.toString(numerator); - } else if (numerator == 0) { - str = "0"; - } else { - str = numerator + " / " + denominator; - } - return str; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/FractionException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/FractionException.java deleted file mode 100644 index b89bb42e0..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/FractionException.java +++ /dev/null @@ -1,60 +0,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. - */ -package org.apache.commons.numbers.fraction; - -import java.text.MessageFormat; - -/** - * Package private exception class with constants for frequently used messages. - */ -class FractionException extends ArithmeticException { - - /** Error message for overflow during conversion. */ - static final String ERROR_CONVERSION_OVERFLOW = "Overflow trying to convert {0} to fraction ({1}/{2})"; - /** Error message when iterative conversion fails. */ - static final String ERROR_CONVERSION = "Unable to convert {0} to fraction after {1} iterations"; - /** Error message for overflow by negation. */ - static final String ERROR_NEGATION_OVERFLOW = "overflow in fraction {0}/{1}, cannot negate"; - /** Error message for zero-valued denominator. */ - static final String ERROR_ZERO_DENOMINATOR = "denominator must be different from 0"; - - /** Serializable version identifier. */ - private static final long serialVersionUID = 201701191744L; - - /** Arguments for formatting the message. */ - protected Object[] formatArguments; - - /** - * Create an exception where the message is constructed by applying - * the {@code format()} method from {@code java.text.MessageFormat}. - * - * @param message the exception message with replaceable parameters - * @param formatArguments the arguments for formatting the message - */ - FractionException(String message, Object... formatArguments) { - super(message); - this.formatArguments = formatArguments; - } - - /** {@inheritDoc} */ - @Override - public String getMessage() { - return MessageFormat.format(super.getMessage(), formatArguments); - } - - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/FractionFormat.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/FractionFormat.java deleted file mode 100644 index cd9b084d7..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/FractionFormat.java +++ /dev/null @@ -1,260 +0,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. - */ - -package org.apache.commons.numbers.fraction; - -import java.text.FieldPosition; -import java.text.NumberFormat; -import java.text.ParseException; -import java.text.ParsePosition; -import java.util.Locale; - -/** - * Formats a Fraction number in proper format or improper format. The number - * format for each of the whole number, numerator and, denominator can be - * configured. - */ -public class FractionFormat extends AbstractFormat { - - /** Serializable version identifier */ - private static final long serialVersionUID = 3008655719530972612L; - - /** - * Create an improper formatting instance with the default number format - * for the numerator and denominator. - */ - public FractionFormat() { - } - - /** - * Create an improper formatting instance with a custom number format for - * both the numerator and denominator. - * @param format the custom format for both the numerator and denominator. - */ - public FractionFormat(final NumberFormat format) { - super(format); - } - - /** - * Create an improper formatting instance with a custom number format for - * the numerator and a custom number format for the denominator. - * @param numeratorFormat the custom format for the numerator. - * @param denominatorFormat the custom format for the denominator. - */ - public FractionFormat(final NumberFormat numeratorFormat, - final NumberFormat denominatorFormat) { - super(numeratorFormat, denominatorFormat); - } - - /** - * Get the set of locales for which complex formats are available. This - * is the same set as the {@link NumberFormat} set. - * @return available complex format locales. - */ - public static Locale[] getAvailableLocales() { - return NumberFormat.getAvailableLocales(); - } - - /** - * This static method calls formatFraction() on a default instance of - * FractionFormat. - * - * @param f Fraction object to format - * @return a formatted fraction in proper form. - */ - public static String formatFraction(Fraction f) { - return getImproperInstance().format(f); - } - - /** - * Returns the default complex format for the current locale. - * @return the default complex format. - */ - public static FractionFormat getImproperInstance() { - return getImproperInstance(Locale.getDefault()); - } - - /** - * Returns the default complex format for the given locale. - * @param locale the specific locale used by the format. - * @return the complex format specific to the given locale. - */ - public static FractionFormat getImproperInstance(final Locale locale) { - return new FractionFormat(getDefaultNumberFormat(locale)); - } - - /** - * Returns the default complex format for the current locale. - * @return the default complex format. - */ - public static FractionFormat getProperInstance() { - return getProperInstance(Locale.getDefault()); - } - - /** - * Returns the default complex format for the given locale. - * @param locale the specific locale used by the format. - * @return the complex format specific to the given locale. - */ - public static FractionFormat getProperInstance(final Locale locale) { - return new ProperFractionFormat(getDefaultNumberFormat(locale)); - } - - /** - * Create a default number format. The default number format is based on - * {@link NumberFormat#getNumberInstance(Locale)} with the only - * customizing is the maximum number of fraction digits, which is set to 0. - * @return the default number format. - */ - protected static NumberFormat getDefaultNumberFormat() { - return getDefaultNumberFormat(Locale.getDefault()); - } - - /** - * Formats a {@link Fraction} object to produce a string. The fraction is - * output in improper format. - * - * @param fraction the object to format. - * @param toAppendTo where the text is to be appended - * @param pos On input: an alignment field, if desired. On output: the - * offsets of the alignment field - * @return the value passed in as toAppendTo. - */ - public StringBuffer format(final Fraction fraction, - final StringBuffer toAppendTo, final FieldPosition pos) { - - pos.setBeginIndex(0); - pos.setEndIndex(0); - - getNumeratorFormat().format(fraction.getNumerator(), toAppendTo, pos); - toAppendTo.append(" / "); - getDenominatorFormat().format(fraction.getDenominator(), toAppendTo, - pos); - - return toAppendTo; - } - - /** - * Formats an object and appends the result to a StringBuffer. obj must be either a - * {@link Fraction} object or a {@link Number} object. Any other type of - * object will result in an {@link IllegalArgumentException} being thrown. - * - * @param obj the object to format. - * @param toAppendTo where the text is to be appended - * @param pos On input: an alignment field, if desired. On output: the - * offsets of the alignment field - * @return the value passed in as toAppendTo. - * @see java.text.Format#format(Object, StringBuffer, FieldPosition) - * @throws ArithmeticException if the number cannot be converted to a fraction - * @throws IllegalArgumentException if obj is not a valid type. - */ - @Override - public StringBuffer format(final Object obj, - final StringBuffer toAppendTo, - final FieldPosition pos) { - StringBuffer ret = null; - - if (obj instanceof Fraction) { - ret = format((Fraction) obj, toAppendTo, pos); - } else if (obj instanceof Number) { - ret = format(new Fraction(((Number) obj).doubleValue()), toAppendTo, pos); - } else { - throw new IllegalArgumentException( - "cannot format given object as a fraction number"); - } - - return ret; - } - - /** - * Parses a string to produce a {@link Fraction} object. - * @param source the string to parse - * @return the parsed {@link Fraction} object. - * @exception ParseException if the beginning of the specified string - * cannot be parsed. - */ - @Override - public Fraction parse(final String source) throws ParseException { - final ParsePosition parsePosition = new ParsePosition(0); - final Fraction result = parse(source, parsePosition); - if (parsePosition.getIndex() == 0) { - throw new FractionParseException(source, parsePosition.getErrorIndex(), Fraction.class); - } - return result; - } - - /** - * Parses a string to produce a {@link Fraction} object. This method - * expects the string to be formatted as an improper fraction. - * @param source the string to parse - * @param pos input/output parsing parameter. - * @return the parsed {@link Fraction} object. - */ - @Override - public Fraction parse(final String source, final ParsePosition pos) { - final int initialIndex = pos.getIndex(); - - // parse whitespace - parseAndIgnoreWhitespace(source, pos); - - // parse numerator - final Number num = getNumeratorFormat().parse(source, pos); - if (num == null) { - // invalid integer number - // set index back to initial, error index should already be set - // character examined. - pos.setIndex(initialIndex); - return null; - } - - // parse '/' - final int startIndex = pos.getIndex(); - final char c = parseNextCharacter(source, pos); - switch (c) { - case 0 : - // no '/' - // return num as a fraction - return new Fraction(num.intValue(), 1); - case '/' : - // found '/', continue parsing denominator - break; - default : - // invalid '/' - // set index back to initial, error index should be the last - // character examined. - pos.setIndex(initialIndex); - pos.setErrorIndex(startIndex); - return null; - } - - // parse whitespace - parseAndIgnoreWhitespace(source, pos); - - // parse denominator - final Number den = getDenominatorFormat().parse(source, pos); - if (den == null) { - // invalid integer number - // set index back to initial, error index should already be set - // character examined. - pos.setIndex(initialIndex); - return null; - } - - return new Fraction(num.intValue(), den.intValue()); - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/FractionParseException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/FractionParseException.java deleted file mode 100644 index f0ae1f5e3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/FractionParseException.java +++ /dev/null @@ -1,43 +0,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. - */ - -package org.apache.commons.numbers.fraction; - -import java.text.MessageFormat; -import java.text.ParseException; - -/** - * Error thrown when a string cannot be parsed into a fraction. - */ -class FractionParseException extends ParseException { - - /** Serializable version identifier. */ - private static final long serialVersionUID = 201701181879L; - - /** - * Constructs an exception with specified formatted detail message. - * Message formatting is delegated to {@link MessageFormat}. - * @param source string being parsed - * @param position position of error - * @param type type of target object - */ - FractionParseException(String source, int position, Class type) { - super(MessageFormat.format("string \"{0}\" unparseable (from position {1}) as an object of type {2}", - source, position, type), - position); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/ProperBigFractionFormat.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/ProperBigFractionFormat.java deleted file mode 100644 index 7460d0e34..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/ProperBigFractionFormat.java +++ /dev/null @@ -1,233 +0,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. - */ -package org.apache.commons.numbers.fraction; - -import java.math.BigInteger; -import java.text.FieldPosition; -import java.text.NumberFormat; -import java.text.ParsePosition; - -/** - * Formats a BigFraction number in proper format. The number format for each of - * the whole number, numerator and, denominator can be configured. - *

- * Minus signs are only allowed in the whole number part - i.e., - * "-3 1/2" is legitimate and denotes -7/2, but "-3 -1/2" is invalid and - * will result in a ParseException.

- */ -public class ProperBigFractionFormat extends BigFractionFormat { - - /** Serializable version identifier */ - private static final long serialVersionUID = -6337346779577272307L; - - /** The format used for the whole number. */ - private NumberFormat wholeFormat; - - /** - * Create a proper formatting instance with the default number format for - * the whole, numerator, and denominator. - */ - public ProperBigFractionFormat() { - this(getDefaultNumberFormat()); - } - - /** - * Create a proper formatting instance with a custom number format for the - * whole, numerator, and denominator. - * @param format the custom format for the whole, numerator, and - * denominator. - */ - public ProperBigFractionFormat(final NumberFormat format) { - this(format, (NumberFormat)format.clone(), (NumberFormat)format.clone()); - } - - /** - * Create a proper formatting instance with a custom number format for each - * of the whole, numerator, and denominator. - * @param wholeFormat the custom format for the whole. - * @param numeratorFormat the custom format for the numerator. - * @param denominatorFormat the custom format for the denominator. - */ - public ProperBigFractionFormat(final NumberFormat wholeFormat, - final NumberFormat numeratorFormat, - final NumberFormat denominatorFormat) { - super(numeratorFormat, denominatorFormat); - setWholeFormat(wholeFormat); - } - - /** - * Formats a {@link BigFraction} object to produce a string. The BigFraction - * is output in proper format. - * - * @param fraction the object to format. - * @param toAppendTo where the text is to be appended - * @param pos On input: an alignment field, if desired. On output: the - * offsets of the alignment field - * @return the value passed in as toAppendTo. - */ - @Override - public StringBuffer format(final BigFraction fraction, - final StringBuffer toAppendTo, final FieldPosition pos) { - - pos.setBeginIndex(0); - pos.setEndIndex(0); - - BigInteger num = fraction.getNumerator(); - BigInteger den = fraction.getDenominator(); - BigInteger whole = num.divide(den); - num = num.remainder(den); - - if (!BigInteger.ZERO.equals(whole)) { - getWholeFormat().format(whole, toAppendTo, pos); - toAppendTo.append(' '); - if (num.compareTo(BigInteger.ZERO) < 0) { - num = num.negate(); - } - } - getNumeratorFormat().format(num, toAppendTo, pos); - toAppendTo.append(" / "); - getDenominatorFormat().format(den, toAppendTo, pos); - - return toAppendTo; - } - - /** - * Access the whole format. - * @return the whole format. - */ - public NumberFormat getWholeFormat() { - return wholeFormat; - } - - /** - * Parses a string to produce a {@link BigFraction} object. This method - * expects the string to be formatted as a proper BigFraction. - *

- * Minus signs are only allowed in the whole number part - i.e., - * "-3 1/2" is legitimate and denotes -7/2, but "-3 -1/2" is invalid and - * will result in a ParseException.

- * - * @param source the string to parse - * @param pos input/ouput parsing parameter. - * @return the parsed {@link BigFraction} object. - */ - @Override - public BigFraction parse(final String source, final ParsePosition pos) { - // try to parse improper BigFraction - BigFraction ret = super.parse(source, pos); - if (ret != null) { - return ret; - } - - final int initialIndex = pos.getIndex(); - - // parse whitespace - parseAndIgnoreWhitespace(source, pos); - - // parse whole - BigInteger whole = parseNextBigInteger(source, pos); - if (whole == null) { - // invalid integer number - // set index back to initial, error index should already be set - // character examined. - pos.setIndex(initialIndex); - return null; - } - - // parse whitespace - parseAndIgnoreWhitespace(source, pos); - - // parse numerator - BigInteger num = parseNextBigInteger(source, pos); - if (num == null) { - // invalid integer number - // set index back to initial, error index should already be set - // character examined. - pos.setIndex(initialIndex); - return null; - } - - if (num.compareTo(BigInteger.ZERO) < 0) { - // minus signs should be leading, invalid expression - pos.setIndex(initialIndex); - return null; - } - - // parse '/' - final int startIndex = pos.getIndex(); - final char c = parseNextCharacter(source, pos); - switch (c) { - case 0 : - // no '/' - // return num as a BigFraction - return new BigFraction(num); - case '/' : - // found '/', continue parsing denominator - break; - default : - // invalid '/' - // set index back to initial, error index should be the last - // character examined. - pos.setIndex(initialIndex); - pos.setErrorIndex(startIndex); - return null; - } - - // parse whitespace - parseAndIgnoreWhitespace(source, pos); - - // parse denominator - final BigInteger den = parseNextBigInteger(source, pos); - if (den == null) { - // invalid integer number - // set index back to initial, error index should already be set - // character examined. - pos.setIndex(initialIndex); - return null; - } - - if (den.compareTo(BigInteger.ZERO) < 0) { - // minus signs must be leading, invalid - pos.setIndex(initialIndex); - return null; - } - - boolean wholeIsNeg = whole.compareTo(BigInteger.ZERO) < 0; - if (wholeIsNeg) { - whole = whole.negate(); - } - num = whole.multiply(den).add(num); - if (wholeIsNeg) { - num = num.negate(); - } - - return new BigFraction(num, den); - - } - - /** - * Modify the whole format. - * @param format The new whole format value. - * @throws NullPointerException if {@code format} is {@code null}. - */ - public void setWholeFormat(final NumberFormat format) { - if (format == null) { - throw new NullPointerException("whole format"); - } - this.wholeFormat = format; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/ProperFractionFormat.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/ProperFractionFormat.java deleted file mode 100644 index bc857c9b3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/ProperFractionFormat.java +++ /dev/null @@ -1,225 +0,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. - */ -package org.apache.commons.numbers.fraction; - -import java.text.FieldPosition; -import java.text.NumberFormat; -import java.text.ParsePosition; - -/** - * Formats a Fraction number in proper format. The number format for each of - * the whole number, numerator and, denominator can be configured. - *

- * Minus signs are only allowed in the whole number part - i.e., - * "-3 1/2" is legitimate and denotes -7/2, but "-3 -1/2" is invalid and - * will result in a ParseException.

- */ -public class ProperFractionFormat extends FractionFormat { - - /** Serializable version identifier */ - private static final long serialVersionUID = 760934726031766749L; - - /** The format used for the whole number. */ - private NumberFormat wholeFormat; - - /** - * Create a proper formatting instance with the default number format for - * the whole, numerator, and denominator. - */ - public ProperFractionFormat() { - this(getDefaultNumberFormat()); - } - - /** - * Create a proper formatting instance with a custom number format for the - * whole, numerator, and denominator. - * @param format the custom format for the whole, numerator, and - * denominator. - */ - public ProperFractionFormat(NumberFormat format) { - this(format, (NumberFormat)format.clone(), (NumberFormat)format.clone()); - } - - /** - * Create a proper formatting instance with a custom number format for each - * of the whole, numerator, and denominator. - * @param wholeFormat the custom format for the whole. - * @param numeratorFormat the custom format for the numerator. - * @param denominatorFormat the custom format for the denominator. - */ - public ProperFractionFormat(NumberFormat wholeFormat, - NumberFormat numeratorFormat, - NumberFormat denominatorFormat) - { - super(numeratorFormat, denominatorFormat); - setWholeFormat(wholeFormat); - } - - /** - * Formats a {@link Fraction} object to produce a string. The fraction - * is output in proper format. - * - * @param fraction the object to format. - * @param toAppendTo where the text is to be appended - * @param pos On input: an alignment field, if desired. On output: the - * offsets of the alignment field - * @return the value passed in as toAppendTo. - */ - @Override - public StringBuffer format(Fraction fraction, StringBuffer toAppendTo, - FieldPosition pos) { - - pos.setBeginIndex(0); - pos.setEndIndex(0); - - int num = fraction.getNumerator(); - int den = fraction.getDenominator(); - int whole = num / den; - num %= den; - - if (whole != 0) { - getWholeFormat().format(whole, toAppendTo, pos); - toAppendTo.append(' '); - num = Math.abs(num); - } - getNumeratorFormat().format(num, toAppendTo, pos); - toAppendTo.append(" / "); - getDenominatorFormat().format(den, toAppendTo, pos); - - return toAppendTo; - } - - /** - * Access the whole format. - * @return the whole format. - */ - public NumberFormat getWholeFormat() { - return wholeFormat; - } - - /** - * Parses a string to produce a {@link Fraction} object. This method - * expects the string to be formatted as a proper fraction. - *

- * Minus signs are only allowed in the whole number part - i.e., - * "-3 1/2" is legitimate and denotes -7/2, but "-3 -1/2" is invalid and - * will result in a ParseException.

- * - * @param source the string to parse - * @param pos input/ouput parsing parameter. - * @return the parsed {@link Fraction} object. - */ - @Override - public Fraction parse(String source, ParsePosition pos) { - // try to parse improper fraction - Fraction ret = super.parse(source, pos); - if (ret != null) { - return ret; - } - - int initialIndex = pos.getIndex(); - - // parse whitespace - parseAndIgnoreWhitespace(source, pos); - - // parse whole - Number whole = getWholeFormat().parse(source, pos); - if (whole == null) { - // invalid integer number - // set index back to initial, error index should already be set - // character examined. - pos.setIndex(initialIndex); - return null; - } - - // parse whitespace - parseAndIgnoreWhitespace(source, pos); - - // parse numerator - Number num = getNumeratorFormat().parse(source, pos); - if (num == null) { - // invalid integer number - // set index back to initial, error index should already be set - // character examined. - pos.setIndex(initialIndex); - return null; - } - - if (num.intValue() < 0) { - // minus signs should be leading, invalid expression - pos.setIndex(initialIndex); - return null; - } - - // parse '/' - int startIndex = pos.getIndex(); - char c = parseNextCharacter(source, pos); - switch (c) { - case 0 : - // no '/' - // return num as a fraction - return new Fraction(num.intValue(), 1); - case '/' : - // found '/', continue parsing denominator - break; - default : - // invalid '/' - // set index back to initial, error index should be the last - // character examined. - pos.setIndex(initialIndex); - pos.setErrorIndex(startIndex); - return null; - } - - // parse whitespace - parseAndIgnoreWhitespace(source, pos); - - // parse denominator - Number den = getDenominatorFormat().parse(source, pos); - if (den == null) { - // invalid integer number - // set index back to initial, error index should already be set - // character examined. - pos.setIndex(initialIndex); - return null; - } - - if (den.intValue() < 0) { - // minus signs must be leading, invalid - pos.setIndex(initialIndex); - return null; - } - - int w = whole.intValue(); - int sign = w >= 0 ? 1 : -1; - int n = num.intValue(); - int d = den.intValue(); - return new Fraction(((Math.abs(w) * d) + n) * sign, d); - } - - /** - * Modify the whole format. - * @param format The new whole format value. - * @throws NullPointerException if {@code format} is {@code null}. - */ - public void setWholeFormat(NumberFormat format) { - if (format == null) { - throw new NullPointerException("whole format"); - } - this.wholeFormat = format; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/package-info.java deleted file mode 100644 index 94bf7848f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/fraction/package-info.java +++ /dev/null @@ -1,22 +0,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. - */ -/** - * - * Fraction number type and fraction number formatting. - * - */ -package org.apache.commons.numbers.fraction; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/Digamma.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/Digamma.java deleted file mode 100644 index 24d329ef2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/Digamma.java +++ /dev/null @@ -1,92 +0,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. - */ -package org.apache.commons.numbers.gamma; - -/** - * Digamma function. - *

- * It is defined as the logarithmic derivative of the \( \Gamma \) - * ({@link Gamma}) function: - * \( \frac{d}{dx}(\ln \Gamma(x)) = \frac{\Gamma^\prime(x)}{\Gamma(x)} \). - *

- * - * @see Gamma - */ -public class Digamma { - /** Euler-Mascheroni constant. */ - private static final double GAMMA = 0.577215664901532860606512090082; - /** C limit. */ - private static final double C_LIMIT = 49; - /** S limit. */ - private static final double S_LIMIT = 1e-5; - /** Fraction. */ - private static final double F_M1_12 = -1d / 12; - /** Fraction. */ - private static final double F_1_120 = 1d / 120; - /** Fraction. */ - private static final double F_M1_252 = -1d / 252; - - /** - * Computes the digamma function. - * - * This is an independently written implementation of the algorithm described in - * Jose Bernardo, - * Algorithm AS 103: Psi (Digamma) Function, Applied Statistics, 1976. - * A - * reflection formula is incorporated to improve performance on negative values. - * - * Some of the constants have been changed to increase accuracy at the moderate - * expense of run-time. The result should be accurate to within {@code 1e-8}. - * relative tolerance for {@code 0 < x < 1e-5} and within {@code 1e-8} absolute - * tolerance otherwise. - * - * @param x Argument. - * @return digamma(x) to within {@code 1e-8} relative or absolute error whichever - * is larger. - */ - public static double value(double x) { - if (Double.isNaN(x) || Double.isInfinite(x)) { - return x; - } - - double digamma = 0; - if (x < 0) { - // Use reflection formula to fall back into positive values. - digamma -= Math.PI / Math.tan(Math.PI * x); - x = 1 - x; - } - - if (x > 0 && x <= S_LIMIT) { - // Use method 5 from Bernardo AS103, accurate to O(x). - return digamma - GAMMA - 1 / x; - } - - while (x < C_LIMIT) { - digamma -= 1 / x; - x += 1; - } - - // Use method 4, accurate to O(1/x^8) - final double inv = 1 / (x * x); - // 1 1 1 1 - // log(x) - --- - ------ + ------- - ------- - // 2 x 12 x^2 120 x^4 252 x^6 - digamma += Math.log(x) - 0.5 / x + inv * (F_M1_12 + inv * (F_1_120 + F_M1_252 * inv)); - - return digamma; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/Erf.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/Erf.java deleted file mode 100644 index 5bef7d8df..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/Erf.java +++ /dev/null @@ -1,50 +0,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. - */ -package org.apache.commons.numbers.gamma; - -/** - * Error function. - */ -public class Erf { - /** - *

- * This implementation computes erf(x) using the - * {@link RegularizedGamma.P#value(double, double, double, int) regularized gamma function}, - * following Erf, equation (3) - *

- * - *

- * The returned value is always between -1 and 1 (inclusive). - * If {@code abs(x) > 40}, then {@code Erf.value(x)} is indistinguishable from - * either 1 or -1 at {@code double} precision, so the appropriate extreme value - * is returned. - *

- * - * @param x the value. - * @return the error function. - * @throws ArithmeticException if the algorithm fails to converge. - * - * @see RegularizedGamma.P#value(double, double, double, int) - */ - public static double value(double x) { - if (Math.abs(x) > 40) { - return x > 0 ? 1 : -1; - } - final double ret = RegularizedGamma.P.value(0.5, x * x, 1e-15, 10000); - return x < 0 ? -ret : ret; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/ErfDifference.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/ErfDifference.java deleted file mode 100644 index 31e1f59ae..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/ErfDifference.java +++ /dev/null @@ -1,65 +0,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. - */ -package org.apache.commons.numbers.gamma; - -/** - * Computes the difference between {@link Erf error function values}. - */ -public class ErfDifference { - /** - * This number solves {@code erf(x) = 0.5} within 1 ulp. - * More precisely, the current implementations of - * {@link Erf#value(double)} and {@link Erfc#value(double)} satisfy: - *
    - *
  • {@code Erf.value(X_CRIT) < 0.5},
  • - *
  • {@code Erf.value(Math.nextUp(X_CRIT) > 0.5},
  • - *
  • {@code Erfc.value(X_CRIT) = 0.5}, and
  • - *
  • {@code Erfc.value(Math.nextUp(X_CRIT) < 0.5}
  • - *
- */ - private static final double X_CRIT = 0.4769362762044697; - - /** - * The implementation uses either {@link Erf} or {@link Erfc}, - * depending on which provides the most precise result. - * - * @param x1 First value. - * @param x2 Second value. - * @return {@link Erf#value(double) Erf.value(x2) - Erf.value(x1)}. - */ - public static double value(double x1, - double x2) { - if (x1 > x2) { - return -value(x2, x1); - } else { - if (x1 < -X_CRIT) { - if (x2 < 0) { - return Erfc.value(-x2) - Erfc.value(-x1); - } else { - return Erf.value(x2) - Erf.value(x1); - } - } else { - if (x2 > X_CRIT && - x1 > 0) { - return Erfc.value(x1) - Erfc.value(x2); - } else { - return Erf.value(x2) - Erf.value(x1); - } - } - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/Erfc.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/Erfc.java deleted file mode 100644 index 6eea0f9a0..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/Erfc.java +++ /dev/null @@ -1,53 +0,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. - */ -package org.apache.commons.numbers.gamma; - -/** - * Complementary error function. - */ -public class Erfc { - /** - *

- * This implementation computes erfc(x) using the - * {@link RegularizedGamma.Q#value(double, double, double, int) regularized gamma function}, - * following Erf, equation (3). - *

- * - *

- * The value returned is always between 0 and 2 (inclusive). - * If {@code abs(x) > 40}, then {@code erf(x)} is indistinguishable from - * either 0 or 2 at {@code double} precision, so the appropriate extreme - * value is returned. - *

- * - * @param x Value. - * @return the complementary error function. - * @throws ArithmeticException if the algorithm fails to converge. - * - * @see RegularizedGamma.Q#value(double, double, double, int) - */ - public static double value(double x) { - if (Math.abs(x) > 40) { - return x > 0 ? 0 : 2; - } - final double ret = RegularizedGamma.Q.value(0.5, x * x, 1e-15, 10000); - return x < 0 ? - 2 - ret : - ret; - } -} - diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/Gamma.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/Gamma.java deleted file mode 100644 index 3fbb838e1..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/Gamma.java +++ /dev/null @@ -1,106 +0,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. - */ -package org.apache.commons.numbers.gamma; - - -/** - * Gamma - * function. - *

- * The gamma - * function can be seen to extend the factorial function to cover real and - * complex numbers, but with its argument shifted by {@code -1}. This - * implementation supports real numbers. - *

- *

- * This class is immutable. - *

- */ -public class Gamma { - /** √(2π). */ - private static final double SQRT_TWO_PI = 2.506628274631000502; - - /** - * Computes the value of \( \Gamma(x) \). - *

- * Based on the NSWC Library of Mathematics Subroutines double - * precision implementation, {@code DGAMMA}. - * - * @param x Argument. - * @return \( \Gamma(x) \) - */ - public static double value(final double x) { - - if ((x == Math.rint(x)) && (x <= 0.0)) { - return Double.NaN; - } - - final double absX = Math.abs(x); - if (absX <= 20) { - if (x >= 1) { - /* - * From the recurrence relation - * Gamma(x) = (x - 1) * ... * (x - n) * Gamma(x - n), - * then - * Gamma(t) = 1 / [1 + InvGamma1pm1.value(t - 1)], - * where t = x - n. This means that t must satisfy - * -0.5 <= t - 1 <= 1.5. - */ - double prod = 1; - double t = x; - while (t > 2.5) { - t -= 1; - prod *= t; - } - return prod / (1 + InvGamma1pm1.value(t - 1)); - } else { - /* - * From the recurrence relation - * Gamma(x) = Gamma(x + n + 1) / [x * (x + 1) * ... * (x + n)] - * then - * Gamma(x + n + 1) = 1 / [1 + InvGamma1pm1.value(x + n)], - * which requires -0.5 <= x + n <= 1.5. - */ - double prod = x; - double t = x; - while (t < -0.5) { - t += 1; - prod *= t; - } - return 1 / (prod * (1 + InvGamma1pm1.value(t))); - } - } else { - final double y = absX + LanczosApproximation.g() + 0.5; - final double gammaAbs = SQRT_TWO_PI / absX * - Math.pow(y, absX + 0.5) * - Math.exp(-y) * LanczosApproximation.value(absX); - if (x > 0) { - return gammaAbs; - } else { - /* - * From the reflection formula - * Gamma(x) * Gamma(1 - x) * sin(pi * x) = pi, - * and the recurrence relation - * Gamma(1 - x) = -x * Gamma(-x), - * it is found - * Gamma(x) = -pi / [x * sin(pi * x) * Gamma(-x)]. - */ - return -Math.PI / (x * Math.sin(Math.PI * x) * gammaAbs); - } - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/GammaException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/GammaException.java deleted file mode 100644 index 7122f2eb7..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/GammaException.java +++ /dev/null @@ -1,52 +0,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. - */ -package org.apache.commons.numbers.gamma; - -import java.text.MessageFormat; - -/** - * Package private exception class with constants for frequently used messages. - */ -class GammaException extends IllegalArgumentException { - /** Error message for "out of range" condition. */ - static final String OUT_OF_RANGE = "Number {0} is out of range [{1}, {2}]"; - /** Error message for convergence failure. */ - static final String CONVERGENCE = "Failed to converge within {0} iterations"; - - /** Serializable version identifier. */ - private static final long serialVersionUID = 20170505L; - - /** Arguments for formatting the message. */ - protected Object[] formatArguments; - - /** - * Create an exception where the message is constructed by applying - * the {@code format()} method from {@code java.text.MessageFormat}. - * - * @param message the exception message with replaceable parameters - * @param formatArguments the arguments for formatting the message - */ - GammaException(String message, Object... formatArguments) { - super(message); - this.formatArguments = formatArguments; - } - - @Override - public String getMessage() { - return MessageFormat.format(super.getMessage(), formatArguments); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/InvGamma1pm1.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/InvGamma1pm1.java deleted file mode 100644 index ab1d77b2d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/InvGamma1pm1.java +++ /dev/null @@ -1,185 +0,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. - */ -package org.apache.commons.numbers.gamma; - -/** - * Function \( \frac{1}{\Gamma(1 + x)} - 1 \). - * - * Class is immutable. - */ -class InvGamma1pm1 { - /* - * Constants copied from DGAM1 in the NSWC library. - */ - /** The constant {@code A0} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_A0 = .611609510448141581788E-08; - /** The constant {@code A1} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_A1 = .624730830116465516210E-08; - /** The constant {@code B1} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_B1 = .203610414066806987300E+00; - /** The constant {@code B2} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_B2 = .266205348428949217746E-01; - /** The constant {@code B3} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_B3 = .493944979382446875238E-03; - /** The constant {@code B4} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_B4 = -.851419432440314906588E-05; - /** The constant {@code B5} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_B5 = -.643045481779353022248E-05; - /** The constant {@code B6} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_B6 = .992641840672773722196E-06; - /** The constant {@code B7} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_B7 = -.607761895722825260739E-07; - /** The constant {@code B8} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_B8 = .195755836614639731882E-09; - /** The constant {@code P0} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_P0 = .6116095104481415817861E-08; - /** The constant {@code P1} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_P1 = .6871674113067198736152E-08; - /** The constant {@code P2} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_P2 = .6820161668496170657918E-09; - /** The constant {@code P3} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_P3 = .4686843322948848031080E-10; - /** The constant {@code P4} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_P4 = .1572833027710446286995E-11; - /** The constant {@code P5} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_P5 = -.1249441572276366213222E-12; - /** The constant {@code P6} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_P6 = .4343529937408594255178E-14; - /** The constant {@code Q1} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_Q1 = .3056961078365221025009E+00; - /** The constant {@code Q2} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_Q2 = .5464213086042296536016E-01; - /** The constant {@code Q3} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_Q3 = .4956830093825887312020E-02; - /** The constant {@code Q4} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_Q4 = .2692369466186361192876E-03; - /** The constant {@code C} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_C = -.422784335098467139393487909917598E+00; - /** The constant {@code C0} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_C0 = .577215664901532860606512090082402E+00; - /** The constant {@code C1} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_C1 = -.655878071520253881077019515145390E+00; - /** The constant {@code C2} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_C2 = -.420026350340952355290039348754298E-01; - /** The constant {@code C3} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_C3 = .166538611382291489501700795102105E+00; - /** The constant {@code C4} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_C4 = -.421977345555443367482083012891874E-01; - /** The constant {@code C5} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_C5 = -.962197152787697356211492167234820E-02; - /** The constant {@code C6} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_C6 = .721894324666309954239501034044657E-02; - /** The constant {@code C7} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_C7 = -.116516759185906511211397108401839E-02; - /** The constant {@code C8} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_C8 = -.215241674114950972815729963053648E-03; - /** The constant {@code C9} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_C9 = .128050282388116186153198626328164E-03; - /** The constant {@code C10} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_C10 = -.201348547807882386556893914210218E-04; - /** The constant {@code C11} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_C11 = -.125049348214267065734535947383309E-05; - /** The constant {@code C12} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_C12 = .113302723198169588237412962033074E-05; - /** The constant {@code C13} defined in {@code DGAM1}. */ - private static final double INV_GAMMA1P_M1_C13 = -.205633841697760710345015413002057E-06; - - /** - * Computes the function \( \frac{1}{\Gamma(1 + x)} - 1 \) for {@code -0.5 <= x <= 1.5}. - * - * This implementation is based on the double precision implementation in - * the NSWC Library of Mathematics Subroutines, {@code DGAM1}. - * - * @param x Argument. - * @return \( \frac{1}{\Gamma(1 + x)} - 1 \) - * @throws IllegalArgumentException if {@code x < -0.5} or {@code x > 1.5} - */ - public static double value(final double x) { - if (x < -0.5 || x > 1.5) { - throw new GammaException(GammaException.OUT_OF_RANGE, x, -0.5, 1.5); - } - - final double t = x <= 0.5 ? x : (x - 0.5) - 0.5; - if (t < 0) { - final double a = INV_GAMMA1P_M1_A0 + t * INV_GAMMA1P_M1_A1; - double b = INV_GAMMA1P_M1_B8; - b = INV_GAMMA1P_M1_B7 + t * b; - b = INV_GAMMA1P_M1_B6 + t * b; - b = INV_GAMMA1P_M1_B5 + t * b; - b = INV_GAMMA1P_M1_B4 + t * b; - b = INV_GAMMA1P_M1_B3 + t * b; - b = INV_GAMMA1P_M1_B2 + t * b; - b = INV_GAMMA1P_M1_B1 + t * b; - b = 1.0 + t * b; - - double c = INV_GAMMA1P_M1_C13 + t * (a / b); - c = INV_GAMMA1P_M1_C12 + t * c; - c = INV_GAMMA1P_M1_C11 + t * c; - c = INV_GAMMA1P_M1_C10 + t * c; - c = INV_GAMMA1P_M1_C9 + t * c; - c = INV_GAMMA1P_M1_C8 + t * c; - c = INV_GAMMA1P_M1_C7 + t * c; - c = INV_GAMMA1P_M1_C6 + t * c; - c = INV_GAMMA1P_M1_C5 + t * c; - c = INV_GAMMA1P_M1_C4 + t * c; - c = INV_GAMMA1P_M1_C3 + t * c; - c = INV_GAMMA1P_M1_C2 + t * c; - c = INV_GAMMA1P_M1_C1 + t * c; - c = INV_GAMMA1P_M1_C + t * c; - if (x > 0.5) { - return t * c / x; - } else { - return x * ((c + 0.5) + 0.5); - } - } else { - double p = INV_GAMMA1P_M1_P6; - p = INV_GAMMA1P_M1_P5 + t * p; - p = INV_GAMMA1P_M1_P4 + t * p; - p = INV_GAMMA1P_M1_P3 + t * p; - p = INV_GAMMA1P_M1_P2 + t * p; - p = INV_GAMMA1P_M1_P1 + t * p; - p = INV_GAMMA1P_M1_P0 + t * p; - - double q = INV_GAMMA1P_M1_Q4; - q = INV_GAMMA1P_M1_Q3 + t * q; - q = INV_GAMMA1P_M1_Q2 + t * q; - q = INV_GAMMA1P_M1_Q1 + t * q; - q = 1.0 + t * q; - - double c = INV_GAMMA1P_M1_C13 + (p / q) * t; - c = INV_GAMMA1P_M1_C12 + t * c; - c = INV_GAMMA1P_M1_C11 + t * c; - c = INV_GAMMA1P_M1_C10 + t * c; - c = INV_GAMMA1P_M1_C9 + t * c; - c = INV_GAMMA1P_M1_C8 + t * c; - c = INV_GAMMA1P_M1_C7 + t * c; - c = INV_GAMMA1P_M1_C6 + t * c; - c = INV_GAMMA1P_M1_C5 + t * c; - c = INV_GAMMA1P_M1_C4 + t * c; - c = INV_GAMMA1P_M1_C3 + t * c; - c = INV_GAMMA1P_M1_C2 + t * c; - c = INV_GAMMA1P_M1_C1 + t * c; - c = INV_GAMMA1P_M1_C0 + t * c; - - if (x > 0.5) { - return (t / x) * ((c - 0.5) - 0.5); - } else { - return x * c; - } - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/InverseErf.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/InverseErf.java deleted file mode 100644 index b149fa5f8..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/InverseErf.java +++ /dev/null @@ -1,124 +0,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. - */ -package org.apache.commons.numbers.gamma; - -/** - * Inverse of the error function. - *

- * This implementation is described in the paper: - * Approximating - * the erfinv function by Mike Giles, Oxford-Man Institute of Quantitative Finance, - * which was published in GPU Computing Gems, volume 2, 2010. - * The source code is available here. - *

- */ -public class InverseErf { - /** - * Returns the inverse error function. - * - * @param x Value. - * @return t such that {@code x =} {@link Erf#value(double) Erf.value(t)}. - */ - public static double value(final double x) { - // Beware that the logarithm argument must be - // commputed as (1 - x) * (1 + x), - // it must NOT be simplified as 1 - x * x as this - // would induce rounding errors near the boundaries +/-1 - double w = -Math.log((1 - x) * (1 + x)); - double p; - - if (w < 6.25) { - w -= 3.125; - p = -3.6444120640178196996e-21; - p = -1.685059138182016589e-19 + p * w; - p = 1.2858480715256400167e-18 + p * w; - p = 1.115787767802518096e-17 + p * w; - p = -1.333171662854620906e-16 + p * w; - p = 2.0972767875968561637e-17 + p * w; - p = 6.6376381343583238325e-15 + p * w; - p = -4.0545662729752068639e-14 + p * w; - p = -8.1519341976054721522e-14 + p * w; - p = 2.6335093153082322977e-12 + p * w; - p = -1.2975133253453532498e-11 + p * w; - p = -5.4154120542946279317e-11 + p * w; - p = 1.051212273321532285e-09 + p * w; - p = -4.1126339803469836976e-09 + p * w; - p = -2.9070369957882005086e-08 + p * w; - p = 4.2347877827932403518e-07 + p * w; - p = -1.3654692000834678645e-06 + p * w; - p = -1.3882523362786468719e-05 + p * w; - p = 0.0001867342080340571352 + p * w; - p = -0.00074070253416626697512 + p * w; - p = -0.0060336708714301490533 + p * w; - p = 0.24015818242558961693 + p * w; - p = 1.6536545626831027356 + p * w; - } else if (w < 16.0) { - w = Math.sqrt(w) - 3.25; - p = 2.2137376921775787049e-09; - p = 9.0756561938885390979e-08 + p * w; - p = -2.7517406297064545428e-07 + p * w; - p = 1.8239629214389227755e-08 + p * w; - p = 1.5027403968909827627e-06 + p * w; - p = -4.013867526981545969e-06 + p * w; - p = 2.9234449089955446044e-06 + p * w; - p = 1.2475304481671778723e-05 + p * w; - p = -4.7318229009055733981e-05 + p * w; - p = 6.8284851459573175448e-05 + p * w; - p = 2.4031110387097893999e-05 + p * w; - p = -0.0003550375203628474796 + p * w; - p = 0.00095328937973738049703 + p * w; - p = -0.0016882755560235047313 + p * w; - p = 0.0024914420961078508066 + p * w; - p = -0.0037512085075692412107 + p * w; - p = 0.005370914553590063617 + p * w; - p = 1.0052589676941592334 + p * w; - p = 3.0838856104922207635 + p * w; - } else if (!Double.isInfinite(w)) { - w = Math.sqrt(w) - 5; - p = -2.7109920616438573243e-11; - p = -2.5556418169965252055e-10 + p * w; - p = 1.5076572693500548083e-09 + p * w; - p = -3.7894654401267369937e-09 + p * w; - p = 7.6157012080783393804e-09 + p * w; - p = -1.4960026627149240478e-08 + p * w; - p = 2.9147953450901080826e-08 + p * w; - p = -6.7711997758452339498e-08 + p * w; - p = 2.2900482228026654717e-07 + p * w; - p = -9.9298272942317002539e-07 + p * w; - p = 4.5260625972231537039e-06 + p * w; - p = -1.9681778105531670567e-05 + p * w; - p = 7.5995277030017761139e-05 + p * w; - p = -0.00021503011930044477347 + p * w; - p = -0.00013871931833623122026 + p * w; - p = 1.0103004648645343977 + p * w; - p = 4.8499064014085844221 + p * w; - } else { - // this branch does not appears in the original code, it - // was added because the previous branch does not handle - // x = +/-1 correctly. In this case, w is positive infinity - // and as the first coefficient (-2.71e-11) is negative. - // Once the first multiplication is done, p becomes negative - // infinity and remains so throughout the polynomial evaluation. - // So the branch above incorrectly returns negative infinity - // instead of the correct positive infinity. - p = Double.POSITIVE_INFINITY; - } - - return p * x; - } -} - diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/InverseErfc.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/InverseErfc.java deleted file mode 100644 index e1a435967..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/InverseErfc.java +++ /dev/null @@ -1,39 +0,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. - */ -package org.apache.commons.numbers.gamma; - -/** - * Inverse of the complementary error function. - *

- * This implementation is described in the paper: - * Approximating - * the erfinv function by Mike Giles, Oxford-Man Institute of Quantitative Finance, - * which was published in GPU Computing Gems, volume 2, 2010. - * The source code is available here. - *

- */ -public class InverseErfc { - /** - * Returns the inverse complementary error function. - * - * @param x Value. - * @return t such that {@code x =} {@link Erfc#value(double) Erfc.value(t)}. - */ - public static double value(double x) { - return InverseErf.value(1 - x); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/LanczosApproximation.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/LanczosApproximation.java deleted file mode 100644 index e95c83150..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/LanczosApproximation.java +++ /dev/null @@ -1,76 +0,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. - */ -package org.apache.commons.numbers.gamma; - -/** - * - * Lanczos approximation to the Gamma function. - * - * It is related to the Gamma function by the following equation - * \[ - * \Gamma(x) = \sqrt{2\pi} \, \frac{(g + x + \frac{1}{2})^{x + \frac{1}{2}} \, e^{-(g + x + \frac{1}{2})} \, \mathrm{lanczos}(x)} - * {x} - * \] - * where \( g \) is the Lanczos constant. - * - * See equations (1) through (5), and Paul Godfrey's - * Note on the computation - * of the convergent Lanczos complex Gamma approximation. - */ -public class LanczosApproximation { - /** \( g = \frac{607}{128} \). */ - private static final double LANCZOS_G = 607d / 128d; - /** Lanczos coefficients. */ - private static final double[] LANCZOS = { - 0.99999999999999709182, - 57.156235665862923517, - -59.597960355475491248, - 14.136097974741747174, - -0.49191381609762019978, - .33994649984811888699e-4, - .46523628927048575665e-4, - -.98374475304879564677e-4, - .15808870322491248884e-3, - -.21026444172410488319e-3, - .21743961811521264320e-3, - -.16431810653676389022e-3, - .84418223983852743293e-4, - -.26190838401581408670e-4, - .36899182659531622704e-5, - }; - - /** - * Computes the Lanczos approximation. - * - * @param x Argument. - * @return the Lanczos approximation. - */ - public static double value(final double x) { - double sum = 0; - for (int i = LANCZOS.length - 1; i > 0; i--) { - sum += LANCZOS[i] / (x + i); - } - return sum + LANCZOS[0]; - } - - /** - * @return the Lanczos constant \( g = \frac{607}{128} \). - */ - public static double g() { - return LANCZOS_G; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/LogBeta.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/LogBeta.java deleted file mode 100644 index d282a4d54..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/LogBeta.java +++ /dev/null @@ -1,287 +0,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. - */ -package org.apache.commons.numbers.gamma; - -/** - * Computes \( log_e \Beta(p, q) \). - *

- * This class is immutable. - *

- */ -public class LogBeta { - /** The constant value of ½log 2π. */ - private static final double HALF_LOG_TWO_PI = 0.9189385332046727; - - /** - *

- * The coefficients of the series expansion of the Δ function. This function - * is defined as follows - *

- * Δ(x) = log Γ(x) - (x - 0.5) log a + a - 0.5 log 2π, - *

- * see equation (23) in Didonato and Morris (1992). The series expansion, - * which applies for x ≥ 10, reads - *

- *
-     *                 14
-     *                ====
-     *             1  \                2 n
-     *     Δ(x) = ---  >    d  (10 / x)
-     *             x  /      n
-     *                ====
-     *                n = 0
-     * 
-     */
-    private static final double[] DELTA = {
-        .833333333333333333333333333333E-01,
-        -.277777777777777777777777752282E-04,
-        .793650793650793650791732130419E-07,
-        -.595238095238095232389839236182E-09,
-        .841750841750832853294451671990E-11,
-        -.191752691751854612334149171243E-12,
-        .641025640510325475730918472625E-14,
-        -.295506514125338232839867823991E-15,
-        .179643716359402238723287696452E-16,
-        -.139228964661627791231203060395E-17,
-        .133802855014020915603275339093E-18,
-        -.154246009867966094273710216533E-19,
-        .197701992980957427278370133333E-20,
-        -.234065664793997056856992426667E-21,
-        .171348014966398575409015466667E-22
-    };
-
-    /**
-     * Returns the value of Δ(b) - Δ(a + b), with 0 ≤ a ≤ b and b ≥ 10. Based
-     * on equations (26), (27) and (28) in Didonato and Morris (1992).
-     *
-     * @param a First argument.
-     * @param b Second argument.
-     * @return the value of {@code Delta(b) - Delta(a + b)}
-     * @throws IllegalArgumentException if {@code a < 0} or {@code a > b}
-     * @throws IllegalArgumentException if {@code b < 10}
-     */
-    private static double deltaMinusDeltaSum(final double a,
-                                             final double b) {
-        if (a < 0 ||
-            a > b) {
-            throw new GammaException(GammaException.OUT_OF_RANGE, a, 0, b);
-        }
-        if (b < 10) {
-            throw new GammaException(GammaException.OUT_OF_RANGE, b, 10, Double.POSITIVE_INFINITY);
-        }
-
-        final double h = a / b;
-        final double p = h / (1 + h);
-        final double q = 1 / (1 + h);
-        final double q2 = q * q;
-        /*
-         * s[i] = 1 + q + ... - q**(2 * i)
-         */
-        final double[] s = new double[DELTA.length];
-        s[0] = 1;
-        for (int i = 1; i < s.length; i++) {
-            s[i] = 1 + (q + q2 * s[i - 1]);
-        }
-        /*
-         * w = Delta(b) - Delta(a + b)
-         */
-        final double sqrtT = 10 / b;
-        final double t = sqrtT * sqrtT;
-        double w = DELTA[DELTA.length - 1] * s[s.length - 1];
-        for (int i = DELTA.length - 2; i >= 0; i--) {
-            w = t * w + DELTA[i] * s[i];
-        }
-        return w * p / b;
-    }
-
-    /**
-     * Returns the value of Δ(p) + Δ(q) - Δ(p + q), with p, q ≥ 10.
-     * Based on the NSWC Library of Mathematics Subroutines implementation,
-     * {@code DBCORR}.
-     *
-     * @param p First argument.
-     * @param q Second argument.
-     * @return the value of {@code Delta(p) + Delta(q) - Delta(p + q)}.
-     * @throws IllegalArgumentException if {@code p < 10} or {@code q < 10}.
-     */
-    private static double sumDeltaMinusDeltaSum(final double p,
-                                                final double q) {
-
-        if (p < 10) {
-            throw new GammaException(GammaException.OUT_OF_RANGE, p, 10, Double.POSITIVE_INFINITY);
-        }
-        if (q < 10) {
-            throw new GammaException(GammaException.OUT_OF_RANGE, q, 10, Double.POSITIVE_INFINITY);
-        }
-
-        final double a = Math.min(p, q);
-        final double b = Math.max(p, q);
-        final double sqrtT = 10 / a;
-        final double t = sqrtT * sqrtT;
-        double z = DELTA[DELTA.length - 1];
-        for (int i = DELTA.length - 2; i >= 0; i--) {
-            z = t * z + DELTA[i];
-        }
-        return z / a + deltaMinusDeltaSum(a, b);
-    }
-
-    /**
-     * Returns the value of {@code log B(p, q)} for {@code 0 ≤ x ≤ 1} and {@code p, q > 0}.
-     * Based on the NSWC Library of Mathematics Subroutines implementation,
-     * {@code DBETLN}.
-     *
-     * @param p First argument.
-     * @param q Second argument.
-     * @return the value of {@code log(Beta(p, q))}, {@code NaN} if
-     * {@code p <= 0} or {@code q <= 0}.
-     */
-    public static double value(double p,
-                               double q) {
-        if (Double.isNaN(p) ||
-            Double.isNaN(q) ||
-            p <= 0 ||
-            q <= 0) {
-            return Double.NaN;
-        }
-
-        final double a = Math.min(p, q);
-        final double b = Math.max(p, q);
-        if (a >= 10) {
-            final double w = sumDeltaMinusDeltaSum(a, b);
-            final double h = a / b;
-            final double c = h / (1 + h);
-            final double u = -(a - 0.5) * Math.log(c);
-            final double v = b * Math.log1p(h);
-            if (u <= v) {
-                return (((-0.5 * Math.log(b) + HALF_LOG_TWO_PI) + w) - u) - v;
-            } else {
-                return (((-0.5 * Math.log(b) + HALF_LOG_TWO_PI) + w) - v) - u;
-            }
-        } else if (a > 2) {
-            if (b > 1000) {
-                final int n = (int) Math.floor(a - 1);
-                double prod = 1;
-                double ared = a;
-                for (int i = 0; i < n; i++) {
-                    ared -= 1;
-                    prod *= ared / (1 + ared / b);
-                }
-                return (Math.log(prod) - n * Math.log(b)) +
-                        (LogGamma.value(ared) +
-                         logGammaMinusLogGammaSum(ared, b));
-            } else {
-                double prod1 = 1;
-                double ared = a;
-                while (ared > 2) {
-                    ared -= 1;
-                    final double h = ared / b;
-                    prod1 *= h / (1 + h);
-                }
-                if (b < 10) {
-                    double prod2 = 1;
-                    double bred = b;
-                    while (bred > 2) {
-                        bred -= 1;
-                        prod2 *= bred / (ared + bred);
-                    }
-                    return Math.log(prod1) +
-                           Math.log(prod2) +
-                           (LogGamma.value(ared) +
-                           (LogGamma.value(bred) -
-                            LogGammaSum.value(ared, bred)));
-                } else {
-                    return Math.log(prod1) +
-                           LogGamma.value(ared) +
-                           logGammaMinusLogGammaSum(ared, b);
-                }
-            }
-        } else if (a >= 1) {
-            if (b > 2) {
-                if (b < 10) {
-                    double prod = 1;
-                    double bred = b;
-                    while (bred > 2) {
-                        bred -= 1;
-                        prod *= bred / (a + bred);
-                    }
-                    return Math.log(prod) +
-                           (LogGamma.value(a) +
-                            (LogGamma.value(bred) -
-                             LogGammaSum.value(a, bred)));
-                } else {
-                    return LogGamma.value(a) +
-                        logGammaMinusLogGammaSum(a, b);
-                }
-            } else {
-                return LogGamma.value(a) +
-                       LogGamma.value(b) -
-                       LogGammaSum.value(a, b);
-            }
-        } else {
-            if (b >= 10) {
-                return LogGamma.value(a) +
-                       logGammaMinusLogGammaSum(a, b);
-            } else {
-                // The original NSWC implementation was
-                //   LogGamma.value(a) + (LogGamma.value(b) - LogGamma.value(a + b));
-                // but the following command turned out to be more accurate.
-                return Math.log(Gamma.value(a) * Gamma.value(b) /
-                                Gamma.value(a + b));
-            }
-        }
-    }
-
-    /**
-     * Returns the value of log[Γ(b) / Γ(a + b)] for a ≥ 0 and b ≥ 10.
-     * Based on the NSWC Library of Mathematics Subroutines implementation,
-     * {@code DLGDIV}.
-     *
-     * @param a First argument.
-     * @param b Second argument.
-     * @return the value of {@code log(Gamma(b) / Gamma(a + b))}.
-     * @throws IllegalArgumentException if {@code a < 0} or {@code b < 10}.
-     */
-    private static double logGammaMinusLogGammaSum(double a,
-                                                   double b) {
-        if (a < 0) {
-            throw new GammaException(GammaException.OUT_OF_RANGE, a, 0, Double.POSITIVE_INFINITY);
-        }
-        if (b < 10) {
-            throw new GammaException(GammaException.OUT_OF_RANGE, b, 10, Double.POSITIVE_INFINITY);
-        }
-
-        /*
-         * d = a + b - 0.5
-         */
-        final double d;
-        final double w;
-        if (a <= b) {
-            d = b + (a - 0.5);
-            w = deltaMinusDeltaSum(a, b);
-        } else {
-            d = a + (b - 0.5);
-            w = deltaMinusDeltaSum(b, a);
-        }
-
-        final double u = d * Math.log1p(a / b);
-        final double v = a * (Math.log(b) - 1);
-
-        return u <= v ?
-            (w - u) - v :
-            (w - v) - u;
-    }
-}
diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/LogGamma.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/LogGamma.java
deleted file mode 100644
index f58a3bc9b..000000000
--- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/LogGamma.java
+++ /dev/null
@@ -1,70 +0,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.
- */
-package org.apache.commons.numbers.gamma;
-
-/**
- * Function \( \ln \Gamma(x) \).
- *
- * Class is immutable.
- */
-public class LogGamma {
-    /** Lanczos constant. */
-    private static final double LANCZOS_G = 607d / 128d;
-    /** Performance. */
-    private static final double HALF_LOG_2_PI = 0.5 * Math.log(2.0 * Math.PI);
-
-    /**
-     * Computes the function \( \ln \Gamma(x) \) for {@code x >= 0}.
-     *
-     * For {@code x <= 8}, the implementation is based on the double precision
-     * implementation in the NSWC Library of Mathematics Subroutines,
-     * {@code DGAMLN}. For {@code x >= 8}, the implementation is based on
-     * 
-     *
-     * @param x Argument.
-     * @return \( \ln \Gamma(x) \), or {@code NaN} if {@code x <= 0}.
-     */
-    public static double value(double x) {
-        if (Double.isNaN(x) || (x <= 0.0)) {
-            return Double.NaN;
-        } else if (x < 0.5) {
-            return LogGamma1p.value(x) - Math.log(x);
-        } else if (x <= 2.5) {
-            return LogGamma1p.value((x - 0.5) - 0.5);
-        } else if (x <= 8.0) {
-            final int n = (int) Math.floor(x - 1.5);
-            double prod = 1.0;
-            for (int i = 1; i <= n; i++) {
-                prod *= x - i;
-            }
-            return LogGamma1p.value(x - (n + 1)) + Math.log(prod);
-        } else {
-            final double sum = LanczosApproximation.value(x);
-            final double tmp = x + LANCZOS_G + .5;
-            return ((x + .5) * Math.log(tmp)) - tmp +
-                HALF_LOG_2_PI + Math.log(sum / x);
-        }
-    }
-}
diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/LogGamma1p.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/LogGamma1p.java
deleted file mode 100644
index 3a9753d3b..000000000
--- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/LogGamma1p.java
+++ /dev/null
@@ -1,42 +0,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.
- */
-package org.apache.commons.numbers.gamma;
-
-/**
- * Function \( \ln \Gamma(1 + x) \).
- *
- * Class is immutable.
- */
-class LogGamma1p {
-    /**
-     * Computes the function \( \ln \Gamma(1 + x) \) for \( -0.5 \leq x \leq 1.5 \).
-     *
-     * This implementation is based on the double precision implementation in
-     * the NSWC Library of Mathematics Subroutines, {@code DGMLN1}.
-     *
-     * @param x Argument.
-     * @return \( \ln \Gamma(1 + x) \)
-     * @throws IllegalArgumentException if {@code x < -0.5} or {@code x > 1.5}.
-     */
-    public static double value(final double x) {
-        if (x < -0.5 || x > 1.5) {
-            throw new GammaException(GammaException.OUT_OF_RANGE, x, -0.5, 1.5);
-        }
-
-        return -Math.log1p(InvGamma1pm1.value(x));
-    }
-}
diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/LogGammaSum.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/LogGammaSum.java
deleted file mode 100644
index 07405aaf0..000000000
--- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/LogGammaSum.java
+++ /dev/null
@@ -1,57 +0,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.
- */
-package org.apache.commons.numbers.gamma;
-
-/**
- * Computes \( \log_e(\Gamma(a+b)) \).
- * 

- * This class is immutable. - *

- */ -class LogGammaSum { - /** - * Computes the value of log Γ(a + b) for 1 ≤ a, b ≤ 2. - * Based on the NSWC Library of Mathematics Subroutines - * implementation, {@code DGSMLN}. - * - * @param a First argument. - * @param b Second argument. - * @return the value of {@code log(Gamma(a + b))}. - * @throws IllegalArgumentException if {@code a} or {@code b} is lower than 1 - * or larger than 2. - */ - static double value(double a, - double b) { - if (a < 1 || - a > 2) { - throw new GammaException(GammaException.OUT_OF_RANGE, a, 1, 2); - } - if (b < 1 || - b > 2) { - throw new GammaException(GammaException.OUT_OF_RANGE, b, 1, 2); - } - - final double x = (a - 1) + (b - 1); - if (x <= 0.5) { - return LogGamma1p.value(1 + x); - } else if (x <= 1.5) { - return LogGamma1p.value(x) + Math.log1p(x); - } else { - return LogGamma1p.value(x - 1) + Math.log(x * (1 + x)); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/RegularizedBeta.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/RegularizedBeta.java deleted file mode 100644 index f54effe75..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/RegularizedBeta.java +++ /dev/null @@ -1,121 +0,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. - */ -package org.apache.commons.numbers.gamma; - -import org.apache.commons.numbers.fraction.ContinuedFraction; - -/** - * - * Regularized Beta function. - *

- * This class is immutable. - *

- */ -public class RegularizedBeta { - /** Maximum allowed numerical error. */ - private static final double DEFAULT_EPSILON = 1e-14; - - /** - * Computes the value of the - * - * regularized beta function I(x, a, b). - * - * @param x Value. - * @param a Parameter {@code a}. - * @param b Parameter {@code b}. - * @return the regularized beta function I(x, a, b). - * @throws ArithmeticException if the algorithm fails to converge. - */ - public static double value(double x, - double a, - double b) { - return value(x, a, b, DEFAULT_EPSILON, Integer.MAX_VALUE); - } - - - /** - * Computes the value of the - * - * regularized beta function I(x, a, b). - * - * The implementation of this method is based on: - * - * - * @param x the value. - * @param a Parameter {@code a}. - * @param b Parameter {@code b}. - * @param epsilon When the absolute value of the nth item in the - * series is less than epsilon the approximation ceases to calculate - * further elements in the series. - * @param maxIterations Maximum number of "iterations" to complete. - * @return the regularized beta function I(x, a, b). - * @throws ArithmeticException if the algorithm fails to converge. - */ - public static double value(double x, - final double a, - final double b, - double epsilon, - int maxIterations) { - if (Double.isNaN(x) || - Double.isNaN(a) || - Double.isNaN(b) || - x < 0 || - x > 1 || - a <= 0 || - b <= 0) { - return Double.NaN; - } else if (x > (a + 1) / (2 + b + a) && - 1 - x <= (b + 1) / (2 + b + a)) { - return 1 - value(1 - x, b, a, epsilon, maxIterations); - } else { - final ContinuedFraction fraction = new ContinuedFraction() { - /** {@inheritDoc} */ - @Override - protected double getB(int n, double x) { - if (n % 2 == 0) { // even - final double m = n / 2d; - return (m * (b - m) * x) / - ((a + (2 * m) - 1) * (a + (2 * m))); - } else { - final double m = (n - 1d) / 2d; - return -((a + m) * (a + b + m) * x) / - ((a + (2 * m)) * (a + (2 * m) + 1)); - } - } - - /** {@inheritDoc} */ - @Override - protected double getA(int n, double x) { - return 1; - } - }; - - return Math.exp((a * Math.log(x)) + (b * Math.log1p(-x)) - - Math.log(a) - LogBeta.value(a, b)) / - fraction.evaluate(x, epsilon, maxIterations); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/RegularizedGamma.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/RegularizedGamma.java deleted file mode 100644 index abf5e51e8..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/RegularizedGamma.java +++ /dev/null @@ -1,190 +0,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. - */ -package org.apache.commons.numbers.gamma; - -import org.apache.commons.numbers.fraction.ContinuedFraction; - -/** - * - * Regularized Gamma functions. - * - * Class is immutable. - */ -public class RegularizedGamma { - /** Maximum allowed numerical error. */ - private static final double DEFAULT_EPSILON = 1e-15; - - /** - * \( P(a, x) \) - * regularized Gamma function. - * - * Class is immutable. - */ - public static class P { - /** - * Computes the regularized gamma function \( P(a, x) \). - * - * @param a Argument. - * @param x Argument. - * @return \( P(a, x) \). - */ - public static double value(double a, - double x) { - return value(a, x, DEFAULT_EPSILON, Integer.MAX_VALUE); - } - - /** - * Computes the regularized gamma function \( P(a, x) \). - * - * The implementation of this method is based on: - * - * - * @param a Argument. - * @param x Argument. - * @param epsilon Tolerance in continued fraction evaluation. - * @param maxIterations Maximum number of iterations in continued fraction evaluation. - * @return \( P(a, x) \). - */ - public static double value(double a, - double x, - double epsilon, - int maxIterations) { - if (Double.isNaN(a) || - Double.isNaN(x) || - a <= 0 || - x < 0) { - return Double.NaN; - } else if (x == 0) { - return 0; - } else if (x >= a + 1) { - // Q should converge faster in this case. - return 1 - Q.value(a, x, epsilon, maxIterations); - } else { - // Series. - double n = 0; // current element index - double an = 1 / a; // n-th element in the series - double sum = an; // partial sum - while (Math.abs(an / sum) > epsilon && - n < maxIterations && - sum < Double.POSITIVE_INFINITY) { - // compute next element in the series - n += 1; - an *= x / (a + n); - - // update partial sum - sum += an; - } - if (n >= maxIterations) { - throw new GammaException(GammaException.CONVERGENCE, maxIterations); - } else if (Double.isInfinite(sum)) { - return 1; - } else { - return Math.exp(-x + (a * Math.log(x)) - LogGamma.value(a)) * sum; - } - } - } - } - - /** - * Creates the \( Q(a, x) \equiv 1 - P(a, x) \) - * regularized Gamma function. - * - * Class is immutable. - */ - public static class Q { - /** - * Computes the regularized gamma function \( Q(a, x) = 1 - P(a, x) \). - * - * @param a Argument. - * @param x Argument. - * @return \( Q(a, x) \). - */ - public static double value(double a, - double x) { - return value(a, x, DEFAULT_EPSILON, Integer.MAX_VALUE); - } - - /** - * Computes the regularized gamma function \( Q(a, x) = 1 - P(a, x) \). - * - * The implementation of this method is based on: - * - * - * @param a Argument. - * @param x Argument. - * @param epsilon Tolerance in continued fraction evaluation. - * @param maxIterations Maximum number of iterations in continued fraction evaluation. - * @return \( Q(a, x) \). - */ - public static double value(final double a, - double x, - double epsilon, - int maxIterations) { - if (Double.isNaN(a) || - Double.isNaN(x) || - a <= 0 || - x < 0) { - return Double.NaN; - } else if (x == 0) { - return 1; - } else if (x < a + 1) { - // P should converge faster in this case. - return 1 - P.value(a, x, epsilon, maxIterations); - } else { - final ContinuedFraction cf = new ContinuedFraction() { - /** {@inheritDoc} */ - @Override - protected double getA(int n, double x) { - return ((2 * n) + 1) - a + x; - } - - /** {@inheritDoc} */ - @Override - protected double getB(int n, double x) { - return n * (a - n); - } - }; - - return Math.exp(-x + (a * Math.log(x)) - LogGamma.value(a)) / - cf.evaluate(x, epsilon, maxIterations); - } - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/Trigamma.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/Trigamma.java deleted file mode 100644 index 3c8242ef3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/Trigamma.java +++ /dev/null @@ -1,63 +0,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. - */ -package org.apache.commons.numbers.gamma; - -/** - * Trigamma function. - * - * It is the derivative of the {@link Digamma digamma function}: - * \( \psi_1(x) = \frac{d^2}{dx^2} (\ln \Gamma(x)) \). - */ -public class Trigamma { - /** C limit. */ - private static final double C_LIMIT = 49; - /** S limit. */ - private static final double S_LIMIT = 1e-5; - /** Fraction. */ - private static final double F_1_6 = 1d / 6; - /** Fraction. */ - private static final double F_1_30 = 1d / 30; - /** Fraction. */ - private static final double F_1_42 = 1d / 42; - - /** - * Computes the trigamma function. - * - * @param x Argument. - * @return trigamma(x) to within {@code 1e-8} relative or absolute error whichever is larger. - */ - public static double value(double x) { - if (Double.isNaN(x) || Double.isInfinite(x)) { - return x; - } - - if (x > 0 && x <= S_LIMIT) { - return 1 / (x * x); - } - - if (x >= C_LIMIT) { - final double inv = 1 / (x * x); - // 1 1 1 1 1 - // - + ---- + ---- - ----- + ----- - // x 2 3 5 7 - // 2 x 6 x 30 x 42 x - return 1 / x + inv / 2 + inv / x * (F_1_6 - inv * (F_1_30 + F_1_42 * inv)); - } - - return value(x + 1) + 1 / (x * x); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/package-info.java deleted file mode 100644 index 375193503..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/numbers/gamma/package-info.java +++ /dev/null @@ -1,39 +0,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. - */ - -/** - * Γ (Gamma) and Β (Beta) family of functions. - * - * Implementation of {@link org.apache.commons.numbers.gamma.InvGamma1pm1 InvGamma1pm1} - * and {@link org.apache.commons.numbers.gamma.LogGamma1p LogGamma1p} is based on the - * algorithms described in - *
    - *
  • - * Didonato and Morris (1986), - * Computation of the Incomplete Gamma Function Ratios and their Inverse, - * TOMS 12(4), 377-393, - *
  • - *
  • - * Didonato and Morris (1992), - * Algorithm 708: Significant Digit Computation of the Incomplete Beta Function - * Ratios, TOMS 18(3), 360-373, - *
  • - *
- * and implemented in the - * NSWC Library of Mathematical Functions. - */ -package org.apache.commons.numbers.gamma; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/RandomProviderState.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/RandomProviderState.java deleted file mode 100644 index f4af719da..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/RandomProviderState.java +++ /dev/null @@ -1,25 +0,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. - */ -package org.apache.commons.rng; - -/** - * Marker interface for objects that represents the state of a random - * generator. - * - * @since 1.0 - */ -public interface RandomProviderState {} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/RestorableUniformRandomProvider.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/RestorableUniformRandomProvider.java deleted file mode 100644 index 476ce7fc5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/RestorableUniformRandomProvider.java +++ /dev/null @@ -1,49 +0,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. - */ -package org.apache.commons.rng; - -/** - * Applies to generators whose internal state can be saved and restored. - * - * @since 1.0 - */ -public interface RestorableUniformRandomProvider extends UniformRandomProvider { - /** - * Saves the state of a generator. - * - * @return the current state of this instance. It is a value that can - * subsequently be passed to the {@link #restoreState(RandomProviderState) - * restore} method. - * @throws UnsupportedOperationException if the underlying source of - * randomness does not support this functionality. - */ - RandomProviderState saveState(); - - /** - * Restores the state of a generator. - * - * @param state State which this instance will be set to. - * This parameter would usually have been obtained by a call to - * {@link #saveState() saveState} performed either on the same - * object as this one, or an object of the exact same class. - * @throws UnsupportedOperationException if the underlying source of - * randomness does not support this functionality. - * @throws IllegalArgumentException if it was detected that the - * {@code state} argument is incompatible with this intance. - */ - void restoreState(RandomProviderState state); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/UniformRandomProvider.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/UniformRandomProvider.java deleted file mode 100644 index 07d310829..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/UniformRandomProvider.java +++ /dev/null @@ -1,116 +0,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. - */ -package org.apache.commons.rng; - -/** - * Applies to generators of random number sequences that follow a uniform - * distribution. - * - * @since 1.0 - */ -public interface UniformRandomProvider { - /** - * Generates {@code byte} values and places them into a user-supplied array. - *

- * The number of random bytes produced is equal to the length of the - * the byte array. - *

- * - * @param bytes Byte array in which to put the random bytes. - * Cannot be {@code null}. - */ - void nextBytes(byte[] bytes); - - /** - * Generates {@code byte} values and places them into a user-supplied array. - * - *

- * The array is filled with bytes extracted from random integers. - * This implies that the number of random bytes generated may be larger than - * the length of the byte array. - *

- * - * @param bytes Array in which to put the generated bytes. - * Cannot be {@code null}. - * @param start Index at which to start inserting the generated bytes. - * @param len Number of bytes to insert. - * @throws IndexOutOfBoundsException if {@code start < 0} or - * {@code start >= bytes.length}. - * @throws IndexOutOfBoundsException if {@code len < 0} or - * {@code len > bytes.length - start}. - */ - void nextBytes(byte[] bytes, - int start, - int len); - - /** - * Generates an {@code int} value. - * - * @return the next random value. - */ - int nextInt(); - - /** - * Generates an {@code int} value between 0 (inclusive) and the - * specified value (exclusive). - * - * @param n Bound on the random number to be returned. Must be positive. - * @return a random {@code int} value between 0 (inclusive) and {@code n} - * (exclusive). - * @throws IllegalArgumentException if {@code n} is negative. - */ - int nextInt(int n); - - /** - * Generates a {@code long} value. - * - * @return the next random value. - */ - long nextLong(); - - /** - * Generates a {@code long} value between 0 (inclusive) and the specified - * value (exclusive). - * - * @param n Bound on the random number to be returned. Must be positive. - * @return a random {@code long} value between 0 (inclusive) and {@code n} - * (exclusive). - * @throws IllegalArgumentException if {@code n} is negative. - */ - long nextLong(long n); - - /** - * Generates a {@code boolean} value. - * - * @return the next random value. - */ - boolean nextBoolean(); - - /** - * Generates a {@code float} value between 0 and 1. - * - * @return the next random value between 0 and 1. - */ - float nextFloat(); - - /** - * Generates a {@code double} value between 0 and 1. - * - * @return the next random value between 0 and 1. - */ - double nextDouble(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/BaseProvider.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/BaseProvider.java deleted file mode 100644 index 2c62c07af..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/BaseProvider.java +++ /dev/null @@ -1,324 +0,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. - */ - -package org.apache.commons.rng.core; - -import org.apache.commons.rng.RandomProviderState; -import org.apache.commons.rng.RestorableUniformRandomProvider; - -/** - * Base class with default implementation for common methods. - */ -public abstract class BaseProvider - implements RestorableUniformRandomProvider { - /** {@inheritDoc} */ - @Override - public int nextInt(int n) { - checkStrictlyPositive(n); - - if ((n & -n) == n) { - return (int) ((n * (long) (nextInt() >>> 1)) >> 31); - } - int bits; - int val; - do { - bits = nextInt() >>> 1; - val = bits % n; - } while (bits - val + (n - 1) < 0); - - return val; - } - - /** {@inheritDoc} */ - @Override - public long nextLong(long n) { - checkStrictlyPositive(n); - - long bits; - long val; - do { - bits = nextLong() >>> 1; - val = bits % n; - } while (bits - val + (n - 1) < 0); - - return val; - } - - /** {@inheritDoc} */ - @Override - public RandomProviderState saveState() { - return new RandomProviderDefaultState(getStateInternal()); - } - - /** {@inheritDoc} */ - @Override - public void restoreState(RandomProviderState state) { - if (state instanceof RandomProviderDefaultState) { - setStateInternal(((RandomProviderDefaultState) state).getState()); - } else { - throw new IllegalArgumentException("Foreign instance"); - } - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return getClass().getName(); - } - - /** - * Combine parent and subclass states. - * This method must be called by all subclasses in order to ensure - * that state can be restored in case some of it is stored higher - * up in the class hierarchy. - * - * I.e. the body of the overridden {@link #getStateInternal()}, - * will end with a statement like the following: - *
-     *  
-     *    return composeStateInternal(state,
-     *                                super.getStateInternal());
-     *  
-     * 
- * where {@code state} is the state needed and defined by the class - * where the method is overridden. - * - * @param state State of the calling class. - * @param parentState State of the calling class' parent. - * @return the combined state. - * Bytes that belong to the local state will be stored at the - * beginning of the resulting array. - */ - protected byte[] composeStateInternal(byte[] state, - byte[] parentState) { - final int len = parentState.length + state.length; - final byte[] c = new byte[len]; - System.arraycopy(state, 0, c, 0, state.length); - System.arraycopy(parentState, 0, c, state.length, parentState.length); - return c; - } - - /** - * Splits the given {@code state} into a part to be consumed by the caller - * in order to restore its local state, while the reminder is passed to - * the parent class. - * - * I.e. the body of the overridden {@link #setStateInternal(byte[])}, - * will contain statements like the following: - *
-     *  
-     *    final byte[][] s = splitState(state, localStateLength);
-     *    // Use "s[0]" to recover the local state.
-     *    super.setStateInternal(s[1]);
-     *  
-     * 
- * where {@code state} is the combined state of the calling class and of - * all its parents. - * - * @param state State. - * The local state must be stored at the beginning of the array. - * @param localStateLength Number of elements that will be consumed by the - * locally defined state. - * @return the local state (in slot 0) and the parent state (in slot 1). - * @throws IllegalStateException if {@code state.length < localStateLength}. - */ - protected byte[][] splitStateInternal(byte[] state, - int localStateLength) { - checkStateSize(state, localStateLength); - - final byte[] local = new byte[localStateLength]; - System.arraycopy(state, 0, local, 0, localStateLength); - final int parentLength = state.length - localStateLength; - final byte[] parent = new byte[parentLength]; - System.arraycopy(state, localStateLength, parent, 0, parentLength); - - return new byte[][] { local, parent }; - } - - /** - * Creates a snapshot of the RNG state. - * - * @return the internal state. - */ - protected byte[] getStateInternal() { - // This class has no state (and is the top-level class that - // declares this method). - return new byte[0]; - } - - /** - * Resets the RNG to the given {@code state}. - * - * @param state State (previously obtained by a call to - * {@link #getStateInternal()}). - * @throws IllegalStateException if the size of the given array is - * not consistent with the state defined by this class. - * - * @see #checkStateSize(byte[],int) - */ - protected void setStateInternal(byte[] state) { - if (state.length != 0) { - // This class has no state. - throw new IllegalStateException("State not fully recovered by subclasses"); - } - } - - /** - * Simple filling procedure. - * It will - *
    - *
  1. - * fill the beginning of {@code state} by copying - * {@code min(seed.length, state.length)} elements from - * {@code seed}, - *
  2. - *
  3. - * set all remaining elements of {@code state} with non-zero - * values (even if {@code seed.length < state.length}). - *
  4. - *
- * - * @param state State. Must be allocated. - * @param seed Seed. Cannot be null. - */ - protected void fillState(int[] state, - int[] seed) { - final int stateSize = state.length; - final int seedSize = seed.length; - System.arraycopy(seed, 0, state, 0, Math.min(seedSize, stateSize)); - - if (seedSize < stateSize) { - for (int i = seedSize; i < stateSize; i++) { - state[i] = (int) (scrambleWell(state[i - seed.length], i) & 0xffffffffL); - } - } - } - - /** - * Simple filling procedure. - * It will - *
    - *
  1. - * fill the beginning of {@code state} by copying - * {@code min(seed.length, state.length)} elements from - * {@code seed}, - *
  2. - *
  3. - * set all remaining elements of {@code state} with non-zero - * values (even if {@code seed.length < state.length}). - *
  4. - *
- * - * @param state State. Must be allocated. - * @param seed Seed. Cannot be null. - */ - protected void fillState(long[] state, - long[] seed) { - final int stateSize = state.length; - final int seedSize = seed.length; - System.arraycopy(seed, 0, state, 0, Math.min(seedSize, stateSize)); - - if (seedSize < stateSize) { - for (int i = seedSize; i < stateSize; i++) { - state[i] = scrambleWell(state[i - seed.length], i); - } - } - } - - /** - * Checks that the {@code state} has the {@code expected} size. - * - * @param state State. - * @param expected Expected length of {@code state} array. - * @throws IllegalStateException if {@code state.length < expected}. - * @deprecated Method is used internally and should be made private in - * some future release. - */ - @Deprecated - protected void checkStateSize(byte[] state, - int expected) { - if (state.length < expected) { - throw new IllegalStateException("State size must be larger than " + - expected + " but was " + state.length); - } - } - - /** - * Checks whether {@code index} is in the range {@code [min, max]}. - * - * @param min Lower bound. - * @param max Upper bound. - * @param index Value that must lie within the {@code [min, max]} interval. - * @throws IndexOutOfBoundsException if {@code index} is not within the - * {@code [min, max]} interval. - */ - protected void checkIndex(int min, - int max, - int index) { - if (index < min || - index > max) { - throw new IndexOutOfBoundsException(index + " is out of interval [" + - min + ", " + - max + "]"); - } - } - - /** - * Checks that the argument is strictly positive. - * - * @param n Number to check. - * @throws IllegalArgumentException if {@code n <= 0}. - */ - private void checkStrictlyPositive(long n) { - if (n <= 0) { - throw new IllegalArgumentException("Must be strictly positive: " + n); - } - } - - /** - * Transformation used to scramble the initial state of - * a generator. - * - * @param n Seed element. - * @param mult Multiplier. - * @param shift Shift. - * @param add Offset. - * @return the transformed seed element. - */ - private static long scramble(long n, - long mult, - int shift, - int add) { - // Code inspired from "AbstractWell" class. - return mult * (n ^ (n >> shift)) + add; - } - - /** - * Transformation used to scramble the initial state of - * a generator. - * - * @param n Seed element. - * @param add Offset. - * @return the transformed seed element. - * @see #scramble(long,long,int,int) - */ - private static long scrambleWell(long n, - int add) { - // Code inspired from "AbstractWell" class. - return scramble(n, 1812433253L, 30, add); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/RandomProviderDefaultState.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/RandomProviderDefaultState.java deleted file mode 100644 index fb4d95828..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/RandomProviderDefaultState.java +++ /dev/null @@ -1,56 +0,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. - */ -package org.apache.commons.rng.core; - -import org.apache.commons.rng.RandomProviderState; - -import java.util.Arrays; - -/** - * Wraps the internal state of a generator instance. - * Its purpose is to store all the data needed to recover the same - * state in order to restart a sequence where it left off. - * External code should not try to modify the data contained in instances - * of this class. - * - * @since 1.0 - */ -public class RandomProviderDefaultState implements RandomProviderState { - /** Internal state. */ - private final byte[] state; - - /** - * Initializes an instance. - * The contents of the {@code state} argument is unspecified, and is - * guaranteed to be valid only if it was generated by implementations - * provided by this library. - * - * @param state Mapping of all the data which an implementation of - * {@link org.apache.commons.rng.UniformRandomProvider} needs in order - * to reset its internal state. - */ - public RandomProviderDefaultState(byte[] state) { - this.state = Arrays.copyOf(state, state.length); - } - - /** - * @return the internal state. - */ - public byte[] getState() { - return Arrays.copyOf(state, state.length); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/package-info.java deleted file mode 100644 index f9d12daa8..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/package-info.java +++ /dev/null @@ -1,52 +0,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. - */ - -/** - *

Base classes for the {@link org.apache.commons.rng.UniformRandomProvider - * generation of uniformly distributed random numbers}. - *

- * - *

- * For internal use only: Direct access to classes in this package - * and below, is discouraged, as they could be modified without notice. - *

- * - *

Notes for developers

- * - *

- * This package contains the common functionality. - *
- * Implementations that produce - * {@link org.apache.commons.rng.core.source32.RandomIntSource int} - * values are defined in the - * org.apache.commons.rng.core.source32 package. - *
- * Implementations that produce - * {@link org.apache.commons.rng.core.source64.RandomLongSource long} - * values are defined in the - * org.apache.commons.rng.core.source64 package. - *

- * - *

- * Each implementation must have an identifier in - * {@code ProviderBuilder.RandomSourceInternal} defined in module - * "commons-rng-simple" (to allow instantiation through the - * {@code RandomSource} factory methods. - *

- */ - -package org.apache.commons.rng.core; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/AbstractWell.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/AbstractWell.java deleted file mode 100644 index 9e15d8d57..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/AbstractWell.java +++ /dev/null @@ -1,205 +0,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. - */ -package org.apache.commons.rng.core.source32; - -import org.apache.commons.rng.core.util.NumberFactory; - -import java.util.Arrays; - -/** - * This abstract class implements the WELL class of pseudo-random number - * generator from François Panneton, Pierre L'Ecuyer and Makoto - * Matsumoto. - *

- * This generator is described in a paper by François Panneton, - * Pierre L'Ecuyer and Makoto Matsumoto - * - * Improved Long-Period Generators Based on Linear Recurrences Modulo 2 - * ACM Transactions on Mathematical Software, 32, 1 (2006). - * The errata for the paper are in - * wellrng-errata.txt. - *

- * - * @see WELL Random number generator - * - * @since 1.0 - */ -public abstract class AbstractWell extends IntProvider { - /** Block size. */ - private static final int BLOCK_SIZE = 32; - /** Current index in the bytes pool. */ - protected int index; - /** Bytes pool. */ - protected final int[] v; - - /** - * Creates an instance with the given {@code seed}. - * - * @param k Number of bits in the pool (not necessarily a multiple of 32). - * @param seed Initial seed. - */ - protected AbstractWell(final int k, - final int[] seed) { - final int r = calculateBlockCount(k); - v = new int[r]; - index = 0; - - // Initialize the pool content. - setSeedInternal(seed); - } - - /** {@inheritDoc} */ - @Override - protected byte[] getStateInternal() { - final int[] s = Arrays.copyOf(v, v.length + 1); - s[v.length] = index; - - return composeStateInternal(NumberFactory.makeByteArray(s), - super.getStateInternal()); - } - - /** {@inheritDoc} */ - @Override - protected void setStateInternal(byte[] s) { - final byte[][] c = splitStateInternal(s, (v.length + 1) * 4); - - final int[] tmp = NumberFactory.makeIntArray(c[0]); - System.arraycopy(tmp, 0, v, 0, v.length); - index = tmp[v.length]; - - super.setStateInternal(c[1]); - } - - /** - * Initializes the generator with the given {@code seed}. - * - * @param seed Seed. Cannot be null. - */ - private void setSeedInternal(final int[] seed) { - System.arraycopy(seed, 0, v, 0, Math.min(seed.length, v.length)); - - if (seed.length < v.length) { - for (int i = seed.length; i < v.length; ++i) { - final long current = v[i - seed.length]; - v[i] = (int) ((1812433253L * (current ^ (current >> 30)) + i) & 0xffffffffL); - } - } - - index = 0; - } - - /** - * Calculate the number of 32-bits blocks. - * - * @param k Number of bits in the pool (not necessarily a multiple of 32). - * @return the number of 32-bits blocks. - */ - private static int calculateBlockCount(final int k) { - // The bits pool contains k bits, k = r w - p where r is the number - // of w bits blocks, w is the block size (always 32 in the original paper) - // and p is the number of unused bits in the last block. - return (k + BLOCK_SIZE - 1) / BLOCK_SIZE; - } - - /** - * Inner class used to store the indirection index table which is fixed for a given - * type of WELL class of pseudo-random number generator. - */ - protected static final class IndexTable { - /** Index indirection table giving for each index its predecessor taking table size into account. */ - private final int[] iRm1; - /** Index indirection table giving for each index its second predecessor taking table size into account. */ - private final int[] iRm2; - /** Index indirection table giving for each index the value index + m1 taking table size into account. */ - private final int[] i1; - /** Index indirection table giving for each index the value index + m2 taking table size into account. */ - private final int[] i2; - /** Index indirection table giving for each index the value index + m3 taking table size into account. */ - private final int[] i3; - - /** Creates a new pre-calculated indirection index table. - * @param k number of bits in the pool (not necessarily a multiple of 32) - * @param m1 first parameter of the algorithm - * @param m2 second parameter of the algorithm - * @param m3 third parameter of the algorithm - */ - public IndexTable(final int k, final int m1, final int m2, final int m3) { - - final int r = calculateBlockCount(k); - - // precompute indirection index tables. These tables are used for optimizing access - // they allow saving computations like "(j + r - 2) % r" with costly modulo operations - iRm1 = new int[r]; - iRm2 = new int[r]; - i1 = new int[r]; - i2 = new int[r]; - i3 = new int[r]; - for (int j = 0; j < r; ++j) { - iRm1[j] = (j + r - 1) % r; - iRm2[j] = (j + r - 2) % r; - i1[j] = (j + m1) % r; - i2[j] = (j + m2) % r; - i3[j] = (j + m3) % r; - } - } - - /** - * Returns the predecessor of the given index modulo the table size. - * @param index the index to look at - * @return (index - 1) % table size - */ - public int getIndexPred(final int index) { - return iRm1[index]; - } - - /** - * Returns the second predecessor of the given index modulo the table size. - * @param index the index to look at - * @return (index - 2) % table size - */ - public int getIndexPred2(final int index) { - return iRm2[index]; - } - - /** - * Returns index + M1 modulo the table size. - * @param index the index to look at - * @return (index + M1) % table size - */ - public int getIndexM1(final int index) { - return i1[index]; - } - - /** - * Returns index + M2 modulo the table size. - * @param index the index to look at - * @return (index + M2) % table size - */ - public int getIndexM2(final int index) { - return i2[index]; - } - - /** - * Returns index + M3 modulo the table size. - * @param index the index to look at - * @return (index + M3) % table size - */ - public int getIndexM3(final int index) { - return i3[index]; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/AbstractXoRoShiRo64.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/AbstractXoRoShiRo64.java deleted file mode 100644 index b3f8b8207..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/AbstractXoRoShiRo64.java +++ /dev/null @@ -1,97 +0,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. - */ - -package org.apache.commons.rng.core.source32; - -import org.apache.commons.rng.core.util.NumberFactory; - -/** - * This abstract class is a base for algorithms from the Xor-Shift-Rotate family of 32-bit - * generators with 64-bits of state. - * - * @see xorshiro / xoroshiro generators - * - * @since 1.3 - */ -abstract class AbstractXoRoShiRo64 extends IntProvider { - /** Size of the state vector. */ - private static final int SEED_SIZE = 2; - - // State is maintained using variables rather than an array for performance - - /** State 0 of the generator. */ - protected int state0; - /** State 1 of the generator. */ - protected int state1; - - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 2, only the first 2 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - */ - AbstractXoRoShiRo64(int[] seed) { - if (seed.length < SEED_SIZE) { - final int[] state = new int[SEED_SIZE]; - fillState(state, seed); - setState(state); - } else { - setState(seed); - } - } - - /** - * Creates a new instance using a 2 element seed. - * A seed containing all zeros will create a non-functional generator. - * - * @param seed0 Initial seed element 0. - * @param seed1 Initial seed element 1. - */ - AbstractXoRoShiRo64(int seed0, int seed1) { - state0 = seed0; - state1 = seed1; - } - - /** - * Copies the state from the array into the generator state. - * - * @param state the new state - */ - private void setState(int[] state) { - state0 = state[0]; - state1 = state[1]; - } - - /** {@inheritDoc} */ - @Override - protected byte[] getStateInternal() { - return composeStateInternal(NumberFactory.makeByteArray(new int[] {state0, state1}), - super.getStateInternal()); - } - - /** {@inheritDoc} */ - @Override - protected void setStateInternal(byte[] s) { - final byte[][] c = splitStateInternal(s, SEED_SIZE * 4); - - setState(NumberFactory.makeIntArray(c[0])); - - super.setStateInternal(c[1]); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/AbstractXoShiRo128.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/AbstractXoShiRo128.java deleted file mode 100644 index 80ec6071a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/AbstractXoShiRo128.java +++ /dev/null @@ -1,108 +0,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. - */ - -package org.apache.commons.rng.core.source32; - -import org.apache.commons.rng.core.util.NumberFactory; - -/** - * This abstract class is a base for algorithms from the Xor-Shift-Rotate family of 32-bit - * generators with 128-bits of state. - * - * @see xorshiro / xoroshiro generators - * - * @since 1.3 - */ -abstract class AbstractXoShiRo128 extends IntProvider { - /** Size of the state vector. */ - private static final int SEED_SIZE = 4; - - // State is maintained using variables rather than an array for performance - - /** State 0 of the generator. */ - protected int state0; - /** State 1 of the generator. */ - protected int state1; - /** State 2 of the generator. */ - protected int state2; - /** State 3 of the generator. */ - protected int state3; - - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 4, only the first 4 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - */ - AbstractXoShiRo128(int[] seed) { - if (seed.length < SEED_SIZE) { - final int[] state = new int[SEED_SIZE]; - fillState(state, seed); - setState(state); - } else { - setState(seed); - } - } - - /** - * Creates a new instance using a 4 element seed. - * A seed containing all zeros will create a non-functional generator. - * - * @param seed0 Initial seed element 0. - * @param seed1 Initial seed element 1. - * @param seed2 Initial seed element 2. - * @param seed3 Initial seed element 3. - */ - AbstractXoShiRo128(int seed0, int seed1, int seed2, int seed3) { - state0 = seed0; - state1 = seed1; - state2 = seed2; - state3 = seed3; - } - - /** - * Copies the state from the array into the generator state. - * - * @param state the new state - */ - private void setState(int[] state) { - state0 = state[0]; - state1 = state[1]; - state2 = state[2]; - state3 = state[3]; - } - - /** {@inheritDoc} */ - @Override - protected byte[] getStateInternal() { - return composeStateInternal(NumberFactory.makeByteArray( - new int[] {state0, state1, state2, state3}), - super.getStateInternal()); - } - - /** {@inheritDoc} */ - @Override - protected void setStateInternal(byte[] s) { - final byte[][] c = splitStateInternal(s, SEED_SIZE * 4); - - setState(NumberFactory.makeIntArray(c[0])); - - super.setStateInternal(c[1]); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/ISAACRandom.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/ISAACRandom.java deleted file mode 100644 index 2b1106ee6..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/ISAACRandom.java +++ /dev/null @@ -1,271 +0,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. - */ - -package org.apache.commons.rng.core.source32; - -import org.apache.commons.rng.core.util.NumberFactory; - -import java.util.Arrays; - -/** - * A fast cryptographic pseudo-random number generator. - *

- * ISAAC (Indirection, Shift, Accumulate, Add, and Count) generates 32-bit - * random numbers. - * ISAAC has been designed to be cryptographically secure and is inspired - * by RC4. - * Cycles are guaranteed to be at least 240 values long, and they - * are 28295 values long on average. - * The results are uniformly distributed, unbiased, and unpredictable unless - * you know the seed. - *

- * This code is based (with minor changes and improvements) on the original - * implementation of the algorithm by Bob Jenkins. - * - * @see - * ISAAC: a fast cryptographic pseudo-random number generator - * - * @see ISAAC (Wikipedia) - * @since 1.0 - */ -public class ISAACRandom extends IntProvider { - /** Log of size of rsl[] and mem[]. */ - private static final int SIZE_L = 8; - /** Size of rsl[] and mem[]. */ - private static final int SIZE = 1 << SIZE_L; - /** Half-size of rsl[] and mem[]. */ - private static final int H_SIZE = SIZE >> 1; - /** For pseudo-random lookup. */ - private static final int MASK = SIZE - 1 << 2; - /** The golden ratio. */ - private static final int GLD_RATIO = 0x9e3779b9; - /** The results given to the user. */ - private final int[] rsl = new int[SIZE]; - /** The internal state. */ - private final int[] mem = new int[SIZE]; - /** Count through the results in rsl[]. */ - private int count; - /** Accumulator. */ - private int isaacA; - /** The last result. */ - private int isaacB; - /** Counter, guarantees cycle is at least 2^40. */ - private int isaacC; - /** Service variable. */ - private final int[] arr = new int[8]; - /** Service variable. */ - private int isaacX; - /** Service variable. */ - private int isaacI; - /** Service variable. */ - private int isaacJ; - - /** - * Creates a new ISAAC random number generator. - * - * @param seed Initial seed - */ - public ISAACRandom(int[] seed) { - setSeedInternal(seed); - } - - /** {@inheritDoc} */ - @Override - protected byte[] getStateInternal() { - final int[] sRsl = Arrays.copyOf(rsl, SIZE); - final int[] sMem = Arrays.copyOf(mem, SIZE); - final int[] sRem = Arrays.copyOf(new int[] { count, isaacA, isaacB, isaacC }, 4); - - final int[] s = new int[2 * SIZE + sRem.length]; - System.arraycopy(sRsl, 0, s, 0, SIZE); - System.arraycopy(sMem, 0, s, SIZE, SIZE); - System.arraycopy(sRem, 0, s, 2 * SIZE, sRem.length); - - return composeStateInternal(NumberFactory.makeByteArray(s), - super.getStateInternal()); - } - - /** {@inheritDoc} */ - @Override - protected void setStateInternal(byte[] s) { - final byte[][] c = splitStateInternal(s, (2 * SIZE + 4) * 4); - - final int[] tmp = NumberFactory.makeIntArray(c[0]); - System.arraycopy(tmp, 0, rsl, 0, SIZE); - System.arraycopy(tmp, SIZE, mem, 0, SIZE); - final int offset = 2 * SIZE; - count = tmp[offset]; - isaacA = tmp[offset + 1]; - isaacB = tmp[offset + 2]; - isaacC = tmp[offset + 3]; - - super.setStateInternal(c[1]); - } - - /** - * Reseeds the RNG. - * - * @param seed Seed. Cannot be null. - */ - private void setSeedInternal(int[] seed) { - final int seedLen = seed.length; - final int rslLen = rsl.length; - System.arraycopy(seed, 0, rsl, 0, Math.min(seedLen, rslLen)); - if (seedLen < rslLen) { - for (int j = seedLen; j < rslLen; j++) { - long k = rsl[j - seedLen]; - rsl[j] = (int) (0x6c078965L * (k ^ k >> 30) + j & 0xffffffffL); - } - } - initState(); - } - - /** {@inheritDoc} */ - @Override - public int next() { - if (count < 0) { - isaac(); - count = SIZE - 1; - } - return rsl[count--]; - } - - /** Generate 256 results */ - private void isaac() { - isaacI = 0; - isaacJ = H_SIZE; - isaacB += ++isaacC; - while (isaacI < H_SIZE) { - isaac2(); - } - isaacJ = 0; - while (isaacJ < H_SIZE) { - isaac2(); - } - } - - /** Intermediate internal loop. */ - private void isaac2() { - isaacX = mem[isaacI]; - isaacA ^= isaacA << 13; - isaacA += mem[isaacJ++]; - isaac3(); - isaacX = mem[isaacI]; - isaacA ^= isaacA >>> 6; - isaacA += mem[isaacJ++]; - isaac3(); - isaacX = mem[isaacI]; - isaacA ^= isaacA << 2; - isaacA += mem[isaacJ++]; - isaac3(); - isaacX = mem[isaacI]; - isaacA ^= isaacA >>> 16; - isaacA += mem[isaacJ++]; - isaac3(); - } - - /** Lowest level internal loop. */ - private void isaac3() { - mem[isaacI] = mem[(isaacX & MASK) >> 2] + isaacA + isaacB; - isaacB = mem[(mem[isaacI] >> SIZE_L & MASK) >> 2] + isaacX; - rsl[isaacI++] = isaacB; - } - - /** Initialize, or reinitialize, this instance of rand. */ - private void initState() { - isaacA = 0; - isaacB = 0; - isaacC = 0; - for (int j = 0; j < arr.length; j++) { - arr[j] = GLD_RATIO; - } - for (int j = 0; j < 4; j++) { - shuffle(); - } - // fill in mem[] with messy stuff - for (int j = 0; j < SIZE; j += 8) { - arr[0] += rsl[j]; - arr[1] += rsl[j + 1]; - arr[2] += rsl[j + 2]; - arr[3] += rsl[j + 3]; - arr[4] += rsl[j + 4]; - arr[5] += rsl[j + 5]; - arr[6] += rsl[j + 6]; - arr[7] += rsl[j + 7]; - shuffle(); - setState(j); - } - // second pass makes all of seed affect all of mem - for (int j = 0; j < SIZE; j += 8) { - arr[0] += mem[j]; - arr[1] += mem[j + 1]; - arr[2] += mem[j + 2]; - arr[3] += mem[j + 3]; - arr[4] += mem[j + 4]; - arr[5] += mem[j + 5]; - arr[6] += mem[j + 6]; - arr[7] += mem[j + 7]; - shuffle(); - setState(j); - } - isaac(); - count = SIZE - 1; - } - - /** Shuffle array. */ - private void shuffle() { - arr[0] ^= arr[1] << 11; - arr[3] += arr[0]; - arr[1] += arr[2]; - arr[1] ^= arr[2] >>> 2; - arr[4] += arr[1]; - arr[2] += arr[3]; - arr[2] ^= arr[3] << 8; - arr[5] += arr[2]; - arr[3] += arr[4]; - arr[3] ^= arr[4] >>> 16; - arr[6] += arr[3]; - arr[4] += arr[5]; - arr[4] ^= arr[5] << 10; - arr[7] += arr[4]; - arr[5] += arr[6]; - arr[5] ^= arr[6] >>> 4; - arr[0] += arr[5]; - arr[6] += arr[7]; - arr[6] ^= arr[7] << 8; - arr[1] += arr[6]; - arr[7] += arr[0]; - arr[7] ^= arr[0] >>> 9; - arr[2] += arr[7]; - arr[0] += arr[1]; - } - - /** Set the state by copying the internal arrays. - * - * @param start First index into {@link #mem} array. - */ - private void setState(int start) { - mem[start] = arr[0]; - mem[start + 1] = arr[1]; - mem[start + 2] = arr[2]; - mem[start + 3] = arr[3]; - mem[start + 4] = arr[4]; - mem[start + 5] = arr[5]; - mem[start + 6] = arr[6]; - mem[start + 7] = arr[7]; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/IntProvider.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/IntProvider.java deleted file mode 100644 index c1257f662..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/IntProvider.java +++ /dev/null @@ -1,173 +0,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. - */ - -package org.apache.commons.rng.core.source32; - -import org.apache.commons.rng.core.BaseProvider; -import org.apache.commons.rng.core.util.NumberFactory; - -/** - * Base class for all implementations that provide an {@code int}-based - * source randomness. - */ -public abstract class IntProvider - extends BaseProvider - implements RandomIntSource { - - /** - * Provides a bit source for booleans. - * - *

A cached value from a call to {@link #nextInt()}. - */ - private int booleanSource; // Initialised as 0 - - /** - * The bit mask of the boolean source to obtain the boolean bit. - * - *

The bit mask contains a single bit set. This begins at the least - * significant bit and is gradually shifted upwards until overflow to zero. - * - *

When zero a new boolean source should be created and the mask set to the - * least significant bit (i.e. 1). - */ - private int booleanBitMask; // Initialised as 0 - - /** {@inheritDoc} */ - @Override - protected byte[] getStateInternal() { - final int[] state = new int[] { booleanSource, - booleanBitMask }; - return composeStateInternal(super.getStateInternal(), - NumberFactory.makeByteArray(state)); - } - - /** {@inheritDoc} */ - @Override - protected void setStateInternal(byte[] s) { - final byte[][] c = splitStateInternal(s, 8); - final int[] state = NumberFactory.makeIntArray(c[0]); - booleanSource = state[0]; - booleanBitMask = state[1]; - super.setStateInternal(c[1]); - } - - /** {@inheritDoc} */ - @Override - public int nextInt() { - return next(); - } - - /** {@inheritDoc} */ - @Override - public boolean nextBoolean() { - // Shift up. This will eventually overflow and become zero. - booleanBitMask <<= 1; - // The mask will either contain a single bit or none. - if (booleanBitMask == 0) { - // Set the least significant bit - booleanBitMask = 1; - // Get the next value - booleanSource = nextInt(); - } - // Return if the bit is set - return (booleanSource & booleanBitMask) != 0; - } - - /** {@inheritDoc} */ - @Override - public double nextDouble() { - return NumberFactory.makeDouble(nextInt(), nextInt()); - } - - /** {@inheritDoc} */ - @Override - public float nextFloat() { - return NumberFactory.makeFloat(nextInt()); - } - - /** {@inheritDoc} */ - @Override - public long nextLong() { - return NumberFactory.makeLong(nextInt(), nextInt()); - } - - /** {@inheritDoc} */ - @Override - public void nextBytes(byte[] bytes) { - nextBytesFill(this, bytes, 0, bytes.length); - } - - /** {@inheritDoc} */ - @Override - public void nextBytes(byte[] bytes, - int start, - int len) { - checkIndex(0, bytes.length - 1, start); - checkIndex(0, bytes.length - start, len); - - nextBytesFill(this, bytes, start, len); - } - - /** - * Generates random bytes and places them into a user-supplied array. - * - *

- * The array is filled with bytes extracted from random {@code int} values. - * This implies that the number of random bytes generated may be larger than - * the length of the byte array. - *

- * - * @param source Source of randomness. - * @param bytes Array in which to put the generated bytes. Cannot be null. - * @param start Index at which to start inserting the generated bytes. - * @param len Number of bytes to insert. - */ - static void nextBytesFill(RandomIntSource source, - byte[] bytes, - int start, - int len) { - int index = start; // Index of first insertion. - - // Index of first insertion plus multiple of 4 part of length - // (i.e. length with 2 least significant bits unset). - final int indexLoopLimit = index + (len & 0x7ffffffc); - - // Start filling in the byte array, 4 bytes at a time. - while (index < indexLoopLimit) { - final int random = source.next(); - bytes[index++] = (byte) random; - bytes[index++] = (byte) (random >>> 8); - bytes[index++] = (byte) (random >>> 16); - bytes[index++] = (byte) (random >>> 24); - } - - final int indexLimit = start + len; // Index of last insertion + 1. - - // Fill in the remaining bytes. - if (index < indexLimit) { - int random = source.next(); - while (true) { - bytes[index++] = (byte) random; - if (index < indexLimit) { - random >>>= 8; - } else { - break; - } - } - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/JDKRandom.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/JDKRandom.java deleted file mode 100644 index 96e8443c5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/JDKRandom.java +++ /dev/null @@ -1,103 +0,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. - */ -package org.apache.commons.rng.core.source32; - -import java.io.*; -import java.util.Random; - -/** - * A provider that uses the {@link Random#nextInt()} method of the JDK's - * {@link Random} class as the source of randomness. - * - *

- * Caveat: All the other calls will be redirected to the methods - * implemented within this library. - *

- * - *

- * The state of this source of randomness is saved and restored through - * the serialization of the {@link Random} instance. - *

- * - * @since 1.0 - */ -public class JDKRandom extends IntProvider { - /** Delegate. Cannot be "final" (to allow serialization). */ - private Random delegate; - /** Size of the byte representation of the state (of the delegate). */ - private int stateSize; - - /** - * Creates an instance with the given seed. - * - * @param seed Initial seed. - */ - public JDKRandom(Long seed) { - delegate = new Random(seed); - } - - /** - * {@inheritDoc} - * - * @see Random#nextInt() - */ - @Override - public int next() { - return delegate.nextInt(); - } - - /** {@inheritDoc} */ - @Override - protected byte[] getStateInternal() { - try { - final ByteArrayOutputStream bos = new ByteArrayOutputStream(); - final ObjectOutputStream oos = new ObjectOutputStream(bos); - - // Serialize the "delegate". - oos.writeObject(delegate); - - final byte[] state = bos.toByteArray(); - stateSize = state.length; // To allow state recovery. - return composeStateInternal(state, - super.getStateInternal()); - } catch (IOException e) { - // Workaround checked exception. - throw new IllegalStateException(e); - } - } - - /** {@inheritDoc} */ - @Override - protected void setStateInternal(byte[] s) { - final byte[][] c = splitStateInternal(s, stateSize); - - try { - final ByteArrayInputStream bis = new ByteArrayInputStream(c[0]); - final ObjectInputStream ois = new ObjectInputStream(bis); - - delegate = (Random) ois.readObject(); - } catch (ClassNotFoundException e) { - // Workaround checked exception. - throw new IllegalStateException(e); - } catch (IOException e) { - // Workaround checked exception. - throw new IllegalStateException(e); - } - - super.setStateInternal(c[1]); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/KISSRandom.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/KISSRandom.java deleted file mode 100644 index 2bf9db41f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/KISSRandom.java +++ /dev/null @@ -1,122 +0,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. - */ -package org.apache.commons.rng.core.source32; - -import org.apache.commons.rng.core.util.NumberFactory; - -/** - * Port from Marsaglia's - * "KISS" algorithm. - * This version contains the correction referred to - * here - * in a reply to the original post. - * - * @see KISS (Wikipedia) - * @since 1.0 - */ -public class KISSRandom extends IntProvider { - /** Size of the seed. */ - private static final int SEED_SIZE = 4; - /** State variable. */ - private int z; - /** State variable. */ - private int w; - /** State variable. */ - private int jsr; - /** State variable. */ - private int jcong; - - /** - * Creates a new instance. - * - * @param seed Seed. - * If the length is larger than 4, only the first 4 elements will - * be used; if smaller, the remaining elements will be automatically - * set. - */ - public KISSRandom(int[] seed) { - setSeedInternal(seed); - } - - /** {@inheritDoc} */ - @Override - protected byte[] getStateInternal() { - return composeStateInternal(NumberFactory.makeByteArray(new int[] { z, w, jsr, jcong }), - super.getStateInternal()); - } - - /** {@inheritDoc} */ - @Override - protected void setStateInternal(byte[] s) { - final byte[][] c = splitStateInternal(s, SEED_SIZE * 4); - - final int[] tmp = NumberFactory.makeIntArray(c[0]); - z = tmp[0]; - w = tmp[1]; - jsr = tmp[2]; - jcong = tmp[3]; - - super.setStateInternal(c[1]); - } - - /** - * Seeds the RNG. - * - * @param seed Seed. - */ - private void setSeedInternal(int[] seed) { - // Reset the whole state of this RNG (i.e. the 4 state variables). - // Filling procedure is not part of the reference code. - final int[] tmp = new int[SEED_SIZE]; - fillState(tmp, seed); - - z = tmp[0]; - w = tmp[1]; - jsr = tmp[2]; - jcong = tmp[3]; - } - - /** {@inheritDoc} */ - @Override - public int next() { - z = computeNew(36969, z); - w = computeNew(18000, w); - final int mwc = (z << 16) + w; - - // Cf. correction mentioned in the reply to the original post: - // https://programmingpraxis.com/2010/10/05/george-marsaglias-random-number-generators/ - jsr ^= jsr << 13; - jsr ^= jsr >>> 17; - jsr ^= jsr << 5; - - jcong = 69069 * jcong + 1234567; - - return (mwc ^ jcong) + jsr; - } - - /** - * Compute new value. - * - * @param mult Multiplier. - * @param previous Previous value. - * @return new value. - */ - private int computeNew(int mult, - int previous) { - return mult * (previous & 65535) + (previous >>> 16); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/MersenneTwister.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/MersenneTwister.java deleted file mode 100644 index c763e37e2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/MersenneTwister.java +++ /dev/null @@ -1,249 +0,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. - */ -package org.apache.commons.rng.core.source32; - -import org.apache.commons.rng.core.util.NumberFactory; - -import java.util.Arrays; - -/** - * This class implements a powerful pseudo-random number generator - * developed by Makoto Matsumoto and Takuji Nishimura during - * 1996-1997. - * - *

- * This generator features an extremely long period - * (219937-1) and 623-dimensional equidistribution up to - * 32 bits accuracy. The home page for this generator is located at - * - * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html. - *

- * - *

- * This generator is described in a paper by Makoto Matsumoto and - * Takuji Nishimura in 1998: - * - * Mersenne Twister: A 623-Dimensionally Equidistributed Uniform Pseudo-Random - * Number Generator, - * ACM Transactions on Modeling and Computer Simulation, Vol. 8, No. 1, - * January 1998, pp 3--30 - *

- * - *

- * This class is mainly a Java port of the - * - * 2002-01-26 version of the generator written in C by Makoto Matsumoto - * and Takuji Nishimura. Here is their original copyright: - *

- * - * - * - * - * - * - * - * - *
Mersenne Twister licence
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, - * All rights reserved.
Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - *
    - *
  1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer.
  2. - *
  3. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution.
  4. - *
  5. The names of its contributors may not be used to endorse or promote - * products derived from this software without specific prior written - * permission.
  6. - *
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE - * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH - * DAMAGE.
- * - * @see Mersenne Twister (Wikipedia) - * @since 1.0 - */ -public class MersenneTwister extends IntProvider { - /** Mask 32 most significant bits. */ - private static final long INT_MASK_LONG = 0xffffffffL; - /** Most significant w-r bits. */ - private static final long UPPER_MASK_LONG = 0x80000000L; - /** Least significant r bits. */ - private static final long LOWER_MASK_LONG = 0x7fffffffL; - /** Most significant w-r bits. */ - private static final int UPPER_MASK = 0x80000000; - /** Least significant r bits. */ - private static final int LOWER_MASK = 0x7fffffff; - /** Size of the bytes pool. */ - private static final int N = 624; - /** Period second parameter. */ - private static final int M = 397; - /** X * MATRIX_A for X = {0, 1}. */ - private static final int[] MAG01 = { 0x0, 0x9908b0df }; - /** Bytes pool. */ - private int[] mt = new int[N]; - /** Current index in the bytes pool. */ - private int mti; - - /** - * Creates a new random number generator. - * - * @param seed Initial seed. - */ - public MersenneTwister(int[] seed) { - setSeedInternal(seed); - } - - /** {@inheritDoc} */ - @Override - protected byte[] getStateInternal() { - final int[] s = Arrays.copyOf(mt, N + 1); - s[N] = mti; - - return composeStateInternal(NumberFactory.makeByteArray(s), - super.getStateInternal()); - } - - /** {@inheritDoc} */ - @Override - protected void setStateInternal(byte[] s) { - final byte[][] c = splitStateInternal(s, (N + 1) * 4); - - final int[] tmp = NumberFactory.makeIntArray(c[0]); - System.arraycopy(tmp, 0, mt, 0, N); - mti = tmp[N]; - - super.setStateInternal(c[1]); - } - - /** - * Initializes the generator with the given seed. - * - * @param seed Initial seed. - */ - private void setSeedInternal(int[] seed) { - fillStateMersenneTwister(mt, seed); - - // Initial index. - mti = N; - } - - /** - * Utility for wholly filling a {@code state} array with non-zero - * bytes, even if the {@code seed} has a smaller size. - * The procedure is the one defined by the standard implementation - * of the algorithm. - * - * @param state State to be filled (must be allocated). - * @param seed Seed (cannot be {@code null}). - */ - private static void fillStateMersenneTwister(int[] state, - int[] seed) { - if (seed.length == 0) { - // Accept empty seed. - seed = new int[1]; - } - - final int stateSize = state.length; - - long mt = 19650218 & INT_MASK_LONG; - state[0] = (int) mt; - for (int i = 1; i < stateSize; i++) { - mt = (1812433253L * (mt ^ (mt >> 30)) + i) & INT_MASK_LONG; - state[i] = (int) mt; - } - - int i = 1; - int j = 0; - - for (int k = Math.max(stateSize, seed.length); k > 0; k--) { - final long a = (state[i] & LOWER_MASK_LONG) | ((state[i] < 0) ? UPPER_MASK_LONG : 0); - final long b = (state[i - 1] & LOWER_MASK_LONG) | ((state[i - 1] < 0) ? UPPER_MASK_LONG : 0); - final long c = (a ^ ((b ^ (b >> 30)) * 1664525L)) + seed[j] + j; // Non linear. - state[i] = (int) (c & INT_MASK_LONG); - i++; - j++; - if (i >= stateSize) { - state[0] = state[stateSize - 1]; - i = 1; - } - if (j >= seed.length) { - j = 0; - } - } - - for (int k = stateSize - 1; k > 0; k--) { - final long a = (state[i] & LOWER_MASK_LONG) | ((state[i] < 0) ? UPPER_MASK_LONG : 0); - final long b = (state[i - 1] & LOWER_MASK_LONG) | ((state[i - 1] < 0) ? UPPER_MASK_LONG : 0); - final long c = (a ^ ((b ^ (b >> 30)) * 1566083941L)) - i; // Non linear. - state[i] = (int) (c & INT_MASK_LONG); - i++; - if (i >= stateSize) { - state[0] = state[stateSize - 1]; - i = 1; - } - } - - state[0] = (int) UPPER_MASK_LONG; // MSB is 1, ensuring non-zero initial array. - } - - /** {@inheritDoc} */ - @Override - public int next() { - int y; - - if (mti >= N) { // Generate N words at one time. - int mtNext = mt[0]; - for (int k = 0; k < N - M; ++k) { - int mtCurr = mtNext; - mtNext = mt[k + 1]; - y = (mtCurr & UPPER_MASK) | (mtNext & LOWER_MASK); - mt[k] = mt[k + M] ^ (y >>> 1) ^ MAG01[y & 1]; - } - for (int k = N - M; k < N - 1; ++k) { - int mtCurr = mtNext; - mtNext = mt[k + 1]; - y = (mtCurr & UPPER_MASK) | (mtNext & LOWER_MASK); - mt[k] = mt[k + (M - N)] ^ (y >>> 1) ^ MAG01[y & 1]; - } - y = (mtNext & UPPER_MASK) | (mt[0] & LOWER_MASK); - mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ MAG01[y & 1]; - - mti = 0; - } - - y = mt[mti++]; - - // Tempering. - y ^= y >>> 11; - y ^= (y << 7) & 0x9d2c5680; - y ^= (y << 15) & 0xefc60000; - y ^= y >>> 18; - - return y; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/MultiplyWithCarry256.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/MultiplyWithCarry256.java deleted file mode 100644 index 50104ae0c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/MultiplyWithCarry256.java +++ /dev/null @@ -1,119 +0,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. - */ -package org.apache.commons.rng.core.source32; - -import org.apache.commons.rng.core.util.NumberFactory; - -import java.util.Arrays; - -/** - * Port from Marsaglia's - * "Multiply-With-Carry" algorithm. - * - *

- * Implementation is based on the (non-portable!) C code reproduced on - * - * that page. - *

- * - * @see Multiply with carry (Wikipedia) - * @since 1.0 - */ -public class MultiplyWithCarry256 extends IntProvider { - /** Length of the state array. */ - private static final int Q_SIZE = 256; - /** Size of the seed. */ - private static final int SEED_SIZE = Q_SIZE + 1; - /** Multiply. */ - private static final long A = 809430660; - /** State. */ - private final int[] state = new int[Q_SIZE]; - /** Current index in "state" array. */ - private int index; - /** Carry. */ - private int carry; - - /** - * Creates a new instance. - * - * @param seed Seed. - * If the length is larger than 257, only the first 257 elements will - * be used; if smaller, the remaining elements will be automatically - * set. - */ - public MultiplyWithCarry256(int[] seed) { - setSeedInternal(seed); - } - - /** {@inheritDoc} */ - @Override - protected byte[] getStateInternal() { - final int[] s = Arrays.copyOf(state, SEED_SIZE + 1); - s[SEED_SIZE - 1] = carry; - s[SEED_SIZE] = index; - - return composeStateInternal(NumberFactory.makeByteArray(s), - super.getStateInternal()); - } - - /** {@inheritDoc} */ - @Override - protected void setStateInternal(byte[] s) { - final byte[][] c = splitStateInternal(s, (SEED_SIZE + 1) * 4); - - final int[] tmp = NumberFactory.makeIntArray(c[0]); - - System.arraycopy(tmp, 0, state, 0, Q_SIZE); - carry = tmp[SEED_SIZE - 1]; - index = tmp[SEED_SIZE]; - - super.setStateInternal(c[1]); - } - - /** - * Seeds the RNG. - * - * @param seed Seed. - */ - private void setSeedInternal(int[] seed) { - // Reset the whole state of this RNG (i.e. "state" and "index"). - // Filling procedure is not part of the reference code. - final int[] tmp = new int[SEED_SIZE]; - fillState(tmp, seed); - - // First element of the "seed" is the initial "carry". - final int c = tmp[0]; - // Marsaglia's recommendation: 0 <= carry < A. - carry = (int) (Math.abs(c) % A); - - // Initial state. - System.arraycopy(tmp, 1, state, 0, Q_SIZE); - - // Initial index. - index = Q_SIZE; - } - - /** {@inheritDoc} */ - @Override - public int next() { - // Produce an index in the range 0-255 - index &= 0xff; - final long t = A * (state[index] & 0xffffffffL) + carry; - carry = (int) (t >> 32); - return state[index++] = (int) t; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/RandomIntSource.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/RandomIntSource.java deleted file mode 100644 index 5f7232990..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/RandomIntSource.java +++ /dev/null @@ -1,30 +0,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. - */ - -package org.apache.commons.rng.core.source32; - -/** - * Source of randomness that generates values of type {@code int}. - * - * @since 1.0 - */ -public interface RandomIntSource { - /** - * @return the next random value. - */ - int next(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well1024a.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well1024a.java deleted file mode 100644 index 5cf049d30..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well1024a.java +++ /dev/null @@ -1,78 +0,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. - */ -package org.apache.commons.rng.core.source32; - -/** - * This class implements the WELL1024a pseudo-random number generator - * from François Panneton, Pierre L'Ecuyer and Makoto Matsumoto. - *

- * This generator is described in a paper by François Panneton, - * Pierre L'Ecuyer and Makoto Matsumoto - * - * Improved Long-Period Generators Based on Linear Recurrences Modulo 2 - * ACM Transactions on Mathematical Software, 32, 1 (2006). - * The errata for the paper are in - * wellrng-errata.txt. - *

- * - * @see WELL Random number generator - * @since 1.0 - */ -public class Well1024a extends AbstractWell { - /** Number of bits in the pool. */ - private static final int K = 1024; - /** First parameter of the algorithm. */ - private static final int M1 = 3; - /** Second parameter of the algorithm. */ - private static final int M2 = 24; - /** Third parameter of the algorithm. */ - private static final int M3 = 10; - /** The indirection index table. */ - private static final IndexTable TABLE = new IndexTable(K, M1, M2, M3); - - /** - * Creates a new random number generator. - * - * @param seed Initial seed. - */ - public Well1024a(int[] seed) { - super(K, seed); - } - - /** {@inheritDoc} */ - @Override - public int next() { - final int indexRm1 = TABLE.getIndexPred(index); - - final int v0 = v[index]; - final int vM1 = v[TABLE.getIndexM1(index)]; - final int vM2 = v[TABLE.getIndexM2(index)]; - final int vM3 = v[TABLE.getIndexM3(index)]; - - final int z0 = v[indexRm1]; - final int z1 = v0 ^ (vM1 ^ (vM1 >>> 8)); - final int z2 = (vM2 ^ (vM2 << 19)) ^ (vM3 ^ (vM3 << 14)); - final int z3 = z1 ^ z2; - final int z4 = (z0 ^ (z0 << 11)) ^ (z1 ^ (z1 << 7)) ^ (z2 ^ (z2 << 13)); - - v[index] = z3; - v[indexRm1] = z4; - index = indexRm1; - - return z4; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well19937a.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well19937a.java deleted file mode 100644 index b0298446b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well19937a.java +++ /dev/null @@ -1,80 +0,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. - */ -package org.apache.commons.rng.core.source32; - -/** - * This class implements the WELL19937a pseudo-random number generator - * from François Panneton, Pierre L'Ecuyer and Makoto Matsumoto. - *

- * This generator is described in a paper by François Panneton, - * Pierre L'Ecuyer and Makoto Matsumoto - * - * Improved Long-Period Generators Based on Linear Recurrences Modulo 2 - * ACM Transactions on Mathematical Software, 32, 1 (2006). - * The errata for the paper are in - * wellrng-errata.txt. - *

- * - * @see WELL Random number generator - * @since 1.0 - */ -public class Well19937a extends AbstractWell { - /** Number of bits in the pool. */ - private static final int K = 19937; - /** First parameter of the algorithm. */ - private static final int M1 = 70; - /** Second parameter of the algorithm. */ - private static final int M2 = 179; - /** Third parameter of the algorithm. */ - private static final int M3 = 449; - /** The indirection index table. */ - private static final IndexTable TABLE = new IndexTable(K, M1, M2, M3); - - /** - * Creates a new random number generator. - * - * @param seed Initial seed. - */ - public Well19937a(int[] seed) { - super(K, seed); - } - - /** {@inheritDoc} */ - @Override - public int next() { - final int indexRm1 = TABLE.getIndexPred(index); - final int indexRm2 = TABLE.getIndexPred2(index); - - final int v0 = v[index]; - final int vM1 = v[TABLE.getIndexM1(index)]; - final int vM2 = v[TABLE.getIndexM2(index)]; - final int vM3 = v[TABLE.getIndexM3(index)]; - - final int z0 = (0x80000000 & v[indexRm1]) ^ (0x7FFFFFFF & v[indexRm2]); - final int z1 = (v0 ^ (v0 << 25)) ^ (vM1 ^ (vM1 >>> 27)); - final int z2 = (vM2 >>> 9) ^ (vM3 ^ (vM3 >>> 1)); - final int z3 = z1 ^ z2; - final int z4 = z0 ^ (z1 ^ (z1 << 9)) ^ (z2 ^ (z2 << 21)) ^ (z3 ^ (z3 >>> 21)); - - v[index] = z3; - v[indexRm1] = z4; - v[indexRm2] &= 0x80000000; - index = indexRm1; - - return z4; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well19937c.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well19937c.java deleted file mode 100644 index 1a0c174e0..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well19937c.java +++ /dev/null @@ -1,56 +0,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. - */ -package org.apache.commons.rng.core.source32; - -/** - * This class implements the WELL19937c pseudo-random number generator - * from François Panneton, Pierre L'Ecuyer and Makoto Matsumoto. - *

- * This generator is described in a paper by François Panneton, - * Pierre L'Ecuyer and Makoto Matsumoto - * - * Improved Long-Period Generators Based on Linear Recurrences Modulo 2 - * ACM Transactions on Mathematical Software, 32, 1 (2006). - * The errata for the paper are in - * wellrng-errata.txt. - *

- * - * @see WELL Random number generator - * @since 1.0 - */ -public class Well19937c extends Well19937a { - /** - * Creates a new random number generator. - * - * @param seed Initial seed. - */ - public Well19937c(int[] seed) { - super(seed); - } - - /** {@inheritDoc} */ - @Override - public int next() { - int z4 = super.next(); - - // Matsumoto-Kurita tempering to get a maximally equidistributed generator. - z4 ^= (z4 << 7) & 0xe46e1700; - z4 ^= (z4 << 15) & 0x9b868000; - - return z4; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well44497a.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well44497a.java deleted file mode 100644 index 4f240379d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well44497a.java +++ /dev/null @@ -1,83 +0,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. - */ -package org.apache.commons.rng.core.source32; - -/** - * This class implements the WELL44497a pseudo-random number generator - * from François Panneton, Pierre L'Ecuyer and Makoto Matsumoto. - *

- * This generator is described in a paper by François Panneton, - * Pierre L'Ecuyer and Makoto Matsumoto - * - * Improved Long-Period Generators Based on Linear Recurrences Modulo 2 - * ACM Transactions on Mathematical Software, 32, 1 (2006). - * The errata for the paper are in - * wellrng-errata.txt. - *

- * - * @see WELL Random number generator - * @since 1.0 - */ -public class Well44497a extends AbstractWell { - /** Number of bits in the pool. */ - private static final int K = 44497; - /** First parameter of the algorithm. */ - private static final int M1 = 23; - /** Second parameter of the algorithm. */ - private static final int M2 = 481; - /** Third parameter of the algorithm. */ - private static final int M3 = 229; - /** The indirection index table. */ - private static final IndexTable TABLE = new IndexTable(K, M1, M2, M3); - - /** - * Creates a new random number generator. - * - * @param seed Initial seed. - */ - public Well44497a(int[] seed) { - super(K, seed); - } - - /** {@inheritDoc} */ - @Override - public int next() { - final int indexRm1 = TABLE.getIndexPred(index); - final int indexRm2 = TABLE.getIndexPred2(index); - - final int v0 = v[index]; - final int vM1 = v[TABLE.getIndexM1(index)]; - final int vM2 = v[TABLE.getIndexM2(index)]; - final int vM3 = v[TABLE.getIndexM3(index)]; - - // the values below include the errata of the original article - final int z0 = (0xFFFF8000 & v[indexRm1]) ^ (0x00007FFF & v[indexRm2]); - final int z1 = (v0 ^ (v0 << 24)) ^ (vM1 ^ (vM1 >>> 30)); - final int z2 = (vM2 ^ (vM2 << 10)) ^ (vM3 << 26); - final int z3 = z1 ^ z2; - final int z2Prime = ((z2 << 9) ^ (z2 >>> 23)) & 0xfbffffff; - final int z2Second = ((z2 & 0x00020000) != 0) ? (z2Prime ^ 0xb729fcec) : z2Prime; - final int z4 = z0 ^ (z1 ^ (z1 >>> 20)) ^ z2Second ^ z3; - - v[index] = z3; - v[indexRm1] = z4; - v[indexRm2] &= 0xFFFF8000; - index = indexRm1; - - return z4; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well44497b.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well44497b.java deleted file mode 100644 index 9d1087c9b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well44497b.java +++ /dev/null @@ -1,56 +0,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. - */ -package org.apache.commons.rng.core.source32; - -/** - * This class implements the WELL44497b pseudo-random number generator - * from François Panneton, Pierre L'Ecuyer and Makoto Matsumoto. - *

- * This generator is described in a paper by François Panneton, - * Pierre L'Ecuyer and Makoto Matsumoto - * - * Improved Long-Period Generators Based on Linear Recurrences Modulo 2 - * ACM Transactions on Mathematical Software, 32, 1 (2006). - * The errata for the paper are in - * wellrng-errata.txt. - *

- * - * @see WELL Random number generator - * @since 1.0 - */ -public class Well44497b extends Well44497a { - /** - * Creates a new random number generator. - * - * @param seed Initial seed. - */ - public Well44497b(int[] seed) { - super(seed); - } - - /** {@inheritDoc} */ - @Override - public int next() { - int z4 = super.next(); - - // Matsumoto-Kurita tempering to get a maximally equidistributed generator. - z4 ^= (z4 << 7) & 0x93dd1400; - z4 ^= (z4 << 15) & 0xfa118000; - - return z4; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well512a.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well512a.java deleted file mode 100644 index 6251d7b06..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/Well512a.java +++ /dev/null @@ -1,78 +0,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. - */ -package org.apache.commons.rng.core.source32; - -/** - * This class implements the WELL512a pseudo-random number generator - * from François Panneton, Pierre L'Ecuyer and Makoto Matsumoto. - *

- * This generator is described in a paper by François Panneton, - * Pierre L'Ecuyer and Makoto Matsumoto - * - * Improved Long-Period Generators Based on Linear Recurrences Modulo 2 - * ACM Transactions on Mathematical Software, 32, 1 (2006). - * The errata for the paper are in - * wellrng-errata.txt. - *

- * - * @see WELL Random number generator - * @since 1.0 - */ -public class Well512a extends AbstractWell { - /** Number of bits in the pool. */ - private static final int K = 512; - /** First parameter of the algorithm. */ - private static final int M1 = 13; - /** Second parameter of the algorithm. */ - private static final int M2 = 9; - /** Third parameter of the algorithm. */ - private static final int M3 = 5; - /** The indirection index table. */ - private static final IndexTable TABLE = new IndexTable(K, M1, M2, M3); - - /** - * Creates a new random number generator. - * - * @param seed Initial seed. - */ - public Well512a(int[] seed) { - super(K, seed); - } - - /** {@inheritDoc} */ - @Override - public int next() { - final int indexRm1 = TABLE.getIndexPred(index); - - final int vi = v[index]; - final int vi1 = v[TABLE.getIndexM1(index)]; - final int vi2 = v[TABLE.getIndexM2(index)]; - final int z0 = v[indexRm1]; - - // the values below include the errata of the original article - final int z1 = (vi ^ (vi << 16)) ^ (vi1 ^ (vi1 << 15)); - final int z2 = vi2 ^ (vi2 >>> 11); - final int z3 = z1 ^ z2; - final int z4 = (z0 ^ (z0 << 2)) ^ (z1 ^ (z1 << 18)) ^ (z2 << 28) ^ (z3 ^ ((z3 << 5) & 0xda442d24)); - - v[index] = z3; - v[indexRm1] = z4; - index = indexRm1; - - return z4; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/XoRoShiRo64Star.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/XoRoShiRo64Star.java deleted file mode 100644 index 762fe0e76..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/XoRoShiRo64Star.java +++ /dev/null @@ -1,69 +0,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. - */ - -package org.apache.commons.rng.core.source32; - -/** - * A fast 32-bit generator suitable for {@code float} generation. This is slightly faster than the - * all-purpose generator {@link XoRoShiRo64StarStar}. - * - *

This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 64 - * bits.

- * - * @see Original source code - * @see xorshiro / xoroshiro generators - * - * @since 1.3 - */ -public class XoRoShiRo64Star extends AbstractXoRoShiRo64 { - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 2, only the first 2 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - */ - public XoRoShiRo64Star(int[] seed) { - super(seed); - } - - /** - * Creates a new instance using a 2 element seed. - * A seed containing all zeros will create a non-functional generator. - * - * @param seed0 Initial seed element 0. - * @param seed1 Initial seed element 1. - */ - public XoRoShiRo64Star(int seed0, int seed1) { - super(seed0, seed1); - } - - /** {@inheritDoc} */ - @Override - public int next() { - final int s0 = state0; - int s1 = state1; - final int result = s0 * 0x9E3779BB; - - s1 ^= s0; - state0 = Integer.rotateLeft(s0, 26) ^ s1 ^ (s1 << 9); // a, b - state1 = Integer.rotateLeft(s1, 13); // c - - return result; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/XoRoShiRo64StarStar.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/XoRoShiRo64StarStar.java deleted file mode 100644 index a7ca604f1..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/XoRoShiRo64StarStar.java +++ /dev/null @@ -1,69 +0,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. - */ - -package org.apache.commons.rng.core.source32; - -/** - * A fast all-purpose 32-bit generator. For faster generation of {@code float} values try the - * {@link XoRoShiRo64Star} generator. - * - *

This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 64 - * bits.

- * - * @see Original source code - * @see xorshiro / xoroshiro generators - * - * @since 1.3 - */ -public class XoRoShiRo64StarStar extends AbstractXoRoShiRo64 { - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 2, only the first 2 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - */ - public XoRoShiRo64StarStar(int[] seed) { - super(seed); - } - - /** - * Creates a new instance using a 2 element seed. - * A seed containing all zeros will create a non-functional generator. - * - * @param seed0 Initial seed element 0. - * @param seed1 Initial seed element 1. - */ - public XoRoShiRo64StarStar(int seed0, int seed1) { - super(seed0, seed1); - } - - /** {@inheritDoc} */ - @Override - public int next() { - final int s0 = state0; - int s1 = state1; - final int result = Integer.rotateLeft(s0 * 0x9E3779BB, 5) * 5; - - s1 ^= s0; - state0 = Integer.rotateLeft(s0, 26) ^ s1 ^ (s1 << 9); // a, b - state1 = Integer.rotateLeft(s1, 13); // c - - return result; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/XoShiRo128Plus.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/XoShiRo128Plus.java deleted file mode 100644 index d49a5b13a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/XoShiRo128Plus.java +++ /dev/null @@ -1,76 +0,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. - */ - -package org.apache.commons.rng.core.source32; - -/** - * A fast 32-bit generator suitable for {@code float} generation. This is slightly faster than the - * all-purpose generator {@link XoShiRo128StarStar}. - * - *

This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 128 - * bits.

- * - * @see Original source code - * @see xorshiro / xoroshiro generators - * - * @since 1.3 - */ -public class XoShiRo128Plus extends AbstractXoShiRo128 { - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 4, only the first 4 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - */ - public XoShiRo128Plus(int[] seed) { - super(seed); - } - - /** - * Creates a new instance using a 4 element seed. - * A seed containing all zeros will create a non-functional generator. - * - * @param seed0 Initial seed element 0. - * @param seed1 Initial seed element 1. - * @param seed2 Initial seed element 2. - * @param seed3 Initial seed element 3. - */ - public XoShiRo128Plus(int seed0, int seed1, int seed2, int seed3) { - super(seed0, seed1, seed2, seed3); - } - - /** {@inheritDoc} */ - @Override - public int next() { - final int result = state0 + state3; - - final int t = state1 << 9; - - state2 ^= state0; - state3 ^= state1; - state1 ^= state2; - state0 ^= state3; - - state2 ^= t; - - state3 = Integer.rotateLeft(state3, 11); - - return result; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/XoShiRo128StarStar.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/XoShiRo128StarStar.java deleted file mode 100644 index 84668a812..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/XoShiRo128StarStar.java +++ /dev/null @@ -1,76 +0,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. - */ - -package org.apache.commons.rng.core.source32; - -/** - * A fast all-purpose 32-bit generator. For faster generation of {@code float} values try the - * {@link XoShiRo128Plus} generator. - * - *

This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 128 - * bits.

- * - * @see Original source code - * @see xorshiro / xoroshiro generators - * - * @since 1.3 - */ -public class XoShiRo128StarStar extends AbstractXoShiRo128 { - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 4, only the first 4 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - */ - public XoShiRo128StarStar(int[] seed) { - super(seed); - } - - /** - * Creates a new instance using a 4 element seed. - * A seed containing all zeros will create a non-functional generator. - * - * @param seed0 Initial seed element 0. - * @param seed1 Initial seed element 1. - * @param seed2 Initial seed element 2. - * @param seed3 Initial seed element 3. - */ - public XoShiRo128StarStar(int seed0, int seed1, int seed2, int seed3) { - super(seed0, seed1, seed2, seed3); - } - - /** {@inheritDoc} */ - @Override - public int next() { - final int result = Integer.rotateLeft(state0 * 5, 7) * 9; - - final int t = state1 << 9; - - state2 ^= state0; - state3 ^= state1; - state1 ^= state2; - state0 ^= state3; - - state2 ^= t; - - state3 = Integer.rotateLeft(state3, 11); - - return result; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/package-info.java deleted file mode 100644 index d7cbc9e35..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source32/package-info.java +++ /dev/null @@ -1,52 +0,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. - */ - -/** - *

- * Concrete algorithms for {@code int}-based sources of randomness - *

- * - *

- * For internal use only: Direct access to classes in this package - * is discouraged, as they could be modified without notice. - *

- * - *

Notes for developers

- * - *
    - *
  • - * A source of randomness must inherit from - * {@link org.apache.commons.rng.core.source32.IntProvider} - *
  • - *
  • - * The "provider" must specify one way for setting the seed. - * For a given seed, the generated sequence must always be the same. - *
  • - *
  • - * The "provider" must implement methods {@code getStateInternal} and - * {@code setStateInternal} in order to save and restore the state of an - * instance (cf. {@link org.apache.commons.rng.core.BaseProvider}). - *
  • - *
  • - * When a new class is implemented here, user-access to it must be - * provided through associated {@code RandomSource} factory methods - * defined in module "commons-rng-simple". - *
  • - *
- */ - -package org.apache.commons.rng.core.source32; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/AbstractXoRoShiRo128.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/AbstractXoRoShiRo128.java deleted file mode 100644 index 3e9bfab6c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/AbstractXoRoShiRo128.java +++ /dev/null @@ -1,97 +0,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. - */ - -package org.apache.commons.rng.core.source64; - -import org.apache.commons.rng.core.util.NumberFactory; - -/** - * This abstract class is a base for algorithms from the Xor-Shift-Rotate family of 64-bit - * generators with 128-bits of state. - * - * @see xorshiro / xoroshiro generators - * - * @since 1.3 - */ -abstract class AbstractXoRoShiRo128 extends LongProvider { - /** Size of the state vector. */ - private static final int SEED_SIZE = 2; - - // State is maintained using variables rather than an array for performance - - /** State 0 of the generator. */ - protected long state0; - /** State 1 of the generator. */ - protected long state1; - - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 2, only the first 2 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - */ - AbstractXoRoShiRo128(long[] seed) { - if (seed.length < SEED_SIZE) { - final long[] state = new long[SEED_SIZE]; - fillState(state, seed); - setState(state); - } else { - setState(seed); - } - } - - /** - * Creates a new instance using a 2 element seed. - * A seed containing all zeros will create a non-functional generator. - * - * @param seed0 Initial seed element 0. - * @param seed1 Initial seed element 1. - */ - AbstractXoRoShiRo128(long seed0, long seed1) { - state0 = seed0; - state1 = seed1; - } - - /** - * Copies the state from the array into the generator state. - * - * @param state the new state - */ - private void setState(long[] state) { - state0 = state[0]; - state1 = state[1]; - } - - /** {@inheritDoc} */ - @Override - protected byte[] getStateInternal() { - return composeStateInternal(NumberFactory.makeByteArray(new long[] {state0, state1}), - super.getStateInternal()); - } - - /** {@inheritDoc} */ - @Override - protected void setStateInternal(byte[] s) { - final byte[][] c = splitStateInternal(s, SEED_SIZE * 8); - - setState(NumberFactory.makeLongArray(c[0])); - - super.setStateInternal(c[1]); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/AbstractXoShiRo256.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/AbstractXoShiRo256.java deleted file mode 100644 index 677e1a6cc..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/AbstractXoShiRo256.java +++ /dev/null @@ -1,108 +0,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. - */ - -package org.apache.commons.rng.core.source64; - -import org.apache.commons.rng.core.util.NumberFactory; - -/** - * This abstract class is a base for algorithms from the Xor-Shift-Rotate family of 64-bit - * generators with 256-bits of state. - * - * @see xorshiro / xoroshiro generators - * - * @since 1.3 - */ -abstract class AbstractXoShiRo256 extends LongProvider { - /** Size of the state vector. */ - private static final int SEED_SIZE = 4; - - // State is maintained using variables rather than an array for performance - - /** State 0 of the generator. */ - protected long state0; - /** State 1 of the generator. */ - protected long state1; - /** State 2 of the generator. */ - protected long state2; - /** State 3 of the generator. */ - protected long state3; - - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 4, only the first 4 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - */ - AbstractXoShiRo256(long[] seed) { - if (seed.length < SEED_SIZE) { - final long[] state = new long[SEED_SIZE]; - fillState(state, seed); - setState(state); - } else { - setState(seed); - } - } - - /** - * Creates a new instance using a 4 element seed. - * A seed containing all zeros will create a non-functional generator. - * - * @param seed0 Initial seed element 0. - * @param seed1 Initial seed element 1. - * @param seed2 Initial seed element 2. - * @param seed3 Initial seed element 3. - */ - AbstractXoShiRo256(long seed0, long seed1, long seed2, long seed3) { - state0 = seed0; - state1 = seed1; - state2 = seed2; - state3 = seed3; - } - - /** - * Copies the state from the array into the generator state. - * - * @param state the new state - */ - private void setState(long[] state) { - state0 = state[0]; - state1 = state[1]; - state2 = state[2]; - state3 = state[3]; - } - - /** {@inheritDoc} */ - @Override - protected byte[] getStateInternal() { - return composeStateInternal(NumberFactory.makeByteArray( - new long[] {state0, state1, state2, state3}), - super.getStateInternal()); - } - - /** {@inheritDoc} */ - @Override - protected void setStateInternal(byte[] s) { - final byte[][] c = splitStateInternal(s, SEED_SIZE * 8); - - setState(NumberFactory.makeLongArray(c[0])); - - super.setStateInternal(c[1]); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/AbstractXoShiRo512.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/AbstractXoShiRo512.java deleted file mode 100644 index fbcbce7a7..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/AbstractXoShiRo512.java +++ /dev/null @@ -1,130 +0,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. - */ - -package org.apache.commons.rng.core.source64; - -import org.apache.commons.rng.core.util.NumberFactory; - -/** - * This abstract class is a base for algorithms from the Xor-Shift-Rotate family of 64-bit - * generators with 512-bits of state. - * - * @see xorshiro / xoroshiro generators - * - * @since 1.3 - */ -abstract class AbstractXoShiRo512 extends LongProvider { - /** Size of the state vector. */ - private static final int SEED_SIZE = 8; - - // State is maintained using variables rather than an array for performance - - /** State 0 of the generator. */ - protected long state0; - /** State 1 of the generator. */ - protected long state1; - /** State 2 of the generator. */ - protected long state2; - /** State 3 of the generator. */ - protected long state3; - /** State 4 of the generator. */ - protected long state4; - /** State 5 of the generator. */ - protected long state5; - /** State 6 of the generator. */ - protected long state6; - /** State 7 of the generator. */ - protected long state7; - - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 8, only the first 8 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - */ - AbstractXoShiRo512(long[] seed) { - if (seed.length < SEED_SIZE) { - final long[] state = new long[SEED_SIZE]; - fillState(state, seed); - setState(state); - } else { - setState(seed); - } - } - - /** - * Creates a new instance using an 8 element seed. - * A seed containing all zeros will create a non-functional generator. - * - * @param seed0 Initial seed element 0. - * @param seed1 Initial seed element 1. - * @param seed2 Initial seed element 2. - * @param seed3 Initial seed element 3. - * @param seed4 Initial seed element 4. - * @param seed5 Initial seed element 5. - * @param seed6 Initial seed element 6. - * @param seed7 Initial seed element 7. - */ - AbstractXoShiRo512(long seed0, long seed1, long seed2, long seed3, - long seed4, long seed5, long seed6, long seed7) { - state0 = seed0; - state1 = seed1; - state2 = seed2; - state3 = seed3; - state4 = seed4; - state5 = seed5; - state6 = seed6; - state7 = seed7; - } - - /** - * Copies the state from the array into the generator state. - * - * @param state the new state - */ - private void setState(long[] state) { - state0 = state[0]; - state1 = state[1]; - state2 = state[2]; - state3 = state[3]; - state4 = state[4]; - state5 = state[5]; - state6 = state[6]; - state7 = state[7]; - } - - /** {@inheritDoc} */ - @Override - protected byte[] getStateInternal() { - return composeStateInternal(NumberFactory.makeByteArray( - new long[] {state0, state1, state2, state3, - state4, state5, state6, state7}), - super.getStateInternal()); - } - - /** {@inheritDoc} */ - @Override - protected void setStateInternal(byte[] s) { - final byte[][] c = splitStateInternal(s, SEED_SIZE * 8); - - setState(NumberFactory.makeLongArray(c[0])); - - super.setStateInternal(c[1]); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/LongProvider.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/LongProvider.java deleted file mode 100644 index 5c6f310ea..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/LongProvider.java +++ /dev/null @@ -1,204 +0,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. - */ - -package org.apache.commons.rng.core.source64; - -import org.apache.commons.rng.core.BaseProvider; -import org.apache.commons.rng.core.util.NumberFactory; - -/** - * Base class for all implementations that provide a {@code long}-based - * source randomness. - */ -public abstract class LongProvider - extends BaseProvider - implements RandomLongSource { - - /** - * Provides a bit source for booleans. - * - *

A cached value from a call to {@link #nextLong()}. - */ - private long booleanSource; // Initialised as 0 - - /** - * The bit mask of the boolean source to obtain the boolean bit. - * - *

The bit mask contains a single bit set. This begins at the least - * significant bit and is gradually shifted upwards until overflow to zero. - * - *

When zero a new boolean source should be created and the mask set to the - * least significant bit (i.e. 1). - */ - private long booleanBitMask; // Initialised as 0 - - /** - * Provides a source for ints. - * - *

A cached value from a call to {@link #nextLong()}. - */ - private long intSource; - - /** Flag to indicate an int source has been cached. */ - private boolean cachedIntSource; // Initialised as false - - /** {@inheritDoc} */ - @Override - protected byte[] getStateInternal() { - // Pack the boolean inefficiently as a long - final long[] state = new long[] { booleanSource, - booleanBitMask, - intSource, - cachedIntSource ? 1 : 0 }; - return composeStateInternal(super.getStateInternal(), - NumberFactory.makeByteArray(state)); - } - - /** {@inheritDoc} */ - @Override - protected void setStateInternal(byte[] s) { - final byte[][] c = splitStateInternal(s, 32); - final long[] state = NumberFactory.makeLongArray(c[0]); - booleanSource = state[0]; - booleanBitMask = state[1]; - intSource = state[2]; - // Non-zero is true - cachedIntSource = state[3] != 0; - super.setStateInternal(c[1]); - } - - /** {@inheritDoc} */ - @Override - public long nextLong() { - return next(); - } - - /** {@inheritDoc} */ - @Override - public int nextInt() { - // Directly store and use the long value as a source for ints - if (cachedIntSource) { - // Consume the cache value - cachedIntSource = false; - // Return the lower 32 bits - return NumberFactory.extractLo(intSource); - } - // Fill the cache - cachedIntSource = true; - intSource = nextLong(); - // Return the upper 32 bits - return NumberFactory.extractHi(intSource); - } - - /** {@inheritDoc} */ - @Override - public double nextDouble() { - return NumberFactory.makeDouble(nextLong()); - } - - /** {@inheritDoc} */ - @Override - public boolean nextBoolean() { - // Shift up. This will eventually overflow and become zero. - booleanBitMask <<= 1; - // The mask will either contain a single bit or none. - if (booleanBitMask == 0) { - // Set the least significant bit - booleanBitMask = 1; - // Get the next value - booleanSource = nextLong(); - } - // Return if the bit is set - return (booleanSource & booleanBitMask) != 0; - } - - /** {@inheritDoc} */ - @Override - public float nextFloat() { - return NumberFactory.makeFloat(nextInt()); - } - - /** {@inheritDoc} */ - @Override - public void nextBytes(byte[] bytes) { - nextBytesFill(this, bytes, 0, bytes.length); - } - - /** {@inheritDoc} */ - @Override - public void nextBytes(byte[] bytes, - int start, - int len) { - checkIndex(0, bytes.length - 1, start); - checkIndex(0, bytes.length - start, len); - - nextBytesFill(this, bytes, start, len); - } - - /** - * Generates random bytes and places them into a user-supplied array. - * - *

- * The array is filled with bytes extracted from random {@code long} values. - * This implies that the number of random bytes generated may be larger than - * the length of the byte array. - *

- * - * @param source Source of randomness. - * @param bytes Array in which to put the generated bytes. Cannot be null. - * @param start Index at which to start inserting the generated bytes. - * @param len Number of bytes to insert. - */ - static void nextBytesFill(RandomLongSource source, - byte[] bytes, - int start, - int len) { - int index = start; // Index of first insertion. - - // Index of first insertion plus multiple of 8 part of length - // (i.e. length with 3 least significant bits unset). - final int indexLoopLimit = index + (len & 0x7ffffff8); - - // Start filling in the byte array, 8 bytes at a time. - while (index < indexLoopLimit) { - final long random = source.next(); - bytes[index++] = (byte) random; - bytes[index++] = (byte) (random >>> 8); - bytes[index++] = (byte) (random >>> 16); - bytes[index++] = (byte) (random >>> 24); - bytes[index++] = (byte) (random >>> 32); - bytes[index++] = (byte) (random >>> 40); - bytes[index++] = (byte) (random >>> 48); - bytes[index++] = (byte) (random >>> 56); - } - - final int indexLimit = start + len; // Index of last insertion + 1. - - // Fill in the remaining bytes. - if (index < indexLimit) { - long random = source.next(); - while (true) { - bytes[index++] = (byte) random; - if (index < indexLimit) { - random >>>= 8; - } else { - break; - } - } - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/MersenneTwister64.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/MersenneTwister64.java deleted file mode 100644 index 72b6aa3bb..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/MersenneTwister64.java +++ /dev/null @@ -1,207 +0,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. - */ -package org.apache.commons.rng.core.source64; - -import org.apache.commons.rng.core.util.NumberFactory; - -import java.util.Arrays; - -/** - * This class provides the 64-bits version of the originally 32-bits - * {@link org.apache.commons.rng.core.source32.MersenneTwister - * Mersenne Twister}. - * - *

- * This class is mainly a Java port of - * - * the 2014/2/23 version of the generator - * written in C by Takuji Nishimura and Makoto Matsumoto. - *

- * - *

- * Here is their original copyright: - *

- * - * - * - * - * - * - * - * - *
Mersenne Twister licence
Copyright (C) 2004, Makoto Matsumoto and Takuji Nishimura, - * All rights reserved.
Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - *
    - *
  1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer.
  2. - *
  3. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution.
  4. - *
  5. The names of its contributors may not be used to endorse or promote - * products derived from this software without specific prior written - * permission.
  6. - *
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE - * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH - * DAMAGE.
- * - * @see Mersenne Twister (Wikipedia) - * @since 1.0 - */ -public class MersenneTwister64 extends LongProvider { - /** Size of the bytes pool. */ - private static final int NN = 312; - /** Period second parameter. */ - private static final int MM = 156; - /** X * MATRIX_A for X = {0, 1}. */ - private static final long[] MAG01 = { 0x0, 0xb5026f5aa96619e9L }; - /** Most significant 33 bits. */ - private static final long UM = 0xffffffff80000000L; - /** Least significant 31 bits. */ - private static final long LM = 0x7fffffffL; - /** Bytes pool. */ - private long[] mt = new long[NN]; - /** Current index in the bytes pool. */ - private int mti; - - /** - * Creates a new random number generator. - * - * @param seed Initial seed. - */ - public MersenneTwister64(long[] seed) { - setSeedInternal(seed); - } - - /** {@inheritDoc} */ - @Override - protected byte[] getStateInternal() { - final long[] s = Arrays.copyOf(mt, NN + 1); - s[NN] = mti; - - return composeStateInternal(NumberFactory.makeByteArray(s), - super.getStateInternal()); - } - - /** {@inheritDoc} */ - @Override - protected void setStateInternal(byte[] s) { - final byte[][] c = splitStateInternal(s, (NN + 1) * 8); - - final long[] tmp = NumberFactory.makeLongArray(c[0]); - System.arraycopy(tmp, 0, mt, 0, NN); - mti = (int) tmp[NN]; - - super.setStateInternal(c[1]); - } - - /** - * Initializes the generator with the given seed. - * - * @param seed Initial seed. - */ - private void setSeedInternal(long[] seed) { - if (seed.length == 0) { - // Accept empty seed. - seed = new long[1]; - } - - initState(19650218L); - int i = 1; - int j = 0; - - for (int k = Math.max(NN, seed.length); k != 0; k--) { - final long mm1 = mt[i - 1]; - mt[i] = (mt[i] ^ ((mm1 ^ (mm1 >>> 62)) * 0x369dea0f31a53f85L)) + seed[j] + j; // non linear - i++; - j++; - if (i >= NN) { - mt[0] = mt[NN - 1]; - i = 1; - } - if (j >= seed.length) { - j = 0; - } - } - for (int k = NN - 1; k != 0; k--) { - final long mm1 = mt[i - 1]; - mt[i] = (mt[i] ^ ((mm1 ^ (mm1 >>> 62)) * 0x27bb2ee687b0b0fdL)) - i; // non linear - i++; - if (i >= NN) { - mt[0] = mt[NN - 1]; - i = 1; - } - } - - mt[0] = 0x8000000000000000L; // MSB is 1; assuring non-zero initial array - } - - /** - * Initialize the internal state of this instance. - * - * @param seed Seed. - */ - private void initState(long seed) { - mt[0] = seed; - for (mti = 1; mti < NN; mti++) { - final long mm1 = mt[mti - 1]; - mt[mti] = 0x5851f42d4c957f2dL * (mm1 ^ (mm1 >>> 62)) + mti; - } - } - - /** {@inheritDoc} */ - @Override - public long next() { - long x; - - if (mti >= NN) { // generate NN words at one time - for (int i = 0; i < NN - MM; i++) { - x = (mt[i] & UM) | (mt[i + 1] & LM); - mt[i] = mt[i + MM] ^ (x >>> 1) ^ MAG01[(int)(x & 0x1L)]; - } - for (int i = NN - MM; i < NN - 1; i++) { - x = (mt[i] & UM) | (mt[i + 1] & LM); - mt[i] = mt[ i + (MM - NN)] ^ (x >>> 1) ^ MAG01[(int)(x & 0x1L)]; - } - - x = (mt[NN - 1] & UM) | (mt[0] & LM); - mt[NN - 1] = mt[MM - 1] ^ (x >>> 1) ^ MAG01[(int)(x & 0x1L)]; - - mti = 0; - } - - x = mt[mti++]; - - x ^= (x >>> 29) & 0x5555555555555555L; - x ^= (x << 17) & 0x71d67fffeda60000L; - x ^= (x << 37) & 0xfff7eee000000000L; - x ^= x >>> 43; - - return x; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/RandomLongSource.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/RandomLongSource.java deleted file mode 100644 index 0b3a19dc7..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/RandomLongSource.java +++ /dev/null @@ -1,30 +0,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. - */ - -package org.apache.commons.rng.core.source64; - -/** - * Source of randomness that generates values of type {@code long}. - * - * @since 1.0 - */ -public interface RandomLongSource { - /** - * @return the next random value. - */ - long next(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/SplitMix64.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/SplitMix64.java deleted file mode 100644 index 145c8741f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/SplitMix64.java +++ /dev/null @@ -1,77 +0,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. - */ - -package org.apache.commons.rng.core.source64; - -import org.apache.commons.rng.core.util.NumberFactory; - -/** - * A fast RNG, with 64 bits of state, that can be used to initialize the - * state of other generators. - * - * @see - * Original source code - * - * @since 1.0 - */ -public class SplitMix64 extends LongProvider { - /** State. */ - private long state; - - /** - * Creates a new instance. - * - * @param seed Initial seed. - */ - public SplitMix64(Long seed) { - setSeedInternal(seed); - } - - /** - * Seeds the RNG. - * - * @param seed Seed. - */ - private void setSeedInternal(Long seed) { - state = seed; - } - - /** {@inheritDoc} */ - @Override - public long next() { - long z = state += 0x9e3779b97f4a7c15L; - z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L; - z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL; - return z ^ (z >>> 31); - } - - /** {@inheritDoc} */ - @Override - protected byte[] getStateInternal() { - return composeStateInternal(NumberFactory.makeByteArray(state), - super.getStateInternal()); - } - - /** {@inheritDoc} */ - @Override - protected void setStateInternal(byte[] s) { - final byte[][] c = splitStateInternal(s, 8); - - state = NumberFactory.makeLong(c[0]); - super.setStateInternal(c[1]); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/TwoCmres.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/TwoCmres.java deleted file mode 100644 index 21d76e756..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/TwoCmres.java +++ /dev/null @@ -1,324 +0,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. - */ - -package org.apache.commons.rng.core.source64; - -import org.apache.commons.rng.core.util.NumberFactory; - -import java.util.ArrayList; -import java.util.List; - -/** - * Random number generator designed by Mark D. Overton. - * - *

It is one of the many generators described by the author in the following article series:

- * - * - * @since 1.0 - */ -public class TwoCmres extends LongProvider { - /** Error message. */ - private static final String INTERNAL_ERROR_MSG = "Internal error: Please file a bug report"; - /** A small positive integer. */ - private static final byte SEED_GUARD = 9; - /** Factory of instances of this class. Singleton. */ - private static final Cmres.Factory FACTORY = new Cmres.Factory(); - /** First subcycle generator. */ - private final Cmres x; - /** Second subcycle generator. */ - private final Cmres y; - /** State of first subcycle generator. */ - private long xx; - /** State of second subcycle generator. */ - private long yy; - - /** - * Creates a new instance. - * - * @param seed Initial seed. - * @param x First subcycle generator. - * @param y Second subcycle generator. - * @throws IllegalArgumentException if {@code x == y}. - */ - private TwoCmres(int seed, - Cmres x, - Cmres y) { - if (x == y) { - throw new IllegalArgumentException("Subcycle generators must be different"); - } - this.x = x; - this.y = y; - setSeedInternal(seed); - } - - /** - * Creates a new instance. - * - * @param seed Seed. - */ - public TwoCmres(Integer seed) { - this(seed, 0, 1); - } - - /** - * Creates a new instance. - * - * @param seed Seed. - * @param i Table entry for first subcycle generator. - * @param j Table entry for second subcycle generator. - * @throws IllegalArgumentException if {@code i == j}. - * @throws IndexOutOfBoundsException if {@code i < 0} or - * {@code i >= numberOfSubcycleGenerators()}. - * @throws IndexOutOfBoundsException if {@code j < 0} or - * {@code j >= numberOfSubcycleGenerators()}. - */ - public TwoCmres(Integer seed, - int i, - int j) { - this(seed, FACTORY.get(i), FACTORY.get(j)); - } - - /** {@inheritDoc} */ - @Override - public long next() { - xx = x.transform(xx); - yy = y.transform(yy); - - return xx + yy; - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return super.toString() + " (" + x + " + " + y + ")"; - } - - /** - * @return the number of subcycle generators. - */ - public static int numberOfSubcycleGenerators() { - return FACTORY.numberOfSubcycleGenerators(); - } - - /** {@inheritDoc} */ - @Override - protected byte[] getStateInternal() { - return composeStateInternal(NumberFactory.makeByteArray(new long[] { xx, yy }), - super.getStateInternal()); - } - - /** {@inheritDoc} */ - @Override - protected void setStateInternal(byte[] s) { - final byte[][] c = splitStateInternal(s, 16); - - final long[] state = NumberFactory.makeLongArray(c[0]); - xx = state[0]; - yy = state[1]; - - super.setStateInternal(c[1]); - } - - /** - * @param seed Seed. - */ - private void setSeedInternal(int seed) { - // The seeding procedure consists in going away from some - // point known to be in the cycle. - // The total number of calls to the "transform" method will - // not exceed about 130,000 (which is negligible as seeding - // will not occur more than once in normal usage). - - // Make two positive 16-bits integers from the 32-bit seed. - // Add the small positive seed guard. The result will never be negative. - final int xMax = (seed & 0xffff) + (SEED_GUARD & 0xff); - final int yMax = (seed >>> 16) + (SEED_GUARD & 0xff); - - if (xMax < 0 || - yMax < 0) { - throw new IllegalStateException(INTERNAL_ERROR_MSG); - } - - xx = x.getStart(); - for (int i = xMax; i > 0; i--) { - xx = x.transform(xx); - } - - yy = y.getStart(); - for (int i = yMax; i > 0; i--) { - yy = y.transform(yy); - } - } - - /** - * Subcycle generator. - * Class is immutable. - */ - static class Cmres { - /** Separator. */ - private static final String SEP = ", "; - /** Hexadecimal format. */ - private static final String HEX_FORMAT = "0x%016xL"; - /** Cycle start. */ - private final int start; - /** Multiplier. */ - private final long multiply; - /** Rotation. */ - private final int rotate; - - /** - * @param multiply Multiplier. - * @param rotate Positive number. Must be in {@code [0, 64]}. - * @param start Cycle start. - */ - Cmres(long multiply, - int rotate, - int start) { - this.multiply = multiply; - this.rotate = rotate; - this.start = start; - } - - /** {@inheritDoc} */ - @Override - public String toString() { - final String m = String.format((java.util.Locale) null, HEX_FORMAT, multiply); - return "Cmres: [" + m + SEP + rotate + SEP + start + "]"; - } - - /** - * @return the multiplier. - */ - public long getMultiply() { - return multiply; - } - - /** - * @return the cycle start. - */ - public int getStart() { - return start; - } - - /** - * @param state Current state. - * @return the new state. - */ - long transform(long state) { - long s = state; - s *= multiply; - s = rotl(s); - s -= state; - return s; - } - - /** - * @param state State. - * @return the rotated state. - */ - private long rotl(long state) { - return (state << rotate) | (state >>> (64 - rotate)); - } - - /** Factory. */ - static class Factory { - /** List of good "Cmres" subcycle generators. */ - private static final List TABLE = new ArrayList(); - - /** - * Populates the table. - * It lists parameters known to be good (provided in - * the article referred to above). - * To maintain compatibility, new entries must be added - * only at the end of the table. - */ - static { - add(0xedce446814d3b3d9L, 33, 0x13b572e7); - add(0xc5b3cf786c806df7L, 33, 0x13c8e18a); - add(0xdd91bbb8ab9e0e65L, 31, 0x06dd03a6); - add(0x7b69342c0790221dL, 31, 0x1646bb8b); - add(0x0c72c0d18614c32bL, 33, 0x06014a3d); - add(0xd8d98c13bebe26c9L, 33, 0x014e8475); - add(0xcb039dc328bbc40fL, 31, 0x008684bd); - add(0x858c5ef3c021ed2fL, 32, 0x0dc8d622); - add(0x4c8be96bfc23b127L, 33, 0x0b6b20cc); - add(0x11eab77f808cf641L, 32, 0x06534421); - add(0xbc9bd78810fd28fdL, 31, 0x1d9ba40d); - add(0x0f1505c780688cb5L, 33, 0x0b7b7b67); - add(0xadc174babc2053afL, 31, 0x267f4197); - add(0x900b6b82b31686d9L, 31, 0x023c6985); - // Add new entries here. - } - - /** - * @return the number of subcycle generators. - */ - int numberOfSubcycleGenerators() { - return TABLE.size(); - } - - /** - * @param index Index into the list of available generators. - * @return the subcycle generator entry at index {@code index}. - */ - Cmres get(int index) { - if (index < 0 || - index >= TABLE.size()) { - throw new IndexOutOfBoundsException("Out of interval [0, " + - (TABLE.size() - 1) + "]"); - } - - return TABLE.get(index); - } - - /** - * Adds an entry to the {@link Factory#TABLE}. - * - * @param multiply Multiplier. - * @param rotate Rotate. - * @param start Cycle start. - */ - private static void add(long multiply, - int rotate, - int start) { - // Sanity check: if there are duplicates, the class initialization - // will fail (and the JVM will report "NoClassDefFoundError"). - checkUnique(TABLE, multiply); - - TABLE.add(new Cmres(multiply, rotate, start)); - } - - /** - * Check the multiply parameter is unique (not contained in any entry in the provided - * table). - * - * @param table the table - * @param multiply the multiply parameter - */ - static void checkUnique(List table, long multiply) { - for (Cmres sg : table) { - if (multiply == sg.getMultiply()) { - throw new IllegalStateException(INTERNAL_ERROR_MSG); - } - } - } - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoRoShiRo128Plus.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoRoShiRo128Plus.java deleted file mode 100644 index 3b764c81e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoRoShiRo128Plus.java +++ /dev/null @@ -1,70 +0,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. - */ - -package org.apache.commons.rng.core.source64; - -/** - * A fast 64-bit generator suitable for {@code double} generation. This is slightly faster than the - * all-purpose generator {@link XoRoShiRo128StarStar}. - * - *

This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 128 bits - * and the period is 2128-1. Speed is expected to be similar to - * {@link XoShiRo256Plus}.

- * - * @see Original source code - * @see xorshiro / xoroshiro generators - * - * @since 1.3 - */ -public class XoRoShiRo128Plus extends AbstractXoRoShiRo128 { - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 2, only the first 2 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - */ - public XoRoShiRo128Plus(long[] seed) { - super(seed); - } - - /** - * Creates a new instance using a 2 element seed. - * A seed containing all zeros will create a non-functional generator. - * - * @param seed0 Initial seed element 0. - * @param seed1 Initial seed element 1. - */ - public XoRoShiRo128Plus(long seed0, long seed1) { - super(seed0, seed1); - } - - /** {@inheritDoc} */ - @Override - public long next() { - final long s0 = state0; - long s1 = state1; - final long result = s0 + s1; - - s1 ^= s0; - state0 = Long.rotateLeft(s0, 24) ^ s1 ^ (s1 << 16); // a, b - state1 = Long.rotateLeft(s1, 37); // c - - return result; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoRoShiRo128StarStar.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoRoShiRo128StarStar.java deleted file mode 100644 index e19a9e9a5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoRoShiRo128StarStar.java +++ /dev/null @@ -1,69 +0,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. - */ - -package org.apache.commons.rng.core.source64; - -/** - * A fast all-purpose 64-bit generator. - * - *

This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 128 bits - * and the period is 2128-1. Speed is expected to be similar to - * {@link XoShiRo256StarStar}.

- * - * @see Original source code - * @see xorshiro / xoroshiro generators - * - * @since 1.3 - */ -public class XoRoShiRo128StarStar extends AbstractXoRoShiRo128 { - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 2, only the first 2 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - */ - public XoRoShiRo128StarStar(long[] seed) { - super(seed); - } - - /** - * Creates a new instance using a 2 element seed. - * A seed containing all zeros will create a non-functional generator. - * - * @param seed0 Initial seed element 0. - * @param seed1 Initial seed element 1. - */ - public XoRoShiRo128StarStar(long seed0, long seed1) { - super(seed0, seed1); - } - - /** {@inheritDoc} */ - @Override - public long next() { - final long s0 = state0; - long s1 = state1; - final long result = Long.rotateLeft(s0 * 5, 7) * 9; - - s1 ^= s0; - state0 = Long.rotateLeft(s0, 24) ^ s1 ^ (s1 << 16); // a, b - state1 = Long.rotateLeft(s1, 37); // c - - return result; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoShiRo256Plus.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoShiRo256Plus.java deleted file mode 100644 index 56572c9c9..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoShiRo256Plus.java +++ /dev/null @@ -1,76 +0,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. - */ - -package org.apache.commons.rng.core.source64; - -/** - * A fast 64-bit generator suitable for {@code double} generation. This is slightly faster than the - * all-purpose generator {@link XoShiRo256StarStar}. - * - *

This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 256 bits - * and the period is 2256-1.

- * - * @see Original source code - * @see xorshiro / xoroshiro generators - * - * @since 1.3 - */ -public class XoShiRo256Plus extends AbstractXoShiRo256 { - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 4, only the first 4 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - */ - public XoShiRo256Plus(long[] seed) { - super(seed); - } - - /** - * Creates a new instance using a 4 element seed. - * A seed containing all zeros will create a non-functional generator. - * - * @param seed0 Initial seed element 0. - * @param seed1 Initial seed element 1. - * @param seed2 Initial seed element 2. - * @param seed3 Initial seed element 3. - */ - public XoShiRo256Plus(long seed0, long seed1, long seed2, long seed3) { - super(seed0, seed1, seed2, seed3); - } - - /** {@inheritDoc} */ - @Override - public long next() { - final long result = state0 + state3; - - final long t = state1 << 17; - - state2 ^= state0; - state3 ^= state1; - state1 ^= state2; - state0 ^= state3; - - state2 ^= t; - - state3 = Long.rotateLeft(state3, 45); - - return result; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoShiRo256StarStar.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoShiRo256StarStar.java deleted file mode 100644 index f6b34adfb..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoShiRo256StarStar.java +++ /dev/null @@ -1,75 +0,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. - */ - -package org.apache.commons.rng.core.source64; - -/** - * A fast all-purpose 64-bit generator. - * - *

This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 256 bits - * and the period is 2256-1.

- * - * @see Original source code - * @see xorshiro / xoroshiro generators - * - * @since 1.3 - */ -public class XoShiRo256StarStar extends AbstractXoShiRo256 { - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 4, only the first 4 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - */ - public XoShiRo256StarStar(long[] seed) { - super(seed); - } - - /** - * Creates a new instance using a 4 element seed. - * A seed containing all zeros will create a non-functional generator. - * - * @param seed0 Initial seed element 0. - * @param seed1 Initial seed element 1. - * @param seed2 Initial seed element 2. - * @param seed3 Initial seed element 3. - */ - public XoShiRo256StarStar(long seed0, long seed1, long seed2, long seed3) { - super(seed0, seed1, seed2, seed3); - } - - /** {@inheritDoc} */ - @Override - public long next() { - final long result = Long.rotateLeft(state1 * 5, 7) * 9; - - final long t = state1 << 17; - - state2 ^= state0; - state3 ^= state1; - state1 ^= state2; - state0 ^= state3; - - state2 ^= t; - - state3 = Long.rotateLeft(state3, 45); - - return result; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoShiRo512Plus.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoShiRo512Plus.java deleted file mode 100644 index 324b0f5c5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoShiRo512Plus.java +++ /dev/null @@ -1,86 +0,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. - */ - -package org.apache.commons.rng.core.source64; - -/** - * A fast 64-bit generator suitable for {@code double} generation. This is slightly faster than the - * all-purpose generator {@link XoShiRo512StarStar}. - * - *

This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 512 bits - * and the period is 2512-1. Speed is expected to be slower than - * {@link XoShiRo256Plus}.

- * - * @see Original source code - * @see xorshiro / xoroshiro generators - * - * @since 1.3 - */ -public class XoShiRo512Plus extends AbstractXoShiRo512 { - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 8, only the first 8 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - */ - public XoShiRo512Plus(long[] seed) { - super(seed); - } - - /** - * Creates a new instance using an 8 element seed. - * A seed containing all zeros will create a non-functional generator. - * - * @param seed0 Initial seed element 0. - * @param seed1 Initial seed element 1. - * @param seed2 Initial seed element 2. - * @param seed3 Initial seed element 3. - * @param seed4 Initial seed element 4. - * @param seed5 Initial seed element 5. - * @param seed6 Initial seed element 6. - * @param seed7 Initial seed element 7. - */ - public XoShiRo512Plus(long seed0, long seed1, long seed2, long seed3, - long seed4, long seed5, long seed6, long seed7) { - super(seed0, seed1, seed2, seed3, seed4, seed5, seed6, seed7); - } - - /** {@inheritDoc} */ - @Override - public long next() { - final long result = state0 + state2; - - final long t = state1 << 11; - - state2 ^= state0; - state5 ^= state1; - state1 ^= state2; - state7 ^= state3; - state3 ^= state4; - state4 ^= state5; - state0 ^= state6; - state6 ^= state7; - - state6 ^= t; - - state7 = Long.rotateLeft(state7, 21); - - return result; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoShiRo512StarStar.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoShiRo512StarStar.java deleted file mode 100644 index 3906a678e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XoShiRo512StarStar.java +++ /dev/null @@ -1,85 +0,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. - */ - -package org.apache.commons.rng.core.source64; - -/** - * A fast all-purpose generator. - * - *

This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 512 bits - * and the period is 2512-1. Speed is expected to be slower than - * {@link XoShiRo256StarStar}.

- * - * @see Original source code - * @see xorshiro / xoroshiro generators - * - * @since 1.3 - */ -public class XoShiRo512StarStar extends AbstractXoShiRo512 { - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 8, only the first 8 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - */ - public XoShiRo512StarStar(long[] seed) { - super(seed); - } - - /** - * Creates a new instance using an 8 element seed. - * A seed containing all zeros will create a non-functional generator. - * - * @param seed0 Initial seed element 0. - * @param seed1 Initial seed element 1. - * @param seed2 Initial seed element 2. - * @param seed3 Initial seed element 3. - * @param seed4 Initial seed element 4. - * @param seed5 Initial seed element 5. - * @param seed6 Initial seed element 6. - * @param seed7 Initial seed element 7. - */ - public XoShiRo512StarStar(long seed0, long seed1, long seed2, long seed3, - long seed4, long seed5, long seed6, long seed7) { - super(seed0, seed1, seed2, seed3, seed4, seed5, seed6, seed7); - } - - /** {@inheritDoc} */ - @Override - public long next() { - final long result = Long.rotateLeft(state1 * 5, 7) * 9; - - final long t = state1 << 11; - - state2 ^= state0; - state5 ^= state1; - state1 ^= state2; - state7 ^= state3; - state3 ^= state4; - state4 ^= state5; - state0 ^= state6; - state6 ^= state7; - - state6 ^= t; - - state7 = Long.rotateLeft(state7, 21); - - return result; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XorShift1024Star.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XorShift1024Star.java deleted file mode 100644 index 6782d8f47..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XorShift1024Star.java +++ /dev/null @@ -1,113 +0,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. - */ - -package org.apache.commons.rng.core.source64; - -import org.apache.commons.rng.core.util.NumberFactory; - -import java.util.Arrays; - -/** - * A fast RNG implementing the {@code XorShift1024*} algorithm. - * - *

Note: This has been superseded by {@link XorShift1024StarPhi}. The sequences emitted - * by both generators are correlated.

- * - * @see Original source code - * @see Xorshift (Wikipedia) - * @since 1.0 - */ -public class XorShift1024Star extends LongProvider { - /** Size of the state vector. */ - private static final int SEED_SIZE = 16; - /** State. */ - private final long[] state = new long[SEED_SIZE]; - /** The multiplier for the XorShift1024 algorithm. */ - private final long multiplier; - /** Index in "state" array. */ - private int index; - - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 16, only the first 16 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - */ - public XorShift1024Star(long[] seed) { - this(seed, 1181783497276652981L); - } - - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 16, only the first 16 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - * @param multiplier The multiplier for the XorShift1024 algorithm. - */ - protected XorShift1024Star(long[] seed, long multiplier) { - setSeedInternal(seed); - this.multiplier = multiplier; - } - - /** {@inheritDoc} */ - @Override - protected byte[] getStateInternal() { - final long[] s = Arrays.copyOf(state, SEED_SIZE + 1); - s[SEED_SIZE] = index; - - return composeStateInternal(NumberFactory.makeByteArray(s), - super.getStateInternal()); - } - - /** {@inheritDoc} */ - @Override - protected void setStateInternal(byte[] s) { - final byte[][] c = splitStateInternal(s, (SEED_SIZE + 1) * 8); - - final long[] tmp = NumberFactory.makeLongArray(c[0]); - System.arraycopy(tmp, 0, state, 0, SEED_SIZE); - index = (int) tmp[SEED_SIZE]; - - super.setStateInternal(c[1]); - } - - /** - * Seeds the RNG. - * - * @param seed Seed. - */ - private void setSeedInternal(long[] seed) { - // Reset the whole state of this RNG (i.e. "state" and "index"). - // Filling procedure is not part of the reference code. - fillState(state, seed); - index = 0; - } - - /** {@inheritDoc} */ - @Override - public long next() { - final long s0 = state[index]; - long s1 = state[index = (index + 1) & 15]; - s1 ^= s1 << 31; // a - state[index] = s1 ^ s0 ^ (s1 >>> 11) ^ (s0 >>> 30); // b,c - return state[index] * multiplier; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XorShift1024StarPhi.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XorShift1024StarPhi.java deleted file mode 100644 index a51d462b6..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/XorShift1024StarPhi.java +++ /dev/null @@ -1,46 +0,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. - */ - -package org.apache.commons.rng.core.source64; - -/** - * A fast RNG implementing the {@code XorShift1024*} algorithm. - * - *

Note: This supersedes {@link XorShift1024Star}. The sequences emitted by both - * generators are correlated.

- * - *

This generator differs only in the final multiplier (a fixed-point representation - * of the golden ratio), which eliminates linear dependencies from one of the lowest - * bits.

- * - * @see Original source code - * @see Xorshift (Wikipedia) - * @since 1.3 - */ -public class XorShift1024StarPhi extends XorShift1024Star { - /** - * Creates a new instance. - * - * @param seed Initial seed. - * If the length is larger than 16, only the first 16 elements will - * be used; if smaller, the remaining elements will be automatically - * set. A seed containing all zeros will create a non-functional generator. - */ - public XorShift1024StarPhi(long[] seed) { - super(seed, 0x9e3779b97f4a7c13L); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/package-info.java deleted file mode 100644 index 22d0e55c1..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/source64/package-info.java +++ /dev/null @@ -1,52 +0,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. - */ - -/** - *

- * Concrete algorithms for {@code long}-based sources of randomness - *

- * - *

- * For internal use only: Direct access to classes in this package - * is discouraged, as they could be modified without notice. - *

- * - *

Notes for developers

- * - *
    - *
  • - * A source of randomness must inherit from - * {@link org.apache.commons.rng.core.source64.LongProvider} - *
  • - *
  • - * The "provider" must specify one way for setting the seed. - * For a given seed, the generated sequence must always be the same. - *
  • - *
  • - * The "provider" must implement methods {@code getStateInternal} and - * {@code setStateInternal} in order to save and restore the state of an - * instance (cf. {@link org.apache.commons.rng.core.BaseProvider}). - *
  • - *
  • - * When a new class is implemented here, user-access to it must be - * provided through associated {@code RandomSource} factory methods - * defined in module "commons-rng-simple". - *
  • - *
- */ - -package org.apache.commons.rng.core.source64; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/util/NumberFactory.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/util/NumberFactory.java deleted file mode 100644 index a1ed60875..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/util/NumberFactory.java +++ /dev/null @@ -1,355 +0,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. - */ -package org.apache.commons.rng.core.util; - -import java.util.Arrays; - -/** - * Utility for creating number types from one or two {@code int} values - * or one {@code long} value, or a sequence of bytes. - */ -public final class NumberFactory { - /** - * The multiplier to convert the least significant 24-bits of an {@code int} to a {@code float}. - * See {@link #makeFloat(int)}. - * - *

This is equivalent to 1.0f / (1 << 24). - */ - private static final float FLOAT_MULTIPLIER = 0x1.0p-24f; - /** - * The multiplier to convert the least significant 53-bits of a {@code long} to a {@code double}. - * See {@link #makeDouble(long)} and {@link #makeDouble(int, int)}. - * - *

This is equivalent to 1.0 / (1L << 53). - */ - private static final double DOUBLE_MULTIPLIER = 0x1.0p-53d; - /** Lowest byte mask. */ - private static final long LONG_LOWEST_BYTE_MASK = 0xffL; - /** Number of bytes in a {@code long}. */ - private static final int LONG_SIZE = 8; - /** Lowest byte mask. */ - private static final int INT_LOWEST_BYTE_MASK = 0xff; - /** Number of bytes in a {@code int}. */ - private static final int INT_SIZE = 4; - - /** - * Class contains only static methods. - */ - private NumberFactory() {} - - /** - * @param v Number. - * @return a boolean. - * - * @deprecated Since version 1.2. Method has become obsolete following - * RNG-57. - */ - @Deprecated - public static boolean makeBoolean(int v) { - return (v >>> 31) != 0; - } - - /** - * @param v Number. - * @return a boolean. - * - * @deprecated Since version 1.2. Method has become obsolete following - * RNG-57. - */ - @Deprecated - public static boolean makeBoolean(long v) { - return (v >>> 63) != 0; - } - - /** - * @param v Number. - * @return a {@code double} value in the interval {@code [0, 1]}. - */ - public static double makeDouble(long v) { - // Require the least significant 53-bits so shift the higher bits across - return (v >>> 11) * DOUBLE_MULTIPLIER; - } - - /** - * @param v Number (high order bits). - * @param w Number (low order bits). - * @return a {@code double} value in the interval {@code [0, 1]}. - */ - public static double makeDouble(int v, - int w) { - // Require the least significant 53-bits from a long. - // Join the most significant 26 from v with 27 from w. - final long high = ((long) (v >>> 6)) << 27; // 26-bits remain - final int low = w >>> 5; // 27-bits remain - return (high | low) * DOUBLE_MULTIPLIER; - } - - /** - * @param v Number. - * @return a {@code float} value in the interval {@code [0, 1]}. - */ - public static float makeFloat(int v) { - // Require the least significant 24-bits so shift the higher bits across - return (v >>> 8) * FLOAT_MULTIPLIER; - } - - /** - * @param v Number (high order bits). - * @param w Number (low order bits). - * @return a {@code long} value. - */ - public static long makeLong(int v, - int w) { - return (((long) v) << 32) | (w & 0xffffffffL); - } - - /** - * Creates an {@code int} from a {@code long}. - * - * @param v Number. - * @return an {@code int} value made from the "xor" of the - * {@link #extractHi(long) high order bits} and - * {@link #extractLo(long) low order bits} of {@code v}. - * - * @deprecated Since version 1.2. Method has become obsolete following - * RNG-57. - */ - @Deprecated - public static int makeInt(long v) { - return extractHi(v) ^ extractLo(v); - } - - /** - * Creates an {@code int} from a {@code long}, using the high order bits. - * - *

The returned value is such that if

- *

-     *  vL = extractLo(v);
-     *  vH = extractHi(v);
-     * 
- * - *

then {@code v} is equal to {@link #makeLong(int,int) makeLong(vH, vL)}.

- * - * @param v Number. - * @return an {@code int} value made from the most significant bits - * of {@code v}. - */ - public static int extractHi(long v) { - return (int) (v >>> 32); - } - - /** - * Creates an {@code int} from a {@code long}, using the low order bits. - * - *

The returned value is such that if

- * - *

-     *  vL = extractLo(v);
-     *  vH = extractHi(v);
-     * 
- * - *

then {@code v} is equal to {@link #makeLong(int,int) makeLong(vH, vL)}.

- * - * @param v Number. - * @return an {@code int} value made from the least significant bits - * of {@code v}. - */ - public static int extractLo(long v) { - return (int) v; - } - - /** - * Splits a {@code long} into 8 bytes. - * - * @param v Value. - * @return the bytes that compose the given value (least-significant - * byte first). - */ - public static byte[] makeByteArray(long v) { - final byte[] b = new byte[LONG_SIZE]; - - for (int i = 0; i < LONG_SIZE; i++) { - final int shift = i * 8; - b[i] = (byte) ((v >>> shift) & LONG_LOWEST_BYTE_MASK); - } - - return b; - } - - /** - * Creates a {@code long} from 8 bytes. - * - * @param input Input. - * @return the value that correspond to the given bytes assuming - * that the is ordered in increasing byte significance (i.e. the - * first byte in the array is the least-siginficant). - * @throws IllegalArgumentException if {@code input.length != 8}. - */ - public static long makeLong(byte[] input) { - checkSize(LONG_SIZE, input.length); - - long v = 0; - for (int i = 0; i < LONG_SIZE; i++) { - final int shift = i * 8; - v |= (((long) input[i]) & LONG_LOWEST_BYTE_MASK) << shift; - } - - return v; - } - - /** - * Splits an array of {@code long} values into a sequence of bytes. - * This method calls {@link #makeByteArray(long)} for each element of - * the {@code input}. - * - * @param input Input. - * @return an array of bytes. - */ - public static byte[] makeByteArray(long[] input) { - final int size = input.length * LONG_SIZE; - final byte[] b = new byte[size]; - - for (int i = 0; i < input.length; i++) { - final byte[] current = makeByteArray(input[i]); - System.arraycopy(current, 0, b, i * LONG_SIZE, LONG_SIZE); - } - - return b; - } - - /** - * Creates an array of {@code long} values from a sequence of bytes. - * This method calls {@link #makeLong(byte[])} for each subsequence - * of 8 bytes. - * - * @param input Input. - * @return an array of {@code long}. - * @throws IllegalArgumentException if {@code input.length} is not - * a multiple of 8. - */ - public static long[] makeLongArray(byte[] input) { - final int size = input.length; - final int num = size / LONG_SIZE; - checkSize(num * LONG_SIZE, size); - - final long[] output = new long[num]; - for (int i = 0; i < num; i++) { - final int from = i * LONG_SIZE; - final byte[] current = Arrays.copyOfRange(input, from, from + LONG_SIZE); - output[i] = makeLong(current); - } - - return output; - } - - /** - * Splits an {@code int} into 4 bytes. - * - * @param v Value. - * @return the bytes that compose the given value (least-significant - * byte first). - */ - public static byte[] makeByteArray(int v) { - final byte[] b = new byte[INT_SIZE]; - - for (int i = 0; i < INT_SIZE; i++) { - final int shift = i * 8; - b[i] = (byte) ((v >>> shift) & INT_LOWEST_BYTE_MASK); - } - - return b; - } - - /** - * Creates an {@code int} from 4 bytes. - * - * @param input Input. - * @return the value that correspond to the given bytes assuming - * that the is ordered in increasing byte significance (i.e. the - * first byte in the array is the least-siginficant). - * @throws IllegalArgumentException if {@code input.length != 4}. - */ - public static int makeInt(byte[] input) { - checkSize(INT_SIZE, input.length); - - int v = 0; - for (int i = 0; i < INT_SIZE; i++) { - final int shift = i * 8; - v |= (((int) input[i]) & INT_LOWEST_BYTE_MASK) << shift; - } - - return v; - } - - /** - * Splits an array of {@code int} values into a sequence of bytes. - * This method calls {@link #makeByteArray(int)} for each element of - * the {@code input}. - * - * @param input Input. - * @return an array of bytes. - */ - public static byte[] makeByteArray(int[] input) { - final int size = input.length * INT_SIZE; - final byte[] b = new byte[size]; - - for (int i = 0; i < input.length; i++) { - final byte[] current = makeByteArray(input[i]); - System.arraycopy(current, 0, b, i * INT_SIZE, INT_SIZE); - } - - return b; - } - - /** - * Creates an array of {@code int} values from a sequence of bytes. - * This method calls {@link #makeInt(byte[])} for each subsequence - * of 4 bytes. - * - * @param input Input. Length must be a multiple of 4. - * @return an array of {@code int}. - * @throws IllegalArgumentException if {@code input.length} is not - * a multiple of 4. - */ - public static int[] makeIntArray(byte[] input) { - final int size = input.length; - final int num = size / INT_SIZE; - checkSize(num * INT_SIZE, size); - - final int[] output = new int[num]; - for (int i = 0; i < num; i++) { - final int from = i * INT_SIZE; - final byte[] current = Arrays.copyOfRange(input, from, from + INT_SIZE); - output[i] = makeInt(current); - } - - return output; - } - - /** - * @param expected Expected value. - * @param actual Actual value. - * @throw IllegalArgumentException if {@code expected != actual}. - */ - private static void checkSize(int expected, - int actual) { - if (expected != actual) { - throw new IllegalArgumentException("Array size: Expected " + expected + - " but was " + actual); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/util/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/util/package-info.java deleted file mode 100644 index 50eaa7f43..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/core/util/package-info.java +++ /dev/null @@ -1,26 +0,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. - */ - -/** - *

Utilities

- * - *

- * This package contains utilities to combine/split primitive types. - *

- */ - -package org.apache.commons.rng.core.util; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/package-info.java deleted file mode 100644 index efbbe65ee..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/package-info.java +++ /dev/null @@ -1,28 +0,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. - */ - -/** - *

Randomness providers API

- * - *

- * This package contains the library's interface to be used by client - * code that needs a generator of sequences of pseudo-random numbers - * that are uniformly distributed in a specified range. - *

- */ - -package org.apache.commons.rng; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/CollectionSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/CollectionSampler.java deleted file mode 100644 index 00e8b7370..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/CollectionSampler.java +++ /dev/null @@ -1,69 +0,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. - */ - -package org.apache.commons.rng.sampling; - -import org.apache.commons.rng.UniformRandomProvider; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * Sampling from a {@link Collection}. - * - *

Sampling uses {@link UniformRandomProvider#nextInt(int)}.

- * - * @param Type of items in the collection. - * - * @since 1.0 - */ -public class CollectionSampler { - /** Collection to be sampled from. */ - private final List items; - /** RNG. */ - private final UniformRandomProvider rng; - - /** - * Creates a sampler. - * - * @param rng Generator of uniformly distributed random numbers. - * @param collection Collection to be sampled. - * A (shallow) copy will be stored in the created instance. - * @throws IllegalArgumentException if {@code collection} is empty. - */ - public CollectionSampler(UniformRandomProvider rng, - Collection collection) { - if (collection.isEmpty()) { - throw new IllegalArgumentException("Empty collection"); - } - - this.rng = rng; - items = new ArrayList(collection); - } - - /** - * Picks one of the items from the - * {@link #CollectionSampler(UniformRandomProvider,Collection) - * collection passed to the constructor}. - * - * @return a random sample. - */ - public T sample() { - return items.get(rng.nextInt(items.size())); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/CombinationSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/CombinationSampler.java deleted file mode 100644 index eeae0d5f6..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/CombinationSampler.java +++ /dev/null @@ -1,104 +0,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. - */ - -package org.apache.commons.rng.sampling; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Class for representing combinations - * of a sequence of integers. - * - *

A combination is a selection of items from a collection, such that (unlike - * permutations) the order of selection does not matter. This - * sampler can be used to generate a combination in an unspecified order and is - * faster than the corresponding {@link PermutationSampler}.

- * - *

Note that the sample order is unspecified. For example a sample - * combination of 2 from 4 may return {@code [0,1]} or {@code [1,0]} as the two are - * equivalent, and the order of a given combination may change in subsequent samples.

- * - *

The sampler can be used to generate indices to select subsets where the - * order of the subset is not important.

- * - *

Sampling uses {@link UniformRandomProvider#nextInt(int)}.

- * - * @see PermutationSampler - */ -public class CombinationSampler { - /** Domain of the combination. */ - private final int[] domain; - /** The number of steps of a full shuffle to perform. */ - private final int steps; - /** - * The section to copy the domain from after a partial shuffle. - */ - private final boolean upper; - /** RNG. */ - private final UniformRandomProvider rng; - - /** - * Creates a generator of combinations. - * - *

The {@link #sample()} method will generate an integer array of - * length {@code k} whose entries are selected randomly, without - * repetition, from the integers 0, 1, ..., {@code n}-1 (inclusive). - * The returned array represents a combination of {@code n} taken - * {@code k}. - * - *

In contrast to a permutation, the returned array is not - * guaranteed to be in a random order. The {@link #sample()} - * method returns the array in an unspecified order. - * - *

If {@code n <= 0} or {@code k <= 0} or {@code k > n} then no combination - * is required and an exception is raised. - * - * @param rng Generator of uniformly distributed random numbers. - * @param n Domain of the combination. - * @param k Size of the combination. - * @throws IllegalArgumentException if {@code n <= 0} or {@code k <= 0} or - * {@code k > n}. - */ - public CombinationSampler(UniformRandomProvider rng, - int n, - int k) { - SubsetSamplerUtils.checkSubset(n, k); - domain = PermutationSampler.natural(n); - // The sample can be optimised by only performing the first k or (n - k) steps - // from a full Fisher-Yates shuffle from the end of the domain to the start. - // The upper positions will then contain a random sample from the domain. The - // lower half is then by definition also a random sample (just not in a random order). - // The sample is then picked using the upper or lower half depending which - // makes the number of steps smaller. - upper = k <= n / 2; - steps = upper ? k : n - k; - this.rng = rng; - } - - /** - * Return a combination of {@code k} whose entries are selected randomly, - * without repetition, from the integers 0, 1, ..., {@code n}-1 (inclusive). - * - *

The order of the returned array is not guaranteed to be in a random order - * as the order of a combination does not matter. - * - * @return a random combination. - */ - public int[] sample() { - return SubsetSamplerUtils.partialSample(domain, steps, rng, upper); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/DiscreteProbabilityCollectionSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/DiscreteProbabilityCollectionSampler.java deleted file mode 100644 index 5b665692f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/DiscreteProbabilityCollectionSampler.java +++ /dev/null @@ -1,182 +0,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. - */ - -package org.apache.commons.rng.sampling; - -import org.apache.commons.rng.UniformRandomProvider; - -import java.util.*; - -/** - * Sampling from a collection of items with user-defined - * - * probabilities. - * Note that if all unique items are assigned the same probability, - * it is much more efficient to use {@link CollectionSampler}. - * - *

Sampling uses {@link UniformRandomProvider#nextDouble()}.

- * - * @param Type of items in the collection. - * - * @since 1.1 - */ -public class DiscreteProbabilityCollectionSampler { - /** Collection to be sampled from. */ - private final List items; - /** RNG. */ - private final UniformRandomProvider rng; - /** Cumulative probabilities. */ - private final double[] cumulativeProbabilities; - - /** - * Creates a sampler. - * - * @param rng Generator of uniformly distributed random numbers. - * @param collection Collection to be sampled, with the probabilities - * associated to each of its items. - * A (shallow) copy of the items will be stored in the created instance. - * The probabilities must be non-negative, but zero values are allowed - * and their sum does not have to equal one (input will be normalized - * to make the probabilities sum to one). - * @throws IllegalArgumentException if {@code collection} is empty, a - * probability is negative, infinite or {@code NaN}, or the sum of all - * probabilities is not strictly positive. - */ - public DiscreteProbabilityCollectionSampler(UniformRandomProvider rng, - Map collection) { - if (collection.isEmpty()) { - throw new IllegalArgumentException("Empty collection"); - } - - this.rng = rng; - final int size = collection.size(); - items = new ArrayList(size); - cumulativeProbabilities = new double[size]; - - double sumProb = 0; - int count = 0; - for (Map.Entry e : collection.entrySet()) { - items.add(e.getKey()); - - final double prob = e.getValue(); - if (prob < 0 || - Double.isInfinite(prob) || - Double.isNaN(prob)) { - throw new IllegalArgumentException("Invalid probability: " + - prob); - } - - // Temporarily store probability. - cumulativeProbabilities[count++] = prob; - sumProb += prob; - } - - if (!(sumProb > 0)) { - throw new IllegalArgumentException("Invalid sum of probabilities"); - } - - // Compute and store cumulative probability. - for (int i = 0; i < size; i++) { - cumulativeProbabilities[i] /= sumProb; - if (i > 0) { - cumulativeProbabilities[i] += cumulativeProbabilities[i - 1]; - } - } - } - - /** - * Creates a sampler. - * - * @param rng Generator of uniformly distributed random numbers. - * @param collection Collection to be sampled. - * A (shallow) copy of the items will be stored in the created instance. - * @param probabilities Probability associated to each item of the - * {@code collection}. - * The probabilities must be non-negative, but zero values are allowed - * and their sum does not have to equal one (input will be normalized - * to make the probabilities sum to one). - * @throws IllegalArgumentException if {@code collection} is empty or - * a probability is negative, infinite or {@code NaN}, or if the number - * of items in the {@code collection} is not equal to the number of - * provided {@code probabilities}. - */ - public DiscreteProbabilityCollectionSampler(UniformRandomProvider rng, - List collection, - double[] probabilities) { - this(rng, consolidate(collection, probabilities)); - } - - /** - * Picks one of the items from the collection passed to the constructor. - * - * @return a random sample. - */ - public T sample() { - final double rand = rng.nextDouble(); - - int index = Arrays.binarySearch(cumulativeProbabilities, rand); - if (index < 0) { - index = -index - 1; - } - - if (index < cumulativeProbabilities.length && - rand < cumulativeProbabilities[index]) { - return items.get(index); - } - - // This should never happen, but it ensures we will return a correct - // object in case there is some floating point inequality problem - // wrt the cumulative probabilities. - return items.get(items.size() - 1); - } - - /** - * @param collection Collection to be sampled. - * @param probabilities Probability associated to each item of the - * {@code collection}. - * @return a consolidated map (where probabilities of equal items - * have been summed). - * @throws IllegalArgumentException if the number of items in the - * {@code collection} is not equal to the number of provided - * {@code probabilities}. - * @param Type of items in the collection. - */ - private static Map consolidate(List collection, - double[] probabilities) { - final int len = probabilities.length; - if (len != collection.size()) { - throw new IllegalArgumentException("Size mismatch: " + - len + " != " + - collection.size()); - } - - final Map map = new HashMap(); - for (int i = 0; i < len; i++) { - final T item = collection.get(i); - final Double prob = probabilities[i]; - - Double currentProb = map.get(item); - if (currentProb == null) { - currentProb = 0d; - } - - map.put(item, currentProb + prob); - } - - return map; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/ListSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/ListSampler.java deleted file mode 100644 index b320ed0c2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/ListSampler.java +++ /dev/null @@ -1,121 +0,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. - */ - -package org.apache.commons.rng.sampling; - -import org.apache.commons.rng.UniformRandomProvider; - -import java.util.ArrayList; -import java.util.List; - -/** - * Sampling from a {@link List}. - * - *

This class also contains utilities for shuffling a {@link List} in-place.

- * - * @since 1.0 - */ -public class ListSampler { - /** - * Class contains only static methods. - */ - private ListSampler() {} - - /** - * Generates a list of size {@code k} whose entries are selected - * randomly, without repetition, from the items in the given - * {@code collection}. - * - *

- * Sampling is without replacement; but if the source collection - * contains identical objects, the sample may include repeats. - *

- * - *

- * Sampling uses {@link UniformRandomProvider#nextInt(int)}. - *

- * - * @param Type of the list items. - * @param rng Generator of uniformly distributed random numbers. - * @param collection List to be sampled from. - * @param k Size of the returned sample. - * @throws IllegalArgumentException if {@code k <= 0} or - * {@code k > collection.size()}. - * @return a shuffled sample from the source collection. - */ - public static List sample(UniformRandomProvider rng, - List collection, - int k) { - final int n = collection.size(); - final PermutationSampler p = new PermutationSampler(rng, n, k); - final List result = new ArrayList(k); - final int[] index = p.sample(); - - for (int i = 0; i < k; i++) { - result.add(collection.get(index[i])); - } - - return result; - } - - /** - * Shuffles the entries of the given array. - * - * @see #shuffle(UniformRandomProvider,List,int,boolean) - * - * @param Type of the list items. - * @param rng Random number generator. - * @param list List whose entries will be shuffled (in-place). - */ - public static void shuffle(UniformRandomProvider rng, - List list) { - shuffle(rng, list, 0, false); - } - - /** - * Shuffles the entries of the given array, using the - * - * Fisher-Yates algorithm. - * The {@code start} and {@code pos} parameters select which part - * of the array is randomized and which is left untouched. - * - *

- * Sampling uses {@link UniformRandomProvider#nextInt(int)}. - *

- * - * @param Type of the list items. - * @param rng Random number generator. - * @param list List whose entries will be shuffled (in-place). - * @param start Index at which shuffling begins. - * @param towardHead Shuffling is performed for index positions between - * {@code start} and either the end (if {@code false}) or the beginning - * (if {@code true}) of the array. - */ - public static void shuffle(UniformRandomProvider rng, - List list, - int start, - boolean towardHead) { - final int len = list.size(); - final int[] indices = PermutationSampler.natural(len); - PermutationSampler.shuffle(rng, indices, start, towardHead); - - final ArrayList items = new ArrayList(list); - for (int i = 0; i < len; i++) { - list.set(i, items.get(indices[i])); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/PermutationSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/PermutationSampler.java deleted file mode 100644 index 7cb72ccdb..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/PermutationSampler.java +++ /dev/null @@ -1,136 +0,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. - */ - -package org.apache.commons.rng.sampling; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Class for representing permutations - * of a sequence of integers. - * - *

Sampling uses {@link UniformRandomProvider#nextInt(int)}.

- * - *

This class also contains utilities for shuffling an {@code int[]} array in-place.

- */ -public class PermutationSampler { - /** Domain of the permutation. */ - private final int[] domain; - /** Size of the permutation. */ - private final int size; - /** RNG. */ - private final UniformRandomProvider rng; - - /** - * Creates a generator of permutations. - * - *

The {@link #sample()} method will generate an integer array of - * length {@code k} whose entries are selected randomly, without - * repetition, from the integers 0, 1, ..., {@code n}-1 (inclusive). - * The returned array represents a permutation of {@code n} taken - * {@code k}.

- * - * @param rng Generator of uniformly distributed random numbers. - * @param n Domain of the permutation. - * @param k Size of the permutation. - * @throws IllegalArgumentException if {@code n <= 0} or {@code k <= 0} - * or {@code k > n}. - */ - public PermutationSampler(UniformRandomProvider rng, - int n, - int k) { - SubsetSamplerUtils.checkSubset(n, k); - domain = natural(n); - size = k; - this.rng = rng; - } - - /** - * @return a random permutation. - * - * @see #PermutationSampler(UniformRandomProvider,int,int) - */ - public int[] sample() { - return SubsetSamplerUtils.partialSample(domain, size, rng, true); - } - - /** - * Shuffles the entries of the given array. - * - * @see #shuffle(UniformRandomProvider,int[],int,boolean) - * - * @param rng Random number generator. - * @param list Array whose entries will be shuffled (in-place). - */ - public static void shuffle(UniformRandomProvider rng, - int[] list) { - shuffle(rng, list, list.length - 1, true); - } - - /** - * Shuffles the entries of the given array, using the - * - * Fisher-Yates algorithm. - * The {@code start} and {@code towardHead} parameters select which part - * of the array is randomized and which is left untouched. - * - *

Sampling uses {@link UniformRandomProvider#nextInt(int)}.

- * - * @param rng Random number generator. - * @param list Array whose entries will be shuffled (in-place). - * @param start Index at which shuffling begins. - * @param towardHead Shuffling is performed for index positions between - * {@code start} and either the end (if {@code false}) or the beginning - * (if {@code true}) of the array. - */ - public static void shuffle(UniformRandomProvider rng, - int[] list, - int start, - boolean towardHead) { - if (towardHead) { - // Visit all positions from start to 0. - // Do not visit 0 to avoid a swap with itself. - for (int i = start; i > 0; i--) { - // Swap index with any position down to 0 - SubsetSamplerUtils.swap(list, i, rng.nextInt(i + 1)); - } - } else { - // Visit all positions from the end to start. - // Start is not visited to avoid a swap with itself. - for (int i = list.length - 1; i > start; i--) { - // Swap index with any position down to start. - // Note: i - start + 1 is the number of elements remaining. - SubsetSamplerUtils.swap(list, i, rng.nextInt(i - start + 1) + start); - } - } - } - - /** - * Creates an array representing the natural number {@code n}. - * - * @param n Natural number. - * @return an array whose entries are the numbers 0, 1, ..., {@code n}-1. - * If {@code n == 0}, the returned array is empty. - */ - public static int[] natural(int n) { - final int[] a = new int[n]; - for (int i = 0; i < n; i++) { - a[i] = i; - } - return a; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/SubsetSamplerUtils.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/SubsetSamplerUtils.java deleted file mode 100644 index 0ac25f070..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/SubsetSamplerUtils.java +++ /dev/null @@ -1,98 +0,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. - */ - -package org.apache.commons.rng.sampling; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Utility class for selecting a subset of a sequence of integers. - */ -final class SubsetSamplerUtils { - - /** No public construction. */ - private SubsetSamplerUtils() {} - - /** - * Checks the subset of length {@code k} from {@code n} is valid. - * - *

If {@code n <= 0} or {@code k <= 0} or {@code k > n} then no subset - * is required and an exception is raised.

- * - * @param n Size of the set. - * @param k Size of the subset. - * @throws IllegalArgumentException if {@code n <= 0} or {@code k <= 0} or - * {@code k > n}. - */ - static void checkSubset(int n, - int k) { - if (n <= 0) { - throw new IllegalArgumentException("n <= 0 : n=" + n); - } - if (k <= 0) { - throw new IllegalArgumentException("k <= 0 : k=" + k); - } - if (k > n) { - throw new IllegalArgumentException("k > n : k=" + k + ", n=" + n); - } - } - - /** - * Perform a partial Fisher-Yates shuffle of the domain in-place and return - * either the upper fully shuffled section or the remaining lower partially - * shuffled section. - * - *

The returned combination will have a length of {@code steps} for - * {@code upper=true}, or {@code domain.length - steps} otherwise.

- * - *

Sampling uses {@link UniformRandomProvider#nextInt(int)}.

- * - * @param domain The domain. - * @param steps The number of shuffle steps. - * @param rng Generator of uniformly distributed random numbers. - * @param upper Set to true to return the upper fully shuffled section. - * @return a random combination. - */ - static int[] partialSample(int[] domain, - int steps, - UniformRandomProvider rng, - boolean upper) { - // Shuffle from the end but limit to a number of steps. - for (int i = domain.length - 1, j = 0; i > 0 && j < steps; i--, j++) { - // Swap index i with any position down to 0 (including itself) - swap(domain, i, rng.nextInt(i + 1)); - } - final int size = upper ? steps : domain.length - steps; - final int from = upper ? domain.length - steps : 0; - final int[] result = new int[size]; - System.arraycopy(domain, from, result, 0, size); - return result; - } - - /** - * Swaps the two specified elements in the specified array. - * - * @param array the array - * @param i the first index - * @param j the second index - */ - static void swap(int[] array, int i, int j) { - final int tmp = array[i]; - array[i] = array[j]; - array[j] = tmp; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/UnitSphereSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/UnitSphereSampler.java deleted file mode 100644 index 661702ba5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/UnitSphereSampler.java +++ /dev/null @@ -1,90 +0,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. - */ - -package org.apache.commons.rng.sampling; - -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.NormalizedGaussianSampler; -import org.apache.commons.rng.sampling.distribution.ZigguratNormalizedGaussianSampler; - -/** - * Generate vectors - * isotropically located on the surface of a sphere. - * - *

Sampling uses:

- * - *
    - *
  • {@link UniformRandomProvider#nextLong()} - *
  • {@link UniformRandomProvider#nextDouble()} - *
- * - * @since 1.1 - */ -public class UnitSphereSampler { - /** Sampler used for generating the individual components of the vectors. */ - private final NormalizedGaussianSampler sampler; - /** Space dimension. */ - private final int dimension; - - /** - * @param dimension Space dimension. - * @param rng Generator for the individual components of the vectors. - * A shallow copy will be stored in this instance. - * @throws IllegalArgumentException If {@code dimension <= 0} - */ - public UnitSphereSampler(int dimension, - UniformRandomProvider rng) { - if (dimension <= 0) { - throw new IllegalArgumentException("Dimension must be strictly positive"); - } - - this.dimension = dimension; - sampler = new ZigguratNormalizedGaussianSampler(rng); - } - - /** - * @return a random normalized Cartesian vector. - */ - public double[] nextVector() { - final double[] v = new double[dimension]; - - // Pick a point by choosing a standard Gaussian for each element, - // and then normalize to unit length. - double normSq = 0; - for (int i = 0; i < dimension; i++) { - final double comp = sampler.sample(); - v[i] = comp; - normSq += comp * comp; - } - - if (normSq == 0) { - // Zero-norm vector is discarded. - // Using recursion as it is highly unlikely to generate more - // than a few such vectors. It also protects against infinite - // loop (in case a buggy generator is used), by eventually - // raising a "StackOverflowError". - return nextVector(); - } - - final double f = 1 / Math.sqrt(normSq); - for (int i = 0; i < dimension; i++) { - v[i] *= f; - } - - return v; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/AhrensDieterExponentialSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/AhrensDieterExponentialSampler.java deleted file mode 100644 index 3f8a2e79e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/AhrensDieterExponentialSampler.java +++ /dev/null @@ -1,127 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Sampling from an exponential distribution. - * - *

Sampling uses {@link UniformRandomProvider#nextDouble()}.

- * - * @since 1.0 - */ -public class AhrensDieterExponentialSampler - extends SamplerBase - implements ContinuousSampler { - /** - * Table containing the constants - * \( q_i = sum_{j=1}^i (\ln 2)^j / j! = \ln 2 + (\ln 2)^2 / 2 + ... + (\ln 2)^i / i! \) - * until the largest representable fraction below 1 is exceeded. - * - * Note that - * \( 1 = 2 - 1 = \exp(\ln 2) - 1 = sum_{n=1}^\infinity (\ln 2)^n / n! \) - * thus \( q_i \rightarrow 1 as i \rightarrow +\infinity \), - * so the higher \( i \), the closer we get to 1 (the series is not alternating). - * - * By trying, n = 16 in Java is enough to reach 1. - */ - private static final double[] EXPONENTIAL_SA_QI = new double[16]; - /** The mean of this distribution. */ - private final double mean; - /** Underlying source of randomness. */ - private final UniformRandomProvider rng; - - /** - * Initialize tables. - */ - static { - /** - * Filling EXPONENTIAL_SA_QI table. - * Note that we don't want qi = 0 in the table. - */ - final double ln2 = Math.log(2); - double qi = 0; - - for (int i = 0; i < EXPONENTIAL_SA_QI.length; i++) { - qi += Math.pow(ln2, i + 1) / InternalUtils.factorial(i + 1); - EXPONENTIAL_SA_QI[i] = qi; - } - } - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param mean Mean of this distribution. - * @throws IllegalArgumentException if {@code mean <= 0} - */ - public AhrensDieterExponentialSampler(UniformRandomProvider rng, - double mean) { - super(null); - if (mean <= 0) { - throw new IllegalArgumentException("mean is not strictly positive: " + mean); - } - this.rng = rng; - this.mean = mean; - } - - /** {@inheritDoc} */ - @Override - public double sample() { - // Step 1: - double a = 0; - double u = rng.nextDouble(); - - // Step 2 and 3: - while (u < 0.5) { - a += EXPONENTIAL_SA_QI[0]; - u *= 2; - } - - // Step 4 (now u >= 0.5): - u += u - 1; - - // Step 5: - if (u <= EXPONENTIAL_SA_QI[0]) { - return mean * (a + u); - } - - // Step 6: - int i = 0; // Should be 1, be we iterate before it in while using 0. - double u2 = rng.nextDouble(); - double umin = u2; - - // Step 7 and 8: - do { - ++i; - u2 = rng.nextDouble(); - - if (u2 < umin) { - umin = u2; - } - - // Step 8: - } while (u > EXPONENTIAL_SA_QI[i]); // Ensured to exit since EXPONENTIAL_SA_QI[MAX] = 1. - - return mean * (a + umin * EXPONENTIAL_SA_QI[0]); - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Ahrens-Dieter Exponential deviate [" + rng.toString() + "]"; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/AhrensDieterMarsagliaTsangGammaSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/AhrensDieterMarsagliaTsangGammaSampler.java deleted file mode 100644 index bb17d54ca..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/AhrensDieterMarsagliaTsangGammaSampler.java +++ /dev/null @@ -1,239 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Sampling from the Gamma distribution. - *
    - *
  • - * For {@code 0 < theta < 1}: - *
    - * Ahrens, J. H. and Dieter, U., - * Computer methods for sampling from gamma, beta, Poisson and binomial distributions, - * Computing, 12, 223-246, 1974. - *
    - *
  • - *
  • - * For {@code theta >= 1}: - *
    - * Marsaglia and Tsang, A Simple Method for Generating - * Gamma Variables. ACM Transactions on Mathematical Software, - * Volume 26 Issue 3, September, 2000. - *
    - *
  • - *
- * - *

Sampling uses:

- * - *
    - *
  • {@link UniformRandomProvider#nextDouble()} (both algorithms) - *
  • {@link UniformRandomProvider#nextLong()} (only for {@code theta >= 1}) - *
- * - * @since 1.0 - */ -public class AhrensDieterMarsagliaTsangGammaSampler - extends SamplerBase - implements ContinuousSampler { - /** The appropriate gamma sampler for the parameters. */ - private final ContinuousSampler delegate; - - /** - * Base class for a sampler from the Gamma distribution. - */ - private abstract static class BaseAhrensDieterMarsagliaTsangGammaSampler - implements ContinuousSampler { - - /** Underlying source of randomness. */ - protected final UniformRandomProvider rng; - /** The shape parameter. */ - protected final double theta; - /** The alpha parameter. */ - protected final double alpha; - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param alpha Alpha shape parameter of the distribution. - * @param theta Theta scale parameter of the distribution. - * @throws IllegalArgumentException if {@code alpha <= 0} or {@code theta <= 0} - */ - BaseAhrensDieterMarsagliaTsangGammaSampler(UniformRandomProvider rng, - double alpha, - double theta) { - if (alpha <= 0) { - throw new IllegalArgumentException("alpha is not strictly positive: " + alpha); - } - if (theta <= 0) { - throw new IllegalArgumentException("theta is not strictly positive: " + theta); - } - this.rng = rng; - this.alpha = alpha; - this.theta = theta; - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Ahrens-Dieter-Marsaglia-Tsang Gamma deviate [" + rng.toString() + "]"; - } - } - - /** - * Class to sample from the Gamma distribution when {@code 0 < theta < 1}. - */ - private static class SmallThetaAhrensDieterMarsagliaTsangGammaSampler - extends BaseAhrensDieterMarsagliaTsangGammaSampler { - - /** Inverse of "theta". */ - private final double oneOverTheta; - /** Optimization (see code). */ - private final double bGSOptim; - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param alpha Alpha shape parameter of the distribution. - * @param theta Theta scale parameter of the distribution. - * @throws IllegalArgumentException if {@code alpha <= 0} or {@code theta <= 0} - */ - SmallThetaAhrensDieterMarsagliaTsangGammaSampler(UniformRandomProvider rng, - double alpha, - double theta) { - super(rng, alpha, theta); - oneOverTheta = 1 / theta; - bGSOptim = 1 + theta / Math.E; - } - - @Override - public double sample() { - // [1]: p. 228, Algorithm GS. - - while (true) { - // Step 1: - final double u = rng.nextDouble(); - final double p = bGSOptim * u; - - if (p <= 1) { - // Step 2: - final double x = Math.pow(p, oneOverTheta); - final double u2 = rng.nextDouble(); - - if (u2 > Math.exp(-x)) { - // Reject. - continue; - } - return alpha * x; - } - - // Step 3: - final double x = -Math.log((bGSOptim - p) * oneOverTheta); - final double u2 = rng.nextDouble(); - - if (u2 > Math.pow(x, theta - 1)) { - // Reject. - continue; - } - return alpha * x; - } - } - } - - /** - * Class to sample from the Gamma distribution when the {@code theta >= 1}. - */ - private static class LargeThetaAhrensDieterMarsagliaTsangGammaSampler - extends BaseAhrensDieterMarsagliaTsangGammaSampler { - - /** 1/3 */ - private static final double ONE_THIRD = 1d / 3; - - /** Optimization (see code). */ - private final double dOptim; - /** Optimization (see code). */ - private final double cOptim; - /** Gaussian sampling. */ - private final NormalizedGaussianSampler gaussian; - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param alpha Alpha shape parameter of the distribution. - * @param theta Theta scale parameter of the distribution. - * @throws IllegalArgumentException if {@code alpha <= 0} or {@code theta <= 0} - */ - LargeThetaAhrensDieterMarsagliaTsangGammaSampler(UniformRandomProvider rng, - double alpha, - double theta) { - super(rng, alpha, theta); - gaussian = new ZigguratNormalizedGaussianSampler(rng); - dOptim = theta - ONE_THIRD; - cOptim = ONE_THIRD / Math.sqrt(dOptim); - } - - @Override - public double sample() { - while (true) { - final double x = gaussian.sample(); - final double oPcTx = 1 + cOptim * x; - final double v = oPcTx * oPcTx * oPcTx; - - if (v <= 0) { - continue; - } - - final double x2 = x * x; - final double u = rng.nextDouble(); - - // Squeeze. - if (u < 1 - 0.0331 * x2 * x2) { - return alpha * dOptim * v; - } - - if (Math.log(u) < 0.5 * x2 + dOptim * (1 - v + Math.log(v))) { - return alpha * dOptim * v; - } - } - } - } - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param alpha Alpha shape parameter of the distribution. - * @param theta Theta scale parameter of the distribution. - * @throws IllegalArgumentException if {@code alpha <= 0} or {@code theta <= 0} - */ - public AhrensDieterMarsagliaTsangGammaSampler(UniformRandomProvider rng, - double alpha, - double theta) { - super(null); - delegate = theta < 1 ? - new SmallThetaAhrensDieterMarsagliaTsangGammaSampler(rng, alpha, theta) : - new LargeThetaAhrensDieterMarsagliaTsangGammaSampler(rng, alpha, theta); - } - - /** {@inheritDoc} */ - @Override - public double sample() { - return delegate.sample(); - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return delegate.toString(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/BoxMullerGaussianSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/BoxMullerGaussianSampler.java deleted file mode 100644 index b1408230d..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/BoxMullerGaussianSampler.java +++ /dev/null @@ -1,98 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * - * Box-Muller algorithm for sampling from a Gaussian distribution. - * - *

Sampling uses {@link UniformRandomProvider#nextDouble()}.

- * - * @since 1.0 - * - * @deprecated Since version 1.1. Please use {@link BoxMullerNormalizedGaussianSampler} - * and {@link GaussianSampler} instead. - */ -@Deprecated -public class BoxMullerGaussianSampler - extends SamplerBase - implements ContinuousSampler { - /** Next gaussian. */ - private double nextGaussian = Double.NaN; - /** Mean. */ - private final double mean; - /** standardDeviation. */ - private final double standardDeviation; - /** Underlying source of randomness. */ - private final UniformRandomProvider rng; - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param mean Mean of the Gaussian distribution. - * @param standardDeviation Standard deviation of the Gaussian distribution. - * @throws IllegalArgumentException if {@code standardDeviation <= 0} - */ - public BoxMullerGaussianSampler(UniformRandomProvider rng, - double mean, - double standardDeviation) { - super(null); - if (standardDeviation <= 0) { - throw new IllegalArgumentException("standard deviation is not strictly positive: " + - standardDeviation); - } - this.rng = rng; - this.mean = mean; - this.standardDeviation = standardDeviation; - } - - /** {@inheritDoc} */ - @Override - public double sample() { - final double random; - if (Double.isNaN(nextGaussian)) { - // Generate a pair of Gaussian numbers. - - final double x = rng.nextDouble(); - final double y = rng.nextDouble(); - final double alpha = 2 * Math.PI * x; - final double r = Math.sqrt(-2 * Math.log(y)); - - // Return the first element of the generated pair. - random = r * Math.cos(alpha); - - // Keep second element of the pair for next invocation. - nextGaussian = r * Math.sin(alpha); - } else { - // Use the second element of the pair (generated at the - // previous invocation). - random = nextGaussian; - - // Both elements of the pair have been used. - nextGaussian = Double.NaN; - } - - return standardDeviation * random + mean; - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Box-Muller Gaussian deviate [" + rng.toString() + "]"; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/BoxMullerLogNormalSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/BoxMullerLogNormalSampler.java deleted file mode 100644 index de8fc298e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/BoxMullerLogNormalSampler.java +++ /dev/null @@ -1,64 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Sampling from a - * log-normal distribution. - * Uses {@link BoxMullerNormalizedGaussianSampler} as the underlying sampler. - * - *

Sampling uses {@link UniformRandomProvider#nextDouble()}.

- * - * @since 1.0 - * - * @deprecated Since version 1.1. Please use {@link LogNormalSampler} instead. - */ -@Deprecated -public class BoxMullerLogNormalSampler - extends SamplerBase - implements ContinuousSampler { - /** Delegate. */ - private final ContinuousSampler sampler; - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param scale Scale of the log-normal distribution. - * @param shape Shape of the log-normal distribution. - * @throws IllegalArgumentException if {@code scale < 0} or {@code shape <= 0}. - */ - public BoxMullerLogNormalSampler(UniformRandomProvider rng, - double scale, - double shape) { - super(null); - sampler = new LogNormalSampler(new BoxMullerNormalizedGaussianSampler(rng), - scale, shape); - } - - /** {@inheritDoc} */ - @Override - public double sample() { - return sampler.sample(); - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return sampler.toString(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/BoxMullerNormalizedGaussianSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/BoxMullerNormalizedGaussianSampler.java deleted file mode 100644 index 49824f255..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/BoxMullerNormalizedGaussianSampler.java +++ /dev/null @@ -1,78 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * - * Box-Muller algorithm for sampling from Gaussian distribution with - * mean 0 and standard deviation 1. - * - *

Sampling uses {@link UniformRandomProvider#nextDouble()}.

- * - * @since 1.1 - */ -public class BoxMullerNormalizedGaussianSampler - implements NormalizedGaussianSampler { - /** Next gaussian. */ - private double nextGaussian = Double.NaN; - /** Underlying source of randomness. */ - private final UniformRandomProvider rng; - - /** - * @param rng Generator of uniformly distributed random numbers. - */ - public BoxMullerNormalizedGaussianSampler(UniformRandomProvider rng) { - this.rng = rng; - } - - /** {@inheritDoc} */ - @Override - public double sample() { - final double random; - if (Double.isNaN(nextGaussian)) { - // Generate a pair of Gaussian numbers. - - final double x = rng.nextDouble(); - final double y = rng.nextDouble(); - final double alpha = 2 * Math.PI * x; - final double r = Math.sqrt(-2 * Math.log(y)); - - // Return the first element of the generated pair. - random = r * Math.cos(alpha); - - // Keep second element of the pair for next invocation. - nextGaussian = r * Math.sin(alpha); - } else { - // Use the second element of the pair (generated at the - // previous invocation). - random = nextGaussian; - - // Both elements of the pair have been used. - nextGaussian = Double.NaN; - } - - return random; - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Box-Muller normalized Gaussian deviate [" + rng.toString() + "]"; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/ChengBetaSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/ChengBetaSampler.java deleted file mode 100644 index fd6895877..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/ChengBetaSampler.java +++ /dev/null @@ -1,187 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Utility class implementing Cheng's algorithms for beta distribution sampling. - * - *
- *
- * R. C. H. Cheng,
- * "Generating beta variates with nonintegral shape parameters",
- * Communications of the ACM, 21, 317-322, 1978.
- * 
- *
- * - *

Sampling uses {@link UniformRandomProvider#nextDouble()}.

- * - * @since 1.0 - */ -public class ChengBetaSampler - extends SamplerBase - implements ContinuousSampler { - /** First shape parameter. */ - private final double alphaShape; - /** Second shape parameter. */ - private final double betaShape; - /** Underlying source of randomness. */ - private final UniformRandomProvider rng; - - /** - * Creates a sampler instance. - * - * @param rng Generator of uniformly distributed random numbers. - * @param alpha Distribution first shape parameter. - * @param beta Distribution second shape parameter. - * @throws IllegalArgumentException if {@code alpha <= 0} or {@code beta <= 0} - */ - public ChengBetaSampler(UniformRandomProvider rng, - double alpha, - double beta) { - super(null); - if (alpha <= 0) { - throw new IllegalArgumentException("alpha is not strictly positive: " + alpha); - } - if (beta <= 0) { - throw new IllegalArgumentException("beta is not strictly positive: " + beta); - } - this.rng = rng; - alphaShape = alpha; - betaShape = beta; - } - - /** {@inheritDoc} */ - @Override - public double sample() { - final double a = Math.min(alphaShape, betaShape); - final double b = Math.max(alphaShape, betaShape); - - if (a > 1) { - return algorithmBB(a, b); - } else { - return algorithmBC(b, a); - } - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Cheng Beta deviate [" + rng.toString() + "]"; - } - - /** - * Computes one sample using Cheng's BB algorithm, when \( \alpha \) and - * \( \beta \) are both larger than 1. - * - * @param a \( \min(\alpha, \beta) \). - * @param b \( \max(\alpha, \beta) \). - * @return a random sample. - */ - private double algorithmBB(double a, - double b) { - final double alpha = a + b; - final double beta = Math.sqrt((alpha - 2) / (2 * a * b - alpha)); - final double gamma = a + 1 / beta; - - double r; - double w; - double t; - do { - final double u1 = rng.nextDouble(); - final double u2 = rng.nextDouble(); - final double v = beta * (Math.log(u1) - Math.log1p(-u1)); - w = a * Math.exp(v); - final double z = u1 * u1 * u2; - r = gamma * v - 1.3862944; - final double s = a + r - w; - if (s + 2.609438 >= 5 * z) { - break; - } - - t = Math.log(z); - if (s >= t) { - break; - } - } while (r + alpha * (Math.log(alpha) - Math.log(b + w)) < t); - - w = Math.min(w, Double.MAX_VALUE); - - return equals(a, alphaShape) ? w / (b + w) : b / (b + w); - } - - /** - * Computes one sample using Cheng's BB algorithm, when at least one of - * \( \alpha \) or \( \beta \) is smaller than 1. - * - * @param a \( \min(\alpha, \beta) \). - * @param b \( \max(\alpha, \beta) \). - * @return a random sample. - */ - private double algorithmBC(double a, - double b) { - final double alpha = a + b; - final double beta = 1 / b; - final double delta = 1 + a - b; - final double k1 = delta * (0.0138889 + 0.0416667 * b) / (a * beta - 0.777778); - final double k2 = 0.25 + (0.5 + 0.25 / delta) * b; - - double w; - while (true) { - final double u1 = rng.nextDouble(); - final double u2 = rng.nextDouble(); - final double y = u1 * u2; - final double z = u1 * y; - if (u1 < 0.5) { - if (0.25 * u2 + z - y >= k1) { - continue; - } - } else { - if (z <= 0.25) { - final double v = beta * (Math.log(u1) - Math.log1p(-u1)); - w = a * Math.exp(v); - break; - } - - if (z >= k2) { - continue; - } - } - - final double v = beta * (Math.log(u1) - Math.log1p(-u1)); - w = a * Math.exp(v); - if (alpha * (Math.log(alpha) - Math.log(b + w) + v) - 1.3862944 >= Math.log(z)) { - break; - } - } - - w = Math.min(w, Double.MAX_VALUE); - - return equals(a, alphaShape) ? w / (b + w) : b / (b + w); - } - - /** - * @param a Value. - * @param b Value. - * @return {@code true} if {@code a} is equal to {@code b}. - */ - private boolean equals(double a, - double b) { - return Math.abs(a - b) <= Double.MIN_VALUE; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/ContinuousInverseCumulativeProbabilityFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/ContinuousInverseCumulativeProbabilityFunction.java deleted file mode 100644 index f82432ffa..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/ContinuousInverseCumulativeProbabilityFunction.java +++ /dev/null @@ -1,42 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -/** - * Interface for a continuous distribution that can be sampled using - * the - * inversion method. - * - * @since 1.0 - */ -public interface ContinuousInverseCumulativeProbabilityFunction { - /** - * Computes the quantile function of the distribution. - * For a random variable {@code X} distributed according to this distribution, - * the returned value is - *
    - *
  • \( \inf_{x \in \mathcal{R}} P(X \le x) \ge p \) for \( 0 \lt p \le 1 \)
  • - *
  • \( \inf_{x \in \mathcal{R}} P(X \le x) \gt 0 \) for \( p = 0 \)
  • - *
- * - * @param p Cumulative probability. - * @return the smallest {@code p}-quantile of the distribution - * (largest 0-quantile for {@code p = 0}). - * @throws IllegalArgumentException if {@code p < 0} or {@code p > 1}. - */ - double inverseCumulativeProbability(double p); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/ContinuousSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/ContinuousSampler.java deleted file mode 100644 index 8f3bc3836..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/ContinuousSampler.java +++ /dev/null @@ -1,31 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -/** - * Sampler that generates values of type {@code double}. - * - * @since 1.0 - */ -public interface ContinuousSampler { - /** - * Creates a sample. - * - * @return a sample. - */ - double sample(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/ContinuousUniformSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/ContinuousUniformSampler.java deleted file mode 100644 index e7d749e50..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/ContinuousUniformSampler.java +++ /dev/null @@ -1,64 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Sampling from a uniform distribution. - * - *

Sampling uses {@link UniformRandomProvider#nextDouble()}.

- * - * @since 1.0 - */ -public class ContinuousUniformSampler - extends SamplerBase - implements ContinuousSampler { - /** Lower bound. */ - private final double lo; - /** Higher bound. */ - private final double hi; - /** Underlying source of randomness. */ - private final UniformRandomProvider rng; - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param lo Lower bound. - * @param hi Higher bound. - */ - public ContinuousUniformSampler(UniformRandomProvider rng, - double lo, - double hi) { - super(null); - this.rng = rng; - this.lo = lo; - this.hi = hi; - } - - /** {@inheritDoc} */ - @Override - public double sample() { - final double u = rng.nextDouble(); - return u * hi + (1 - u) * lo; - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Uniform deviate [" + rng.toString() + "]"; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/DiscreteInverseCumulativeProbabilityFunction.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/DiscreteInverseCumulativeProbabilityFunction.java deleted file mode 100644 index 17b4b4aa8..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/DiscreteInverseCumulativeProbabilityFunction.java +++ /dev/null @@ -1,42 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -/** - * Interface for a discrete distribution that can be sampled using - * the - * inversion method. - * - * @since 1.0 - */ -public interface DiscreteInverseCumulativeProbabilityFunction { - /** - * Computes the quantile function of the distribution. - * For a random variable {@code X} distributed according to this distribution, - * the returned value is - *
    - *
  • \( \inf_{x \in \mathcal{Z}} P(X \le x) \ge p \) for \( 0 \lt p \le 1 \)
  • - *
  • \( \inf_{x \in \mathcal{Z}} P(X \le x) \gt 0 \) for \( p = 0 \)
  • - *
- * - * @param p Cumulative probability. - * @return the smallest {@code p}-quantile of the distribution - * (largest 0-quantile for {@code p = 0}). - * @throws IllegalArgumentException if {@code p < 0} or {@code p > 1}. - */ - int inverseCumulativeProbability(double p); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/DiscreteSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/DiscreteSampler.java deleted file mode 100644 index 4c01a0af0..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/DiscreteSampler.java +++ /dev/null @@ -1,31 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -/** - * Sampler that generates values of type {@code int}. - * - * @since 1.0 - */ -public interface DiscreteSampler { - /** - * Creates a sample. - * - * @return a sample. - */ - int sample(); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/DiscreteUniformSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/DiscreteUniformSampler.java deleted file mode 100644 index 2b5ea528a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/DiscreteUniformSampler.java +++ /dev/null @@ -1,166 +0,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. - */ - -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Discrete uniform distribution sampler. - * - *

Sampling uses {@link UniformRandomProvider#nextInt(int)} when - * the range {@code (upper - lower) <} {@link Integer#MAX_VALUE}, otherwise - * {@link UniformRandomProvider#nextInt()}.

- * - * @since 1.0 - */ -public class DiscreteUniformSampler - extends SamplerBase - implements DiscreteSampler { - - /** The appropriate uniform sampler for the parameters. */ - private final DiscreteSampler delegate; - - /** - * Base class for a sampler from a discrete uniform distribution. - */ - private abstract static class AbstractDiscreteUniformSampler - implements DiscreteSampler { - - /** Underlying source of randomness. */ - protected final UniformRandomProvider rng; - /** Lower bound. */ - protected final int lower; - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param lower Lower bound (inclusive) of the distribution. - */ - AbstractDiscreteUniformSampler(UniformRandomProvider rng, - int lower) { - this.rng = rng; - this.lower = lower; - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Uniform deviate [" + rng.toString() + "]"; - } - } - - /** - * Discrete uniform distribution sampler when the range between lower and upper is small - * enough to fit in a positive integer. - */ - private static class SmallRangeDiscreteUniformSampler - extends AbstractDiscreteUniformSampler { - - /** Maximum range of the sample from the lower bound (exclusive). */ - private final int range; - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param lower Lower bound (inclusive) of the distribution. - * @param range Maximum range of the sample from the lower bound (exclusive). - */ - SmallRangeDiscreteUniformSampler(UniformRandomProvider rng, - int lower, - int range) { - super(rng, lower); - this.range = range; - } - - @Override - public int sample() { - return lower + rng.nextInt(range); - } - } - - /** - * Discrete uniform distribution sampler when the range between lower and upper is too large - * to fit in a positive integer. - */ - private static class LargeRangeDiscreteUniformSampler - extends AbstractDiscreteUniformSampler { - - /** Upper bound. */ - private final int upper; - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param lower Lower bound (inclusive) of the distribution. - * @param upper Upper bound (inclusive) of the distribution. - */ - LargeRangeDiscreteUniformSampler(UniformRandomProvider rng, - int lower, - int upper) { - super(rng, lower); - this.upper = upper; - } - - @Override - public int sample() { - // Use a simple rejection method. - // This is used when (upper-lower) >= Integer.MAX_VALUE. - // This will loop on average 2 times in the worst case scenario - // when (upper-lower) == Integer.MAX_VALUE. - while (true) { - final int r = rng.nextInt(); - if (r >= lower && - r <= upper) { - return r; - } - } - } - } - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param lower Lower bound (inclusive) of the distribution. - * @param upper Upper bound (inclusive) of the distribution. - * @throws IllegalArgumentException if {@code lower > upper}. - */ - public DiscreteUniformSampler(UniformRandomProvider rng, - int lower, - int upper) { - super(null); - if (lower > upper) { - throw new IllegalArgumentException(lower + " > " + upper); - } - // Choose the algorithm depending on the range - final int range = (upper - lower) + 1; - delegate = range <= 0 ? - // The range is too wide to fit in a positive int (larger - // than 2^31); use a simple rejection method. - new LargeRangeDiscreteUniformSampler(rng, lower, upper) : - // Use a sample from the range added to the lower bound. - new SmallRangeDiscreteUniformSampler(rng, lower, range); - } - - /** {@inheritDoc} */ - @Override - public int sample() { - return delegate.sample(); - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return delegate.toString(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/GaussianSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/GaussianSampler.java deleted file mode 100644 index 9c997422f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/GaussianSampler.java +++ /dev/null @@ -1,62 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -/** - * Sampling from a Gaussian distribution with given mean and - * standard deviation. - * - * @since 1.1 - */ -public class GaussianSampler implements ContinuousSampler { - /** Mean. */ - private final double mean; - /** standardDeviation. */ - private final double standardDeviation; - /** Normalized Gaussian sampler. */ - private final NormalizedGaussianSampler normalized; - - /** - * @param normalized Generator of N(0,1) Gaussian distributed random numbers. - * @param mean Mean of the Gaussian distribution. - * @param standardDeviation Standard deviation of the Gaussian distribution. - * @throws IllegalArgumentException if {@code standardDeviation <= 0} - */ - public GaussianSampler(NormalizedGaussianSampler normalized, - double mean, - double standardDeviation) { - if (standardDeviation <= 0) { - throw new IllegalArgumentException( - "standard deviation is not strictly positive: " + standardDeviation); - } - this.normalized = normalized; - this.mean = mean; - this.standardDeviation = standardDeviation; - } - - /** {@inheritDoc} */ - @Override - public double sample() { - return standardDeviation * normalized.sample() + mean; - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Gaussian deviate [" + normalized.toString() + "]"; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java deleted file mode 100644 index f4683ac64..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java +++ /dev/null @@ -1,152 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Sampling from a geometric - * distribution. - * - *

This distribution samples the number of failures before the first success taking values in the - * set {@code [0, 1, 2, ...]}.

- * - *

The sample is computed using a related exponential distribution. If \( X \) is an - * exponentially distributed random variable with parameter \( \lambda \), then - * \( Y = \left \lfloor X \right \rfloor \) is a geometrically distributed random variable with - * parameter \( p = 1 − e^\lambda \), with \( p \) the probability of success.

- * - *

This sampler outperforms using the {@link InverseTransformDiscreteSampler} with an appropriate - * Geometric inverse cumulative probability function.

- * - *

Usage note: As the probability of success (\( p \)) tends towards zero the mean of the - * distribution (\( \frac{1-p}{p} \)) tends towards infinity and due to the use of {@code int} - * for the sample this can result in truncation of the distribution.

- * - *

Sampling uses {@link UniformRandomProvider#nextDouble()}.

- * - * @see Geometric - * distribution - related distributions - * - * @since 1.3 - */ -public class GeometricSampler implements DiscreteSampler { - /** The appropriate geometric sampler for the parameters. */ - private final DiscreteSampler delegate; - - /** - * Sample from the geometric distribution when the probability of success is 1. - */ - private static class GeometricP1Sampler implements DiscreteSampler { - /** The single instance. */ - static final GeometricP1Sampler INSTANCE = new GeometricP1Sampler(); - - @Override - public int sample() { - // When probability of success is 1 the sample is always zero - return 0; - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Geometric(p=1) deviate"; - } - } - - /** - * Sample from the geometric distribution by using a related exponential distribution. - */ - private static class GeometricExponentialSampler implements DiscreteSampler { - /** Underlying source of randomness. Used only for the {@link #toString()} method. */ - private final UniformRandomProvider rng; - /** The related exponential sampler for the geometric distribution. */ - private final AhrensDieterExponentialSampler exponentialSampler; - - /** - * @param rng Generator of uniformly distributed random numbers - * @param probabilityOfSuccess The probability of success (must be in the range - * {@code [0 < probabilityOfSuccess < 1]}) - */ - GeometricExponentialSampler(UniformRandomProvider rng, double probabilityOfSuccess) { - this.rng = rng; - // Use a related exponential distribution: - // λ = −ln(1 − probabilityOfSuccess) - // exponential mean = 1 / λ - // -- - // Note on validation: - // If probabilityOfSuccess == Math.nextDown(1.0) the exponential mean is >0 (valid). - // If probabilityOfSuccess == Double.MIN_VALUE the exponential mean is +Infinity - // and the sample will always be Integer.MAX_VALUE (the distribution is truncated). It - // is noted in the class Javadoc that the use of a small p leads to truncation so - // no checks are made for this case. - final double exponentialMean = 1.0 / (-Math.log1p(-probabilityOfSuccess)); - exponentialSampler = new AhrensDieterExponentialSampler(rng, exponentialMean); - } - - @Override - public int sample() { - // Return the floor of the exponential sample - return (int) Math.floor(exponentialSampler.sample()); - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Geometric deviate [" + rng.toString() + "]"; - } - } - - /** - * Creates a new geometric distribution sampler. The samples will be provided in the set - * {@code k=[0, 1, 2, ...]} where {@code k} indicates the number of failures before the first - * success. - * - * @param rng Generator of uniformly distributed random numbers - * @param probabilityOfSuccess The probability of success - * @throws IllegalArgumentException if {@code probabilityOfSuccess} is not in the range - * {@code [0 < probabilityOfSuccess <= 1]}) - */ - public GeometricSampler(UniformRandomProvider rng, double probabilityOfSuccess) { - if (probabilityOfSuccess <= 0 || probabilityOfSuccess > 1) { - throw new IllegalArgumentException( - "Probability of success (p) must be in the range [0 < p <= 1]: " + - probabilityOfSuccess); - } - delegate = probabilityOfSuccess == 1 ? - GeometricP1Sampler.INSTANCE : - new GeometricExponentialSampler(rng, probabilityOfSuccess); - } - - /** - * Create a sample from a geometric distribution. - * - *

The sample will take the values in the set {@code [0, 1, 2, ...]}, equivalent to the - * number of failures before the first success. - */ - @Override - public int sample() { - return delegate.sample(); - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return delegate.toString(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/InternalGamma.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/InternalGamma.java deleted file mode 100644 index 8317510b3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/InternalGamma.java +++ /dev/null @@ -1,126 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -/** - *

- * Adapted and stripped down copy of class - * {@code "org.apache.commons.math4.special.Gamma"}. - * TODO: Include it in a "core" component upon which high-level functionality - * such as sampling can depend. - *

- * - *

- * This is a utility class that provides computation methods related to the - * Γ (Gamma) family of functions. - *

- */ -class InternalGamma { // Class is package-private on purpose; do not make it public. - /** - * Constant \( g = \frac{607}{128} \) in the Lanczos approximation. - */ - public static final double LANCZOS_G = 607.0 / 128.0; - - /** Lanczos coefficients */ - private static final double[] LANCZOS = { - 0.99999999999999709182, - 57.156235665862923517, - -59.597960355475491248, - 14.136097974741747174, - -0.49191381609762019978, - .33994649984811888699e-4, - .46523628927048575665e-4, - -.98374475304879564677e-4, - .15808870322491248884e-3, - -.21026444172410488319e-3, - .21743961811521264320e-3, - -.16431810653676389022e-3, - .84418223983852743293e-4, - -.26190838401581408670e-4, - .36899182659531622704e-5, - }; - - /** Avoid repeated computation of log of 2 PI in logGamma */ - private static final double HALF_LOG_2_PI = 0.5 * Math.log(2.0 * Math.PI); - - /** - * Class contains only static methods. - */ - private InternalGamma() {} - - /** - * Computes the function \( \ln \Gamma(x) \) for \( x > 0 \). - * - *

- * For \( x \leq 8 \), the implementation is based on the double precision - * implementation in the NSWC Library of Mathematics Subroutines, - * {@code DGAMLN}. For \( x \geq 8 \), the implementation is based on - *

- * - * - * - * @param x Argument. - * @return \( \ln \Gamma(x) \), or {@code NaN} if {@code x <= 0}. - */ - public static double logGamma(double x) { - // Stripped-down version of the same method defined in "Commons Math": - // Unused "if" branches (for when x < 8) have been removed here since - // this method is only used (by class "InternalUtils") in order to - // compute log(n!) for x > 20. - - final double sum = lanczos(x); - final double tmp = x + LANCZOS_G + 0.5; - return (x + 0.5) * Math.log(tmp) - tmp + HALF_LOG_2_PI + Math.log(sum / x); - } - - /** - * Computes the Lanczos approximation used to compute the gamma function. - * - *

- * The Lanczos approximation is related to the Gamma function by the - * following equation - * \[ - * \Gamma(x) = \sqrt{2\pi} \, \frac{(g + x + \frac{1}{2})^{x + \frac{1}{2}} \, e^{-(g + x + \frac{1}{2})} \, \mathrm{lanczos}(x)} - * {x} - * \] - * where \(g\) is the Lanczos constant. - *

- * - * @param x Argument. - * @return The Lanczos approximation. - * - * @see Lanczos Approximation - * equations (1) through (5), and Paul Godfrey's - * Note on the computation - * of the convergent Lanczos complex Gamma approximation - */ - private static double lanczos(final double x) { - double sum = 0.0; - for (int i = LANCZOS.length - 1; i > 0; --i) { - sum += LANCZOS[i] / (x + i); - } - return sum + LANCZOS[0]; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/InternalUtils.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/InternalUtils.java deleted file mode 100644 index 5a9e11b68..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/InternalUtils.java +++ /dev/null @@ -1,132 +0,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. - */ - -package org.apache.commons.rng.sampling.distribution; - -/** - * Functions used by some of the samplers. - * This class is not part of the public API, as it would be - * better to group these utilities in a dedicated components. - */ -class InternalUtils { // Class is package-private on purpose; do not make it public. - /** All long-representable factorials. */ - private static final long[] FACTORIALS = new long[] { - 1L, 1L, 2L, - 6L, 24L, 120L, - 720L, 5040L, 40320L, - 362880L, 3628800L, 39916800L, - 479001600L, 6227020800L, 87178291200L, - 1307674368000L, 20922789888000L, 355687428096000L, - 6402373705728000L, 121645100408832000L, 2432902008176640000L }; - - /** Utility class. */ - private InternalUtils() {} - - /** - * @param n Argument. - * @return {@code n!} - * @throws IndexOutOfBoundsException if the result is too large to be represented - * by a {@code long} (i.e. if {@code n > 20}), or {@code n} is negative. - */ - public static long factorial(int n) { - return FACTORIALS[n]; - } - - /** - * Class for computing the natural logarithm of the factorial of {@code n}. - * It allows to allocate a cache of precomputed values. - * In case of cache miss, computation is performed by a call to - * {@link InternalGamma#logGamma(double)}. - */ - public static final class FactorialLog { - /** - * Precomputed values of the function: - * {@code LOG_FACTORIALS[i] = log(i!)}. - */ - private final double[] LOG_FACTORIALS; - - /** - * Creates an instance, reusing the already computed values if available. - * - * @param numValues Number of values of the function to compute. - * @param cache Existing cache. - * @throws NegativeArraySizeException if {@code numValues < 0}. - */ - private FactorialLog(int numValues, - double[] cache) { - LOG_FACTORIALS = new double[numValues]; - - final int beginCopy = 2; - final int endCopy = cache == null || cache.length <= beginCopy ? - beginCopy : cache.length <= numValues ? - cache.length : numValues; - - // Copy available values. - for (int i = beginCopy; i < endCopy; i++) { - LOG_FACTORIALS[i] = cache[i]; - } - - // Precompute. - for (int i = endCopy; i < numValues; i++) { - LOG_FACTORIALS[i] = LOG_FACTORIALS[i - 1] + Math.log(i); - } - } - - /** - * Creates an instance with no precomputed values. - * - * @return an instance with no precomputed values. - */ - public static FactorialLog create() { - return new FactorialLog(0, null); - } - - /** - * Creates an instance with the specified cache size. - * - * @param cacheSize Number of precomputed values of the function. - * @return a new instance where {@code cacheSize} values have been - * precomputed. - * @throws IllegalArgumentException if {@code n < 0}. - */ - public FactorialLog withCache(final int cacheSize) { - return new FactorialLog(cacheSize, LOG_FACTORIALS); - } - - /** - * Computes {@code log(n!)}. - * - * @param n Argument. - * @return {@code log(n!)}. - * @throws IndexOutOfBoundsException if {@code numValues < 0}. - */ - public double value(final int n) { - // Use cache of precomputed values. - if (n < LOG_FACTORIALS.length) { - return LOG_FACTORIALS[n]; - } - - // Use cache of precomputed factorial values. - if (n < FACTORIALS.length) { - return Math.log(FACTORIALS[n]); - } - - // Delegate. - return InternalGamma.logGamma(n + 1); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/InverseTransformContinuousSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/InverseTransformContinuousSampler.java deleted file mode 100644 index 5ba32fd59..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/InverseTransformContinuousSampler.java +++ /dev/null @@ -1,88 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Distribution sampler that uses the - * - * inversion method. - * - * It can be used to sample any distribution that provides access to its - * inverse cumulative probability function. - * - *

Sampling uses {@link UniformRandomProvider#nextDouble()}.

- * - *

Example:

- *

- * import org.apache.commons.math3.distribution.RealDistribution;
- * import org.apache.commons.math3.distribution.ChiSquaredDistribution;
- *
- * import org.apache.commons.rng.simple.RandomSource;
- * import org.apache.commons.rng.sampling.distribution.ContinuousSampler;
- * import org.apache.commons.rng.sampling.distribution.InverseTransformContinuousSampler;
- * import org.apache.commons.rng.sampling.distribution.ContinuousInverseCumulativeProbabilityFunction;
- *
- * // Distribution to sample.
- * final RealDistribution dist = new ChiSquaredDistribution(9);
- * // Create the sampler.
- * final ContinuousSampler chiSquareSampler =
- *     new InverseTransformContinuousSampler(RandomSource.create(RandomSource.MT),
- *                                           new ContinuousInverseCumulativeProbabilityFunction() {
- *                                               public double inverseCumulativeProbability(double p) {
- *                                                   return dist.inverseCumulativeProbability(p);
- *                                               }
- *                                           });
- *
- * // Generate random deviate.
- * double random = chiSquareSampler.sample();
- * 
- * - * @since 1.0 - */ -public class InverseTransformContinuousSampler - extends SamplerBase - implements ContinuousSampler { - /** Inverse cumulative probability function. */ - private final ContinuousInverseCumulativeProbabilityFunction function; - /** Underlying source of randomness. */ - private final UniformRandomProvider rng; - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param function Inverse cumulative probability function. - */ - public InverseTransformContinuousSampler(UniformRandomProvider rng, - ContinuousInverseCumulativeProbabilityFunction function) { - super(null); - this.rng = rng; - this.function = function; - } - - /** {@inheritDoc} */ - @Override - public double sample() { - return function.inverseCumulativeProbability(rng.nextDouble()); - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return function.toString() + " (inverse method) [" + rng.toString() + "]"; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/InverseTransformDiscreteSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/InverseTransformDiscreteSampler.java deleted file mode 100644 index 276fb8e99..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/InverseTransformDiscreteSampler.java +++ /dev/null @@ -1,88 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Distribution sampler that uses the - * - * inversion method. - * - * It can be used to sample any distribution that provides access to its - * inverse cumulative probability function. - * - *

Sampling uses {@link UniformRandomProvider#nextDouble()}.

- * - *

Example:

- *

- * import org.apache.commons.math3.distribution.IntegerDistribution;
- * import org.apache.commons.math3.distribution.BinomialDistribution;
- *
- * import org.apache.commons.rng.simple.RandomSource;
- * import org.apache.commons.rng.sampling.distribution.DiscreteSampler;
- * import org.apache.commons.rng.sampling.distribution.InverseTransformDiscreteSampler;
- * import org.apache.commons.rng.sampling.distribution.DiscreteInverseCumulativeProbabilityFunction;
- *
- * // Distribution to sample.
- * final IntegerDistribution dist = new BinomialDistribution(11, 0.56);
- * // Create the sampler.
- * final DiscreteSampler binomialSampler =
- *     new InverseTransformDiscreteSampler(RandomSource.create(RandomSource.MT),
- *                                         new DiscreteInverseCumulativeProbabilityFunction() {
- *                                             public int inverseCumulativeProbability(double p) {
- *                                                 return dist.inverseCumulativeProbability(p);
- *                                             }
- *                                         });
- *
- * // Generate random deviate.
- * int random = binomialSampler.sample();
- * 
- * - * @since 1.0 - */ -public class InverseTransformDiscreteSampler - extends SamplerBase - implements DiscreteSampler { - /** Inverse cumulative probability function. */ - private final DiscreteInverseCumulativeProbabilityFunction function; - /** Underlying source of randomness. */ - private final UniformRandomProvider rng; - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param function Inverse cumulative probability function. - */ - public InverseTransformDiscreteSampler(UniformRandomProvider rng, - DiscreteInverseCumulativeProbabilityFunction function) { - super(null); - this.rng = rng; - this.function = function; - } - - /** {@inheritDoc} */ - @Override - public int sample() { - return function.inverseCumulativeProbability(rng.nextDouble()); - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return function.toString() + " (inverse method) [" + rng.toString() + "]"; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/InverseTransformParetoSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/InverseTransformParetoSampler.java deleted file mode 100644 index 69f7a11e3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/InverseTransformParetoSampler.java +++ /dev/null @@ -1,70 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Sampling from a Pareto distribution. - * - *

Sampling uses {@link UniformRandomProvider#nextDouble()}.

- * - * @since 1.0 - */ -public class InverseTransformParetoSampler - extends SamplerBase - implements ContinuousSampler { - /** Scale. */ - private final double scale; - /** 1 / Shape. */ - private final double oneOverShape; - /** Underlying source of randomness. */ - private final UniformRandomProvider rng; - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param scale Scale of the distribution. - * @param shape Shape of the distribution. - * @throws IllegalArgumentException if {@code scale <= 0} or {@code shape <= 0} - */ - public InverseTransformParetoSampler(UniformRandomProvider rng, - double scale, - double shape) { - super(null); - if (scale <= 0) { - throw new IllegalArgumentException("scale is not strictly positive: " + scale); - } - if (shape <= 0) { - throw new IllegalArgumentException("shape is not strictly positive: " + shape); - } - this.rng = rng; - this.scale = scale; - this.oneOverShape = 1 / shape; - } - - /** {@inheritDoc} */ - @Override - public double sample() { - return scale / Math.pow(rng.nextDouble(), oneOverShape); - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "[Inverse method for Pareto distribution " + rng.toString() + "]"; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/LargeMeanPoissonSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/LargeMeanPoissonSampler.java deleted file mode 100644 index a02c13160..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/LargeMeanPoissonSampler.java +++ /dev/null @@ -1,413 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.InternalUtils.FactorialLog; - -/** - * Sampler for the Poisson distribution. - * - *
    - *
  • - * For large means, we use the rejection algorithm described in - *
    - * Devroye, Luc. (1981).The Computer Generation of Poisson Random Variables
    - * Computing vol. 26 pp. 197-207. - *
    - *
  • - *
- * - *

This sampler is suitable for {@code mean >= 40}.

- * - *

Sampling uses:

- * - *
    - *
  • {@link UniformRandomProvider#nextLong()} - *
  • {@link UniformRandomProvider#nextDouble()} - *
- * - * @since 1.1 - */ -public class LargeMeanPoissonSampler - implements DiscreteSampler { - /** Upper bound to avoid truncation. */ - private static final double MAX_MEAN = 0.5 * Integer.MAX_VALUE; - /** Class to compute {@code log(n!)}. This has no cached values. */ - private static final InternalUtils.FactorialLog NO_CACHE_FACTORIAL_LOG; - /** Used when there is no requirement for a small mean Poisson sampler. */ - private static final DiscreteSampler NO_SMALL_MEAN_POISSON_SAMPLER = null; - - static { - // Create without a cache. - NO_CACHE_FACTORIAL_LOG = FactorialLog.create(); - } - - /** Underlying source of randomness. */ - private final UniformRandomProvider rng; - /** Exponential. */ - private final ContinuousSampler exponential; - /** Gaussian. */ - private final ContinuousSampler gaussian; - /** Local class to compute {@code log(n!)}. This may have cached values. */ - private final InternalUtils.FactorialLog factorialLog; - - // Working values - - /** Algorithm constant: {@code Math.floor(mean)}. */ - private final double lambda; - /** Algorithm constant: {@code Math.log(lambda)}. */ - private final double logLambda; - /** Algorithm constant: {@code factorialLog((int) lambda)}. */ - private final double logLambdaFactorial; - /** Algorithm constant: {@code Math.sqrt(lambda * Math.log(32 * lambda / Math.PI + 1))}. */ - private final double delta; - /** Algorithm constant: {@code delta / 2}. */ - private final double halfDelta; - /** Algorithm constant: {@code 2 * lambda + delta}. */ - private final double twolpd; - /** - * Algorithm constant: {@code a1 / aSum} with - *
    - *
  • {@code a1 = Math.sqrt(Math.PI * twolpd) * Math.exp(c1)}
  • - *
  • {@code aSum = a1 + a2 + 1}
  • - *
- */ - private final double p1; - /** - * Algorithm constant: {@code a2 / aSum} with - *
    - *
  • {@code a2 = (twolpd / delta) * Math.exp(-delta * (1 + delta) / twolpd)}
  • - *
  • {@code aSum = a1 + a2 + 1}
  • - *
- */ - private final double p2; - /** Algorithm constant: {@code 1 / (8 * lambda)}. */ - private final double c1; - - /** The internal Poisson sampler for the lambda fraction. */ - private final DiscreteSampler smallMeanPoissonSampler; - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param mean Mean. - * @throws IllegalArgumentException if {@code mean < 1} or - * {@code mean > 0.5 *} {@link Integer#MAX_VALUE}. - */ - public LargeMeanPoissonSampler(UniformRandomProvider rng, - double mean) { - if (mean < 1) { - throw new IllegalArgumentException("mean is not >= 1: " + mean); - } - // The algorithm is not valid if Math.floor(mean) is not an integer. - if (mean > MAX_MEAN) { - throw new IllegalArgumentException("mean " + mean + " > " + MAX_MEAN); - } - this.rng = rng; - - gaussian = new ZigguratNormalizedGaussianSampler(rng); - exponential = new AhrensDieterExponentialSampler(rng, 1); - // Plain constructor uses the uncached function. - factorialLog = NO_CACHE_FACTORIAL_LOG; - - // Cache values used in the algorithm - lambda = Math.floor(mean); - logLambda = Math.log(lambda); - logLambdaFactorial = factorialLog((int) lambda); - delta = Math.sqrt(lambda * Math.log(32 * lambda / Math.PI + 1)); - halfDelta = delta / 2; - twolpd = 2 * lambda + delta; - c1 = 1 / (8 * lambda); - final double a1 = Math.sqrt(Math.PI * twolpd) * Math.exp(c1); - final double a2 = (twolpd / delta) * Math.exp(-delta * (1 + delta) / twolpd); - final double aSum = a1 + a2 + 1; - p1 = a1 / aSum; - p2 = a2 / aSum; - - // The algorithm requires a Poisson sample from the remaining lambda fraction. - final double lambdaFractional = mean - lambda; - smallMeanPoissonSampler = (lambdaFractional < Double.MIN_VALUE) ? - NO_SMALL_MEAN_POISSON_SAMPLER : // Not used. - new SmallMeanPoissonSampler(rng, lambdaFractional); - } - - /** - * Instantiates a sampler using a precomputed state. - * - * @param rng Generator of uniformly distributed random numbers. - * @param state The state for {@code lambda = (int)Math.floor(mean)}. - * @param lambdaFractional The lambda fractional value - * ({@code mean - (int)Math.floor(mean))}. - * @throws IllegalArgumentException - * if {@code lambdaFractional < 0 || lambdaFractional >= 1}. - */ - LargeMeanPoissonSampler(UniformRandomProvider rng, - LargeMeanPoissonSamplerState state, - double lambdaFractional) { - if (lambdaFractional < 0 || lambdaFractional >= 1) { - throw new IllegalArgumentException( - "lambdaFractional must be in the range 0 (inclusive) to 1 (exclusive): " + lambdaFractional); - } - this.rng = rng; - - gaussian = new ZigguratNormalizedGaussianSampler(rng); - exponential = new AhrensDieterExponentialSampler(rng, 1); - // Plain constructor uses the uncached function. - factorialLog = NO_CACHE_FACTORIAL_LOG; - - // Use the state to initialise the algorithm - lambda = state.getLambdaRaw(); - logLambda = state.getLogLambda(); - logLambdaFactorial = state.getLogLambdaFactorial(); - delta = state.getDelta(); - halfDelta = state.getHalfDelta(); - twolpd = state.getTwolpd(); - p1 = state.getP1(); - p2 = state.getP2(); - c1 = state.getC1(); - - // The algorithm requires a Poisson sample from the remaining lambda fraction. - smallMeanPoissonSampler = (lambdaFractional < Double.MIN_VALUE) ? - NO_SMALL_MEAN_POISSON_SAMPLER : // Not used. - new SmallMeanPoissonSampler(rng, lambdaFractional); - } - - /** {@inheritDoc} */ - @Override - public int sample() { - - final int y2 = (smallMeanPoissonSampler == null) ? - 0 : // No lambda fraction - smallMeanPoissonSampler.sample(); - - double x; - double y; - double v; - int a; - double t; - double qr; - double qa; - while (true) { - final double u = rng.nextDouble(); - if (u <= p1) { - final double n = gaussian.sample(); - x = n * Math.sqrt(lambda + halfDelta) - 0.5d; - if (x > delta || x < -lambda) { - continue; - } - y = x < 0 ? Math.floor(x) : Math.ceil(x); - final double e = exponential.sample(); - v = -e - 0.5 * n * n + c1; - } else { - if (u > p1 + p2) { - y = lambda; - break; - } - x = delta + (twolpd / delta) * exponential.sample(); - y = Math.ceil(x); - v = -exponential.sample() - delta * (x + 1) / twolpd; - } - a = x < 0 ? 1 : 0; - t = y * (y + 1) / (2 * lambda); - if (v < -t && a == 0) { - y = lambda + y; - break; - } - qr = t * ((2 * y + 1) / (6 * lambda) - 1); - qa = qr - (t * t) / (3 * (lambda + a * (y + 1))); - if (v < qa) { - y = lambda + y; - break; - } - if (v > qr) { - continue; - } - if (v < y * logLambda - factorialLog((int) (y + lambda)) + logLambdaFactorial) { - y = lambda + y; - break; - } - } - - return (int) Math.min(y2 + (long) y, Integer.MAX_VALUE); - } - - /** - * Compute the natural logarithm of the factorial of {@code n}. - * - * @param n Argument. - * @return {@code log(n!)} - * @throws IllegalArgumentException if {@code n < 0}. - */ - private double factorialLog(int n) { - return factorialLog.value(n); - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Large Mean Poisson deviate [" + rng.toString() + "]"; - } - - /** - * Gets the initialisation state of the sampler. - * - *

The state is computed using an integer {@code lambda} value of - * {@code lambda = (int)Math.floor(mean)}. - * - *

The state will be suitable for reconstructing a new sampler with a mean - * in the range {@code lambda <= mean < lambda+1} using - * {@link #LargeMeanPoissonSampler(UniformRandomProvider, LargeMeanPoissonSamplerState, double)}. - * - * @return the state - */ - LargeMeanPoissonSamplerState getState() { - return new LargeMeanPoissonSamplerState(lambda, logLambda, logLambdaFactorial, - delta, halfDelta, twolpd, p1, p2, c1); - } - - /** - * Encapsulate the state of the sampler. The state is valid for construction of - * a sampler in the range {@code lambda <= mean < lambda+1}. - * - *

This class is immutable. - * - * @see #getLambda() - */ - static final class LargeMeanPoissonSamplerState { - /** Algorithm constant {@code lambda}. */ - private final double lambda; - /** Algorithm constant {@code logLambda}. */ - private final double logLambda; - /** Algorithm constant {@code logLambdaFactorial}. */ - private final double logLambdaFactorial; - /** Algorithm constant {@code delta}. */ - private final double delta; - /** Algorithm constant {@code halfDelta}. */ - private final double halfDelta; - /** Algorithm constant {@code twolpd}. */ - private final double twolpd; - /** Algorithm constant {@code p1}. */ - private final double p1; - /** Algorithm constant {@code p2}. */ - private final double p2; - /** Algorithm constant {@code c1}. */ - private final double c1; - - /** - * Creates the state. - * - *

The state is valid for construction of a sampler in the range - * {@code lambda <= mean < lambda+1} where {@code lambda} is an integer. - * - * @param lambda the lambda - * @param logLambda the log lambda - * @param logLambdaFactorial the log lambda factorial - * @param delta the delta - * @param halfDelta the half delta - * @param twolpd the two lambda plus delta - * @param p1 the p1 constant - * @param p2 the p2 constant - * @param c1 the c1 constant - */ - private LargeMeanPoissonSamplerState(double lambda, double logLambda, - double logLambdaFactorial, double delta, double halfDelta, double twolpd, - double p1, double p2, double c1) { - this.lambda = lambda; - this.logLambda = logLambda; - this.logLambdaFactorial = logLambdaFactorial; - this.delta = delta; - this.halfDelta = halfDelta; - this.twolpd = twolpd; - this.p1 = p1; - this.p2 = p2; - this.c1 = c1; - } - - /** - * Get the lambda value for the state. - * - *

Equal to {@code floor(mean)} for a Poisson sampler. - * @return the lambda value - */ - int getLambda() { - return (int) getLambdaRaw(); - } - - /** - * @return algorithm constant {@code lambda} - */ - double getLambdaRaw() { - return lambda; - } - - /** - * @return algorithm constant {@code logLambda} - */ - double getLogLambda() { - return logLambda; - } - - /** - * @return algorithm constant {@code logLambdaFactorial} - */ - double getLogLambdaFactorial() { - return logLambdaFactorial; - } - - /** - * @return algorithm constant {@code delta} - */ - double getDelta() { - return delta; - } - - /** - * @return algorithm constant {@code halfDelta} - */ - double getHalfDelta() { - return halfDelta; - } - - /** - * @return algorithm constant {@code twolpd} - */ - double getTwolpd() { - return twolpd; - } - - /** - * @return algorithm constant {@code p1} - */ - double getP1() { - return p1; - } - - /** - * @return algorithm constant {@code p2} - */ - double getP2() { - return p2; - } - - /** - * @return algorithm constant {@code c1} - */ - double getC1() { - return c1; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/LogNormalSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/LogNormalSampler.java deleted file mode 100644 index 258f2f561..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/LogNormalSampler.java +++ /dev/null @@ -1,63 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -/** - * Sampling from a log-normal distribution. - * - * @since 1.1 - */ -public class LogNormalSampler implements ContinuousSampler { - /** Scale. */ - private final double scale; - /** Shape. */ - private final double shape; - /** Gaussian sampling. */ - private final NormalizedGaussianSampler gaussian; - - /** - * @param gaussian N(0,1) generator. - * @param scale Scale of the log-normal distribution. - * @param shape Shape of the log-normal distribution. - * @throws IllegalArgumentException if {@code scale < 0} or {@code shape <= 0}. - */ - public LogNormalSampler(NormalizedGaussianSampler gaussian, - double scale, - double shape) { - if (scale < 0) { - throw new IllegalArgumentException("scale is not positive: " + scale); - } - if (shape <= 0) { - throw new IllegalArgumentException("shape is not strictly positive: " + shape); - } - this.scale = scale; - this.shape = shape; - this.gaussian = gaussian; - } - - /** {@inheritDoc} */ - @Override - public double sample() { - return Math.exp(scale + shape * gaussian.sample()); - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Log-normal deviate [" + gaussian.toString() + "]"; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/MarsagliaNormalizedGaussianSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/MarsagliaNormalizedGaussianSampler.java deleted file mode 100644 index af50b55dd..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/MarsagliaNormalizedGaussianSampler.java +++ /dev/null @@ -1,87 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * - * Marsaglia polar method for sampling from a Gaussian distribution - * with mean 0 and standard deviation 1. - * This is a variation of the algorithm implemented in - * {@link BoxMullerNormalizedGaussianSampler}. - * - *

Sampling uses {@link UniformRandomProvider#nextDouble()}.

- * - * @since 1.1 - */ -public class MarsagliaNormalizedGaussianSampler - implements NormalizedGaussianSampler { - /** Next gaussian. */ - private double nextGaussian = Double.NaN; - /** Underlying source of randomness. */ - private final UniformRandomProvider rng; - - /** - * @param rng Generator of uniformly distributed random numbers. - */ - public MarsagliaNormalizedGaussianSampler(UniformRandomProvider rng) { - this.rng = rng; - } - - /** {@inheritDoc} */ - @Override - public double sample() { - if (Double.isNaN(nextGaussian)) { - // Rejection scheme for selecting a pair that lies within the unit circle. - while (true) { - // Generate a pair of numbers within [-1 , 1). - final double x = 2 * rng.nextDouble() - 1; - final double y = 2 * rng.nextDouble() - 1; - final double r2 = x * x + y * y; - - if (r2 < 1 && r2 > 0) { - // Pair (x, y) is within unit circle. - final double alpha = Math.sqrt(-2 * Math.log(r2) / r2); - - // Keep second element of the pair for next invocation. - nextGaussian = alpha * y; - - // Return the first element of the generated pair. - return alpha * x; - } - - // Pair is not within the unit circle: Generate another one. - } - } else { - // Use the second element of the pair (generated at the - // previous invocation). - final double r = nextGaussian; - - // Both elements of the pair have been used. - nextGaussian = Double.NaN; - - return r; - } - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Box-Muller (with rejection) normalized Gaussian deviate [" + rng.toString() + "]"; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/NormalizedGaussianSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/NormalizedGaussianSampler.java deleted file mode 100644 index d62915bdc..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/NormalizedGaussianSampler.java +++ /dev/null @@ -1,26 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -/** - * Marker interface for a sampler that generates values from an N(0,1) - * - * Gaussian distribution. - * - * @since 1.1 - */ -public interface NormalizedGaussianSampler extends ContinuousSampler {} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/PoissonSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/PoissonSampler.java deleted file mode 100644 index d2da6f0b4..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/PoissonSampler.java +++ /dev/null @@ -1,89 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Sampler for the Poisson distribution. - * - *
    - *
  • - * For small means, a Poisson process is simulated using uniform deviates, as - * described here. - * The Poisson process (and hence, the returned value) is bounded by 1000 * mean. - *
  • - *
  • - * For large means, we use the rejection algorithm described in - *
    - * Devroye, Luc. (1981). The Computer Generation of Poisson Random Variables
    - * Computing vol. 26 pp. 197-207. - *
    - *
  • - *
- * - *

Sampling uses:

- * - *
    - *
  • {@link UniformRandomProvider#nextDouble()} - *
  • {@link UniformRandomProvider#nextLong()} (large means only) - *
- * - * @since 1.0 - */ -public class PoissonSampler - extends SamplerBase - implements DiscreteSampler { - - /** - * Value for switching sampling algorithm. - * - *

Package scope for the {@link PoissonSamplerCache}. - */ - static final double PIVOT = 40; - /** The internal Poisson sampler. */ - private final DiscreteSampler poissonSamplerDelegate; - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param mean Mean. - * @throws IllegalArgumentException if {@code mean <= 0} or - * {@code mean >} {@link Integer#MAX_VALUE}. - */ - public PoissonSampler(UniformRandomProvider rng, - double mean) { - super(null); - - // Delegate all work to specialised samplers. - // These should check the input arguments. - poissonSamplerDelegate = mean < PIVOT ? - new SmallMeanPoissonSampler(rng, mean) : - new LargeMeanPoissonSampler(rng, mean); - } - - /** {@inheritDoc} */ - @Override - public int sample() { - return poissonSamplerDelegate.sample(); - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return poissonSamplerDelegate.toString(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/PoissonSamplerCache.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/PoissonSamplerCache.java deleted file mode 100644 index 61aa73b8e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/PoissonSamplerCache.java +++ /dev/null @@ -1,355 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.LargeMeanPoissonSampler.LargeMeanPoissonSamplerState; - -/** - * Create a sampler for the - * Poisson - * distribution using a cache to minimise construction cost. - * - *

The cache will return a sampler equivalent to - * {@link PoissonSampler#PoissonSampler(UniformRandomProvider, double)}.

- * - *

The cache allows the {@link PoissonSampler} construction cost to be minimised - * for low size Poisson samples. The cache stores state for a range of integers where - * integer value {@code n} can be used to construct a sampler for the range - * {@code n <= mean < n+1}.

- * - *

The cache is advantageous under the following conditions:

- * - *
    - *
  • The mean of the Poisson distribution falls within a known range. - *
  • The sample size to be made with the same sampler is - * small. - *
  • The Poisson samples have different means with the same integer - * value(s) after rounding down. - *
- * - *

If the sample size to be made with the same sampler is large - * then the construction cost is low compared to the sampling time and the cache - * has minimal benefit.

- * - *

Performance improvement is dependent on the speed of the - * {@link UniformRandomProvider}. A fast provider can obtain a two-fold speed - * improvement for a single-use Poisson sampler.

- * - *

The cache is thread safe. Note that concurrent threads using the cache - * must ensure a thread safe {@link UniformRandomProvider} is used when creating - * samplers, e.g. a unique sampler per thread.

- * - *

Sampling uses:

- * - *
    - *
  • {@link UniformRandomProvider#nextDouble()} - *
  • {@link UniformRandomProvider#nextLong()} (large means only) - *
- * - * @since 1.2 - */ -public class PoissonSamplerCache { - - /** - * The minimum N covered by the cache where - * {@code N = (int)Math.floor(mean)}. - */ - private final int minN; - /** - * The maximum N covered by the cache where - * {@code N = (int)Math.floor(mean)}. - */ - private final int maxN; - /** The cache of states between {@link minN} and {@link maxN}. */ - private final LargeMeanPoissonSamplerState[] values; - - /** - * @param minMean The minimum mean covered by the cache. - * @param maxMean The maximum mean covered by the cache. - * @throws IllegalArgumentException if {@code maxMean < minMean} - */ - public PoissonSamplerCache(double minMean, - double maxMean) { - - checkMeanRange(minMean, maxMean); - - // The cache can only be used for the LargeMeanPoissonSampler. - if (maxMean < PoissonSampler.PIVOT) { - // The upper limit is too small so no cache will be used. - // This class will just construct new samplers. - minN = 0; - maxN = 0; - values = null; - } else { - // Convert the mean into integers. - // Note the minimum is clipped to the algorithm switch point. - this.minN = (int) Math.floor(Math.max(minMean, PoissonSampler.PIVOT)); - this.maxN = (int) Math.floor(Math.min(maxMean, Integer.MAX_VALUE)); - values = new LargeMeanPoissonSamplerState[maxN - minN + 1]; - } - } - - /** - * @param minN The minimum N covered by the cache where {@code N = (int)Math.floor(mean)}. - * @param maxN The maximum N covered by the cache where {@code N = (int)Math.floor(mean)}. - * @param states The precomputed states. - */ - private PoissonSamplerCache(int minN, - int maxN, - LargeMeanPoissonSamplerState[] states) { - this.minN = minN; - this.maxN = maxN; - // Stored directly as the states were newly created within this class. - this.values = states; - } - - /** - * Check the mean range. - * - * @param minMean The minimum mean covered by the cache. - * @param maxMean The maximum mean covered by the cache. - * @throws IllegalArgumentException if {@code maxMean < minMean} - */ - private static void checkMeanRange(double minMean, double maxMean) - { - // Note: - // Although a mean of 0 is invalid for a Poisson sampler this case - // is handled to make the cache user friendly. Any low means will - // be handled by the SmallMeanPoissonSampler and not cached. - // For this reason it is also OK if the means are negative. - - // Allow minMean == maxMean so that the cache can be used - // to create samplers with distinct RNGs and the same mean. - if (maxMean < minMean) { - throw new IllegalArgumentException( - "Max mean: " + maxMean + " < " + minMean); - } - } - - /** - * Creates a new Poisson sampler. - * - *

The returned sampler will function exactly the - * same as {@link PoissonSampler#PoissonSampler(UniformRandomProvider, double)}. - * - * @param rng Generator of uniformly distributed random numbers. - * @param mean Mean. - * @return A Poisson sampler - * @throws IllegalArgumentException if {@code mean <= 0} or - * {@code mean >} {@link Integer#MAX_VALUE}. - */ - public DiscreteSampler createPoissonSampler(UniformRandomProvider rng, - double mean) { - // Ensure the same functionality as the PoissonSampler by - // using a SmallMeanPoissonSampler under the switch point. - if (mean < PoissonSampler.PIVOT) { - return new SmallMeanPoissonSampler(rng, mean); - } - if (mean > maxN) { - // Outside the range of the cache. - // This avoids extra parameter checks and handles the case when - // the cache is empty or if Math.floor(mean) is not an integer. - return new LargeMeanPoissonSampler(rng, mean); - } - - // Convert the mean into an integer. - final int n = (int) Math.floor(mean); - if (n < minN) { - // Outside the lower range of the cache. - return new LargeMeanPoissonSampler(rng, mean); - } - - // Look in the cache for a state that can be reused. - // Note: The cache is offset by minN. - final int index = n - minN; - final LargeMeanPoissonSamplerState state = values[index]; - if (state == null) { - // Create a sampler and store the state for reuse. - // Do not worry about thread contention - // as the state is effectively immutable. - // If recomputed and replaced it will the same. - final LargeMeanPoissonSampler sampler = new LargeMeanPoissonSampler(rng, mean); - values[index] = sampler.getState(); - return sampler; - } - // Compute the remaining fraction of the mean - final double lambdaFractional = mean - n; - return new LargeMeanPoissonSampler(rng, state, lambdaFractional); - } - - /** - * Check if the mean is within the range where the cache can minimise the - * construction cost of the {@link PoissonSampler}. - * - * @param mean - * the mean - * @return true, if within the cache range - */ - public boolean withinRange(double mean) { - if (mean < PoissonSampler.PIVOT) { - // Construction is optimal - return true; - } - // Convert the mean into an integer. - final int n = (int) Math.floor(mean); - return n <= maxN && n >= minN; - } - - /** - * Checks if the cache covers a valid range of mean values. - * - *

Note that the cache is only valid for one of the Poisson sampling - * algorithms. In the instance that a range was requested that was too - * low then there is nothing to cache and this functions returns - * {@code false}. - * - *

The cache can still be used to create a {@link PoissonSampler} using - * {@link #createPoissonSampler(UniformRandomProvider, double)}. - * - *

This method can be used to determine if the cache has a potential - * performance benefit. - * - * @return true, if the cache covers a range of mean values - */ - public boolean isValidRange() { - return values != null; - } - - /** - * Gets the minimum mean covered by the cache. - * - *

This value is the inclusive lower bound and is equal to - * the lowest integer-valued mean that is covered by the cache. - * - *

Note that this value may not match the value passed to the constructor - * due to the following reasons: - * - *

    - *
  • At small mean values a different algorithm is used for Poisson - * sampling and the cache is unnecessary. - *
  • The minimum is always an integer so may be below the constructor - * minimum mean. - *
- * - *

If {@link #isValidRange()} returns {@code true} the cache will store - * state to reduce construction cost of samplers in - * the range {@link #getMinMean()} inclusive to {@link #getMaxMean()} - * inclusive. Otherwise this method returns 0; - * - * @return The minimum mean covered by the cache. - */ - public double getMinMean() - { - return minN; - } - - /** - * Gets the maximum mean covered by the cache. - * - *

This value is the inclusive upper bound and is equal to - * the double value below the first integer-valued mean that is - * above range covered by the cache. - * - *

Note that this value may not match the value passed to the constructor - * due to the following reasons: - *

    - *
  • At small mean values a different algorithm is used for Poisson - * sampling and the cache is unnecessary. - *
  • The maximum is always the double value below an integer so - * may be above the constructor maximum mean. - *
- * - *

If {@link #isValidRange()} returns {@code true} the cache will store - * state to reduce construction cost of samplers in - * the range {@link #getMinMean()} inclusive to {@link #getMaxMean()} - * inclusive. Otherwise this method returns 0; - * - * @return The maximum mean covered by the cache. - */ - public double getMaxMean() - { - if (isValidRange()) { - return Math.nextAfter(maxN + 1.0, -1); - } - return 0; - } - - /** - * Gets the minimum mean value that can be cached. - * - *

Any {@link PoissonSampler} created with a mean below this level will not - * have any state that can be cached. - * - * @return the minimum cached mean - */ - public static double getMinimumCachedMean() { - return PoissonSampler.PIVOT; - } - - /** - * Create a new {@link PoissonSamplerCache} with the given range - * reusing the current cache values. - * - *

This will create a new object even if the range is smaller or the - * same as the current cache. - * - * @param minMean The minimum mean covered by the cache. - * @param maxMean The maximum mean covered by the cache. - * @throws IllegalArgumentException if {@code maxMean < minMean} - * @return the poisson sampler cache - */ - public PoissonSamplerCache withRange(double minMean, - double maxMean) { - if (values == null) { - // Nothing to reuse - return new PoissonSamplerCache(minMean, maxMean); - } - checkMeanRange(minMean, maxMean); - - // The cache can only be used for the LargeMeanPoissonSampler. - if (maxMean < PoissonSampler.PIVOT) { - return new PoissonSamplerCache(0, 0); - } - - // Convert the mean into integers. - // Note the minimum is clipped to the algorithm switch point. - final int withMinN = (int) Math.floor(Math.max(minMean, PoissonSampler.PIVOT)); - final int withMaxN = (int) Math.floor(maxMean); - final LargeMeanPoissonSamplerState[] states = - new LargeMeanPoissonSamplerState[withMaxN - withMinN + 1]; - - // Preserve values from the current array to the next - int currentIndex; - int nextIndex; - if (this.minN <= withMinN) { - // The current array starts before the new array - currentIndex = withMinN - this.minN; - nextIndex = 0; - } else { - // The new array starts before the current array - currentIndex = 0; - nextIndex = this.minN - withMinN; - } - final int length = Math.min(values.length - currentIndex, states.length - nextIndex); - if (length > 0) { - System.arraycopy(values, currentIndex, states, nextIndex, length); - } - - return new PoissonSamplerCache(withMinN, withMaxN, states); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/RejectionInversionZipfSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/RejectionInversionZipfSampler.java deleted file mode 100644 index d948c4bef..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/RejectionInversionZipfSampler.java +++ /dev/null @@ -1,255 +0,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. - */ - -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Implementation of the Zipf distribution. - * - *

Sampling uses {@link UniformRandomProvider#nextDouble()}.

- * - * @since 1.0 - */ -public class RejectionInversionZipfSampler - extends SamplerBase - implements DiscreteSampler { - /** Threshold below which Taylor series will be used. */ - private static final double TAYLOR_THRESHOLD = 1e-8; - /** 1/2 */ - private static final double F_1_2 = 0.5; - /** 1/3 */ - private static final double F_1_3 = 1d / 3; - /** 1/4 */ - private static final double F_1_4 = 0.25; - /** Number of elements. */ - private final int numberOfElements; - /** Exponent parameter of the distribution. */ - private final double exponent; - /** {@code hIntegral(1.5) - 1}. */ - private final double hIntegralX1; - /** {@code hIntegral(numberOfElements + 0.5)}. */ - private final double hIntegralNumberOfElements; - /** {@code 2 - hIntegralInverse(hIntegral(2.5) - h(2)}. */ - private final double s; - /** Underlying source of randomness. */ - private final UniformRandomProvider rng; - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param numberOfElements Number of elements. - * @param exponent Exponent. - * @throws IllegalArgumentException if {@code numberOfElements <= 0} - * or {@code exponent <= 0}. - */ - public RejectionInversionZipfSampler(UniformRandomProvider rng, - int numberOfElements, - double exponent) { - super(null); - this.rng = rng; - if (numberOfElements <= 0) { - throw new IllegalArgumentException("number of elements is not strictly positive: " + numberOfElements); - } - if (exponent <= 0) { - throw new IllegalArgumentException("exponent is not strictly positive: " + exponent); - } - - this.numberOfElements = numberOfElements; - this.exponent = exponent; - this.hIntegralX1 = hIntegral(1.5) - 1; - this.hIntegralNumberOfElements = hIntegral(numberOfElements + F_1_2); - this.s = 2 - hIntegralInverse(hIntegral(2.5) - h(2)); - } - - /** - * Rejection inversion sampling method for a discrete, bounded Zipf - * distribution that is based on the method described in - *
- * Wolfgang Hörmann and Gerhard Derflinger. - * "Rejection-inversion to generate variates from monotone discrete - * distributions",
- * ACM Transactions on Modeling and Computer Simulation (TOMACS) 6.3 (1996): 169-184. - *
- */ - @Override - public int sample() { - // The paper describes an algorithm for exponents larger than 1 - // (Algorithm ZRI). - // The original method uses - // H(x) = (v + x)^(1 - q) / (1 - q) - // as the integral of the hat function. - // This function is undefined for q = 1, which is the reason for - // the limitation of the exponent. - // If instead the integral function - // H(x) = ((v + x)^(1 - q) - 1) / (1 - q) - // is used, - // for which a meaningful limit exists for q = 1, the method works - // for all positive exponents. - // The following implementation uses v = 0 and generates integral - // number in the range [1, numberOfElements]. - // This is different to the original method where v is defined to - // be positive and numbers are taken from [0, i_max]. - // This explains why the implementation looks slightly different. - - while(true) { - final double u = hIntegralNumberOfElements + rng.nextDouble() * (hIntegralX1 - hIntegralNumberOfElements); - // u is uniformly distributed in (hIntegralX1, hIntegralNumberOfElements] - - double x = hIntegralInverse(u); - int k = (int) (x + F_1_2); - - // Limit k to the range [1, numberOfElements] if it would be outside - // due to numerical inaccuracies. - if (k < 1) { - k = 1; - } else if (k > numberOfElements) { - k = numberOfElements; - } - - // Here, the distribution of k is given by: - // - // P(k = 1) = C * (hIntegral(1.5) - hIntegralX1) = C - // P(k = m) = C * (hIntegral(m + 1/2) - hIntegral(m - 1/2)) for m >= 2 - // - // where C = 1 / (hIntegralNumberOfElements - hIntegralX1) - - if (k - x <= s || u >= hIntegral(k + F_1_2) - h(k)) { - - // Case k = 1: - // - // The right inequality is always true, because replacing k by 1 gives - // u >= hIntegral(1.5) - h(1) = hIntegralX1 and u is taken from - // (hIntegralX1, hIntegralNumberOfElements]. - // - // Therefore, the acceptance rate for k = 1 is P(accepted | k = 1) = 1 - // and the probability that 1 is returned as random value is - // P(k = 1 and accepted) = P(accepted | k = 1) * P(k = 1) = C = C / 1^exponent - // - // Case k >= 2: - // - // The left inequality (k - x <= s) is just a short cut - // to avoid the more expensive evaluation of the right inequality - // (u >= hIntegral(k + 0.5) - h(k)) in many cases. - // - // If the left inequality is true, the right inequality is also true: - // Theorem 2 in the paper is valid for all positive exponents, because - // the requirements h'(x) = -exponent/x^(exponent + 1) < 0 and - // (-1/hInverse'(x))'' = (1+1/exponent) * x^(1/exponent-1) >= 0 - // are both fulfilled. - // Therefore, f(x) = x - hIntegralInverse(hIntegral(x + 0.5) - h(x)) - // is a non-decreasing function. If k - x <= s holds, - // k - x <= s + f(k) - f(2) is obviously also true which is equivalent to - // -x <= -hIntegralInverse(hIntegral(k + 0.5) - h(k)), - // -hIntegralInverse(u) <= -hIntegralInverse(hIntegral(k + 0.5) - h(k)), - // and finally u >= hIntegral(k + 0.5) - h(k). - // - // Hence, the right inequality determines the acceptance rate: - // P(accepted | k = m) = h(m) / (hIntegrated(m+1/2) - hIntegrated(m-1/2)) - // The probability that m is returned is given by - // P(k = m and accepted) = P(accepted | k = m) * P(k = m) = C * h(m) = C / m^exponent. - // - // In both cases the probabilities are proportional to the probability mass function - // of the Zipf distribution. - - return k; - } - } - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Rejection inversion Zipf deviate [" + rng.toString() + "]"; - } - - /** - * {@code H(x)} is defined as - *
    - *
  • {@code (x^(1 - exponent) - 1) / (1 - exponent)}, if {@code exponent != 1}
  • - *
  • {@code log(x)}, if {@code exponent == 1}
  • - *
- * H(x) is an integral function of h(x), the derivative of H(x) is h(x). - * - * @param x Free parameter. - * @return {@code H(x)}. - */ - private double hIntegral(final double x) { - final double logX = Math.log(x); - return helper2((1 - exponent) * logX) * logX; - } - - /** - * {@code h(x) = 1 / x^exponent} - * - * @param x Free parameter. - * @return {@code h(x)}. - */ - private double h(final double x) { - return Math.exp(-exponent * Math.log(x)); - } - - /** - * The inverse function of {@code H(x)}. - * - * @param x Free parameter - * @return y for which {@code H(y) = x}. - */ - private double hIntegralInverse(final double x) { - double t = x * (1 - exponent); - if (t < -1) { - // Limit value to the range [-1, +inf). - // t could be smaller than -1 in some rare cases due to numerical errors. - t = -1; - } - return Math.exp(helper1(t) * x); - } - - /** - * Helper function that calculates {@code log(1 + x) / x}. - *

- * A Taylor series expansion is used, if x is close to 0. - *

- * - * @param x A value larger than or equal to -1. - * @return {@code log(1 + x) / x}. - */ - private static double helper1(final double x) { - if (Math.abs(x) > TAYLOR_THRESHOLD) { - return Math.log1p(x) / x; - } else { - return 1 - x * (F_1_2 - x * (F_1_3 - F_1_4 * x)); - } - } - - /** - * Helper function to calculate {@code (exp(x) - 1) / x}. - *

- * A Taylor series expansion is used, if x is close to 0. - *

- * - * @param x Free parameter. - * @return {@code (exp(x) - 1) / x} if x is non-zero, or 1 if x = 0. - */ - private static double helper2(final double x) { - if (Math.abs(x) > TAYLOR_THRESHOLD) { - return Math.expm1(x) / x; - } else { - return 1 + x * F_1_2 * (1 + x * F_1_3 * (1 + F_1_4 * x)); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/SamplerBase.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/SamplerBase.java deleted file mode 100644 index 2b1e0a167..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/SamplerBase.java +++ /dev/null @@ -1,75 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Base class for a sampler. - * - * @since 1.0 - * - * @deprecated Since version 1.1. Class intended for internal use only. - */ -@Deprecated -public class SamplerBase { - /** RNG. */ - private final UniformRandomProvider rng; - - /** - * @param rng Generator of uniformly distributed random numbers. - */ - protected SamplerBase(UniformRandomProvider rng) { - this.rng = rng; - } - - /** - * @return a random value from a uniform distribution in the - * interval {@code [0, 1)}. - */ - protected double nextDouble() { - return rng.nextDouble(); - } - - /** - * @return a random {@code int} value. - */ - protected int nextInt() { - return rng.nextInt(); - } - - /** - * @param max Upper bound (excluded). - * @return a random {@code int} value in the interval {@code [0, max)}. - */ - protected int nextInt(int max) { - return rng.nextInt(max); - } - - /** - * @return a random {@code long} value. - */ - protected long nextLong() { - return rng.nextLong(); - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "rng=" + rng.toString(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/SmallMeanPoissonSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/SmallMeanPoissonSampler.java deleted file mode 100644 index 9e920bd96..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/SmallMeanPoissonSampler.java +++ /dev/null @@ -1,94 +0,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. - */ -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Sampler for the Poisson distribution. - * - *
    - *
  • - * For small means, a Poisson process is simulated using uniform deviates, as - * described here. - * The Poisson process (and hence, the returned value) is bounded by 1000 * mean. - *
  • - *
- * - *

This sampler is suitable for {@code mean < 40}. - * For large means, {@link LargeMeanPoissonSampler} should be used instead.

- * - *

Sampling uses {@link UniformRandomProvider#nextDouble()}.

- * - * @since 1.1 - */ -public class SmallMeanPoissonSampler - implements DiscreteSampler { - /** - * Pre-compute {@code Math.exp(-mean)}. - * Note: This is the probability of the Poisson sample {@code P(n=0)}. - */ - private final double p0; - /** Pre-compute {@code 1000 * mean} as the upper limit of the sample. */ - private final int limit; - /** Underlying source of randomness. */ - private final UniformRandomProvider rng; - - /** - * @param rng Generator of uniformly distributed random numbers. - * @param mean Mean. - * @throws IllegalArgumentException if {@code mean <= 0} or {@code Math.exp(-mean)} is not positive. - */ - public SmallMeanPoissonSampler(UniformRandomProvider rng, - double mean) { - this.rng = rng; - if (mean <= 0) { - throw new IllegalArgumentException("mean is not strictly positive: " + mean); - } - p0 = Math.exp(-mean); - if (p0 > 0) { - // The returned sample is bounded by 1000 * mean - limit = (int) Math.ceil(1000 * mean); - } else { - // This excludes NaN values for the mean - throw new IllegalArgumentException("No p(x=0) probability for mean: " + mean); - } - } - - /** {@inheritDoc} */ - @Override - public int sample() { - int n = 0; - double r = 1; - - while (n < limit) { - r *= rng.nextDouble(); - if (r >= p0) { - n++; - } else { - break; - } - } - return n; - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Small Mean Poisson deviate [" + rng.toString() + "]"; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/ZigguratNormalizedGaussianSampler.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/ZigguratNormalizedGaussianSampler.java deleted file mode 100644 index bd7345d79..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/ZigguratNormalizedGaussianSampler.java +++ /dev/null @@ -1,163 +0,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. - */ - -package org.apache.commons.rng.sampling.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * - * Marsaglia and Tsang "Ziggurat" method for sampling from a Gaussian - * distribution with mean 0 and standard deviation 1. - * - *

The algorithm is explained in this - * paper - * and this implementation has been adapted from the C code provided therein.

- * - *

Sampling uses:

- * - *
    - *
  • {@link UniformRandomProvider#nextLong()} - *
  • {@link UniformRandomProvider#nextDouble()} - *
- * - * @since 1.1 - */ -public class ZigguratNormalizedGaussianSampler - implements NormalizedGaussianSampler { - /** Start of tail. */ - private static final double R = 3.442619855899; - /** Inverse of R. */ - private static final double ONE_OVER_R = 1 / R; - /** Rectangle area. */ - private static final double V = 9.91256303526217e-3; - /** 2^63 */ - private static final double MAX = Math.pow(2, 63); - /** 2^-63 */ - private static final double ONE_OVER_MAX = 1d / MAX; - /** Number of entries. */ - private static final int LEN = 128; - /** Index of last entry. */ - private static final int LAST = LEN - 1; - /** Auxiliary table. */ - private static final long[] K = new long[LEN]; - /** Auxiliary table. */ - private static final double[] W = new double[LEN]; - /** Auxiliary table. */ - private static final double[] F = new double[LEN]; - /** Underlying source of randomness. */ - private final UniformRandomProvider rng; - - static { - // Filling the tables. - - double d = R; - double t = d; - double fd = gauss(d); - final double q = V / fd; - - K[0] = (long) ((d / q) * MAX); - K[1] = 0; - - W[0] = q * ONE_OVER_MAX; - W[LAST] = d * ONE_OVER_MAX; - - F[0] = 1; - F[LAST] = fd; - - for (int i = LAST - 1; i >= 1; i--) { - d = Math.sqrt(-2 * Math.log(V / d + fd)); - fd = gauss(d); - - K[i + 1] = (long) ((d / t) * MAX); - t = d; - - F[i] = fd; - - W[i] = d * ONE_OVER_MAX; - } - } - - /** - * @param rng Generator of uniformly distributed random numbers. - */ - public ZigguratNormalizedGaussianSampler(UniformRandomProvider rng) { - this.rng = rng; - } - - /** {@inheritDoc} */ - @Override - public double sample() { - final long j = rng.nextLong(); - final int i = (int) (j & LAST); - if (Math.abs(j) < K[i]) { - return j * W[i]; - } else { - return fix(j, i); - } - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Ziggurat normalized Gaussian deviate [" + rng.toString() + "]"; - } - - /** - * Gets the value from the tail of the distribution. - * - * @param hz Start random integer. - * @param iz Index of cell corresponding to {@code hz}. - * @return the requested random value. - */ - private double fix(long hz, - int iz) { - double x; - double y; - - x = hz * W[iz]; - if (iz == 0) { - // Base strip. - // This branch is called about 5.7624515E-4 times per sample. - do { - y = -Math.log(rng.nextDouble()); - x = -Math.log(rng.nextDouble()) * ONE_OVER_R; - } while (y + y < x * x); - - final double out = R + x; - return hz > 0 ? out : -out; - } else { - // Wedge of other strips. - // This branch is called about 0.027323 times per sample. - if (F[iz] + rng.nextDouble() * (F[iz - 1] - F[iz]) < gauss(x)) { - return x; - } else { - // Try again. - // This branch is called about 0.012362 times per sample. - return sample(); - } - } - } - - /** - * @param x Argument. - * @return \( e^{-\frac{x^2}{2}} \) - */ - private static double gauss(double x) { - return Math.exp(-0.5 * x * x); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/package-info.java deleted file mode 100644 index c98f99bb1..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/distribution/package-info.java +++ /dev/null @@ -1,43 +0,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. - */ - -/** - *

Distribution samplers

- * - *

- * This package contains classes for sampling from statistical distributions. - *

- * - *

As of version 1.0, the code for specific distributions was adapted from - * the corresponding classes in the development version of "Commons Math" (in - * package {@code org.apache.commons.math4.distribution}). - *

- *

- * When no specific algorithm is provided, one can still sample from any - * distribution, using the inverse method, as illustrated in: - *

    - *
  • {@link org.apache.commons.rng.sampling.distribution.InverseTransformDiscreteSampler InverseTransformDiscreteSampler}
  • - *
  • {@link org.apache.commons.rng.sampling.distribution.InverseTransformContinuousSampler InverseTransformContinuousSampler}
  • - *
- * - * Algorithms are described in e.g. Luc Devroye (1986), chapter 9 - * and chapter 10. - * - * This paper discusses Gaussian generators. - */ - -package org.apache.commons.rng.sampling.distribution; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/package-info.java deleted file mode 100644 index 3c49113e8..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/sampling/package-info.java +++ /dev/null @@ -1,28 +0,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. - */ - -/** - *

Samplers

- * - *

- * This package provides sampling utilities. - *

- * The org.apache.commons.rng.sampling.distribution - * sub-package provides sampling from statistical distributions. - */ - -package org.apache.commons.rng.sampling; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/JDKRandomBridge.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/JDKRandomBridge.java deleted file mode 100644 index aec58ff6b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/JDKRandomBridge.java +++ /dev/null @@ -1,127 +0,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. - */ -package org.apache.commons.rng.simple; - -import org.apache.commons.rng.RestorableUniformRandomProvider; -import org.apache.commons.rng.core.RandomProviderDefaultState; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.util.Random; - -/** - * Subclass of {@link Random} that {@link #next(int) delegates} to a - * {@link RestorableUniformRandomProvider} instance but will otherwise rely - * on the base class for generating all the random types. - * - *

- * Legacy applications coded against the JDK's API could use this subclass - * of {@link Random} in order to replace its linear congruential generator - * by any {@link RandomSource}. - *

- * - * Caveat: Use of this class is not recommended for new applications. - * In particular, there is no guarantee that the serialized form of this class - * will be compatible across (even minor) releases of the library. - * - * @since 1.0 - */ -public final class JDKRandomBridge extends Random { - /** Serializable version identifier. */ - private static final long serialVersionUID = 20161107L; - /** Source. */ - private final RandomSource source; - /** Delegate. */ - private transient RestorableUniformRandomProvider delegate; - /** Workaround JDK's "Random" bug: https://bugs.openjdk.java.net/browse/JDK-8154225 */ - private final transient boolean isInitialized; - - /** - * Creates a new instance. - * - * @param source Source of randomness. - * @param seed Seed. Can be {@code null}. - */ - public JDKRandomBridge(RandomSource source, - Object seed) { - this.source = source; - delegate = RandomSource.create(source, seed); - isInitialized = true; - } - - /** {@inheritDoc} */ - @Override - public synchronized void setSeed(long seed) { - if (isInitialized) { - delegate = RandomSource.create(source, seed); - - // Force the clearing of the "haveNextNextGaussian" flag - // (cf. Javadoc of the base class); the value passed here - // is irrelevant (since it will not be used). - super.setSeed(0L); - } - } - - /** - * Delegates the generation of 32 random bits to the - * {@code RandomSource} argument provided at - * {@link #JDKRandomBridge(RandomSource,Object) construction}. - * The returned value is such that if the source of randomness is - * {@link RandomSource#JDK}, all the generated values will be identical - * to those produced by the same sequence of calls on a {@link Random} - * instance initialized with the same seed. - * - * @param n Number of random bits which the requested value must contain. - * @return the value represented by the {@code n} high-order bits of a - * pseudo-random 32-bits integer. - */ - @Override - protected synchronized int next(int n) { - return delegate.nextInt() >>> (32 - n); - } - - /** - * @param out Output stream. - * @throws IOException if an error occurs. - */ - private synchronized void writeObject(ObjectOutputStream out) - throws IOException { - // Write non-transient fields. - out.defaultWriteObject(); - - // Save current state. - out.writeObject(((RandomProviderDefaultState) delegate.saveState()).getState()); - } - - /** - * @param in Input stream. - * @throws IOException if an error occurs. - * @throws ClassNotFoundException if an error occurs. - */ - private void readObject(ObjectInputStream in) - throws IOException, - ClassNotFoundException { - // Read non-transient fields. - in.defaultReadObject(); - - // Recreate the "delegate" from serialized info. - delegate = RandomSource.create(source); - // And restore its state. - delegate.restoreState(new RandomProviderDefaultState((byte[]) in.readObject())); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/RandomSource.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/RandomSource.java deleted file mode 100644 index cc043ef91..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/RandomSource.java +++ /dev/null @@ -1,607 +0,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. - */ -package org.apache.commons.rng.simple; - -import org.apache.commons.rng.RestorableUniformRandomProvider; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.simple.internal.ProviderBuilder; -import org.apache.commons.rng.simple.internal.SeedFactory; - -/** - * This class provides the API for creating generators of random numbers. - * - *

Usage examples:

- *

- *  UniformRandomProvider rng = RandomSource.create(RandomSource.MT);
- * 
- * or - *

- *  final int[] seed = new int[] { 196, 9, 0, 226 };
- *  UniformRandomProvider rng = RandomSource.create(RandomSource.MT, seed);
- * 
- * or - *

- *  final int[] seed = RandomSource.createIntArray(256);
- *  UniformRandomProvider rng = RandomSource.create(RandomSource.MT, seed);
- * 
- * where the first argument to method {@code create} is the identifier - * of the generator's concrete implementation, and the second the is the - * (optional) seed. - * - *

- * In the first form, a random seed will be {@link SeedFactory generated - * automatically}; in the second form, a fixed seed is used; a random seed - * is explicitly generated in the third form. - *

- * - *

- * Seeding is the procedure by which a value (or set of values) is - * used to initialize a generator instance. - * The requirement that a given seed will always result in the same - * internal state allows to create different instances of a generator - * that will produce the same sequence of pseudo-random numbers. - *

- * - *

- * The type of data used as a seed depends on the concrete implementation - * as some types may not provide enough information to fully initialize - * the generator's internal state. - *
- * The reference algorithm's seeding procedure (if provided) operates - * on a value of a (single) native type: - * Each concrete implementation's constructor creates an instance using - * the native type whose information contents is used to set the - * internal state. - *
- * When the seed value passed by the caller is of the native type, it is - * expected that the sequences produced will be identical to those - * produced by other implementations of the same reference algorithm. - *
- * However, when the seed value passed by the caller is not of the native - * type, a transformation is performed by this library and the resulting - * native type value will not contain more information than the - * original seed value. - * If the algorithm's native type is "simpler" than the type passed by - * the caller, then some (unused) information will even be lost. - *
- * The transformation from non-native to native seed type is arbitrary, - * as long as it does not reduce the amount of information required by - * the algorithm to initialize its state. - * The consequence of the transformation is that sequences produced - * by this library may not be the same as the sequences produced - * by other implementations of the same algorithm! - *

- * - *

- * For each algorithm, the Javadoc mentions the "ideal" size of the seed, - * meaning the number of {@code int} or {@code long} values that is neither - * too large (i.e. some of the seed is useless) or too small (i.e. an - * internal procedure will fill the state with redundant information - * computed from the given seed). - *

- * - *

- * Note that some algorithms are inherently sensitive to having too low - * diversity in their initial state. - * For example, it is often a bad idea to use a seed that is mostly - * composed of zeroes, or of repeated values. - *

- * - *

- * This class provides methods to generate random seeds (single values - * or arrays of values, of {@code int} or {@code long} types) that can - * be passed to the {@link RandomSource#create(RandomSource,Object,Object[]) - * generators factory method}. - *

- *

- * Although the seed-generating methods defined in this class will likely - * return different values each time they are called, there is no guarantee: - *

- *
    - *
  • - * In any sub-sequence, it is - * expected that the same numbers can occur, with a probability getting - * higher as the range of allowed values is smaller and the sequence becomes - * longer. - *
  • - *
  • - * It possible that the resulting "seed" will not be good (i.e. - * it will not generate a sufficiently uniformly random sequence for the - * intended purpose), even if the generator is good! - * The only way to ensure that the selected seed will make the generator - * produce a good sequence is to submit that sequence to a series of - * stringent tests, as provided by tools such as - * dieharder - * or TestU01. - *
  • - *
- * - *

- * The current implementations have no provision for producing non-overlapping - * sequences. - * For parallel applications, a possible workaround is that each thread uses - * a generator of a different type (see {@link #TWO_CMRES_SELECT}). - *

- * - *

- * Note: - * Seeding is not equivalent to restoring the internal state of an - * already initialized generator. - * Indeed, generators can have a state that is more complex than the - * seed, and seeding is thus a transformation (from seed to state). - * Implementations do not provide the inverse transformation (from - * state to seed), hence it is not generally possible to know the seed - * that would initialize a new generator instance to the current state - * of another instance. - * Reseeding is also inefficient if the purpose is to continue the - * same sequence where another instance left off, as it would require - * to "replay" all the calls performed by that other instance (and it - * would require to know the number of calls to the primary source of - * randomness, which is also not usually accessible). - *

- * - * @since 1.0 - */ -public enum RandomSource { - /** - * Source of randomness is {@link org.apache.commons.rng.core.source32.JDKRandom}. - *
    - *
  • Native seed type: {@code Long}.
  • - *
  • Native seed size: 1.
  • - *
- */ - JDK(ProviderBuilder.RandomSourceInternal.JDK), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source32.Well512a}. - *
    - *
  • Native seed type: {@code int[]}.
  • - *
  • Native seed size: 16.
  • - *
- */ - WELL_512_A(ProviderBuilder.RandomSourceInternal.WELL_512_A), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source32.Well1024a}. - *
    - *
  • Native seed type: {@code int[]}.
  • - *
  • Native seed size: 32.
  • - *
- */ - WELL_1024_A(ProviderBuilder.RandomSourceInternal.WELL_1024_A), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source32.Well19937a}. - *
    - *
  • Native seed type: {@code int[]}.
  • - *
  • Native seed size: 624.
  • - *
- */ - WELL_19937_A(ProviderBuilder.RandomSourceInternal.WELL_19937_A), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source32.Well19937c}. - *
    - *
  • Native seed type: {@code int[]}.
  • - *
  • Native seed size: 624.
  • - *
- */ - WELL_19937_C(ProviderBuilder.RandomSourceInternal.WELL_19937_C), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source32.Well44497a}. - *
    - *
  • Native seed type: {@code int[]}.
  • - *
  • Native seed size: 1391.
  • - *
- */ - WELL_44497_A(ProviderBuilder.RandomSourceInternal.WELL_44497_A), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source32.Well44497b}. - *
    - *
  • Native seed type: {@code int[]}.
  • - *
  • Native seed size: 1391.
  • - *
- */ - WELL_44497_B(ProviderBuilder.RandomSourceInternal.WELL_44497_B), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source32.MersenneTwister}. - *
    - *
  • Native seed type: {@code int[]}.
  • - *
  • Native seed size: 624.
  • - *
- */ - MT(ProviderBuilder.RandomSourceInternal.MT), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source32.ISAACRandom}. - *
    - *
  • Native seed type: {@code int[]}.
  • - *
  • Native seed size: 256.
  • - *
- */ - ISAAC(ProviderBuilder.RandomSourceInternal.ISAAC), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source64.SplitMix64}. - *
    - *
  • Native seed type: {@code Long}.
  • - *
  • Native seed size: 1.
  • - *
- */ - SPLIT_MIX_64(ProviderBuilder.RandomSourceInternal.SPLIT_MIX_64), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source64.XorShift1024Star}. - *
    - *
  • Native seed type: {@code long[]}.
  • - *
  • Native seed size: 16.
  • - *
- * - * @deprecated Since 1.3, where it is recommended to use {@code XOR_SHIFT_1024_S_PHI} - * instead due to its slightly better (more uniform) output. {@code XOR_SHIFT_1024_S} - * is still quite usable but both are variants of the same algorithm and maintain their - * internal state identically. Their outputs are correlated and the two should not be - * used together when independent sequences are assumed. - */ - @Deprecated - XOR_SHIFT_1024_S(ProviderBuilder.RandomSourceInternal.XOR_SHIFT_1024_S), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source64.TwoCmres}. - * This generator is equivalent to {@link #TWO_CMRES_SELECT} with the choice of the - * pair {@code (0, 1)} for the two subcycle generators. - *
    - *
  • Native seed type: {@code Integer}.
  • - *
  • Native seed size: 1.
  • - *
- */ - TWO_CMRES(ProviderBuilder.RandomSourceInternal.TWO_CMRES), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source64.TwoCmres}, - * with explicit selection of the two subcycle generators. - * The selection of the subcycle generator is by passing its index in the internal - * table, a value between 0 (included) and 13 (included). - * The two indices must be different. - * Different choices of an ordered pair of indices create independent generators. - *
    - *
  • Native seed type: {@code Integer}.
  • - *
  • Native seed size: 1.
  • - *
- */ - TWO_CMRES_SELECT(ProviderBuilder.RandomSourceInternal.TWO_CMRES_SELECT), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source64.MersenneTwister64}. - *
    - *
  • Native seed type: {@code long[]}.
  • - *
  • Native seed size: 312.
  • - *
- */ - MT_64(ProviderBuilder.RandomSourceInternal.MT_64), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source32.MultiplyWithCarry256}. - *
    - *
  • Native seed type: {@code int[]}.
  • - *
  • Native seed size: 257.
  • - *
- */ - MWC_256(ProviderBuilder.RandomSourceInternal.MWC_256), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source32.KISSRandom}. - *
    - *
  • Native seed type: {@code int[]}.
  • - *
  • Native seed size: 4.
  • - *
- */ - KISS(ProviderBuilder.RandomSourceInternal.KISS), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source64.XorShift1024StarPhi}. - *
    - *
  • Native seed type: {@code long[]}.
  • - *
  • Native seed size: 16.
  • - *
- */ - XOR_SHIFT_1024_S_PHI(ProviderBuilder.RandomSourceInternal.XOR_SHIFT_1024_S_PHI), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source32.XoRoShiRo64Star}. - *
    - *
  • Native seed type: {@code int[]}.
  • - *
  • Native seed size: 2.
  • - *
- */ - XO_RO_SHI_RO_64_S(ProviderBuilder.RandomSourceInternal.XO_RO_SHI_RO_64_S), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source32.XoRoShiRo64StarStar}. - *
    - *
  • Native seed type: {@code int[]}.
  • - *
  • Native seed size: 2.
  • - *
- */ - XO_RO_SHI_RO_64_SS(ProviderBuilder.RandomSourceInternal.XO_RO_SHI_RO_64_SS), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source32.XoShiRo128Plus}. - *
    - *
  • Native seed type: {@code int[]}.
  • - *
  • Native seed size: 4.
  • - *
- */ - XO_SHI_RO_128_PLUS(ProviderBuilder.RandomSourceInternal.XO_SHI_RO_128_PLUS), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source32.XoShiRo128StarStar}. - *
    - *
  • Native seed type: {@code int[]}.
  • - *
  • Native seed size: 4.
  • - *
- */ - XO_SHI_RO_128_SS(ProviderBuilder.RandomSourceInternal.XO_SHI_RO_128_SS), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source64.XoRoShiRo128Plus}. - *
    - *
  • Native seed type: {@code long[]}.
  • - *
  • Native seed size: 2.
  • - *
- */ - XO_RO_SHI_RO_128_PLUS(ProviderBuilder.RandomSourceInternal.XO_RO_SHI_RO_128_PLUS), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source64.XoRoShiRo128StarStar}. - *
    - *
  • Native seed type: {@code long[]}.
  • - *
  • Native seed size: 2.
  • - *
- */ - XO_RO_SHI_RO_128_SS(ProviderBuilder.RandomSourceInternal.XO_RO_SHI_RO_128_SS), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source64.XoShiRo256Plus}. - *
    - *
  • Native seed type: {@code long[]}.
  • - *
  • Native seed size: 4.
  • - *
- */ - XO_SHI_RO_256_PLUS(ProviderBuilder.RandomSourceInternal.XO_SHI_RO_256_PLUS), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source64.XoShiRo256StarStar}. - *
    - *
  • Native seed type: {@code long[]}.
  • - *
  • Native seed size: 4.
  • - *
- */ - XO_SHI_RO_256_SS(ProviderBuilder.RandomSourceInternal.XO_SHI_RO_256_SS), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source64.XoShiRo512Plus}. - *
    - *
  • Native seed type: {@code long[]}.
  • - *
  • Native seed size: 8.
  • - *
- */ - XO_SHI_RO_512_PLUS(ProviderBuilder.RandomSourceInternal.XO_SHI_RO_512_PLUS), - /** - * Source of randomness is {@link org.apache.commons.rng.core.source64.XoShiRo512StarStar}. - *
    - *
  • Native seed type: {@code long[]}.
  • - *
  • Native seed size: 8.
  • - *
- */ - XO_SHI_RO_512_SS(ProviderBuilder.RandomSourceInternal.XO_SHI_RO_512_SS), - ; - - /** Internal identifier. */ - private final ProviderBuilder.RandomSourceInternal internalIdentifier; - - /** - * @param id Internal identifier. - */ - RandomSource(ProviderBuilder.RandomSourceInternal id) { - internalIdentifier = id; - } - - /** - * @return the internal identifier. - */ - ProviderBuilder.RandomSourceInternal getInternalIdentifier() { - return internalIdentifier; - } - - /** - * Checks whether the type of given {@code seed} is the native type - * of the implementation. - * - * @param seed Seed value. - * @return {@code true} if the type of {@code seed} is the native - * type for this RNG source. - */ - public boolean isNativeSeed(Object seed) { - return internalIdentifier.isNativeSeed(seed); - } - - /** - * Creates a random number generator with a random seed. - * - *

Usage example:

- *

-     *  UniformRandomProvider rng = RandomSource.create(RandomSource.MT);
-     * 
- *

or, if a {@link RestorableUniformRandomProvider "save/restore"} functionality is needed,

- *

-     *  RestorableUniformRandomProvider rng = RandomSource.create(RandomSource.MT);
-     * 
- * - * @param source RNG type. - * @return the RNG. - * - * @see #create(RandomSource,Object,Object[]) - */ - public static RestorableUniformRandomProvider create(RandomSource source) { - return create(source, null); - } - - /** - * Creates a random number generator with the given {@code seed}. - * - *

Usage example:

- *

-     *  UniformRandomProvider rng = RandomSource.create(RandomSource.TWO_CMRES_SELECT, 26219, 6, 9);
-     * 
- * - *

Valid types for the {@code seed} are:

- *
    - *
  • {@code Integer} (or {@code int})
  • - *
  • {@code Long} (or {@code long})
  • - *
  • {@code int[]}
  • - *
  • {@code long[]}
  • - *
  • {@code byte[]}
  • - *
- * - *

Notes:

- *
    - *
  • - * When the seed type passed as argument is more complex (i.e. more - * bits can be independently chosen) than the generator's - * {@link #isNativeSeed(Object) native type}, the conversion of a - * set of different seeds will necessarily result in the same value - * of the native seed type. - *
  • - *
  • - * When the native seed type is an array, the same remark applies - * when the array contains more bits than the state of the generator. - *
  • - *
  • - * When the native seed type is an array and the {@code seed} is - * {@code null}, the size of the generated array will be 128. - *
  • - *
- * - * @param source RNG type. - * @param seed Seed value. It can be {@code null} (in which case a - * random value will be used). - * @param data Additional arguments to the implementation's constructor. - * Please refer to the documentation of each specific implementation. - * @return the RNG. - * @throws UnsupportedOperationException if the type of the {@code seed} - * is invalid. - * @throws IllegalStateException if data is missing to initialize the - * generator implemented by the given {@code source}. - * - * @see #create(RandomSource) - */ - public static RestorableUniformRandomProvider create(RandomSource source, - Object seed, - Object ... data) { - return ProviderBuilder.create(source.getInternalIdentifier(), seed, data); - } - - /** - * Creates a number for use as a seed. - * - * @return a random number. - */ - public static int createInt() { - return SeedFactory.createInt(); - } - - /** - * Creates a number for use as a seed. - * - * @return a random number. - */ - public static long createLong() { - return SeedFactory.createLong(); - } - - /** - * Creates an array of numbers for use as a seed. - * - * @param n Size of the array to create. - * @return an array of {@code n} random numbers. - */ - public static int[] createIntArray(int n) { - return SeedFactory.createIntArray(n); - } - - /** - * Creates an array of numbers for use as a seed. - * - * @param n Size of the array to create. - * @return an array of {@code n} random numbers. - */ - public static long[] createLongArray(int n) { - return SeedFactory.createLongArray(n); - } - - /** - * Wraps the given {@code delegate} generator in a new instance that - * does not allow access to the "save/restore" functionality. - * - * @param delegate Generator to which calls will be delegated. - * @return a new instance whose state cannot be saved or restored. - */ - public static UniformRandomProvider unrestorable(final UniformRandomProvider delegate) { - return new UniformRandomProvider() { - /** {@inheritDoc} */ - @Override - public void nextBytes(byte[] bytes) { - delegate.nextBytes(bytes); - } - - /** {@inheritDoc} */ - @Override - public void nextBytes(byte[] bytes, - int start, - int len) { - delegate.nextBytes(bytes, start, len); - } - - /** {@inheritDoc} */ - @Override - public int nextInt() { - return delegate.nextInt(); - } - - /** {@inheritDoc} */ - @Override - public int nextInt(int n) { - return delegate.nextInt(n); - } - - /** {@inheritDoc} */ - @Override - public long nextLong() { - return delegate.nextLong(); - } - - /** {@inheritDoc} */ - @Override - public long nextLong(long n) { - return delegate.nextLong(n); - } - - /** {@inheritDoc} */ - @Override - public boolean nextBoolean() { - return delegate.nextBoolean(); - } - - /** {@inheritDoc} */ - @Override - public float nextFloat() { - return delegate.nextFloat(); - } - - /** {@inheritDoc} */ - @Override - public double nextDouble() { - return delegate.nextDouble(); - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return delegate.toString(); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/ThreadLocalRandomSource.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/ThreadLocalRandomSource.java deleted file mode 100644 index b58ef718c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/ThreadLocalRandomSource.java +++ /dev/null @@ -1,135 +0,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. - */ -package org.apache.commons.rng.simple; - -import org.apache.commons.rng.UniformRandomProvider; - -import java.util.EnumMap; - -/** - * This class provides a thread-local {@link UniformRandomProvider}. - * - *

The {@link UniformRandomProvider} is created once-per-thread using the default - * construction method {@link RandomSource#create(RandomSource)}. - * - *

Example:

- *

- * import org.apache.commons.rng.simple.RandomSource;
- * import org.apache.commons.rng.simple.ThreadLocalRandomSource;
- * import org.apache.commons.rng.sampling.distribution.PoissonSampler;
- *
- * // Access a thread-safe random number generator
- * UniformRandomProvider rng = ThreadLocalRandomSource.current(RandomSource.SPLIT_MIX_64);
- *
- * // One-time Poisson sample
- * double mean = 12.3;
- * int counts = new PoissonSampler(rng, mean).sample();
- * 
- * - *

Note if the {@link RandomSource} requires additional arguments then it is not - * supported. The same can be achieved using:

- * - *

- * import org.apache.commons.rng.simple.RandomSource;
- * import org.apache.commons.rng.sampling.distribution.PoissonSampler;
- *
- * // Provide a thread-safe random number generator with data arguments
- * private static ThreadLocal<UniformRandomProvider> rng =
- *     new ThreadLocal<UniformRandomProvider>() {
- *         @Override
- *         protected UniformRandomProvider initialValue() {
- *             return RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 3, 4);
- *         }
- *     };
- *
- * // One-time Poisson sample using a thread-safe random number generator
- * double mean = 12.3;
- * int counts = new PoissonSampler(rng.get(), mean).sample();
- * 
- * - * @since 1.3 - */ -public final class ThreadLocalRandomSource { - /** - * A map containing the {@link ThreadLocal} instance for each {@link RandomSource}. - * - *

This should only be modified to create new instances in a synchronized block. - */ - private static EnumMap> sources = - new EnumMap>(RandomSource.class); - - /** No public construction. */ - private ThreadLocalRandomSource() {} - - /** - * Extend the {@link ThreadLocal} to allow creation of the desired {@link RandomSource}. - */ - private static class ThreadLocalRng extends ThreadLocal { - /** The source. */ - private final RandomSource source; - - /** - * Create a new instance. - * - * @param source the source - */ - ThreadLocalRng(RandomSource source) { - this.source = source; - } - - @Override - protected UniformRandomProvider initialValue() { - // Create with the default seed generation method - return RandomSource.create(source, null); - } - } - - /** - * Returns the current thread's copy of the given {@code source}. If there is no - * value for the current thread, it is first initialized to the value returned - * by {@link RandomSource#create(RandomSource)}. - * - *

Note if the {@code source} requires additional arguments then it is not - * supported. - * - * @param source the source - * @return the current thread's value of the {@code source}. - * @throws IllegalArgumentException if the source is null or the source requires arguments - */ - public static UniformRandomProvider current(RandomSource source) { - ThreadLocal rng = sources.get(source); - // Implement double-checked locking: - // https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java - if (rng == null) { - // Do the checks on the source here since it is an edge case - // and the EnumMap handles null (returning null). - if (source == null) { - throw new IllegalArgumentException("Random source is null"); - } - - synchronized (sources) { - rng = sources.get(source); - if (rng == null) { - rng = new ThreadLocalRng(source); - sources.put(source, rng); - } - } - } - return rng.get(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/ByteArray2IntArray.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/ByteArray2IntArray.java deleted file mode 100644 index e1a6c9943..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/ByteArray2IntArray.java +++ /dev/null @@ -1,41 +0,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. - */ -package org.apache.commons.rng.simple.internal; - -import org.apache.commons.rng.core.util.NumberFactory; - -import java.util.Arrays; - -/** - * Creates a {@code int[]} from a {@code byte[]}. - * - * @since 1.0 - */ -public class ByteArray2IntArray implements SeedConverter { - /** Number of bytes in an {@code int}. */ - private static final int INT_SIZE = 4; - - /** {@inheritDoc} */ - @Override - public int[] convert(byte[] seed) { - final byte[] tmp = seed.length % INT_SIZE == 0 ? - seed : - Arrays.copyOf(seed, INT_SIZE * ((seed.length + INT_SIZE - 1) / INT_SIZE)); - - return NumberFactory.makeIntArray(tmp); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/ByteArray2LongArray.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/ByteArray2LongArray.java deleted file mode 100644 index 3dad216a5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/ByteArray2LongArray.java +++ /dev/null @@ -1,41 +0,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. - */ -package org.apache.commons.rng.simple.internal; - -import org.apache.commons.rng.core.util.NumberFactory; - -import java.util.Arrays; - -/** - * Creates a {@code long[]} from a {@code byte[]}. - * - * @since 1.0 - */ -public class ByteArray2LongArray implements SeedConverter { - /** Number of bytes in a {@code long}. */ - private static final int LONG_SIZE = 8; - - /** {@inheritDoc} */ - @Override - public long[] convert(byte[] seed) { - final byte[] tmp = seed.length % LONG_SIZE == 0 ? - seed : - Arrays.copyOf(seed, LONG_SIZE * ((seed.length + LONG_SIZE - 1) / LONG_SIZE)); - - return NumberFactory.makeLongArray(tmp); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/Int2Long.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/Int2Long.java deleted file mode 100644 index e614bec93..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/Int2Long.java +++ /dev/null @@ -1,33 +0,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. - */ -package org.apache.commons.rng.simple.internal; - -import org.apache.commons.rng.core.util.NumberFactory; - -/** - * Converts a {@code Integer} to an {@code Long}. - * - * @since 1.0 - */ -public class Int2Long implements SeedConverter { - /** {@inheritDoc} */ - @Override - public Long convert(Integer seed) { - final int s = seed; - return NumberFactory.makeLong(s, ~s); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/IntArray2Int.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/IntArray2Int.java deleted file mode 100644 index 1befeeffd..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/IntArray2Int.java +++ /dev/null @@ -1,35 +0,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. - */ -package org.apache.commons.rng.simple.internal; - -/** - * Creates a single value by "xor" of all the values in the input array. - * - * @since 1.0 - */ -public class IntArray2Int implements SeedConverter { - /** {@inheritDoc} */ - @Override - public Integer convert(int[] seed) { - int out = 0; - for (int s : seed) { - out ^= s; - } - - return out; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/IntArray2LongArray.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/IntArray2LongArray.java deleted file mode 100644 index dd77d2d0a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/IntArray2LongArray.java +++ /dev/null @@ -1,40 +0,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. - */ -package org.apache.commons.rng.simple.internal; - -import org.apache.commons.rng.core.util.NumberFactory; - -/** - * Creates a {@code long[]} from an {@code int[]}. - * - * @since 1.0 - */ -public class IntArray2LongArray implements SeedConverter { - /** {@inheritDoc} */ - @Override - public long[] convert(int[] seed) { - final int outSize = (seed.length + 1) / 2; - final long[] out = new long[outSize]; - for (int i = 0; i < outSize; i++) { - final int lo = seed[i]; - final int hi = outSize + i < seed.length ? seed[outSize + i] : 0; - out[i] = NumberFactory.makeLong(hi, lo); - } - - return out; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/Long2Int.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/Long2Int.java deleted file mode 100644 index 6218f0880..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/Long2Int.java +++ /dev/null @@ -1,32 +0,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. - */ -package org.apache.commons.rng.simple.internal; - -import org.apache.commons.rng.core.util.NumberFactory; - -/** - * Converts a {@code Long} to an {@code Integer}. - * - * @since 1.0 - */ -public class Long2Int implements SeedConverter { - /** {@inheritDoc} */ - @Override - public Integer convert(Long seed) { - return NumberFactory.makeInt(seed); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/Long2IntArray.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/Long2IntArray.java deleted file mode 100644 index b1b66f2e2..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/Long2IntArray.java +++ /dev/null @@ -1,44 +0,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. - */ -package org.apache.commons.rng.simple.internal; - -import org.apache.commons.rng.core.source64.SplitMix64; - -/** - * Uses a {@code long} value to seed a {@link SplitMix64} RNG and - * create a {@code int[]} with the requested number of random - * values. - * - * @since 1.0 - */ -public class Long2IntArray implements SeedConverter { - /** Size of the output array. */ - private final int size; - - /** - * @param size Size of the output array. - */ - public Long2IntArray(int size) { - this.size = size; - } - - /** {@inheritDoc} */ - @Override - public int[] convert(Long seed) { - return SeedFactory.createIntArray(size, new SplitMix64(seed)); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/Long2LongArray.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/Long2LongArray.java deleted file mode 100644 index 9d223830c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/Long2LongArray.java +++ /dev/null @@ -1,50 +0,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. - */ -package org.apache.commons.rng.simple.internal; - -import org.apache.commons.rng.core.source64.SplitMix64; - -/** - * Uses a {@code Long} value to seed a {@link SplitMix64} RNG and - * create a {@code long[]} with the requested number of random - * values. - * - * @since 1.0 - */ -public class Long2LongArray implements SeedConverter { - /** Size of the output array. */ - private final int size; - - /** - * @param size Size of the output array. - */ - public Long2LongArray(int size) { - this.size = size; - } - - /** {@inheritDoc} */ - @Override - public long[] convert(Long seed) { - final long[] out = new long[size]; - final SplitMix64 rng = new SplitMix64(seed); - for (int i = 0; i < size; i++) { - out[i] = rng.nextLong(); - } - - return out; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/LongArray2IntArray.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/LongArray2IntArray.java deleted file mode 100644 index d5f2bcade..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/LongArray2IntArray.java +++ /dev/null @@ -1,39 +0,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. - */ -package org.apache.commons.rng.simple.internal; - -import org.apache.commons.rng.core.util.NumberFactory; - -/** - * Creates an {@code int[]} from a {@code long[]}. - * - * @since 1.0 - */ -public class LongArray2IntArray implements SeedConverter { - /** {@inheritDoc} */ - @Override - public int[] convert(long[] seed) { - final int[] out = new int[seed.length * 2]; - for (int i = 0; i < seed.length; i++) { - final long current = seed[i]; - out[i] = NumberFactory.extractLo(current); - out[seed.length + i] = NumberFactory.extractHi(current); - } - - return out; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/LongArray2Long.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/LongArray2Long.java deleted file mode 100644 index f683d77aa..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/LongArray2Long.java +++ /dev/null @@ -1,35 +0,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. - */ -package org.apache.commons.rng.simple.internal; - -/** - * Creates a single value by "xor" of all the values in the input array. - * - * @since 1.0 - */ -public class LongArray2Long implements SeedConverter { - /** {@inheritDoc} */ - @Override - public Long convert(long[] seed) { - long out = 0; - for (long s : seed) { - out ^= s; - } - - return out; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/NoOpConverter.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/NoOpConverter.java deleted file mode 100644 index b340357a5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/NoOpConverter.java +++ /dev/null @@ -1,34 +0,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. - */ -package org.apache.commons.rng.simple.internal; - - -/** - * Dummy converter that simply passes on its input. - * It can be useful to avoid "unchecked" compiler warnings. - * - * @param Seed type. - * - * @since 1.0 - */ -public class NoOpConverter implements SeedConverter { - /** {@inheritDoc} */ - @Override - public SEED convert(SEED seed) { - return seed; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/ProviderBuilder.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/ProviderBuilder.java deleted file mode 100644 index 836139bc6..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/ProviderBuilder.java +++ /dev/null @@ -1,388 +0,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. - */ -package org.apache.commons.rng.simple.internal; - -import org.apache.commons.rng.RestorableUniformRandomProvider; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.core.source32.*; -import org.apache.commons.rng.core.source64.*; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * RNG builder. - *

- * It uses reflection to find the factory method of the RNG implementation, - * and performs seed type conversions. - *

- */ -public final class ProviderBuilder { - /** Error message. */ - private static final String INTERNAL_ERROR_MSG = "Internal error: Please file a bug report"; - /** Length of the seed array (for random seed). */ - private static final int RANDOM_SEED_ARRAY_SIZE = 128; - /** Seed converter. */ - private static final Long2Int LONG_TO_INT = new Long2Int(); - /** Seed converter. */ - private static final Int2Long INT_TO_LONG = new Int2Long(); - /** Seed converter. */ - private static final Long2IntArray LONG_TO_INT_ARRAY = new Long2IntArray(RANDOM_SEED_ARRAY_SIZE); - /** Seed converter. */ - private static final Long2LongArray LONG_TO_LONG_ARRAY = new Long2LongArray(RANDOM_SEED_ARRAY_SIZE); - /** Seed converter. */ - private static final LongArray2Long LONG_ARRAY_TO_LONG = new LongArray2Long(); - /** Seed converter. */ - private static final IntArray2Int INT_ARRAY_TO_INT = new IntArray2Int(); - /** Seed converter. */ - private static final LongArray2IntArray LONG_ARRAY_TO_INT_ARRAY = new LongArray2IntArray(); - /** Seed converter. */ - private static final IntArray2LongArray INT_ARRAY_TO_LONG_ARRAY = new IntArray2LongArray(); - /** Seed converter. */ - private static final ByteArray2IntArray BYTE_ARRAY_TO_INT_ARRAY = new ByteArray2IntArray(); - /** Seed converter. */ - private static final ByteArray2LongArray BYTE_ARRAY_TO_LONG_ARRAY = new ByteArray2LongArray(); - /** Map to convert "Integer" seeds. */ - private static final Map, SeedConverter> CONV_INT = - new ConcurrentHashMap, SeedConverter>(); - /** Map to convert "int[]" seeds. */ - private static final Map, SeedConverter> CONV_INT_ARRAY = - new ConcurrentHashMap, SeedConverter>(); - /** Map to convert "Long" seeds. */ - private static final Map, SeedConverter> CONV_LONG = - new ConcurrentHashMap, SeedConverter>(); - /** Map to convert "long[]" seeds. */ - private static final Map, SeedConverter> CONV_LONG_ARRAY = - new ConcurrentHashMap, SeedConverter>(); - /** Map to convert "byte[]" seeds. */ - private static final Map, SeedConverter> CONV_BYTE_ARRAY = - new ConcurrentHashMap, SeedConverter>(); - - static { - // Input seed type is "Long". - // Key is the implementation's "native" seed type. - CONV_LONG.put(Integer.class, LONG_TO_INT); - CONV_LONG.put(Long.class, new NoOpConverter()); - CONV_LONG.put(int[].class, LONG_TO_INT_ARRAY); - CONV_LONG.put(long[].class, LONG_TO_LONG_ARRAY); - - // Input seed type is "Integer". - // Key is the implementation's "native" seed type. - CONV_INT.put(Integer.class, new NoOpConverter()); - CONV_INT.put(Long.class, INT_TO_LONG); - CONV_INT.put(int[].class, new SeedConverterComposer(INT_TO_LONG, LONG_TO_INT_ARRAY)); - CONV_INT.put(long[].class, new SeedConverterComposer(INT_TO_LONG, LONG_TO_LONG_ARRAY)); - - // Input seed type is "int[]". - // Key is the implementation's "native" seed type. - CONV_INT_ARRAY.put(Integer.class, INT_ARRAY_TO_INT); - CONV_INT_ARRAY.put(Long.class, new SeedConverterComposer(INT_ARRAY_TO_INT, INT_TO_LONG)); - CONV_INT_ARRAY.put(int[].class, new NoOpConverter()); - CONV_INT_ARRAY.put(long[].class, INT_ARRAY_TO_LONG_ARRAY); - - // Input seed type is "long[]". - // Key is the implementation's "native" seed type. - CONV_LONG_ARRAY.put(Integer.class, new SeedConverterComposer(LONG_ARRAY_TO_LONG, LONG_TO_INT)); - CONV_LONG_ARRAY.put(Long.class, LONG_ARRAY_TO_LONG); - CONV_LONG_ARRAY.put(int[].class, LONG_ARRAY_TO_INT_ARRAY); - CONV_LONG_ARRAY.put(long[].class, new NoOpConverter()); - - // Input seed type is "byte[]". - // Key is the implementation's "native" seed type. - CONV_BYTE_ARRAY.put(Integer.class, new SeedConverterComposer(BYTE_ARRAY_TO_INT_ARRAY, INT_ARRAY_TO_INT)); - CONV_BYTE_ARRAY.put(Long.class, new SeedConverterComposer(BYTE_ARRAY_TO_LONG_ARRAY, LONG_ARRAY_TO_LONG)); - CONV_BYTE_ARRAY.put(int[].class, BYTE_ARRAY_TO_INT_ARRAY); - CONV_BYTE_ARRAY.put(long[].class, BYTE_ARRAY_TO_LONG_ARRAY); - } - - /** - * Class only contains static method. - */ - private ProviderBuilder() {} - - /** - * Creates a RNG instance. - * - * @param source RNG specification. - * @param seed Seed value. It can be {@code null} (in which case a - * random value will be used). - * @param args Additional arguments to the implementation's constructor. - * @return a new RNG instance. - * @throws UnsupportedOperationException if the seed type is invalid. - */ - public static RestorableUniformRandomProvider create(RandomSourceInternal source, - Object seed, - Object[] args) { - // Convert seed to native type. - final Object nativeSeed = createSeed(source, seed); - - // Build a single array with all the arguments to be passed - // (in the right order) to the constructor. - final List all = new ArrayList(); - all.add(nativeSeed); - if (args != null) { - all.addAll(Arrays.asList(args)); - } - - // Instantiate. - return create(createConstructor(source), all.toArray()); - } - - /** - * Creates a native seed from any of the supported seed types. - * - * @param source Source. - * @param seed Input seed. - * @return the native seed. - * @throw UnsupportedOperationException if the {@code seed} type is invalid. - */ - private static Object createSeed(RandomSourceInternal source, - Object seed) { - Object nativeSeed = null; - - if (seed == null) { - // Create a random seed of the appropriate native type. - - if (source.getSeed().equals(Integer.class)) { - nativeSeed = SeedFactory.createInt(); - } else if (source.getSeed().equals(Long.class)) { - nativeSeed = SeedFactory.createLong(); - } else if (source.getSeed().equals(int[].class)) { - nativeSeed = SeedFactory.createIntArray(RANDOM_SEED_ARRAY_SIZE); - } else if (source.getSeed().equals(long[].class)) { - nativeSeed = SeedFactory.createLongArray(RANDOM_SEED_ARRAY_SIZE); - } else { - // Source's native type is not handled. - throw new IllegalStateException(INTERNAL_ERROR_MSG); - } - } else { - // Convert to native type. - - if (seed instanceof Integer) { - nativeSeed = CONV_INT.get(source.getSeed()).convert((Integer) seed); - } else if (seed instanceof Long) { - nativeSeed = CONV_LONG.get(source.getSeed()).convert((Long) seed); - } else if (seed instanceof int[]) { - nativeSeed = CONV_INT_ARRAY.get(source.getSeed()).convert((int[]) seed); - } else if (seed instanceof long[]) { - nativeSeed = CONV_LONG_ARRAY.get(source.getSeed()).convert((long[]) seed); - } else if (seed instanceof byte[]) { - nativeSeed = CONV_BYTE_ARRAY.get(source.getSeed()).convert((byte[]) seed); - } - - if (nativeSeed == null) { - // Since the input seed was not null, getting here means that - // no suitable converter is present in the maps. - throw new UnsupportedOperationException("Unrecognized seed type"); - } - - if (!source.isNativeSeed(nativeSeed)) { - // Conversion setup is wrong. - throw new IllegalStateException(INTERNAL_ERROR_MSG); - } - } - - return nativeSeed; - } - - /** - * Creates a constructor. - * - * @param source RNG specification. - * @return a RNG constructor. - */ - private static Constructor createConstructor(RandomSourceInternal source) { - try { - return source.getRng().getConstructor(source.getArgs()); - } catch (NoSuchMethodException e) { - // Info in "RandomSourceInternal" is inconsistent with the - // constructor of the implementation. - throw new IllegalStateException(INTERNAL_ERROR_MSG, e); - } - } - - /** - * Creates a RNG. - * - * @param rng RNG specification. - * @param args Arguments to the implementation's constructor. - * @return a new RNG instance. - */ - private static RestorableUniformRandomProvider create(Constructor rng, - Object[] args) { - try { - return (RestorableUniformRandomProvider) rng.newInstance(args); - } catch (InvocationTargetException e) { - throw new IllegalStateException(INTERNAL_ERROR_MSG, e); - } catch (InstantiationException e) { - throw new IllegalStateException(INTERNAL_ERROR_MSG, e); - } catch (IllegalAccessException e) { - throw new IllegalStateException(INTERNAL_ERROR_MSG, e); - } - } - - /** - * Identifiers of the generators. - */ - public enum RandomSourceInternal { - /** Source of randomness is {@link JDKRandom}. */ - JDK(JDKRandom.class, - Long.class), - /** Source of randomness is {@link Well512a}. */ - WELL_512_A(Well512a.class, - int[].class), - /** Source of randomness is {@link Well1024a}. */ - WELL_1024_A(Well1024a.class, - int[].class), - /** Source of randomness is {@link Well19937a}. */ - WELL_19937_A(Well19937a.class, - int[].class), - /** Source of randomness is {@link Well19937c}. */ - WELL_19937_C(Well19937c.class, - int[].class), - /** Source of randomness is {@link Well44497a}. */ - WELL_44497_A(Well44497a.class, - int[].class), - /** Source of randomness is {@link Well44497b}. */ - WELL_44497_B(Well44497b.class, - int[].class), - /** Source of randomness is {@link MersenneTwister}. */ - MT(MersenneTwister.class, - int[].class), - /** Source of randomness is {@link ISAACRandom}. */ - ISAAC(ISAACRandom.class, - int[].class), - /** Source of randomness is {@link SplitMix64}. */ - SPLIT_MIX_64(SplitMix64.class, - Long.class), - /** Source of randomness is {@link XorShift1024Star}. */ - XOR_SHIFT_1024_S(XorShift1024Star.class, - long[].class), - /** Source of randomness is {@link TwoCmres}. */ - TWO_CMRES(TwoCmres.class, - Integer.class), - /** - * Source of randomness is {@link TwoCmres} with explicit selection - * of the two subcycle generators. - */ - TWO_CMRES_SELECT(TwoCmres.class, - Integer.class, - Integer.TYPE, - Integer.TYPE), - /** Source of randomness is {@link MersenneTwister64}. */ - MT_64(MersenneTwister64.class, - long[].class), - /** Source of randomness is {@link MultiplyWithCarry256}. */ - MWC_256(MultiplyWithCarry256.class, - int[].class), - /** Source of randomness is {@link KISSRandom}. */ - KISS(KISSRandom.class, - int[].class), - /** Source of randomness is {@link XorShift1024StarPhi}. */ - XOR_SHIFT_1024_S_PHI(XorShift1024StarPhi.class, - long[].class), - /** Source of randomness is {@link XoRoShiRo64Star}. */ - XO_RO_SHI_RO_64_S(XoRoShiRo64Star.class, - int[].class), - /** Source of randomness is {@link XoRoShiRo64StarStar}. */ - XO_RO_SHI_RO_64_SS(XoRoShiRo64StarStar.class, - int[].class), - /** Source of randomness is {@link XoShiRo128Plus}. */ - XO_SHI_RO_128_PLUS(XoShiRo128Plus.class, - int[].class), - /** Source of randomness is {@link XoShiRo128StarStar}. */ - XO_SHI_RO_128_SS(XoShiRo128StarStar.class, - int[].class), - /** Source of randomness is {@link XoRoShiRo128Plus}. */ - XO_RO_SHI_RO_128_PLUS(XoRoShiRo128Plus.class, - long[].class), - /** Source of randomness is {@link XoRoShiRo128StarStar}. */ - XO_RO_SHI_RO_128_SS(XoRoShiRo128StarStar.class, - long[].class), - /** Source of randomness is {@link XoShiRo256Plus}. */ - XO_SHI_RO_256_PLUS(XoShiRo256Plus.class, - long[].class), - /** Source of randomness is {@link XoShiRo256StarStar}. */ - XO_SHI_RO_256_SS(XoShiRo256StarStar.class, - long[].class), - /** Source of randomness is {@link XoShiRo512Plus}. */ - XO_SHI_RO_512_PLUS(XoShiRo512Plus.class, - long[].class), - /** Source of randomness is {@link XoShiRo512StarStar}. */ - XO_SHI_RO_512_SS(XoShiRo512StarStar.class, - long[].class), - ; - - /** Source type. */ - private final Class rng; - /** Data needed to build the generator. */ - private final Class[] args; - - /** - * @param rng Source type. - * @param args Data needed to create a generator instance. - * The first element must be the native seed type. - */ - RandomSourceInternal(Class rng, - Class ... args) { - this.rng = rng; - this.args = Arrays.copyOf(args, args.length); - } - - /** - * @return the source type. - */ - public Class getRng() { - return rng; - } - - /** - * @return the seed type. - */ - Class getSeed() { - return args[0]; - } - - /** - * @return the data needed to build the generator. - */ - Class[] getArgs() { - return args; - } - - /** - * Checks whether the type of given {@code seed} is the native type - * of the implementation. - * - * @param Seed type. - * - * @param seed Seed value. - * @return {@code true} if the seed can be passed to the builder - * for this RNG type. - */ - public boolean isNativeSeed(SEED seed) { - return seed == null ? - false : - getSeed().equals(seed.getClass()); - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/SeedConverter.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/SeedConverter.java deleted file mode 100644 index af616feec..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/SeedConverter.java +++ /dev/null @@ -1,35 +0,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. - */ -package org.apache.commons.rng.simple.internal; - -/** - * Seed converter. - * - * @param Input seed type. - * @param Output seed type. - * - * @since 1.0 - */ -public interface SeedConverter { - /** - * Converts seed from input type to output type. - * - * @param seed Original seed value. - * @return the converted seed value. - */ - OUT convert(IN seed); -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/SeedConverterComposer.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/SeedConverterComposer.java deleted file mode 100644 index 4125a28b3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/SeedConverterComposer.java +++ /dev/null @@ -1,50 +0,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. - */ -package org.apache.commons.rng.simple.internal; - -/** - * Composes two {@link SeedConverter converters}. - * - * @param Input seed type. - * @param Transitional seed type. - * @param Output seed type. - * - * @since 1.0 - */ -public class SeedConverterComposer implements SeedConverter { - /** First conversion. */ - private final SeedConverter first; - /** Second conversion. */ - private final SeedConverter second; - - /** - * @param first First conversion. - * @param second second conversion. - */ - public SeedConverterComposer(SeedConverter first, - SeedConverter second) { - this.first = first; - this.second = second; - } - - /** {@inheritDoc} */ - @Override - public OUT convert(IN seed) { - final TRANS trans = first.convert(seed); - return second.convert(trans); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/SeedFactory.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/SeedFactory.java deleted file mode 100644 index e66928257..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/SeedFactory.java +++ /dev/null @@ -1,266 +0,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. - */ -package org.apache.commons.rng.simple.internal; - -import org.apache.commons.rng.core.source32.RandomIntSource; -import org.apache.commons.rng.core.source32.Well44497b; -import org.apache.commons.rng.core.source64.RandomLongSource; -import org.apache.commons.rng.core.source64.SplitMix64; -import org.apache.commons.rng.core.util.NumberFactory; - -import java.security.SecureRandom; - -/** - * Utilities related to seeding. - * - *

- * This class provides methods to generate random seeds (single values - * or arrays of values, of {@code int} or {@code long} types) that can - * be passed to the {@link org.apache.commons.rng.simple.RandomSource - * methods that create a generator instance}. - *
- * Although the seed-generating methods defined in this class will likely - * return different values for all calls, there is no guarantee that the - * produced seed will result always in a "good" sequence of numbers (even - * if the generator initialized with that seed is good). - *
- * There is no guarantee that sequences will not overlap. - *

- * - * @since 1.0 - */ -public final class SeedFactory { - /** Generator with a long period. */ - private static final RandomIntSource SEED_GENERATOR; - - static { - // Use a secure RNG so that different instances (e.g. in multiple JVM - // instances started in rapid succession) will have different seeds. - final SecureRandom seedGen = new SecureRandom(); - final long initSeed = NumberFactory.makeLong(seedGen.generateSeed(8)); - final SplitMix64 rng = new SplitMix64(initSeed); - - final int blockCount = 1391; // Size of the state array of "Well44497b". - SEED_GENERATOR = new Well44497b(createIntArray(blockCount, rng)); - } - - /** - * Class contains only static methods. - */ - private SeedFactory() {} - - /** - * Creates a number for use as a seed. - * - * @return a random number. - */ - public static int createInt() { - return createInt(SEED_GENERATOR, System.identityHashCode(new Object())); - } - - /** - * Creates a number for use as a seed. - * - * @return a random number. - */ - public static long createLong() { - return createLong(SEED_GENERATOR, System.identityHashCode(new Object())); - } - - /** - * Creates an array of numbers for use as a seed. - * - * @param n Size of the array to create. - * @return an array of {@code n} random numbers. - */ - public static int[] createIntArray(int n) { - return createIntArray(n, SEED_GENERATOR, new Object()); - } - - /** - * Creates an array of numbers for use as a seed. - * - * @param n Size of the array to create. - * @return an array of {@code n} random numbers. - */ - public static long[] createLongArray(int n) { - return createLongArray(n, SEED_GENERATOR, new Object()); - } - - /** - * Creates an array of numbers for use as a seed. - * - * @param n Size of the array to create. - * @param source Source of randomness. - * @return an array of {@code n} random numbers drawn from the - * {@code source}. - */ - static long[] createLongArray(int n, - RandomIntSource source) { - return createLongArray(n, source, null); - } - - /** - * Creates an array of numbers for use as a seed. - * - * @param n Size of the array to create. - * @param source Source of randomness. - * @return an array of {@code n} random numbers drawn from the - * {@code source}. - */ - static int[] createIntArray(int n, - RandomLongSource source) { - return createIntArray(n, source, null); - } - - /** - * Creates an array of numbers for use as a seed. - * - * @param n Size of the array to create. - * @param source Source of randomness. - * @return an array of {@code n} random numbers drawn from the - * {@code source}. - */ - static int[] createIntArray(int n, - RandomIntSource source) { - return createIntArray(n, source, null); - } - - /** - * Creates an array of numbers for use as a seed. - * - * @param n Size of the array to create. - * @param source Source of randomness. - * @param h Arbitrary object whose {@link System#identityHashCode(Object) - * hash code} will be combined with the next number drawn from - * the {@code source}. - * @return an array of {@code n} random numbers. - */ - private static long[] createLongArray(int n, - RandomIntSource source, - Object h) { - final long[] array = new long[n]; - - final int hash = System.identityHashCode(h); - for (int i = 0; i < n; i++) { - array[i] = createLong(source, hash); - } - - return array; - } - - /** - * Creates an array of numbers for use as a seed. - * - * @param n Size of the array to create. - * @param source Source of randomness. - * @param h Arbitrary object whose {@link System#identityHashCode(Object) - * hash code} will be combined with the next number drawn from - * the {@code source}. - * @return an array of {@code n} random numbers. - */ - private static int[] createIntArray(int n, - RandomLongSource source, - Object h) { - final int[] array = new int[n]; - - final int hash = System.identityHashCode(h); - for (int i = 0; i < n; i += 2) { - final long v = createLong(source, hash); - - array[i] = NumberFactory.extractHi(v); - - if (i + 1 < n) { - array[i + 1] = NumberFactory.extractLo(v); - } - } - - return array; - } - - /** - * Creates an array of numbers for use as a seed. - * - * @param n Size of the array to create. - * @param source Source of randomness. - * @param h Arbitrary object whose {@link System#identityHashCode(Object) - * hash code} will be combined with the next number drawn from - * the {@code source}. - * @return an array of {@code n} random numbers. - */ - private static int[] createIntArray(int n, - RandomIntSource source, - Object h) { - final int[] array = new int[n]; - - final int hash = System.identityHashCode(h); - for (int i = 0; i < n; i++) { - array[i] = createInt(source, hash); - } - - return array; - } - - /** - * Creates a random number by performing an "xor" between the - * next value in the sequence of the {@code source} and the - * given {@code number}. - * - * @param source Source of randomness. - * @param number Arbitrary number. - * @return a random number. - */ - private static long createLong(RandomLongSource source, - int number) { - synchronized (source) { - return source.next() ^ NumberFactory.makeLong(number, number); - } - } - - /** - * Creates a random number by performing an "xor" between the - * the next value in the sequence of the {@code source} and the - * given {@code number}. - * - * @param source Source of randomness. - * @param number Arbitrary number. - * @return a random number. - */ - private static long createLong(RandomIntSource source, - int number) { - synchronized (source) { - return NumberFactory.makeLong(source.next() ^ number, - source.next() ^ number); - } - } - - /** - * Creates a random number by performing an "xor" between the - * next value in the sequence of the {@code source} and the - * given {@code number}. - * - * @param source Source of randomness. - * @param number Arbitrary number. - * @return a random number. - */ - private static int createInt(RandomIntSource source, - int number) { - synchronized (source) { - return source.next() ^ number; - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/package-info.java deleted file mode 100644 index 807fd2c8f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/internal/package-info.java +++ /dev/null @@ -1,22 +0,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. - */ - -/** - * Utilities for seed conversion. - */ - -package org.apache.commons.rng.simple.internal; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/package-info.java deleted file mode 100644 index eef28e9ec..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/rng/simple/package-info.java +++ /dev/null @@ -1,93 +0,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. - */ - -/** - *

Randomness providers

- * - *

- * This package provides - * {@link org.apache.commons.rng.simple.RandomSource factory methods} - * by which low-level classes implemented in module "commons-rng-core" - * are instantiated. - *
- * Classes in package org.apache.commons.rng.simple.internal - * should not be used directly. - *
- * The generators are not thread-safe: Parallel applications must - * use different generator instances in different threads. - *

- * - *

- * In the case of pseudo-random generators, the source of randomness is - * usually a set of numbers whose bits representation are scrambled in such - * a way as to produce a random-looking sequence. - *
- * The main property of the sequence is that the numbers must be uniformly - * distributed within their allowed range. - *
- * Classes in this package do not provide any further processing of the - * number generation such as to match other types of distribution. - *

- * - *

- * Which source of randomness to choose may depend on which properties - * are more important. - * Considerations can include speed of generation, memory usage, period - * size, equidistribution, correlation, etc. - *
- * For some of the generators, interesting properties (of the reference - * implementations) are proven in scientific papers. - * Some generators can also suffer from potential weaknesses. - *

- * - *

- * For simple sampling, any of the generators implemented in this library - * may be sufficient. - *
- * For Monte-Carlo simulations that require generating high-dimensional - * vectors), equidistribution and non-correlation are crucial. - * The Mersenne Twister and Well generators have - * equidistribution properties proven according to their bits pool size - * which is directly related to their period (all of them have maximal - * period, i.e. a generator with size {@code n} pool has a period - * 2n-1). - * They also have equidistribution properties for 32 bits blocks up to - * {@code s/32} dimension where {@code s} is their pool size. - *
- * For example, {@code Well19937c} is equidistributed up to dimension 623 - * (i.e. 19937 divided by 32). - * It means that a Monte-Carlo simulation generating vectors of {@code n} - * (32-bits integer) variables at each iteration has some guarantee on the - * properties of its components as long as {@code n < 623}. - * Note that if the variables are of type {@code double}, the limit is - * divided by two (since 64 bits are needed to create a {@code double}). - *
- * Reference to the relevant publications are listed in the specific - * documentation of each class. - *

- * - *

- * Memory usage can vary a lot between providers. - * The state of {@code MersenneTwister} is composed of 624 integers, - * using about 2.5 kB. - * The Well generators use 6 integer arrays, the length of each - * being equal to the pool size; thus, for example, {@code Well44497b} - * uses about 33 kB. - *

- */ - -package org.apache.commons.rng.simple; diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/AbstractContinuousDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/AbstractContinuousDistribution.java deleted file mode 100644 index 7dfe034b5..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/AbstractContinuousDistribution.java +++ /dev/null @@ -1,411 +0,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. - */ -package org.apache.commons.statistics.distribution; - -import org.apache.commons.numbers.core.Precision; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.ContinuousInverseCumulativeProbabilityFunction; -import org.apache.commons.rng.sampling.distribution.ContinuousSampler; -import org.apache.commons.rng.sampling.distribution.InverseTransformContinuousSampler; - -import java.util.function.DoubleUnaryOperator; - -/** - * Base class for probability distributions on the reals. - * Default implementations are provided for some of the methods - * that do not vary from distribution to distribution. - * - * This base class provides a default factory method for creating - * a {@link ContinuousDistribution.Sampler sampler instance} that uses the - * - * inversion method for generating random samples that follow the - * distribution. - */ -abstract class AbstractContinuousDistribution - implements ContinuousDistribution { - /** - * {@inheritDoc} - * - * The default implementation returns - *
    - *
  • {@link #getSupportLowerBound()} for {@code p = 0},
  • - *
  • {@link #getSupportUpperBound()} for {@code p = 1}.
  • - *
- */ - @Override - public double inverseCumulativeProbability(final double p) { - /* - * IMPLEMENTATION NOTES - * -------------------- - * Where applicable, use is made of the one-sided Chebyshev inequality - * to bracket the root. This inequality states that - * P(X - mu >= k * sig) <= 1 / (1 + k^2), - * mu: mean, sig: standard deviation. Equivalently - * 1 - P(X < mu + k * sig) <= 1 / (1 + k^2), - * F(mu + k * sig) >= k^2 / (1 + k^2). - * - * For k = sqrt(p / (1 - p)), we find - * F(mu + k * sig) >= p, - * and (mu + k * sig) is an upper-bound for the root. - * - * Then, introducing Y = -X, mean(Y) = -mu, sd(Y) = sig, and - * P(Y >= -mu + k * sig) <= 1 / (1 + k^2), - * P(-X >= -mu + k * sig) <= 1 / (1 + k^2), - * P(X <= mu - k * sig) <= 1 / (1 + k^2), - * F(mu - k * sig) <= 1 / (1 + k^2). - * - * For k = sqrt((1 - p) / p), we find - * F(mu - k * sig) <= p, - * and (mu - k * sig) is a lower-bound for the root. - * - * In cases where the Chebyshev inequality does not apply, geometric - * progressions 1, 2, 4, ... and -1, -2, -4, ... are used to bracket - * the root. - */ - if (p < 0 || - p > 1) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, p, 0, 1); - } - - double lowerBound = getSupportLowerBound(); - if (p == 0) { - return lowerBound; - } - - double upperBound = getSupportUpperBound(); - if (p == 1) { - return upperBound; - } - - final double mu = getMean(); - final double sig = Math.sqrt(getVariance()); - final boolean chebyshevApplies; - chebyshevApplies = !(Double.isInfinite(mu) || - Double.isNaN(mu) || - Double.isInfinite(sig) || - Double.isNaN(sig)); - - if (lowerBound == Double.NEGATIVE_INFINITY) { - if (chebyshevApplies) { - lowerBound = mu - sig * Math.sqrt((1 - p) / p); - } else { - lowerBound = -1; - while (cumulativeProbability(lowerBound) >= p) { - lowerBound *= 2; - } - } - } - - if (upperBound == Double.POSITIVE_INFINITY) { - if (chebyshevApplies) { - upperBound = mu + sig * Math.sqrt(p / (1 - p)); - } else { - upperBound = 1; - while (cumulativeProbability(upperBound) < p) { - upperBound *= 2; - } - } - } - - // XXX Values copied from defaults in class - // "o.a.c.math4.analysis.solvers.BaseAbstractUnivariateSolver" - final double solverRelativeAccuracy = 1e-14; - final double solverAbsoluteAccuracy = 1e-9; - final double solverFunctionValueAccuracy = 1e-15; - - double x = new BrentSolver(solverRelativeAccuracy, - solverAbsoluteAccuracy, - solverFunctionValueAccuracy) - .solve((arg) -> cumulativeProbability(arg) - p, - lowerBound, - 0.5 * (lowerBound + upperBound), - upperBound); - - if (!isSupportConnected()) { - /* Test for plateau. */ - final double dx = solverAbsoluteAccuracy; - if (x - dx >= getSupportLowerBound()) { - double px = cumulativeProbability(x); - if (cumulativeProbability(x - dx) == px) { - upperBound = x; - while (upperBound - lowerBound > dx) { - final double midPoint = 0.5 * (lowerBound + upperBound); - if (cumulativeProbability(midPoint) < px) { - lowerBound = midPoint; - } else { - upperBound = midPoint; - } - } - return upperBound; - } - } - } - return x; - } - - /** - * Utility function for allocating an array and filling it with {@code n} - * samples generated by the given {@code sampler}. - * - * @param n Number of samples. - * @param sampler Sampler. - * @return an array of size {@code n}. - */ - public static double[] sample(int n, - ContinuousDistribution.Sampler sampler) { - final double[] samples = new double[n]; - for (int i = 0; i < n; i++) { - samples[i] = sampler.sample(); - } - return samples; - } - - /**{@inheritDoc} */ - @Override - public ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng) { - return new ContinuousDistribution.Sampler() { - /** - * Inversion method distribution sampler. - */ - private final ContinuousSampler sampler = - new InverseTransformContinuousSampler(rng, createICPF()); - - /** {@inheritDoc} */ - @Override - public double sample() { - return sampler.sample(); - } - }; - } - - /** - * @return an instance for use by {@link #createSampler(UniformRandomProvider)} - */ - private ContinuousInverseCumulativeProbabilityFunction createICPF() { - return new ContinuousInverseCumulativeProbabilityFunction() { - /** {@inheritDoc} */ - @Override - public double inverseCumulativeProbability(double p) { - return AbstractContinuousDistribution.this.inverseCumulativeProbability(p); - } - }; - } - - /** - * This class implements the - * Brent algorithm for finding zeros of real univariate functions. - * The function should be continuous but not necessarily smooth. - * The {@code solve} method returns a zero {@code x} of the function {@code f} - * in the given interval {@code [a, b]} to within a tolerance - * {@code 2 eps abs(x) + t} where {@code eps} is the relative accuracy and - * {@code t} is the absolute accuracy. - *

The given interval must bracket the root.

- *

- * The reference implementation is given in chapter 4 of - *

- * Algorithms for Minimization Without Derivatives, - * Richard P. Brent, - * Dover, 2002 - *
- * - * Used by {@link AbstractContinuousDistribution#inverseCumulativeProbability(double)}. - */ - private static class BrentSolver { - /** Relative accuracy. */ - private final double relativeAccuracy; - /** Absolutee accuracy. */ - private final double absoluteAccuracy; - /** Function accuracy. */ - private final double functionValueAccuracy; - - /** - * Construct a solver. - * - * @param relativeAccuracy Relative accuracy. - * @param absoluteAccuracy Absolute accuracy. - * @param functionValueAccuracy Function value accuracy. - */ - BrentSolver(double relativeAccuracy, - double absoluteAccuracy, - double functionValueAccuracy) { - this.relativeAccuracy = relativeAccuracy; - this.absoluteAccuracy = absoluteAccuracy; - this.functionValueAccuracy = functionValueAccuracy; - } - - /** - * @param func Function to solve. - * @param min Lower bound. - * @param initial Initial guess. - * @param max Upper bound. - * @return the root. - */ - double solve(DoubleUnaryOperator func, - double min, - double initial, - double max) { - if (min > max) { - throw new DistributionException(DistributionException.TOO_LARGE, min, max); - } - if (initial < min || - initial > max) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, initial, min, max); - } - - // Return the initial guess if it is good enough. - double yInitial = func.applyAsDouble(initial); - if (Math.abs(yInitial) <= functionValueAccuracy) { - return initial; - } - - // Return the first endpoint if it is good enough. - double yMin = func.applyAsDouble(min); - if (Math.abs(yMin) <= functionValueAccuracy) { - return min; - } - - // Reduce interval if min and initial bracket the root. - if (yInitial * yMin < 0) { - return brent(func, min, initial, yMin, yInitial); - } - - // Return the second endpoint if it is good enough. - double yMax = func.applyAsDouble(max); - if (Math.abs(yMax) <= functionValueAccuracy) { - return max; - } - - // Reduce interval if initial and max bracket the root. - if (yInitial * yMax < 0) { - return brent(func, initial, max, yInitial, yMax); - } - - throw new DistributionException(DistributionException.BRACKETING, min, yMin, max, yMax); - } - - /** - * Search for a zero inside the provided interval. - * This implementation is based on the algorithm described at page 58 of - * the book - *
- * Algorithms for Minimization Without Derivatives, - * Richard P. Brent, - * Dover 0-486-41998-3 - *
- * - * @param func Function to solve. - * @param lo Lower bound of the search interval. - * @param hi Higher bound of the search interval. - * @param fLo Function value at the lower bound of the search interval. - * @param fHi Function value at the higher bound of the search interval. - * @return the value where the function is zero. - */ - private double brent(DoubleUnaryOperator func, - double lo, double hi, - double fLo, double fHi) { - double a = lo; - double fa = fLo; - double b = hi; - double fb = fHi; - double c = a; - double fc = fa; - double d = b - a; - double e = d; - - final double t = absoluteAccuracy; - final double eps = relativeAccuracy; - - while (true) { - if (Math.abs(fc) < Math.abs(fb)) { - a = b; - b = c; - c = a; - fa = fb; - fb = fc; - fc = fa; - } - - final double tol = 2 * eps * Math.abs(b) + t; - final double m = 0.5 * (c - b); - - if (Math.abs(m) <= tol || - Precision.equals(fb, 0)) { - return b; - } - if (Math.abs(e) < tol || - Math.abs(fa) <= Math.abs(fb)) { - // Force bisection. - d = m; - e = d; - } else { - double s = fb / fa; - double p; - double q; - // The equality test (a == c) is intentional, - // it is part of the original Brent's method and - // it should NOT be replaced by proximity test. - if (a == c) { - // Linear interpolation. - p = 2 * m * s; - q = 1 - s; - } else { - // Inverse quadratic interpolation. - q = fa / fc; - final double r = fb / fc; - p = s * (2 * m * q * (q - r) - (b - a) * (r - 1)); - q = (q - 1) * (r - 1) * (s - 1); - } - if (p > 0) { - q = -q; - } else { - p = -p; - } - s = e; - e = d; - if (p >= 1.5 * m * q - Math.abs(tol * q) || - p >= Math.abs(0.5 * s * q)) { - // Inverse quadratic interpolation gives a value - // in the wrong direction, or progress is slow. - // Fall back to bisection. - d = m; - e = d; - } else { - d = p / q; - } - } - a = b; - fa = fb; - - if (Math.abs(d) > tol) { - b += d; - } else if (m > 0) { - b += tol; - } else { - b -= tol; - } - fb = func.applyAsDouble(b); - if ((fb > 0 && fc > 0) || - (fb <= 0 && fc <= 0)) { - c = a; - fc = fa; - d = b - a; - e = d; - } - } - } - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/AbstractDiscreteDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/AbstractDiscreteDistribution.java deleted file mode 100644 index cae880c95..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/AbstractDiscreteDistribution.java +++ /dev/null @@ -1,210 +0,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. - */ -package org.apache.commons.statistics.distribution; - -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.DiscreteInverseCumulativeProbabilityFunction; -import org.apache.commons.rng.sampling.distribution.DiscreteSampler; -import org.apache.commons.rng.sampling.distribution.InverseTransformDiscreteSampler; - -/** - * Base class for integer-valued discrete distributions. Default - * implementations are provided for some of the methods that do not vary - * from distribution to distribution. - */ -abstract class AbstractDiscreteDistribution - implements DiscreteDistribution { - /** - * {@inheritDoc} - * - * The default implementation uses the identity - * {@code P(x0 < X <= x1) = P(X <= x1) - P(X <= x0)} - */ - @Override - public double probability(int x0, - int x1) { - if (x1 < x0) { - throw new DistributionException(DistributionException.TOO_SMALL, - x1, x0); - } - return cumulativeProbability(x1) - cumulativeProbability(x0); - } - - /** - * {@inheritDoc} - * - * The default implementation returns - *
    - *
  • {@link #getSupportLowerBound()} for {@code p = 0},
  • - *
  • {@link #getSupportUpperBound()} for {@code p = 1}, and
  • - *
  • {@link #solveInverseCumulativeProbability(double, int, int)} for - * {@code 0 < p < 1}.
  • - *
- */ - @Override - public int inverseCumulativeProbability(final double p) { - if (p < 0 || - p > 1) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, p, 0, 1); - } - - int lower = getSupportLowerBound(); - if (p == 0.0) { - return lower; - } - if (lower == Integer.MIN_VALUE) { - if (checkedCumulativeProbability(lower) >= p) { - return lower; - } - } else { - lower -= 1; // this ensures cumulativeProbability(lower) < p, which - // is important for the solving step - } - - int upper = getSupportUpperBound(); - if (p == 1.0) { - return upper; - } - - // use the one-sided Chebyshev inequality to narrow the bracket - // cf. AbstractRealDistribution.inverseCumulativeProbability(double) - final double mu = getMean(); - final double sigma = Math.sqrt(getVariance()); - final boolean chebyshevApplies = !(Double.isInfinite(mu) || - Double.isNaN(mu) || - Double.isInfinite(sigma) || - Double.isNaN(sigma) || - sigma == 0.0); - if (chebyshevApplies) { - double k = Math.sqrt((1.0 - p) / p); - double tmp = mu - k * sigma; - if (tmp > lower) { - lower = ((int) Math.ceil(tmp)) - 1; - } - k = 1.0 / k; - tmp = mu + k * sigma; - if (tmp < upper) { - upper = ((int) Math.ceil(tmp)) - 1; - } - } - - return solveInverseCumulativeProbability(p, lower, upper); - } - - /** - * This is a utility function used by {@link - * #inverseCumulativeProbability(double)}. It assumes {@code 0 < p < 1} and - * that the inverse cumulative probability lies in the bracket {@code - * (lower, upper]}. The implementation does simple bisection to find the - * smallest {@code p}-quantile {@code inf{x in Z | P(X <= x) >= p}}. - * - * @param p Cumulative probability. - * @param lower Value satisfying {@code cumulativeProbability(lower) < p}. - * @param upper Value satisfying {@code p <= cumulativeProbability(upper)}. - * @return the smallest {@code p}-quantile of this distribution. - */ - private int solveInverseCumulativeProbability(final double p, - int lower, - int upper) { - while (lower + 1 < upper) { - int xm = (lower + upper) / 2; - if (xm < lower || xm > upper) { - /* - * Overflow. - * There will never be an overflow in both calculation methods - * for xm at the same time - */ - xm = lower + (upper - lower) / 2; - } - - double pm = checkedCumulativeProbability(xm); - if (pm >= p) { - upper = xm; - } else { - lower = xm; - } - } - return upper; - } - - /** - * Computes the cumulative probability function and checks for {@code NaN} - * values returned. Throws {@code MathInternalError} if the value is - * {@code NaN}. Rethrows any exception encountered evaluating the cumulative - * probability function. Throws {@code MathInternalError} if the cumulative - * probability function returns {@code NaN}. - * - * @param argument Input value. - * @return the cumulative probability. - * @throws IllegalStateException if the cumulative probability is {@code NaN}. - */ - private double checkedCumulativeProbability(int argument) { - final double result = cumulativeProbability(argument); - if (Double.isNaN(result)) { - throw new IllegalStateException("Internal error"); - } - return result; - } - - /** - * Utility function for allocating an array and filling it with {@code n} - * samples generated by the given {@code sampler}. - * - * @param n Number of samples. - * @param sampler Sampler. - * @return an array of size {@code n}. - */ - public static int[] sample(int n, - DiscreteDistribution.Sampler sampler) { - final int[] samples = new int[n]; - for (int i = 0; i < n; i++) { - samples[i] = sampler.sample(); - } - return samples; - } - - /** {@inheritDoc} */ - @Override - public DiscreteDistribution.Sampler createSampler(final UniformRandomProvider rng) { - return new DiscreteDistribution.Sampler() { - /** - * Inversion method distribution sampler. - */ - private final DiscreteSampler sampler = - new InverseTransformDiscreteSampler(rng, createICPF()); - - /** {@inheritDoc} */ - @Override - public int sample() { - return sampler.sample(); - } - }; - } - - /** - * @return an instance for use by {@link #createSampler(UniformRandomProvider)}. - */ - private DiscreteInverseCumulativeProbabilityFunction createICPF() { - return new DiscreteInverseCumulativeProbabilityFunction() { - /** {@inheritDoc} */ - @Override - public int inverseCumulativeProbability(double p) { - return AbstractDiscreteDistribution.this.inverseCumulativeProbability(p); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/BetaDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/BetaDistribution.java deleted file mode 100644 index 817d4c30a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/BetaDistribution.java +++ /dev/null @@ -1,202 +0,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. - */ -package org.apache.commons.statistics.distribution; - -import org.apache.commons.numbers.gamma.LogGamma; -import org.apache.commons.numbers.gamma.RegularizedBeta; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.ChengBetaSampler; -import org.apache.commons.rng.sampling.distribution.ContinuousSampler; - -/** - * Implementation of the Beta distribution. - */ -public class BetaDistribution extends AbstractContinuousDistribution { - /** First shape parameter. */ - private final double alpha; - /** Second shape parameter. */ - private final double beta; - /** Normalizing factor used in density computations.*/ - private final double z; - - /** - * Creates a new instance. - * - * @param alpha First shape parameter (must be positive). - * @param beta Second shape parameter (must be positive). - */ - public BetaDistribution(double alpha, - double beta) { - this.alpha = alpha; - this.beta = beta; - z = LogGamma.value(alpha) + LogGamma.value(beta) - LogGamma.value(alpha + beta); - } - - /** - * Access the first shape parameter, {@code alpha}. - * - * @return the first shape parameter. - */ - public double getAlpha() { - return alpha; - } - - /** - * Access the second shape parameter, {@code beta}. - * - * @return the second shape parameter. - */ - public double getBeta() { - return beta; - } - - /** {@inheritDoc} */ - @Override - public double density(double x) { - final double logDensity = logDensity(x); - return logDensity == Double.NEGATIVE_INFINITY ? 0 : Math.exp(logDensity); - } - - /** {@inheritDoc} **/ - @Override - public double logDensity(double x) { - if (x < 0 || - x > 1) { - return Double.NEGATIVE_INFINITY; - } else if (x == 0) { - if (alpha < 1) { - throw new DistributionException(DistributionException.TOO_SMALL, - alpha, 1); - } - return Double.NEGATIVE_INFINITY; - } else if (x == 1) { - if (beta < 1) { - throw new DistributionException(DistributionException.TOO_SMALL, - beta, 1); - } - return Double.NEGATIVE_INFINITY; - } else { - double logX = Math.log(x); - double log1mX = Math.log1p(-x); - return (alpha - 1) * logX + (beta - 1) * log1mX - z; - } - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(double x) { - if (x <= 0) { - return 0; - } else if (x >= 1) { - return 1; - } else { - return RegularizedBeta.value(x, alpha, beta); - } - } - - /** - * {@inheritDoc} - * - * For first shape parameter {@code alpha} and second shape parameter - * {@code beta}, the mean is {@code alpha / (alpha + beta)}. - */ - @Override - public double getMean() { - final double a = getAlpha(); - return a / (a + getBeta()); - } - - /** - * {@inheritDoc} - * - * For first shape parameter {@code alpha} and second shape parameter - * {@code beta}, the variance is - * {@code (alpha * beta) / [(alpha + beta)^2 * (alpha + beta + 1)]}. - */ - @Override - public double getVariance() { - final double a = getAlpha(); - final double b = getBeta(); - final double alphabetasum = a + b; - return (a * b) / ((alphabetasum * alphabetasum) * (alphabetasum + 1)); - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is always 0 no matter the parameters. - * - * @return lower bound of the support (always 0) - */ - @Override - public double getSupportLowerBound() { - return 0; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is always 1 no matter the parameters. - * - * @return upper bound of the support (always 1) - */ - @Override - public double getSupportUpperBound() { - return 1; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } - - /** - * {@inheritDoc} - * - * Sampling is performed using Cheng's algorithm: - *
- *
-     * R. C. H. Cheng,
-     * "Generating beta variates with nonintegral shape parameters",
-     * Communications of the ACM, 21, 317-322, 1978.
-     * 
- *
- */ - @Override - public ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng) { - return new ContinuousDistribution.Sampler() { - /** - * Beta distribution sampler. - */ - private final ContinuousSampler sampler = - new ChengBetaSampler(rng, alpha, beta); - - /**{@inheritDoc} */ - @Override - public double sample() { - return sampler.sample(); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/BinomialDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/BinomialDistribution.java deleted file mode 100644 index 97389be79..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/BinomialDistribution.java +++ /dev/null @@ -1,170 +0,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. - */ -package org.apache.commons.statistics.distribution; - -import org.apache.commons.numbers.gamma.RegularizedBeta; - -/** - * Implementation of the binomial distribution. - */ -public class BinomialDistribution extends AbstractDiscreteDistribution { - /** The number of trials. */ - private final int numberOfTrials; - /** The probability of success. */ - private final double probabilityOfSuccess; - - /** - * Creates a binomial distribution. - * - * @param trials Number of trials. - * @param p Probability of success. - * @throws IllegalArgumentException if {@code trials < 0}, or if - * {@code p < 0} or {@code p > 1}. - */ - public BinomialDistribution(int trials, - double p) { - if (trials < 0) { - throw new DistributionException(DistributionException.NEGATIVE, - trials); - } - if (p < 0 || - p > 1) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, p, 0, 1); - } - - probabilityOfSuccess = p; - numberOfTrials = trials; - } - - /** - * Access the number of trials for this distribution. - * - * @return the number of trials. - */ - public int getNumberOfTrials() { - return numberOfTrials; - } - - /** - * Access the probability of success for this distribution. - * - * @return the probability of success. - */ - public double getProbabilityOfSuccess() { - return probabilityOfSuccess; - } - - /** {@inheritDoc} */ - @Override - public double probability(int x) { - final double logProbability = logProbability(x); - return logProbability == Double.NEGATIVE_INFINITY ? 0 : Math.exp(logProbability); - } - - /** {@inheritDoc} **/ - @Override - public double logProbability(int x) { - if (numberOfTrials == 0) { - return (x == 0) ? 0. : Double.NEGATIVE_INFINITY; - } - double ret; - if (x < 0 || x > numberOfTrials) { - ret = Double.NEGATIVE_INFINITY; - } else { - ret = SaddlePointExpansion.logBinomialProbability(x, - numberOfTrials, probabilityOfSuccess, - 1.0 - probabilityOfSuccess); - } - return ret; - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(int x) { - double ret; - if (x < 0) { - ret = 0.0; - } else if (x >= numberOfTrials) { - ret = 1.0; - } else { - ret = 1.0 - RegularizedBeta.value(probabilityOfSuccess, - x + 1.0, numberOfTrials - x); - } - return ret; - } - - /** - * {@inheritDoc} - * - * For {@code n} trials and probability parameter {@code p}, the mean is - * {@code n * p}. - */ - @Override - public double getMean() { - return numberOfTrials * probabilityOfSuccess; - } - - /** - * {@inheritDoc} - * - * For {@code n} trials and probability parameter {@code p}, the variance is - * {@code n * p * (1 - p)}. - */ - @Override - public double getVariance() { - final double p = probabilityOfSuccess; - return numberOfTrials * p * (1 - p); - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is always 0 except for the probability - * parameter {@code p = 1}. - * - * @return lower bound of the support (0 or the number of trials) - */ - @Override - public int getSupportLowerBound() { - return probabilityOfSuccess < 1.0 ? 0 : numberOfTrials; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is the number of trials except for the - * probability parameter {@code p = 0}. - * - * @return upper bound of the support (number of trials or 0) - */ - @Override - public int getSupportUpperBound() { - return probabilityOfSuccess > 0.0 ? numberOfTrials : 0; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/CauchyDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/CauchyDistribution.java deleted file mode 100644 index b0eb0cac9..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/CauchyDistribution.java +++ /dev/null @@ -1,158 +0,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. - */ -package org.apache.commons.statistics.distribution; - -/** - * Implementation of the Cauchy distribution. - */ -public class CauchyDistribution extends AbstractContinuousDistribution { - /** The median of this distribution. */ - private final double median; - /** The scale of this distribution. */ - private final double scale; - - /** - * Creates a distribution. - * - * @param median Median for this distribution. - * @param scale Scale parameter for this distribution. - * @throws IllegalArgumentException if {@code scale <= 0}. - */ - public CauchyDistribution(double median, - double scale) { - if (scale <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, scale); - } - this.scale = scale; - this.median = median; - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(double x) { - return 0.5 + (Math.atan((x - median) / scale) / Math.PI); - } - - /** - * Access the median. - * - * @return the median for this distribution. - */ - public double getMedian() { - return median; - } - - /** - * Access the scale parameter. - * - * @return the scale parameter for this distribution. - */ - public double getScale() { - return scale; - } - - /** {@inheritDoc} */ - @Override - public double density(double x) { - final double dev = x - median; - return (1 / Math.PI) * (scale / (dev * dev + scale * scale)); - } - - /** - * {@inheritDoc} - * - * Returns {@code Double.NEGATIVE_INFINITY} when {@code p == 0} - * and {@code Double.POSITIVE_INFINITY} when {@code p == 1}. - */ - @Override - public double inverseCumulativeProbability(double p) { - double ret; - if (p < 0 || - p > 1) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, p, 0, 1); - } else if (p == 0) { - ret = Double.NEGATIVE_INFINITY; - } else if (p == 1) { - ret = Double.POSITIVE_INFINITY; - } else { - ret = median + scale * Math.tan(Math.PI * (p - .5)); - } - return ret; - } - - /** - * {@inheritDoc} - * - * The mean is always undefined no matter the parameters. - * - * @return mean (always Double.NaN) - */ - @Override - public double getMean() { - return Double.NaN; - } - - /** - * {@inheritDoc} - * - * The variance is always undefined no matter the parameters. - * - * @return variance (always Double.NaN) - */ - @Override - public double getVariance() { - return Double.NaN; - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is always negative infinity no matter - * the parameters. - * - * @return lower bound of the support (always Double.NEGATIVE_INFINITY) - */ - @Override - public double getSupportLowerBound() { - return Double.NEGATIVE_INFINITY; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is always positive infinity no matter - * the parameters. - * - * @return upper bound of the support (always Double.POSITIVE_INFINITY) - */ - @Override - public double getSupportUpperBound() { - return Double.POSITIVE_INFINITY; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ChiSquaredDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ChiSquaredDistribution.java deleted file mode 100644 index 3407cc607..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ChiSquaredDistribution.java +++ /dev/null @@ -1,119 +0,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. - */ -package org.apache.commons.statistics.distribution; - -/** - * Implementation of the chi-squared distribution. - */ -public class ChiSquaredDistribution extends AbstractContinuousDistribution { - /** Internal Gamma distribution. */ - private final GammaDistribution gamma; - - /** - * Creates a distribution. - * - * @param degreesOfFreedom Degrees of freedom. - */ - public ChiSquaredDistribution(double degreesOfFreedom) { - gamma = new GammaDistribution(degreesOfFreedom / 2, 2); - } - - /** - * Access the number of degrees of freedom. - * - * @return the degrees of freedom. - */ - public double getDegreesOfFreedom() { - return gamma.getShape() * 2; - } - - /** {@inheritDoc} */ - @Override - public double density(double x) { - return gamma.density(x); - } - - /** {@inheritDoc} **/ - @Override - public double logDensity(double x) { - return gamma.logDensity(x); - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(double x) { - return gamma.cumulativeProbability(x); - } - - /** - * {@inheritDoc} - * - * For {@code k} degrees of freedom, the mean is {@code k}. - */ - @Override - public double getMean() { - return getDegreesOfFreedom(); - } - - /** - * {@inheritDoc} - * - * @return {@code 2 * k}, where {@code k} is the number of degrees of freedom. - */ - @Override - public double getVariance() { - return 2 * getDegreesOfFreedom(); - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is always 0 no matter the - * degrees of freedom. - * - * @return zero. - */ - @Override - public double getSupportLowerBound() { - return 0; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is always positive infinity no matter the - * degrees of freedom. - * - * @return {@code Double.POSITIVE_INFINITY}. - */ - @Override - public double getSupportUpperBound() { - return Double.POSITIVE_INFINITY; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ConstantContinuousDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ConstantContinuousDistribution.java deleted file mode 100644 index 592e19e5c..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ConstantContinuousDistribution.java +++ /dev/null @@ -1,116 +0,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. - */ - -package org.apache.commons.statistics.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Implementation of the constant real distribution. - */ -public class ConstantContinuousDistribution extends AbstractContinuousDistribution { - /** Constant value of the distribution. */ - private final double value; - - /** - * Create a constant real distribution with the given value. - * - * @param value Value of this distribution. - */ - public ConstantContinuousDistribution(double value) { - this.value = value; - } - - /** {@inheritDoc} */ - @Override - public double density(double x) { - return x == value ? 1 : 0; - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(double x) { - return x < value ? 0 : 1; - } - - /** {@inheritDoc} */ - @Override - public double inverseCumulativeProbability(final double p) { - if (p < 0 || - p > 1) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, p, 0, 1); - } - return value; - } - - /** - * {@inheritDoc} - */ - @Override - public double getMean() { - return value; - } - - /** - * {@inheritDoc} - */ - @Override - public double getVariance() { - return 0; - } - - /** - * {@inheritDoc} - */ - @Override - public double getSupportLowerBound() { - return value; - } - - /** - * {@inheritDoc} - */ - @Override - public double getSupportUpperBound() { - return value; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isSupportConnected() { - return true; - } - - /** - * {@inheritDoc} - * - * @param rng Not used: distribution contains a single value. - * @return the value of the distribution. - */ - @Override - public ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng) { - return new ContinuousDistribution.Sampler() { - /** {@inheritDoc} */ - @Override - public double sample() { - return value; - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ContinuousDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ContinuousDistribution.java deleted file mode 100644 index 9bf59e003..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ContinuousDistribution.java +++ /dev/null @@ -1,176 +0,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. - */ -package org.apache.commons.statistics.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Base interface for distributions on the reals. - */ -public interface ContinuousDistribution { - /** - * For a random variable {@code X} whose values are distributed according - * to this distribution, this method returns {@code P(X = x)}. - * In other words, this method represents the probability mass function - * (PMF) for the distribution. - * - * @param x Point at which the PMF is evaluated. - * @return the value of the probability mass function at point {@code x}. - */ - default double probability(double x) { - return 0; - } - - /** - * For a random variable {@code X} whose values are distributed according - * to this distribution, this method returns {@code P(x0 < X <= x1)}. - * The default implementation uses the identity - * {@code P(x0 < X <= x1) = P(X <= x1) - P(X <= x0)} - * - * @param x0 Lower bound (exclusive). - * @param x1 Upper bound (inclusive). - * @return the probability that a random variable with this distribution - * takes a value between {@code x0} and {@code x1}, excluding the lower - * and including the upper endpoint. - * @throws IllegalArgumentException if {@code x0 > x1}. - */ - default double probability(double x0, - double x1) { - if (x0 > x1) { - throw new DistributionException(DistributionException.TOO_LARGE, x0, x1); - } - return cumulativeProbability(x1) - cumulativeProbability(x0); - } - - /** - * Returns the probability density function (PDF) of this distribution - * evaluated at the specified point {@code x}. - * In general, the PDF is the derivative of the {@link #cumulativeProbability(double) CDF}. - * If the derivative does not exist at {@code x}, then an appropriate - * replacement should be returned, e.g. {@code Double.POSITIVE_INFINITY}, - * {@code Double.NaN}, or the limit inferior or limit superior of the - * difference quotient. - * - * @param x Point at which the PDF is evaluated. - * @return the value of the probability density function at {@code x}. - */ - double density(double x); - - /** - * Returns the natural logarithm of the probability density function - * (PDF) of this distribution evaluated at the specified point {@code x}. - * - * @param x Point at which the PDF is evaluated. - * @return the logarithm of the value of the probability density function - * at {@code x}. - */ - default double logDensity(double x) { - return Math.log(density(x)); - } - - /** - * For a random variable {@code X} whose values are distributed according - * to this distribution, this method returns {@code P(X <= x)}. - * In other words, this method represents the (cumulative) distribution - * function (CDF) for this distribution. - * - * @param x Point at which the CDF is evaluated. - * @return the probability that a random variable with this - * distribution takes a value less than or equal to {@code x}. - */ - double cumulativeProbability(double x); - - /** - * Computes the quantile function of this distribution. For a random - * variable {@code X} distributed according to this distribution, the - * returned value is - *
    - *
  • {@code inf{x in R | P(X<=x) >= p}} for {@code 0 < p <= 1},
  • - *
  • {@code inf{x in R | P(X<=x) > 0}} for {@code p = 0}.
  • - *
- * - * @param p Cumulative probability. - * @return the smallest {@code p}-quantile of this distribution - * (largest 0-quantile for {@code p = 0}). - * @throws IllegalArgumentException if {@code p < 0} or {@code p > 1}. - */ - double inverseCumulativeProbability(double p); - - /** - * Gets the mean of this distribution. - * - * @return the mean, or {@code Double.NaN} if it is not defined. - */ - double getMean(); - - /** - * Gets the variance of this distribution. - * - * @return the variance, or {@code Double.NaN} if it is not defined. - */ - double getVariance(); - - /** - * Gets the lower bound of the support. - * It must return the same value as - * {@code inverseCumulativeProbability(0)}, i.e. - * {@code inf {x in R | P(X <= x) > 0}}. - * - * @return the lower bound of the support. - */ - double getSupportLowerBound(); - - /** - * Gets the upper bound of the support. - * It must return the same - * value as {@code inverseCumulativeProbability(1)}, i.e. - * {@code inf {x in R | P(X <= x) = 1}}. - * - * @return the upper bound of the support. - */ - double getSupportUpperBound(); - - /** - * Indicates whether the support is connected, i.e. whether - * all values between the lower and upper bound of the support - * are included in the support. - * - * @return whether the support is connected. - */ - boolean isSupportConnected(); - - /** - * Creates a sampler. - * - * @param rng Generator of uniformly distributed numbers. - * @return a sampler that produces random numbers according this - * distribution. - */ - Sampler createSampler(UniformRandomProvider rng); - - /** - * Sampling functionality. - */ - interface Sampler { - /** - * Generates a random value sampled from this distribution. - * - * @return a random value. - */ - double sample(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/DiscreteDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/DiscreteDistribution.java deleted file mode 100644 index e2d6cb906..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/DiscreteDistribution.java +++ /dev/null @@ -1,160 +0,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. - */ -package org.apache.commons.statistics.distribution; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Interface for distributions on the integers. - */ -public interface DiscreteDistribution { - - /** - * For a random variable {@code X} whose values are distributed according - * to this distribution, this method returns {@code log(P(X = x))}, where - * {@code log} is the natural logarithm. - * - * @param x Point at which the PMF is evaluated. - * @return the logarithm of the value of the probability mass function at - * {@code x}. - */ - default double logProbability(int x) { - return Math.log(probability(x)); - } - - /** - * For a random variable {@code X} whose values are distributed according - * to this distribution, this method returns {@code P(X = x)}. - * In other words, this method represents the probability mass function (PMF) - * for the distribution. - * - * @param x Point at which the PMF is evaluated. - * @return the value of the probability mass function at {@code x}. - */ - double probability(int x); - - /** - * For a random variable {@code X} whose values are distributed according - * to this distribution, this method returns {@code P(x0 < X <= x1)}. - * - * @param x0 Lower bound (exclusive). - * @param x1 Upper bound (inclusive). - * @return the probability that a random variable with this distribution - * will take a value between {@code x0} and {@code x1}, excluding the lower - * and including the upper endpoint. - * @throws IllegalArgumentException if {@code x0 > x1}. - */ - double probability(int x0, int x1); - - /** - * For a random variable {@code X} whose values are distributed according - * to this distribution, this method returns {@code P(X <= x)}. - * In other, words, this method represents the (cumulative) distribution - * function (CDF) for this distribution. - * - * @param x Point at which the CDF is evaluated. - * @return the probability that a random variable with this distribution - * takes a value less than or equal to {@code x}. - */ - double cumulativeProbability(int x); - - /** - * Computes the quantile function of this distribution. - * For a random variable {@code X} distributed according to this distribution, - * the returned value is - *
    - *
  • {@code inf{x in Z | P(X<=x) >= p}} for {@code 0 < p <= 1},
  • - *
  • {@code inf{x in Z | P(X<=x) > 0}} for {@code p = 0}.
  • - *
- * If the result exceeds the range of the data type {@code int}, - * then {@code Integer.MIN_VALUE} or {@code Integer.MAX_VALUE} is returned. - * - * @param p Cumulative probability. - * @return the smallest {@code p}-quantile of this distribution - * (largest 0-quantile for {@code p = 0}). - * @throws IllegalArgumentException if {@code p < 0} or {@code p > 1}. - */ - int inverseCumulativeProbability(double p); - - /** - * Gets the mean of this distribution. - * - * @return the mean, or {@code Double.NaN} if it is not defined. - */ - double getMean(); - - /** - * Gets the variance of this distribution. - * - * @return the variance, or {@code Double.NaN} if it is not defined. - */ - double getVariance(); - - /** - * Gets the lower bound of the support. - * This method must return the same value as - * {@code inverseCumulativeProbability(0)}, i.e. - * {@code inf {x in Z | P(X <= x) > 0}}. - * By convention, {@code Integer.MIN_VALUE} should be substituted - * for negative infinity. - * - * @return the lower bound of the support. - */ - int getSupportLowerBound(); - - /** - * Gets the upper bound of the support. - * This method must return the same value as - * {@code inverseCumulativeProbability(1)}, i.e. - * {@code inf {x in R | P(X <= x) = 1}}. - * By convention, {@code Integer.MAX_VALUE} should be substituted - * for positive infinity. - * - * @return the upper bound of the support. - */ - int getSupportUpperBound(); - - /** - * Indicates whether the support is connected, i.e. whether all - * integers between the lower and upper bound of the support are - * included in the support. - * - * @return whether the support is connected. - */ - boolean isSupportConnected(); - - /** - * Creates a sampler. - * - * @param rng Generator of uniformly distributed numbers. - * @return a sampler that produces random numbers according this - * distribution. - */ - Sampler createSampler(UniformRandomProvider rng); - - /** - * Sampling functionality. - */ - interface Sampler { - /** - * Generates a random value sampled from this distribution. - * - * @return a random value. - */ - int sample(); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/DistributionException.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/DistributionException.java deleted file mode 100644 index 31d7adcf3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/DistributionException.java +++ /dev/null @@ -1,61 +0,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. - */ -package org.apache.commons.statistics.distribution; - -import java.text.MessageFormat; - -/** - * Package private exception class with constants for frequently used messages. - */ -class DistributionException extends IllegalArgumentException { - /** Error message for "too large" condition. */ - static final String TOO_LARGE = "{0} > {1}"; - /** Error message for "too small" condition. */ - static final String TOO_SMALL = "{0} < {1}"; - /** Error message for "out of range" condition. */ - static final String OUT_OF_RANGE = "Number {0} is out of range [{1}, {2}]"; - /** Error message for "out of range" condition. */ - static final String NEGATIVE = "Number {0} is negative"; - /** Error message for "mismatch" condition. */ - static final String MISMATCH = "Expected {1} but was {0}"; - /** Error message for "failed bracketing" condition. */ - static final String BRACKETING = "No bracketing: f({0})={1}, f({2})={3}"; - - /** Serializable version identifier. */ - private static final long serialVersionUID = 20180119L; - - /** Arguments for formatting the message. */ - private Object[] formatArguments; - - /** - * Create an exception where the message is constructed by applying - * the {@code format()} method from {@code java.text.MessageFormat}. - * - * @param message the exception message with replaceable parameters - * @param formatArguments the arguments for formatting the message - */ - DistributionException(String message, Object... formatArguments) { - super(message); - this.formatArguments = formatArguments; - } - - /** {@inheritDoc} */ - @Override - public String getMessage() { - return MessageFormat.format(super.getMessage(), formatArguments); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ExponentialDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ExponentialDistribution.java deleted file mode 100644 index 942c2d380..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ExponentialDistribution.java +++ /dev/null @@ -1,183 +0,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. - */ -package org.apache.commons.statistics.distribution; - -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.AhrensDieterExponentialSampler; -import org.apache.commons.rng.sampling.distribution.ContinuousSampler; - -/** - * Implementation of the exponential distribution. - */ -public class ExponentialDistribution extends AbstractContinuousDistribution { - /** The mean of this distribution. */ - private final double mean; - /** The logarithm of the mean, stored to reduce computing time. */ - private final double logMean; - - /** - * Creates a distribution. - * - * @param mean Mean of this distribution. - * @throws IllegalArgumentException if {@code mean <= 0}. - */ - public ExponentialDistribution(double mean) { - if (mean <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, mean); - } - this.mean = mean; - logMean = Math.log(mean); - } - - /** {@inheritDoc} */ - @Override - public double density(double x) { - final double logDensity = logDensity(x); - return logDensity == Double.NEGATIVE_INFINITY ? 0 : Math.exp(logDensity); - } - - /** {@inheritDoc} **/ - @Override - public double logDensity(double x) { - if (x < 0) { - return Double.NEGATIVE_INFINITY; - } - return -x / mean - logMean; - } - - /** - * {@inheritDoc} - * - * The implementation of this method is based on: - * - */ - @Override - public double cumulativeProbability(double x) { - double ret; - if (x <= 0) { - ret = 0; - } else { - ret = 1 - Math.exp(-x / mean); - } - return ret; - } - - /** - * {@inheritDoc} - * - * Returns {@code 0} when {@code p= = 0} and - * {@code Double.POSITIVE_INFINITY} when {@code p == 1}. - */ - @Override - public double inverseCumulativeProbability(double p) { - double ret; - - if (p < 0 || - p > 1) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, p, 0, 1); - } else if (p == 1) { - ret = Double.POSITIVE_INFINITY; - } else { - ret = -mean * Math.log(1 - p); - } - - return ret; - } - - /** {@inheritDoc} */ - @Override - public double getMean() { - return mean; - } - - /** - * {@inheritDoc} - * - * For mean parameter {@code k}, the variance is {@code k^2}. - */ - @Override - public double getVariance() { - return mean * mean; - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is always 0 no matter the mean parameter. - * - * @return lower bound of the support (always 0) - */ - @Override - public double getSupportLowerBound() { - return 0; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is always positive infinity - * no matter the mean parameter. - * - * @return upper bound of the support (always Double.POSITIVE_INFINITY) - */ - @Override - public double getSupportUpperBound() { - return Double.POSITIVE_INFINITY; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } - - /** - * {@inheritDoc} - * - *

Sampling algorithm uses the - * - * inversion method to generate exponentially distributed - * random values from uniform deviates. - *

- */ - @Override - public ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng) { - return new ContinuousDistribution.Sampler() { - /** - * Exponential distribution sampler. - */ - private final ContinuousSampler sampler = - new AhrensDieterExponentialSampler(rng, mean); - - /**{@inheritDoc} */ - @Override - public double sample() { - return sampler.sample(); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/FDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/FDistribution.java deleted file mode 100644 index 7f1924847..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/FDistribution.java +++ /dev/null @@ -1,209 +0,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. - */ - -package org.apache.commons.statistics.distribution; - -import org.apache.commons.numbers.gamma.LogBeta; -import org.apache.commons.numbers.gamma.RegularizedBeta; - -/** - * Implementation of the F-distribution. - * - * @see F-distribution (Wikipedia) - * @see F-distribution (MathWorld) - */ -public class FDistribution extends AbstractContinuousDistribution { - /** The numerator degrees of freedom. */ - private final double numeratorDegreesOfFreedom; - /** The numerator degrees of freedom. */ - private final double denominatorDegreesOfFreedom; - - /** - * Creates a distribution. - * - * @param numeratorDegreesOfFreedom Numerator degrees of freedom. - * @param denominatorDegreesOfFreedom Denominator degrees of freedom. - * @throws IllegalArgumentException if {@code numeratorDegreesOfFreedom <= 0} or - * {@code denominatorDegreesOfFreedom <= 0}. - */ - public FDistribution(double numeratorDegreesOfFreedom, - double denominatorDegreesOfFreedom) { - if (numeratorDegreesOfFreedom <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, - numeratorDegreesOfFreedom); - } - if (denominatorDegreesOfFreedom <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, - denominatorDegreesOfFreedom); - } - this.numeratorDegreesOfFreedom = numeratorDegreesOfFreedom; - this.denominatorDegreesOfFreedom = denominatorDegreesOfFreedom; - } - - /** - * {@inheritDoc} - */ - @Override - public double density(double x) { - return Math.exp(logDensity(x)); - } - - /** {@inheritDoc} **/ - @Override - public double logDensity(double x) { - final double nhalf = numeratorDegreesOfFreedom / 2; - final double mhalf = denominatorDegreesOfFreedom / 2; - final double logx = Math.log(x); - final double logn = Math.log(numeratorDegreesOfFreedom); - final double logm = Math.log(denominatorDegreesOfFreedom); - final double lognxm = Math.log(numeratorDegreesOfFreedom * x + - denominatorDegreesOfFreedom); - return nhalf * logn + nhalf * logx - logx + - mhalf * logm - nhalf * lognxm - mhalf * lognxm - - LogBeta.value(nhalf, mhalf); - } - - /** - * {@inheritDoc} - * - * The implementation of this method is based on - * - */ - @Override - public double cumulativeProbability(double x) { - double ret; - if (x <= 0) { - ret = 0; - } else { - double n = numeratorDegreesOfFreedom; - double m = denominatorDegreesOfFreedom; - - ret = RegularizedBeta.value((n * x) / (m + n * x), - 0.5 * n, - 0.5 * m); - } - return ret; - } - - /** - * Access the numerator degrees of freedom. - * - * @return the numerator degrees of freedom. - */ - public double getNumeratorDegreesOfFreedom() { - return numeratorDegreesOfFreedom; - } - - /** - * Access the denominator degrees of freedom. - * - * @return the denominator degrees of freedom. - */ - public double getDenominatorDegreesOfFreedom() { - return denominatorDegreesOfFreedom; - } - - /** - * {@inheritDoc} - * - * For denominator degrees of freedom parameter {@code b}, the mean is - *
    - *
  • if {@code b > 2} then {@code b / (b - 2)},
  • - *
  • else undefined ({@code Double.NaN}). - *
- */ - @Override - public double getMean() { - final double denominatorDF = getDenominatorDegreesOfFreedom(); - - if (denominatorDF > 2) { - return denominatorDF / (denominatorDF - 2); - } - - return Double.NaN; - } - - /** - * {@inheritDoc} - * - * For numerator degrees of freedom parameter {@code a} and denominator - * degrees of freedom parameter {@code b}, the variance is - *
    - *
  • - * if {@code b > 4} then - * {@code [2 * b^2 * (a + b - 2)] / [a * (b - 2)^2 * (b - 4)]}, - *
  • - *
  • else undefined ({@code Double.NaN}). - *
- */ - @Override - public double getVariance() { - final double denominatorDF = getDenominatorDegreesOfFreedom(); - - if (denominatorDF > 4) { - final double numeratorDF = getNumeratorDegreesOfFreedom(); - final double denomDFMinusTwo = denominatorDF - 2; - - return (2 * (denominatorDF * denominatorDF) * (numeratorDF + denominatorDF - 2)) / - ((numeratorDF * (denomDFMinusTwo * denomDFMinusTwo) * (denominatorDF - 4))); - } - - return Double.NaN; - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is always 0 no matter the parameters. - * - * @return lower bound of the support (always 0) - */ - @Override - public double getSupportLowerBound() { - return 0; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is always positive infinity - * no matter the parameters. - * - * @return upper bound of the support (always Double.POSITIVE_INFINITY) - */ - @Override - public double getSupportUpperBound() { - return Double.POSITIVE_INFINITY; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/GammaDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/GammaDistribution.java deleted file mode 100644 index b45ab7cc3..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/GammaDistribution.java +++ /dev/null @@ -1,354 +0,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. - */ -package org.apache.commons.statistics.distribution; - -import org.apache.commons.numbers.gamma.LanczosApproximation; -import org.apache.commons.numbers.gamma.RegularizedGamma; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.AhrensDieterMarsagliaTsangGammaSampler; -import org.apache.commons.rng.sampling.distribution.ContinuousSampler; - -/** - * Implementation of the Gamma distribution. - */ -public class GammaDistribution extends AbstractContinuousDistribution { - /** Lanczos constant. */ - private static final double LANCZOS_G = LanczosApproximation.g(); - /** The shape parameter. */ - private final double shape; - /** The scale parameter. */ - private final double scale; - /** - * The constant value of {@code shape + g + 0.5}, where {@code g} is the - * Lanczos constant {@link LanczosApproximation#g()}. - */ - private final double shiftedShape; - /** - * The constant value of - * {@code shape / scale * sqrt(e / (2 * pi * (shape + g + 0.5))) / L(shape)}, - * where {@code L(shape)} is the Lanczos approximation returned by - * {@link LanczosApproximation#value(double)}. This prefactor is used in - * {@link #density(double)}, when no overflow occurs with the natural - * calculation. - */ - private final double densityPrefactor1; - /** - * The constant value of - * {@code log(shape / scale * sqrt(e / (2 * pi * (shape + g + 0.5))) / L(shape))}, - * where {@code L(shape)} is the Lanczos approximation returned by - * {@link LanczosApproximation#value(double)}. This prefactor is used in - * {@link #logDensity(double)}, when no overflow occurs with the natural - * calculation. - */ - private final double logDensityPrefactor1; - /** - * The constant value of - * {@code shape * sqrt(e / (2 * pi * (shape + g + 0.5))) / L(shape)}, - * where {@code L(shape)} is the Lanczos approximation returned by - * {@link LanczosApproximation#value(double)}. This prefactor is used in - * {@link #density(double)}, when overflow occurs with the natural - * calculation. - */ - private final double densityPrefactor2; - /** - * The constant value of - * {@code log(shape * sqrt(e / (2 * pi * (shape + g + 0.5))) / L(shape))}, - * where {@code L(shape)} is the Lanczos approximation returned by - * {@link LanczosApproximation#value(double)}. This prefactor is used in - * {@link #logDensity(double)}, when overflow occurs with the natural - * calculation. - */ - private final double logDensityPrefactor2; - /** - * Lower bound on {@code y = x / scale} for the selection of the computation - * method in {@link #density(double)}. For {@code y <= minY}, the natural - * calculation overflows. - */ - private final double minY; - /** - * Upper bound on {@code log(y)} ({@code y = x / scale}) for the selection - * of the computation method in {@link #density(double)}. For - * {@code log(y) >= maxLogY}, the natural calculation overflows. - */ - private final double maxLogY; - - /** - * Creates a distribution. - * - * @param shape the shape parameter - * @param scale the scale parameter - * @throws IllegalArgumentException if {@code shape <= 0} or - * {@code scale <= 0}. - */ - public GammaDistribution(double shape, - double scale) { - if (shape <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, shape); - } - if (scale <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, scale); - } - - this.shape = shape; - this.scale = scale; - this.shiftedShape = shape + LANCZOS_G + 0.5; - final double aux = Math.E / (2.0 * Math.PI * shiftedShape); - this.densityPrefactor2 = shape * Math.sqrt(aux) / LanczosApproximation.value(shape); - this.logDensityPrefactor2 = Math.log(shape) + 0.5 * Math.log(aux) - - Math.log(LanczosApproximation.value(shape)); - this.densityPrefactor1 = this.densityPrefactor2 / scale * - Math.pow(shiftedShape, -shape) * // XXX FastMath vs Math - Math.exp(shape + LANCZOS_G); - this.logDensityPrefactor1 = this.logDensityPrefactor2 - Math.log(scale) - - Math.log(shiftedShape) * shape + - shape + LANCZOS_G; - this.minY = shape + LANCZOS_G - Math.log(Double.MAX_VALUE); - this.maxLogY = Math.log(Double.MAX_VALUE) / (shape - 1.0); - } - - /** - * Returns the shape parameter of {@code this} distribution. - * - * @return the shape parameter - */ - public double getShape() { - return shape; - } - - /** - * Returns the scale parameter of {@code this} distribution. - * - * @return the scale parameter - */ - public double getScale() { - return scale; - } - - /** {@inheritDoc} */ - @Override - public double density(double x) { - /* The present method must return the value of - * - * 1 x a - x - * ---------- (-) exp(---) - * x Gamma(a) b b - * - * where a is the shape parameter, and b the scale parameter. - * Substituting the Lanczos approximation of Gamma(a) leads to the - * following expression of the density - * - * a e 1 y a - * - sqrt(------------------) ---- (-----------) exp(a - y + g), - * x 2 pi (a + g + 0.5) L(a) a + g + 0.5 - * - * where y = x / b. The above formula is the "natural" computation, which - * is implemented when no overflow is likely to occur. If overflow occurs - * with the natural computation, the following identity is used. It is - * based on the BOOST library - * http://www.boost.org/doc/libs/1_35_0/libs/math/doc/sf_and_dist/html/math_toolkit/special/sf_gamma/igamma.html - * Formula (15) needs adaptations, which are detailed below. - * - * y a - * (-----------) exp(a - y + g) - * a + g + 0.5 - * y - a - g - 0.5 y (g + 0.5) - * = exp(a log1pm(---------------) - ----------- + g), - * a + g + 0.5 a + g + 0.5 - * - * where log1pm(z) = log(1 + z) - z. Therefore, the value to be - * returned is - * - * a e 1 - * - sqrt(------------------) ---- - * x 2 pi (a + g + 0.5) L(a) - * y - a - g - 0.5 y (g + 0.5) - * * exp(a log1pm(---------------) - ----------- + g). - * a + g + 0.5 a + g + 0.5 - */ - if (x < 0) { - return 0; - } - final double y = x / scale; - if ((y <= minY) || (Math.log(y) >= maxLogY)) { - /* - * Overflow. - */ - final double aux1 = (y - shiftedShape) / shiftedShape; - final double aux2 = shape * (Math.log1p(aux1) - aux1); // XXX FastMath vs Math - final double aux3 = -y * (LANCZOS_G + 0.5) / shiftedShape + LANCZOS_G + aux2; - return densityPrefactor2 / x * Math.exp(aux3); - } - /* - * Natural calculation. - */ - return densityPrefactor1 * Math.exp(-y) * Math.pow(y, shape - 1); - } - - /** {@inheritDoc} **/ - @Override - public double logDensity(double x) { - /* - * see the comment in {@link #density(double)} for computation details - */ - if (x < 0) { - return Double.NEGATIVE_INFINITY; - } - final double y = x / scale; - if ((y <= minY) || (Math.log(y) >= maxLogY)) { - /* - * Overflow. - */ - final double aux1 = (y - shiftedShape) / shiftedShape; - final double aux2 = shape * (Math.log1p(aux1) - aux1); - final double aux3 = -y * (LANCZOS_G + 0.5) / shiftedShape + LANCZOS_G + aux2; - return logDensityPrefactor2 - Math.log(x) + aux3; - } - /* - * Natural calculation. - */ - return logDensityPrefactor1 - y + Math.log(y) * (shape - 1); - } - - /** - * {@inheritDoc} - * - * The implementation of this method is based on: - *
    - *
  • - * - * Chi-Squared Distribution, equation (9). - *
  • - *
  • Casella, G., & Berger, R. (1990). Statistical Inference. - * Belmont, CA: Duxbury Press. - *
  • - *
- */ - @Override - public double cumulativeProbability(double x) { - double ret; - - if (x <= 0) { - ret = 0; - } else { - ret = RegularizedGamma.P.value(shape, x / scale); - } - - return ret; - } - - /** - * {@inheritDoc} - * - * For shape parameter {@code alpha} and scale parameter {@code beta}, the - * mean is {@code alpha * beta}. - */ - @Override - public double getMean() { - return shape * scale; - } - - /** - * {@inheritDoc} - * - * For shape parameter {@code alpha} and scale parameter {@code beta}, the - * variance is {@code alpha * beta^2}. - * - * @return {@inheritDoc} - */ - @Override - public double getVariance() { - return shape * scale * scale; - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is always 0 no matter the parameters. - * - * @return lower bound of the support (always 0) - */ - @Override - public double getSupportLowerBound() { - return 0; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is always positive infinity - * no matter the parameters. - * - * @return upper bound of the support (always Double.POSITIVE_INFINITY) - */ - @Override - public double getSupportUpperBound() { - return Double.POSITIVE_INFINITY; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } - - /** - * {@inheritDoc} - * - *

- * Sampling algorithms: - *

    - *
  • - * For {@code 0 < shape < 1}: - *
    - * Ahrens, J. H. and Dieter, U., - * Computer methods for sampling from gamma, beta, Poisson and binomial distributions, - * Computing, 12, 223-246, 1974. - *
    - *
  • - *
  • - * For {@code shape >= 1}: - *
    - * Marsaglia and Tsang, A Simple Method for Generating - * Gamma Variables. ACM Transactions on Mathematical Software, - * Volume 26 Issue 3, September, 2000. - *
    - *
  • - *
- */ - @Override - public ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng) { - return new ContinuousDistribution.Sampler() { - /** - * Gamma distribution sampler. - */ - private final ContinuousSampler sampler = - new AhrensDieterMarsagliaTsangGammaSampler(rng, scale, shape); - - /**{@inheritDoc} */ - @Override - public double sample() { - return sampler.sample(); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/GeometricDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/GeometricDistribution.java deleted file mode 100644 index 0f8876f62..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/GeometricDistribution.java +++ /dev/null @@ -1,160 +0,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. - */ -package org.apache.commons.statistics.distribution; - -/** - * Implementation of the geometric distribution. - */ -public class GeometricDistribution extends AbstractDiscreteDistribution { - /** The probability of success. */ - private final double probabilityOfSuccess; - /** {@code log(p)} where p is the probability of success. */ - private final double logProbabilityOfSuccess; - /** {@code log(1 - p)} where p is the probability of success. */ - private final double log1mProbabilityOfSuccess; - - /** - * Creates a geometric distribution. - * - * @param p Probability of success. - * @throws IllegalArgumentException if {@code p <= 0} or {@code p > 1}. - */ - public GeometricDistribution(double p) { - if (p <= 0 || p > 1) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, p, 0, 1); - } - - probabilityOfSuccess = p; - logProbabilityOfSuccess = Math.log(p); - log1mProbabilityOfSuccess = Math.log1p(-p); - } - - /** - * Access the probability of success for this distribution. - * - * @return the probability of success. - */ - public double getProbabilityOfSuccess() { - return probabilityOfSuccess; - } - - /** {@inheritDoc} */ - @Override - public double probability(int x) { - if (x < 0) { - return 0.0; - } else { - return Math.exp(log1mProbabilityOfSuccess * x) * probabilityOfSuccess; - } - } - - /** {@inheritDoc} */ - @Override - public double logProbability(int x) { - if (x < 0) { - return Double.NEGATIVE_INFINITY; - } else { - return x * log1mProbabilityOfSuccess + logProbabilityOfSuccess; - } - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(int x) { - if (x < 0) { - return 0.0; - } else { - return -Math.expm1(log1mProbabilityOfSuccess * (x + 1)); - } - } - - /** - * {@inheritDoc} - * - * For probability parameter {@code p}, the mean is {@code (1 - p) / p}. - */ - @Override - public double getMean() { - return (1 - probabilityOfSuccess) / probabilityOfSuccess; - } - - /** - * {@inheritDoc} - * - * For probability parameter {@code p}, the variance is - * {@code (1 - p) / (p * p)}. - */ - @Override - public double getVariance() { - return (1 - probabilityOfSuccess) / (probabilityOfSuccess * probabilityOfSuccess); - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is always 0. - * - * @return lower bound of the support (always 0) - */ - @Override - public int getSupportLowerBound() { - return 0; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is infinite (which we approximate as - * {@code Integer.MAX_VALUE}). - * - * @return upper bound of the support (always Integer.MAX_VALUE) - */ - @Override - public int getSupportUpperBound() { - return Integer.MAX_VALUE; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public int inverseCumulativeProbability(double p) { - if (p < 0 || - p > 1) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, p, 0, 1); - } - if (p == 1) { - return Integer.MAX_VALUE; - } - if (p == 0) { - return 0; - } - return Math.max(0, (int) Math.ceil(Math.log1p(-p)/log1mProbabilityOfSuccess-1)); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/GumbelDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/GumbelDistribution.java deleted file mode 100644 index 5c7185544..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/GumbelDistribution.java +++ /dev/null @@ -1,128 +0,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. - */ -package org.apache.commons.statistics.distribution; - -/** - * This class implements the Gumbel distribution. - */ -public class GumbelDistribution extends AbstractContinuousDistribution { - /** π2/6. */ - private static final double PI_SQUARED_OVER_SIX = Math.PI * Math.PI / 6; - /** - * - * Approximation of Euler's constant. - */ - private static final double EULER = Math.PI / (2 * Math.E); - /** Location parameter. */ - private final double mu; - /** Scale parameter. */ - private final double beta; - - /** - * Creates a distribution. - * - * @param mu location parameter - * @param beta scale parameter (must be positive) - * @throws IllegalArgumentException if {@code beta <= 0} - */ - public GumbelDistribution(double mu, - double beta) { - if (beta <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, beta); - } - - this.beta = beta; - this.mu = mu; - } - - /** - * Gets the location parameter. - * - * @return the location parameter. - */ - public double getLocation() { - return mu; - } - - /** - * Gets the scale parameter. - * - * @return the scale parameter. - */ - public double getScale() { - return beta; - } - - /** {@inheritDoc} */ - @Override - public double density(double x) { - final double z = (x - mu) / beta; - final double t = Math.exp(-z); - return Math.exp(-z - t) / beta; - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(double x) { - final double z = (x - mu) / beta; - return Math.exp(-Math.exp(-z)); - } - - /** {@inheritDoc} */ - @Override - public double inverseCumulativeProbability(double p) { - if (p < 0 || p > 1) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, p, 0, 1); - } else if (p == 0) { - return Double.NEGATIVE_INFINITY; - } else if (p == 1) { - return Double.POSITIVE_INFINITY; - } - return mu - Math.log(-Math.log(p)) * beta; - } - - /** {@inheritDoc} */ - @Override - public double getMean() { - return mu + EULER * beta; - } - - /** {@inheritDoc} */ - @Override - public double getVariance() { - return PI_SQUARED_OVER_SIX * beta * beta; - } - - /** {@inheritDoc} */ - @Override - public double getSupportLowerBound() { - return Double.NEGATIVE_INFINITY; - } - - /** {@inheritDoc} */ - @Override - public double getSupportUpperBound() { - return Double.POSITIVE_INFINITY; - } - - /** {@inheritDoc} */ - @Override - public boolean isSupportConnected() { - return true; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/HypergeometricDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/HypergeometricDistribution.java deleted file mode 100644 index d2bdbb0d7..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/HypergeometricDistribution.java +++ /dev/null @@ -1,293 +0,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. - */ - -package org.apache.commons.statistics.distribution; - -/** - * Implementation of the hypergeometric distribution. - */ -public class HypergeometricDistribution extends AbstractDiscreteDistribution { - /** The number of successes in the population. */ - private final int numberOfSuccesses; - /** The population size. */ - private final int populationSize; - /** The sample size. */ - private final int sampleSize; - - /** - * Creates a new hypergeometric distribution. - * - * @param populationSize Population size. - * @param numberOfSuccesses Number of successes in the population. - * @param sampleSize Sample size. - * @throws IllegalArgumentException if {@code numberOfSuccesses < 0}, or - * {@code populationSize <= 0} or {@code numberOfSuccesses > populationSize}, - * or {@code sampleSize > populationSize}. - */ - public HypergeometricDistribution(int populationSize, - int numberOfSuccesses, - int sampleSize) { - if (populationSize <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, - populationSize); - } - if (numberOfSuccesses < 0) { - throw new DistributionException(DistributionException.NEGATIVE, - numberOfSuccesses); - } - if (sampleSize < 0) { - throw new DistributionException(DistributionException.NEGATIVE, - sampleSize); - } - - if (numberOfSuccesses > populationSize) { - throw new DistributionException(DistributionException.TOO_LARGE, - numberOfSuccesses, populationSize); - } - if (sampleSize > populationSize) { - throw new DistributionException(DistributionException.TOO_LARGE, - sampleSize, populationSize); - } - - this.numberOfSuccesses = numberOfSuccesses; - this.populationSize = populationSize; - this.sampleSize = sampleSize; - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(int x) { - double ret; - - int[] domain = getDomain(populationSize, numberOfSuccesses, sampleSize); - if (x < domain[0]) { - ret = 0.0; - } else if (x >= domain[1]) { - ret = 1.0; - } else { - ret = innerCumulativeProbability(domain[0], x, 1); - } - - return ret; - } - - /** - * Return the domain for the given hypergeometric distribution parameters. - * - * @param n Population size. - * @param m Number of successes in the population. - * @param k Sample size. - * @return a two element array containing the lower and upper bounds of the - * hypergeometric distribution. - */ - private int[] getDomain(int n, int m, int k) { - return new int[] { getLowerDomain(n, m, k), getUpperDomain(m, k) }; - } - - /** - * Return the lowest domain value for the given hypergeometric distribution - * parameters. - * - * @param n Population size. - * @param m Number of successes in the population. - * @param k Sample size. - * @return the lowest domain value of the hypergeometric distribution. - */ - private int getLowerDomain(int n, int m, int k) { - return Math.max(0, m - (n - k)); - } - - /** - * Access the number of successes. - * - * @return the number of successes. - */ - public int getNumberOfSuccesses() { - return numberOfSuccesses; - } - - /** - * Access the population size. - * - * @return the population size. - */ - public int getPopulationSize() { - return populationSize; - } - - /** - * Access the sample size. - * - * @return the sample size. - */ - public int getSampleSize() { - return sampleSize; - } - - /** - * Return the highest domain value for the given hypergeometric distribution - * parameters. - * - * @param m Number of successes in the population. - * @param k Sample size. - * @return the highest domain value of the hypergeometric distribution. - */ - private int getUpperDomain(int m, int k) { - return Math.min(k, m); - } - - /** {@inheritDoc} */ - @Override - public double probability(int x) { - final double logProbability = logProbability(x); - return logProbability == Double.NEGATIVE_INFINITY ? 0 : Math.exp(logProbability); - } - - /** {@inheritDoc} */ - @Override - public double logProbability(int x) { - double ret; - - int[] domain = getDomain(populationSize, numberOfSuccesses, sampleSize); - if (x < domain[0] || x > domain[1]) { - ret = Double.NEGATIVE_INFINITY; - } else { - double p = (double) sampleSize / (double) populationSize; - double q = (double) (populationSize - sampleSize) / (double) populationSize; - double p1 = SaddlePointExpansion.logBinomialProbability(x, - numberOfSuccesses, p, q); - double p2 = - SaddlePointExpansion.logBinomialProbability(sampleSize - x, - populationSize - numberOfSuccesses, p, q); - double p3 = - SaddlePointExpansion.logBinomialProbability(sampleSize, populationSize, p, q); - ret = p1 + p2 - p3; - } - - return ret; - } - - /** - * For this distribution, {@code X}, this method returns {@code P(X >= x)}. - * - * @param x Value at which the CDF is evaluated. - * @return the upper tail CDF for this distribution. - * @since 1.1 - */ - public double upperCumulativeProbability(int x) { - double ret; - - final int[] domain = getDomain(populationSize, numberOfSuccesses, sampleSize); - if (x <= domain[0]) { - ret = 1.0; - } else if (x > domain[1]) { - ret = 0.0; - } else { - ret = innerCumulativeProbability(domain[1], x, -1); - } - - return ret; - } - - /** - * For this distribution, {@code X}, this method returns - * {@code P(x0 <= X <= x1)}. - * This probability is computed by summing the point probabilities for the - * values {@code x0, x0 + 1, x0 + 2, ..., x1}, in the order directed by - * {@code dx}. - * - * @param x0 Inclusive lower bound. - * @param x1 Inclusive upper bound. - * @param dx Direction of summation (1 indicates summing from x0 to x1, and - * 0 indicates summing from x1 to x0). - * @return {@code P(x0 <= X <= x1)}. - */ - private double innerCumulativeProbability(int x0, int x1, int dx) { - double ret = probability(x0); - while (x0 != x1) { - x0 += dx; - ret += probability(x0); - } - return ret; - } - - /** - * {@inheritDoc} - * - * For population size {@code N}, number of successes {@code m}, and sample - * size {@code n}, the mean is {@code n * m / N}. - */ - @Override - public double getMean() { - return getSampleSize() * (getNumberOfSuccesses() / (double) getPopulationSize()); - } - - /** - * {@inheritDoc} - * - * For population size {@code N}, number of successes {@code m}, and sample - * size {@code n}, the variance is - * {@code (n * m * (N - n) * (N - m)) / (N^2 * (N - 1))}. - */ - @Override - public double getVariance() { - final double N = getPopulationSize(); - final double m = getNumberOfSuccesses(); - final double n = getSampleSize(); - return (n * m * (N - n) * (N - m)) / (N * N * (N - 1)); - } - - /** - * {@inheritDoc} - * - * For population size {@code N}, number of successes {@code m}, and sample - * size {@code n}, the lower bound of the support is - * {@code max(0, n + m - N)}. - * - * @return lower bound of the support - */ - @Override - public int getSupportLowerBound() { - return Math.max(0, - getSampleSize() + getNumberOfSuccesses() - getPopulationSize()); - } - - /** - * {@inheritDoc} - * - * For number of successes {@code m} and sample size {@code n}, the upper - * bound of the support is {@code min(m, n)}. - * - * @return upper bound of the support - */ - @Override - public int getSupportUpperBound() { - return Math.min(getNumberOfSuccesses(), getSampleSize()); - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/LaplaceDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/LaplaceDistribution.java deleted file mode 100644 index 15c67f94f..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/LaplaceDistribution.java +++ /dev/null @@ -1,132 +0,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. - */ -package org.apache.commons.statistics.distribution; - -/** - * This class implements the Laplace distribution. - * - * @see Laplace distribution (Wikipedia) - * - * @since 3.4 - */ -public class LaplaceDistribution extends AbstractContinuousDistribution { - - /** Serializable version identifier. */ - private static final long serialVersionUID = 20160311L; - - /** The location parameter. */ - private final double mu; - /** The scale parameter. */ - private final double beta; - - /** - * Creates a distribution. - * - * @param mu location parameter - * @param beta scale parameter (must be positive) - * @throws IllegalArgumentException if {@code beta <= 0} - */ - public LaplaceDistribution(double mu, - double beta) { - if (beta <= 0.0) { - throw new DistributionException(DistributionException.NEGATIVE, beta); - } - - this.mu = mu; - this.beta = beta; - } - - /** - * Access the location parameter, {@code mu}. - * - * @return the location parameter. - */ - public double getLocation() { - return mu; - } - - /** - * Access the scale parameter, {@code beta}. - * - * @return the scale parameter. - */ - public double getScale() { - return beta; - } - - /** {@inheritDoc} */ - @Override - public double density(double x) { - return Math.exp(-Math.abs(x - mu) / beta) / (2.0 * beta); - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(double x) { - if (x <= mu) { - return Math.exp((x - mu) / beta) / 2.0; - } else { - return 1.0 - Math.exp((mu - x) / beta) / 2.0; - } - } - - /** {@inheritDoc} */ - @Override - public double inverseCumulativeProbability(double p) { - if (p < 0 || - p > 1) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, p, 0, 1); - } else if (p == 0) { - return Double.NEGATIVE_INFINITY; - } else if (p == 1) { - return Double.POSITIVE_INFINITY; - } - double x = (p > 0.5) ? -Math.log(2.0 - 2.0 * p) : Math.log(2.0 * p); - return mu + beta * x; - } - - /** {@inheritDoc} */ - @Override - public double getMean() { - return mu; - } - - /** {@inheritDoc} */ - @Override - public double getVariance() { - return 2.0 * beta * beta; - } - - /** {@inheritDoc} */ - @Override - public double getSupportLowerBound() { - return Double.NEGATIVE_INFINITY; - } - - /** {@inheritDoc} */ - @Override - public double getSupportUpperBound() { - return Double.POSITIVE_INFINITY; - } - - /** {@inheritDoc} */ - @Override - public boolean isSupportConnected() { - return true; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/LevyDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/LevyDistribution.java deleted file mode 100644 index c61d6da38..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/LevyDistribution.java +++ /dev/null @@ -1,161 +0,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. - */ -package org.apache.commons.statistics.distribution; - -import org.apache.commons.numbers.gamma.Erfc; -import org.apache.commons.numbers.gamma.InverseErfc; - -/** - * This class implements the - * Lévy distribution. - */ -public class LevyDistribution extends AbstractContinuousDistribution { - /** Location parameter. */ - private final double mu; - /** Scale parameter. */ - private final double c; - /** Half of c (for calculations). */ - private final double halfC; - - /** - * Creates a distribution. - * - * @param mu location - * @param c scale parameter - */ - public LevyDistribution(final double mu, - final double c) { - this.mu = mu; - this.c = c; - this.halfC = 0.5 * c; - } - - /** {@inheritDoc} - *

- * From Wikipedia: The probability density function of the Lévy distribution - * over the domain is - *

- *
- * f(x; μ, c) = √(c / 2π) * e-c / 2 (x - μ) / (x - μ)3/2 - *
- *

- * For this distribution, {@code X}, this method returns {@code P(X < x)}. - * If {@code x} is less than location parameter μ, {@code Double.NaN} is - * returned, as in these cases the distribution is not defined. - *

- */ - @Override - public double density(final double x) { - if (x < mu) { - return Double.NaN; - } - - final double delta = x - mu; - final double f = halfC / delta; - return Math.sqrt(f / Math.PI) * Math.exp(-f) /delta; - } - - /** {@inheritDoc} - * - * See documentation of {@link #density(double)} for computation details. - */ - @Override - public double logDensity(double x) { - if (x < mu) { - return Double.NaN; - } - - final double delta = x - mu; - final double f = halfC / delta; - return 0.5 * Math.log(f / Math.PI) - f - Math.log(delta); - } - - /** {@inheritDoc} - *

- * From Wikipedia: the cumulative distribution function is - *

- *
-     * f(x; u, c) = erfc (√ (c / 2 (x - u )))
-     * 
- */ - @Override - public double cumulativeProbability(final double x) { - if (x < mu) { - return Double.NaN; - } - return Erfc.value(Math.sqrt(halfC / (x - mu))); - } - - /** {@inheritDoc} */ - @Override - public double inverseCumulativeProbability(final double p) { - if (p < 0 || - p > 1) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, p, 0, 1); - } - final double t = InverseErfc.value(p); - return mu + halfC / (t * t); - } - - /** - * Gets the scale parameter of the distribution. - * - * @return scale parameter of the distribution - */ - public double getScale() { - return c; - } - - /** - * Gets the location parameter of the distribution. - * - * @return location parameter of the distribution - */ - public double getLocation() { - return mu; - } - - /** {@inheritDoc} */ - @Override - public double getMean() { - return Double.POSITIVE_INFINITY; - } - - /** {@inheritDoc} */ - @Override - public double getVariance() { - return Double.POSITIVE_INFINITY; - } - - /** {@inheritDoc} */ - @Override - public double getSupportLowerBound() { - return mu; - } - - /** {@inheritDoc} */ - @Override - public double getSupportUpperBound() { - return Double.POSITIVE_INFINITY; - } - - /** {@inheritDoc} */ - @Override - public boolean isSupportConnected() { - return true; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/LogNormalDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/LogNormalDistribution.java deleted file mode 100644 index 935c42148..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/LogNormalDistribution.java +++ /dev/null @@ -1,255 +0,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. - */ - -package org.apache.commons.statistics.distribution; - -import org.apache.commons.numbers.gamma.Erf; -import org.apache.commons.numbers.gamma.ErfDifference; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.ContinuousSampler; -import org.apache.commons.rng.sampling.distribution.LogNormalSampler; -import org.apache.commons.rng.sampling.distribution.ZigguratNormalizedGaussianSampler; - -/** - * Implementation of the log-normal distribution. - * - *

- * Parameters: - * {@code X} is log-normally distributed if its natural logarithm {@code log(X)} - * is normally distributed. The probability distribution function of {@code X} - * is given by (for {@code x > 0}) - *

- *

- * {@code exp(-0.5 * ((ln(x) - m) / s)^2) / (s * sqrt(2 * pi) * x)} - *

- *
    - *
  • {@code m} is the scale parameter: this is the mean of the - * normally distributed natural logarithm of this distribution,
  • - *
  • {@code s} is the shape parameter: this is the standard - * deviation of the normally distributed natural logarithm of this - * distribution. - *
- */ -public class LogNormalDistribution extends AbstractContinuousDistribution { - /** √(2 π) */ - private static final double SQRT2PI = Math.sqrt(2 * Math.PI); - /** √(2) */ - private static final double SQRT2 = Math.sqrt(2); - /** The scale parameter of this distribution. */ - private final double scale; - /** The shape parameter of this distribution. */ - private final double shape; - /** The value of {@code log(shape) + 0.5 * log(2*PI)} stored for faster computation. */ - private final double logShapePlusHalfLog2Pi; - - /** - * Creates a log-normal distribution. - * - * @param scale Scale parameter of this distribution. - * @param shape Shape parameter of this distribution. - * @throws IllegalArgumentException if {@code shape <= 0}. - */ - public LogNormalDistribution(double scale, - double shape) { - if (shape <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, shape); - } - - this.scale = scale; - this.shape = shape; - this.logShapePlusHalfLog2Pi = Math.log(shape) + 0.5 * Math.log(2 * Math.PI); - } - - /** - * Returns the scale parameter of this distribution. - * - * @return the scale parameter - */ - public double getScale() { - return scale; - } - - /** - * Returns the shape parameter of this distribution. - * - * @return the shape parameter - */ - public double getShape() { - return shape; - } - - /** - * {@inheritDoc} - * - * For scale {@code m}, and shape {@code s} of this distribution, the PDF - * is given by - *
    - *
  • {@code 0} if {@code x <= 0},
  • - *
  • {@code exp(-0.5 * ((ln(x) - m) / s)^2) / (s * sqrt(2 * pi) * x)} - * otherwise.
  • - *
- */ - @Override - public double density(double x) { - if (x <= 0) { - return 0; - } - final double x0 = Math.log(x) - scale; - final double x1 = x0 / shape; - return Math.exp(-0.5 * x1 * x1) / (shape * SQRT2PI * x); - } - - /** {@inheritDoc} - * - * See documentation of {@link #density(double)} for computation details. - */ - @Override - public double logDensity(double x) { - if (x <= 0) { - return Double.NEGATIVE_INFINITY; - } - final double logX = Math.log(x); - final double x0 = logX - scale; - final double x1 = x0 / shape; - return -0.5 * x1 * x1 - (logShapePlusHalfLog2Pi + logX); - } - - /** - * {@inheritDoc} - * - * For scale {@code m}, and shape {@code s} of this distribution, the CDF - * is given by - *
    - *
  • {@code 0} if {@code x <= 0},
  • - *
  • {@code 0} if {@code ln(x) - m < 0} and {@code m - ln(x) > 40 * s}, as - * in these cases the actual value is within {@code Double.MIN_VALUE} of 0, - *
  • {@code 1} if {@code ln(x) - m >= 0} and {@code ln(x) - m > 40 * s}, - * as in these cases the actual value is within {@code Double.MIN_VALUE} of - * 1,
  • - *
  • {@code 0.5 + 0.5 * erf((ln(x) - m) / (s * sqrt(2))} otherwise.
  • - *
- */ - @Override - public double cumulativeProbability(double x) { - if (x <= 0) { - return 0; - } - final double dev = Math.log(x) - scale; - if (Math.abs(dev) > 40 * shape) { - return dev < 0 ? 0.0d : 1.0d; - } - return 0.5 + 0.5 * Erf.value(dev / (shape * SQRT2)); - } - - /** {@inheritDoc} */ - @Override - public double probability(double x0, - double x1) { - if (x0 > x1) { - throw new DistributionException(DistributionException.TOO_LARGE, - x0, x1); - } - if (x0 <= 0 || x1 <= 0) { - return super.probability(x0, x1); - } - final double denom = shape * SQRT2; - final double v0 = (Math.log(x0) - scale) / denom; - final double v1 = (Math.log(x1) - scale) / denom; - return 0.5 * ErfDifference.value(v0, v1); - } - - /** - * {@inheritDoc} - * - * For scale {@code m} and shape {@code s}, the mean is - * {@code exp(m + s^2 / 2)}. - */ - @Override - public double getMean() { - double s = shape; - return Math.exp(scale + (s * s / 2)); - } - - /** - * {@inheritDoc} - * - * For scale {@code m} and shape {@code s}, the variance is - * {@code (exp(s^2) - 1) * exp(2 * m + s^2)}. - */ - @Override - public double getVariance() { - final double s = shape; - final double ss = s * s; - return (Math.expm1(ss)) * Math.exp(2 * scale + ss); - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is always 0 no matter the parameters. - * - * @return lower bound of the support (always 0) - */ - @Override - public double getSupportLowerBound() { - return 0; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is always positive infinity - * no matter the parameters. - * - * @return upper bound of the support (always - * {@code Double.POSITIVE_INFINITY}) - */ - @Override - public double getSupportUpperBound() { - return Double.POSITIVE_INFINITY; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } - - /** {@inheritDoc} */ - @Override - public ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng) { - return new ContinuousDistribution.Sampler() { - /** - * Log normal distribution sampler. - */ - private final ContinuousSampler sampler = - new LogNormalSampler(new ZigguratNormalizedGaussianSampler(rng), scale, shape); - - /**{@inheritDoc} */ - @Override - public double sample() { - return sampler.sample(); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/LogisticDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/LogisticDistribution.java deleted file mode 100644 index ecf9efb31..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/LogisticDistribution.java +++ /dev/null @@ -1,128 +0,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. - */ -package org.apache.commons.statistics.distribution; - -/** - * Implementation of the Logistic distribution. - */ -public class LogisticDistribution extends AbstractContinuousDistribution { - /** π2/3. */ - private static final double PI_SQUARED_OVER_THREE = Math.PI * Math.PI / 3; - /** Location parameter. */ - private final double mu; - /** Scale parameter. */ - private final double scale; - /** Inverse of "scale". */ - private final double oneOverScale; - - /** - * Creates a distribution. - * - * @param mu Location parameter. - * @param scale Scale parameter (must be positive). - * @throws IllegalArgumentException if {@code scale <= 0}. - */ - public LogisticDistribution(double mu, - double scale) { - if (scale <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, - scale); - } - - this.mu = mu; - this.scale = scale; - this.oneOverScale = 1 / scale; - } - - /** - * Gets the location parameter. - * - * @return the location parameter. - */ - public double getLocation() { - return mu; - } - - /** - * Gets the scale parameter. - * - * @return the scale parameter. - */ - public double getScale() { - return scale; - } - - /** {@inheritDoc} */ - @Override - public double density(double x) { - final double z = oneOverScale * (x - mu); - final double v = Math.exp(-z); - return oneOverScale * v / ((1 + v) * (1 + v)); - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(double x) { - final double z = oneOverScale * (x - mu); - return 1 / (1 + Math.exp(-z)); - } - - /** {@inheritDoc} */ - @Override - public double inverseCumulativeProbability(double p) { - if (p < 0 || - p > 1) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, p, 0, 1); - } else if (p == 0) { - return 0; - } else if (p == 1) { - return Double.POSITIVE_INFINITY; - } else { - return scale * Math.log(p / (1 - p)) + mu; - } - } - - /** {@inheritDoc} */ - @Override - public double getMean() { - return mu; - } - - /** {@inheritDoc} */ - @Override - public double getVariance() { - return oneOverScale * oneOverScale * PI_SQUARED_OVER_THREE; - } - - /** {@inheritDoc} */ - @Override - public double getSupportLowerBound() { - return Double.NEGATIVE_INFINITY; - } - - /** {@inheritDoc} */ - @Override - public double getSupportUpperBound() { - return Double.POSITIVE_INFINITY; - } - - /** {@inheritDoc} */ - @Override - public boolean isSupportConnected() { - return true; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/NakagamiDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/NakagamiDistribution.java deleted file mode 100644 index ab94bb80b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/NakagamiDistribution.java +++ /dev/null @@ -1,117 +0,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. - */ -package org.apache.commons.statistics.distribution; - -import org.apache.commons.numbers.gamma.Gamma; -import org.apache.commons.numbers.gamma.RegularizedGamma; - -/** - * This class implements the Nakagami distribution. - */ -public class NakagamiDistribution extends AbstractContinuousDistribution { - /** The shape parameter. */ - private final double mu; - /** The scale parameter. */ - private final double omega; - - /** - * Creates a distribution. - * - * @param mu shape parameter - * @param omega scale parameter (must be positive) - * @throws IllegalArgumentException if {@code mu < 0.5} or if - * {@code omega <= 0}. - */ - public NakagamiDistribution(double mu, - double omega) { - if (mu < 0.5) { - throw new DistributionException(DistributionException.TOO_SMALL, mu, 0.5); - } - if (omega <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, omega); - } - - this.mu = mu; - this.omega = omega; - } - - /** - * Access the shape parameter, {@code mu}. - * - * @return the shape parameter. - */ - public double getShape() { - return mu; - } - - /** - * Access the scale parameter, {@code omega}. - * - * @return the scale parameter. - */ - public double getScale() { - return omega; - } - - /** {@inheritDoc} */ - @Override - public double density(double x) { - if (x <= 0) { - return 0.0; - } - return 2.0 * Math.pow(mu, mu) / (Gamma.value(mu) * Math.pow(omega, mu)) * - Math.pow(x, 2 * mu - 1) * Math.exp(-mu * x * x / omega); - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(double x) { - return RegularizedGamma.P.value(mu, mu * x * x / omega); - } - - /** {@inheritDoc} */ - @Override - public double getMean() { - return Gamma.value(mu + 0.5) / Gamma.value(mu) * Math.sqrt(omega / mu); - } - - /** {@inheritDoc} */ - @Override - public double getVariance() { - double v = Gamma.value(mu + 0.5) / Gamma.value(mu); - return omega * (1 - 1 / mu * v * v); - } - - /** {@inheritDoc} */ - @Override - public double getSupportLowerBound() { - return 0; - } - - /** {@inheritDoc} */ - @Override - public double getSupportUpperBound() { - return Double.POSITIVE_INFINITY; - } - - /** {@inheritDoc} */ - @Override - public boolean isSupportConnected() { - return true; - } - -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/NormalDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/NormalDistribution.java deleted file mode 100644 index 7b37b5e0e..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/NormalDistribution.java +++ /dev/null @@ -1,195 +0,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. - */ - -package org.apache.commons.statistics.distribution; - -import org.apache.commons.numbers.gamma.ErfDifference; -import org.apache.commons.numbers.gamma.Erfc; -import org.apache.commons.numbers.gamma.InverseErf; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.ContinuousSampler; -import org.apache.commons.rng.sampling.distribution.GaussianSampler; -import org.apache.commons.rng.sampling.distribution.ZigguratNormalizedGaussianSampler; - -/** - * Implementation of the normal (Gaussian) distribution. - */ -public class NormalDistribution extends AbstractContinuousDistribution { - /** √(2) */ - private static final double SQRT2 = Math.sqrt(2.0); - /** Mean of this distribution. */ - private final double mean; - /** Standard deviation of this distribution. */ - private final double standardDeviation; - /** The value of {@code log(sd) + 0.5*log(2*pi)} stored for faster computation. */ - private final double logStandardDeviationPlusHalfLog2Pi; - - /** - * Creates a distribution. - * - * @param mean Mean for this distribution. - * @param sd Standard deviation for this distribution. - * @throws IllegalArgumentException if {@code sd <= 0}. - */ - public NormalDistribution(double mean, - double sd) { - if (sd <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, sd); - } - - this.mean = mean; - standardDeviation = sd; - logStandardDeviationPlusHalfLog2Pi = Math.log(sd) + 0.5 * Math.log(2 * Math.PI); - } - - /** - * Access the standard deviation. - * - * @return the standard deviation for this distribution. - */ - public double getStandardDeviation() { - return standardDeviation; - } - - /** {@inheritDoc} */ - @Override - public double density(double x) { - return Math.exp(logDensity(x)); - } - - /** {@inheritDoc} */ - @Override - public double logDensity(double x) { - final double x0 = x - mean; - final double x1 = x0 / standardDeviation; - return -0.5 * x1 * x1 - logStandardDeviationPlusHalfLog2Pi; - } - - /** - * {@inheritDoc} - * - * If {@code x} is more than 40 standard deviations from the mean, 0 or 1 - * is returned, as in these cases the actual value is within - * {@code Double.MIN_VALUE} of 0 or 1. - */ - @Override - public double cumulativeProbability(double x) { - final double dev = x - mean; - if (Math.abs(dev) > 40 * standardDeviation) { - return dev < 0 ? 0.0d : 1.0d; - } - return 0.5 * Erfc.value(-dev / (standardDeviation * SQRT2)); - } - - /** {@inheritDoc} */ - @Override - public double inverseCumulativeProbability(final double p) { - if (p < 0 || - p > 1) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, p, 0, 1); - } - return mean + standardDeviation * SQRT2 * InverseErf.value(2 * p - 1); - } - - /** {@inheritDoc} */ - @Override - public double probability(double x0, - double x1) { - if (x0 > x1) { - throw new DistributionException(DistributionException.TOO_LARGE, - x0, x1); - } - final double denom = standardDeviation * SQRT2; - final double v0 = (x0 - mean) / denom; - final double v1 = (x1 - mean) / denom; - return 0.5 * ErfDifference.value(v0, v1); - } - - /** {@inheritDoc} */ - @Override - public double getMean() { - return mean; - } - - /** - * {@inheritDoc} - * - * For standard deviation parameter {@code s}, the variance is {@code s^2}. - */ - @Override - public double getVariance() { - final double s = getStandardDeviation(); - return s * s; - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is always negative infinity - * no matter the parameters. - * - * @return lower bound of the support (always - * {@code Double.NEGATIVE_INFINITY}) - */ - @Override - public double getSupportLowerBound() { - return Double.NEGATIVE_INFINITY; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is always positive infinity - * no matter the parameters. - * - * @return upper bound of the support (always - * {@code Double.POSITIVE_INFINITY}) - */ - @Override - public double getSupportUpperBound() { - return Double.POSITIVE_INFINITY; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } - - /** {@inheritDoc} */ - @Override - public ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng) { - return new ContinuousDistribution.Sampler() { - /** Gaussian distribution sampler. */ - private final ContinuousSampler sampler = - new GaussianSampler(new ZigguratNormalizedGaussianSampler(rng), - mean, standardDeviation); - - /** {@inheritDoc} */ - @Override - public double sample() { - return sampler.sample(); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ParetoDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ParetoDistribution.java deleted file mode 100644 index f97b7f1bc..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ParetoDistribution.java +++ /dev/null @@ -1,218 +0,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. - */ - -package org.apache.commons.statistics.distribution; - -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.ContinuousSampler; -import org.apache.commons.rng.sampling.distribution.InverseTransformParetoSampler; - -/** - * Implementation of the Pareto distribution. - * - *

- * Parameters: - * The probability distribution function of {@code X} is given by (for {@code x >= k}): - *

- *  α * k^α / x^(α + 1)
- * 
- *
    - *
  • {@code k} is the scale parameter: this is the minimum possible value of {@code X},
  • - *
  • {@code α} is the shape parameter: this is the Pareto index
  • - *
- */ -public class ParetoDistribution extends AbstractContinuousDistribution { - /** The scale parameter of this distribution. */ - private final double scale; - /** The shape parameter of this distribution. */ - private final double shape; - - /** - * Creates a Pareto distribution. - * - * @param scale Scale parameter of this distribution. - * @param shape Shape parameter of this distribution. - * @throws IllegalArgumentException if {@code scale <= 0} or {@code shape <= 0}. - */ - public ParetoDistribution(double scale, - double shape) { - if (scale <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, scale); - } - - if (shape <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, shape); - } - - this.scale = scale; - this.shape = shape; - } - - /** - * Returns the scale parameter of this distribution. - * - * @return the scale parameter - */ - public double getScale() { - return scale; - } - - /** - * Returns the shape parameter of this distribution. - * - * @return the shape parameter - */ - public double getShape() { - return shape; - } - - /** - * {@inheritDoc} - *

- * For scale {@code k}, and shape {@code α} of this distribution, the PDF - * is given by - *

    - *
  • {@code 0} if {@code x < k},
  • - *
  • {@code α * k^α / x^(α + 1)} otherwise.
  • - *
- */ - @Override - public double density(double x) { - if (x < scale) { - return 0; - } - return Math.pow(scale, shape) / Math.pow(x, shape + 1) * shape; - } - - /** {@inheritDoc} - * - * See documentation of {@link #density(double)} for computation details. - */ - @Override - public double logDensity(double x) { - if (x < scale) { - return Double.NEGATIVE_INFINITY; - } - return Math.log(scale) * shape - Math.log(x) * (shape + 1) + Math.log(shape); - } - - /** - * {@inheritDoc} - *

- * For scale {@code k}, and shape {@code α} of this distribution, the CDF is given by - *

    - *
  • {@code 0} if {@code x < k},
  • - *
  • {@code 1 - (k / x)^α} otherwise.
  • - *
- */ - @Override - public double cumulativeProbability(double x) { - if (x <= scale) { - return 0; - } - return 1 - Math.pow(scale / x, shape); - } - - /** - * {@inheritDoc} - *

- * For scale {@code k} and shape {@code α}, the mean is given by - *

    - *
  • {@code ∞} if {@code α <= 1},
  • - *
  • {@code α * k / (α - 1)} otherwise.
  • - *
- */ - @Override - public double getMean() { - if (shape <= 1) { - return Double.POSITIVE_INFINITY; - } - return shape * scale / (shape - 1); - } - - /** - * {@inheritDoc} - *

- * For scale {@code k} and shape {@code α}, the variance is given by - *

    - *
  • {@code ∞} if {@code 1 < α <= 2},
  • - *
  • {@code k^2 * α / ((α - 1)^2 * (α - 2))} otherwise.
  • - *
- */ - @Override - public double getVariance() { - if (shape <= 2) { - return Double.POSITIVE_INFINITY; - } - double s = shape - 1; - return scale * scale * shape / (s * s) / (shape - 2); - } - - /** - * {@inheritDoc} - *

- * The lower bound of the support is equal to the scale parameter {@code k}. - * - * @return lower bound of the support - */ - @Override - public double getSupportLowerBound() { - return scale; - } - - /** - * {@inheritDoc} - *

- * The upper bound of the support is always positive infinity no matter the parameters. - * - * @return upper bound of the support (always {@code Double.POSITIVE_INFINITY}) - */ - @Override - public double getSupportUpperBound() { - return Double.POSITIVE_INFINITY; - } - - /** - * {@inheritDoc} - *

- * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } - - /** {@inheritDoc} */ - @Override - public ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng) { - return new ContinuousDistribution.Sampler() { - /** - * Pareto distribution sampler. - */ - private final ContinuousSampler sampler = - new InverseTransformParetoSampler(rng, scale, shape); - - /**{@inheritDoc} */ - @Override - public double sample() { - return sampler.sample(); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/PascalDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/PascalDistribution.java deleted file mode 100644 index 7520bba45..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/PascalDistribution.java +++ /dev/null @@ -1,211 +0,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. - */ -package org.apache.commons.statistics.distribution; - -import org.apache.commons.numbers.combinatorics.BinomialCoefficientDouble; -import org.apache.commons.numbers.combinatorics.LogBinomialCoefficient; -import org.apache.commons.numbers.gamma.RegularizedBeta; - -/** - * Implementation of the Pascal distribution. - * - * The Pascal distribution is a special case of the Negative Binomial distribution - * where the number of successes parameter is an integer. - * - * There are various ways to express the probability mass and distribution - * functions for the Pascal distribution. The present implementation represents - * the distribution of the number of failures before {@code r} successes occur. - * This is the convention adopted in e.g. - * MathWorld, - * but not in - * Wikipedia. - * - * For a random variable {@code X} whose values are distributed according to this - * distribution, the probability mass function is given by
- * {@code P(X = k) = C(k + r - 1, r - 1) * p^r * (1 - p)^k,}
- * where {@code r} is the number of successes, {@code p} is the probability of - * success, and {@code X} is the total number of failures. {@code C(n, k)} is - * the binomial coefficient ({@code n} choose {@code k}). The mean and variance - * of {@code X} are
- * {@code E(X) = (1 - p) * r / p, var(X) = (1 - p) * r / p^2.}
- * Finally, the cumulative distribution function is given by
- * {@code P(X <= k) = I(p, r, k + 1)}, - * where I is the regularized incomplete Beta function. - */ -public class PascalDistribution extends AbstractDiscreteDistribution { - /** The number of successes. */ - private final int numberOfSuccesses; - /** The probability of success. */ - private final double probabilityOfSuccess; - /** The value of {@code log(p)}, where {@code p} is the probability of success, - * stored for faster computation. */ - private final double logProbabilityOfSuccess; - /** The value of {@code log(1-p)}, where {@code p} is the probability of success, - * stored for faster computation. */ - private final double log1mProbabilityOfSuccess; - - /** - * Create a Pascal distribution with the given number of successes and - * probability of success. - * - * @param r Number of successes. - * @param p Probability of success. - * @throws IllegalArgumentException if {@code r <= 0} or {@code p < 0} - * or {@code p > 1}. - */ - public PascalDistribution(int r, - double p) { - if (r <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, - r); - } - if (p < 0 || - p > 1) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, p, 0, 1); - } - - numberOfSuccesses = r; - probabilityOfSuccess = p; - logProbabilityOfSuccess = Math.log(p); - log1mProbabilityOfSuccess = Math.log1p(-p); - } - - /** - * Access the number of successes for this distribution. - * - * @return the number of successes. - */ - public int getNumberOfSuccesses() { - return numberOfSuccesses; - } - - /** - * Access the probability of success for this distribution. - * - * @return the probability of success. - */ - public double getProbabilityOfSuccess() { - return probabilityOfSuccess; - } - - /** {@inheritDoc} */ - @Override - public double probability(int x) { - double ret; - if (x < 0) { - ret = 0.0; - } else { - ret = BinomialCoefficientDouble.value(x + - numberOfSuccesses - 1, numberOfSuccesses - 1) * - Math.pow(probabilityOfSuccess, numberOfSuccesses) * - Math.pow(1.0 - probabilityOfSuccess, x); - } - return ret; - } - - /** {@inheritDoc} */ - @Override - public double logProbability(int x) { - double ret; - if (x < 0) { - ret = Double.NEGATIVE_INFINITY; - } else { - ret = LogBinomialCoefficient.value(x + - numberOfSuccesses - 1, numberOfSuccesses - 1) + - logProbabilityOfSuccess * numberOfSuccesses + - log1mProbabilityOfSuccess * x; - } - return ret; - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(int x) { - double ret; - if (x < 0) { - ret = 0.0; - } else { - ret = RegularizedBeta.value(probabilityOfSuccess, - numberOfSuccesses, x + 1.0); - } - return ret; - } - - /** - * {@inheritDoc} - * - * For number of successes {@code r} and probability of success {@code p}, - * the mean is {@code r * (1 - p) / p}. - */ - @Override - public double getMean() { - final double p = getProbabilityOfSuccess(); - final double r = getNumberOfSuccesses(); - return (r * (1 - p)) / p; - } - - /** - * {@inheritDoc} - * - * For number of successes {@code r} and probability of success {@code p}, - * the variance is {@code r * (1 - p) / p^2}. - */ - @Override - public double getVariance() { - final double p = getProbabilityOfSuccess(); - final double r = getNumberOfSuccesses(); - return r * (1 - p) / (p * p); - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is always 0 no matter the parameters. - * - * @return lower bound of the support (always 0) - */ - @Override - public int getSupportLowerBound() { - return 0; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is always positive infinity no matter the - * parameters. Positive infinity is symbolized by {@code Integer.MAX_VALUE}. - * - * @return upper bound of the support (always {@code Integer.MAX_VALUE} - * for positive infinity) - */ - @Override - public int getSupportUpperBound() { - return Integer.MAX_VALUE; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/PoissonDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/PoissonDistribution.java deleted file mode 100644 index 545e2b463..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/PoissonDistribution.java +++ /dev/null @@ -1,199 +0,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. - */ -package org.apache.commons.statistics.distribution; - -import org.apache.commons.numbers.gamma.RegularizedGamma; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.DiscreteSampler; -import org.apache.commons.rng.sampling.distribution.PoissonSampler; - -/** - * Implementation of the Poisson distribution. - */ -public class PoissonDistribution extends AbstractDiscreteDistribution { - /** ln(2 π). */ - private static final double LOG_TWO_PI = Math.log(2 * Math.PI); - /** Default maximum number of iterations. */ - private static final int DEFAULT_MAX_ITERATIONS = 10000000; - /** Default convergence criterion. */ - private static final double DEFAULT_EPSILON = 1e-12; - /** Distribution used to compute normal approximation. */ - private final NormalDistribution normal; - /** Mean of the distribution. */ - private final double mean; - /** Maximum number of iterations for cumulative probability. */ - private final int maxIterations; - /** Convergence criterion for cumulative probability. */ - private final double epsilon; - - /** - * Creates a new Poisson distribution with specified mean. - * - * @param p the Poisson mean - * @throws IllegalArgumentException if {@code p <= 0}. - */ - public PoissonDistribution(double p) { - this(p, DEFAULT_EPSILON, DEFAULT_MAX_ITERATIONS); - } - - /** - * Creates a new Poisson distribution with specified mean, convergence - * criterion and maximum number of iterations. - * - * @param p Poisson mean. - * @param epsilon Convergence criterion for cumulative probabilities. - * @param maxIterations Maximum number of iterations for cumulative - * probabilities. - * @throws IllegalArgumentException if {@code p <= 0}. - */ - private PoissonDistribution(double p, - double epsilon, - int maxIterations) { - if (p <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, p); - } - mean = p; - this.epsilon = epsilon; - this.maxIterations = maxIterations; - - normal = new NormalDistribution(p, Math.sqrt(p)); - } - - /** {@inheritDoc} */ - @Override - public double probability(int x) { - final double logProbability = logProbability(x); - return logProbability == Double.NEGATIVE_INFINITY ? 0 : Math.exp(logProbability); - } - - /** {@inheritDoc} */ - @Override - public double logProbability(int x) { - double ret; - if (x < 0 || x == Integer.MAX_VALUE) { - ret = Double.NEGATIVE_INFINITY; - } else if (x == 0) { - ret = -mean; - } else { - ret = -SaddlePointExpansion.getStirlingError(x) - - SaddlePointExpansion.getDeviancePart(x, mean) - - 0.5 * LOG_TWO_PI - 0.5 * Math.log(x); - } - return ret; - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(int x) { - if (x < 0) { - return 0; - } - if (x == Integer.MAX_VALUE) { - return 1; - } - return RegularizedGamma.Q.value((double) x + 1, mean, epsilon, - maxIterations); - } - - /** - * Calculates the Poisson distribution function using a normal - * approximation. The {@code N(mean, sqrt(mean))} distribution is used - * to approximate the Poisson distribution. The computation uses - * "half-correction" (evaluating the normal distribution function at - * {@code x + 0.5}). - * - * @param x Upper bound, inclusive. - * @return the distribution function value calculated using a normal - * approximation. - */ - public double normalApproximateProbability(int x) { - // Calculate the probability using half-correction. - return normal.cumulativeProbability(x + 0.5); - } - - /** {@inheritDoc} */ - @Override - public double getMean() { - return mean; - } - - /** - * {@inheritDoc} - * - * For mean parameter {@code p}, the variance is {@code p}. - */ - @Override - public double getVariance() { - return mean; - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is always 0 no matter the mean parameter. - * - * @return lower bound of the support (always 0) - */ - @Override - public int getSupportLowerBound() { - return 0; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is positive infinity, - * regardless of the parameter values. There is no integer infinity, - * so this method returns {@code Integer.MAX_VALUE}. - * - * @return upper bound of the support (always {@code Integer.MAX_VALUE} for - * positive infinity) - */ - @Override - public int getSupportUpperBound() { - return Integer.MAX_VALUE; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } - - /**{@inheritDoc} */ - @Override - public DiscreteDistribution.Sampler createSampler(final UniformRandomProvider rng) { - return new DiscreteDistribution.Sampler() { - /** - * Poisson distribution sampler. - */ - private final DiscreteSampler sampler = new PoissonSampler(rng, mean); - - /**{@inheritDoc} */ - @Override - public int sample() { - return sampler.sample(); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/SaddlePointExpansion.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/SaddlePointExpansion.java deleted file mode 100644 index 7bb847a0a..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/SaddlePointExpansion.java +++ /dev/null @@ -1,191 +0,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. - */ -package org.apache.commons.statistics.distribution; - -import org.apache.commons.numbers.gamma.LogGamma; - -/** - * Utility class used by various distributions to accurately compute their - * respective probability mass functions. The implementation for this class is - * based on the Catherine Loader's - * dbinom routines. - * - * This class is not intended to be called directly. - * - * @since 1.0 - */ -final class SaddlePointExpansion { - /** 2 π */ - private static final double TWO_PI = 2 * Math.PI; - /** 1/2 * log(2 π). */ - private static final double HALF_LOG_TWO_PI = 0.5 * Math.log(TWO_PI); - - /** exact Stirling expansion error for certain values. */ - private static final double[] EXACT_STIRLING_ERRORS = { 0.0, /* 0.0 */ - 0.1534264097200273452913848, /* 0.5 */ - 0.0810614667953272582196702, /* 1.0 */ - 0.0548141210519176538961390, /* 1.5 */ - 0.0413406959554092940938221, /* 2.0 */ - 0.03316287351993628748511048, /* 2.5 */ - 0.02767792568499833914878929, /* 3.0 */ - 0.02374616365629749597132920, /* 3.5 */ - 0.02079067210376509311152277, /* 4.0 */ - 0.01848845053267318523077934, /* 4.5 */ - 0.01664469118982119216319487, /* 5.0 */ - 0.01513497322191737887351255, /* 5.5 */ - 0.01387612882307074799874573, /* 6.0 */ - 0.01281046524292022692424986, /* 6.5 */ - 0.01189670994589177009505572, /* 7.0 */ - 0.01110455975820691732662991, /* 7.5 */ - 0.010411265261972096497478567, /* 8.0 */ - 0.009799416126158803298389475, /* 8.5 */ - 0.009255462182712732917728637, /* 9.0 */ - 0.008768700134139385462952823, /* 9.5 */ - 0.008330563433362871256469318, /* 10.0 */ - 0.007934114564314020547248100, /* 10.5 */ - 0.007573675487951840794972024, /* 11.0 */ - 0.007244554301320383179543912, /* 11.5 */ - 0.006942840107209529865664152, /* 12.0 */ - 0.006665247032707682442354394, /* 12.5 */ - 0.006408994188004207068439631, /* 13.0 */ - 0.006171712263039457647532867, /* 13.5 */ - 0.005951370112758847735624416, /* 14.0 */ - 0.005746216513010115682023589, /* 14.5 */ - 0.005554733551962801371038690 /* 15.0 */ - }; - - /** - * Forbid construction. - */ - private SaddlePointExpansion() {} - - /** - * Compute the error of Stirling's series at the given value. - *

- * References: - *

    - *
  1. Eric W. Weisstein. "Stirling's Series." From MathWorld--A Wolfram Web - * Resource. - * http://mathworld.wolfram.com/StirlingsSeries.html
  2. - *
- *

- * - * @param z the value. - * @return the Striling's series error. - */ - static double getStirlingError(double z) { - double ret; - if (z < 15.0) { - double z2 = 2.0 * z; - if (Math.floor(z2) == z2) { - ret = EXACT_STIRLING_ERRORS[(int) z2]; - } else { - ret = LogGamma.value(z + 1.0) - (z + 0.5) * Math.log(z) + - z - HALF_LOG_TWO_PI; - } - } else { - double z2 = z * z; - ret = (0.083333333333333333333 - - (0.00277777777777777777778 - - (0.00079365079365079365079365 - - (0.000595238095238095238095238 - - 0.0008417508417508417508417508 / - z2) / z2) / z2) / z2) / z; - } - return ret; - } - - /** - * A part of the deviance portion of the saddle point approximation. - *

- * References: - *

    - *
  1. Catherine Loader (2000). "Fast and Accurate Computation of Binomial - * Probabilities.". - * http://www.herine.net/stat/papers/dbinom.pdf
  2. - *
- *

- * - * @param x the x value. - * @param mu the average. - * @return a part of the deviance. - */ - static double getDeviancePart(double x, double mu) { - double ret; - if (Math.abs(x - mu) < 0.1 * (x + mu)) { - double d = x - mu; - double v = d / (x + mu); - double s1 = v * d; - double s = Double.NaN; - double ej = 2.0 * x * v; - v *= v; - int j = 1; - while (s1 != s) { - s = s1; - ej *= v; - s1 = s + ej / ((j * 2) + 1); - ++j; - } - ret = s1; - } else { - if (x == 0) { - return mu; - } - ret = x * Math.log(x / mu) + mu - x; - } - return ret; - } - - /** - * Compute the logarithm of the PMF for a binomial distribution - * using the saddle point expansion. - * - * @param x the value at which the probability is evaluated. - * @param n the number of trials. - * @param p the probability of success. - * @param q the probability of failure (1 - p). - * @return log(p(x)). - */ - static double logBinomialProbability(int x, int n, double p, double q) { - double ret; - if (x == 0) { - if (p < 0.1) { - ret = -getDeviancePart(n, n * q) - n * p; - } else { - if (n == 0) { - return 0; - } - ret = n * Math.log(q); - } - } else if (x == n) { - if (q < 0.1) { - ret = -getDeviancePart(n, n * p) - n * q; - } else { - ret = n * Math.log(p); - } - } else { - ret = getStirlingError(n) - getStirlingError(x) - - getStirlingError(n - x) - getDeviancePart(x, n * p) - - getDeviancePart(n - x, n * q); - final double f = (TWO_PI * x * (n - x)) / n; - ret = -0.5 * Math.log(f) + ret; - } - return ret; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/TDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/TDistribution.java deleted file mode 100644 index 6ca2711df..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/TDistribution.java +++ /dev/null @@ -1,165 +0,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. - */ -package org.apache.commons.statistics.distribution; - -import org.apache.commons.numbers.gamma.LogGamma; -import org.apache.commons.numbers.gamma.RegularizedBeta; - -/** - * Implementation of Student's t-distribution. - */ -public class TDistribution extends AbstractContinuousDistribution { - /** The degrees of freedom. */ - private final double degreesOfFreedom; - /** degreesOfFreedom / 2 */ - private final double dofOver2; - /** Cached value. */ - private final double factor; - /** Cached value. */ - private final double mean; - /** Cached value. */ - private final double variance; - - /** - * Creates a distribution. - * - * @param degreesOfFreedom Degrees of freedom. - * @throws IllegalArgumentException if {@code degreesOfFreedom <= 0} - */ - public TDistribution(double degreesOfFreedom) { - if (degreesOfFreedom <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, - degreesOfFreedom); - } - this.degreesOfFreedom = degreesOfFreedom; - - dofOver2 = 0.5 * degreesOfFreedom; - factor = LogGamma.value(dofOver2 + 0.5) - - 0.5 * (Math.log(Math.PI) + Math.log(degreesOfFreedom)) - - LogGamma.value(dofOver2); - mean = degreesOfFreedom > 1 ? 0 : - Double.NaN; - variance = degreesOfFreedom > 2 ? degreesOfFreedom / (degreesOfFreedom - 2) : - degreesOfFreedom > 1 && degreesOfFreedom <= 2 ? Double.POSITIVE_INFINITY : - Double.NaN; - } - - /** - * Access the degrees of freedom. - * - * @return the degrees of freedom. - */ - public double getDegreesOfFreedom() { - return degreesOfFreedom; - } - - /** {@inheritDoc} */ - @Override - public double density(double x) { - return Math.exp(logDensity(x)); - } - - /** {@inheritDoc} */ - @Override - public double logDensity(double x) { - final double nPlus1Over2 = dofOver2 + 0.5; - return factor - nPlus1Over2 * Math.log1p(x * x / degreesOfFreedom); - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(double x) { - if (x == 0) { - return 0.5; - } else { - final double t = - RegularizedBeta.value(degreesOfFreedom / (degreesOfFreedom + (x * x)), - dofOver2, - 0.5); - return x < 0 ? - 0.5 * t : - 1 - 0.5 * t; - } - } - - /** - * {@inheritDoc} - * - * For degrees of freedom parameter {@code df}, the mean is - *
    - *
  • zero if {@code df > 1}, and
  • - *
  • undefined ({@code Double.NaN}) otherwise.
  • - *
- */ - @Override - public double getMean() { - return mean; - } - - /** - * {@inheritDoc} - * - * For degrees of freedom parameter {@code df}, the variance is - *
    - *
  • {@code df / (df - 2)} if {@code df > 2},
  • - *
  • infinite ({@code Double.POSITIVE_INFINITY}) if {@code 1 < df <= 2}, and
  • - *
  • undefined ({@code Double.NaN}) otherwise.
  • - *
- */ - @Override - public double getVariance() { - return variance; - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is always negative infinity.. - * - * @return lower bound of the support (always - * {@code Double.NEGATIVE_INFINITY}) - */ - @Override - public double getSupportLowerBound() { - return Double.NEGATIVE_INFINITY; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is always positive infinity. - * - * @return upper bound of the support (always - * {@code Double.POSITIVE_INFINITY}) - */ - @Override - public double getSupportUpperBound() { - return Double.POSITIVE_INFINITY; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/TriangularDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/TriangularDistribution.java deleted file mode 100644 index 01fab1a7b..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/TriangularDistribution.java +++ /dev/null @@ -1,222 +0,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. - */ - -package org.apache.commons.statistics.distribution; - -/** - * Implementation of the triangular real distribution. - * - * @see - * Triangular distribution (Wikipedia) - * - * @since 3.0 - */ -public class TriangularDistribution extends AbstractContinuousDistribution { - /** Serializable version identifier. */ - private static final long serialVersionUID = 20160311L; - /** Lower limit of this distribution (inclusive). */ - private final double a; - /** Upper limit of this distribution (inclusive). */ - private final double b; - /** Mode of this distribution. */ - private final double c; - - /** - * Creates a distribution. - * - * @param a Lower limit of this distribution (inclusive). - * @param b Upper limit of this distribution (inclusive). - * @param c Mode of this distribution. - * @throws IllegalArgumentException if {@code a >= b}, if {@code c > b} - * or if {@code c < a}. - */ - public TriangularDistribution(double a, - double c, - double b) { - if (a >= b) { - throw new DistributionException(DistributionException.TOO_LARGE, - a, b); - } - if (c < a) { - throw new DistributionException(DistributionException.TOO_SMALL, - c, a); - } - if (c > b) { - throw new DistributionException(DistributionException.TOO_LARGE, - c, b); - } - - this.a = a; - this.c = c; - this.b = b; - } - - /** - * Gets the mode. - * - * @return the mode of the distribution. - */ - public double getMode() { - return c; - } - - /** - * {@inheritDoc} - * - * For lower limit {@code a}, upper limit {@code b} and mode {@code c}, the - * PDF is given by - *
    - *
  • {@code 2 * (x - a) / [(b - a) * (c - a)]} if {@code a <= x < c},
  • - *
  • {@code 2 / (b - a)} if {@code x = c},
  • - *
  • {@code 2 * (b - x) / [(b - a) * (b - c)]} if {@code c < x <= b},
  • - *
  • {@code 0} otherwise. - *
- */ - @Override - public double density(double x) { - if (x < a) { - return 0; - } - if (a <= x && x < c) { - double divident = 2 * (x - a); - double divisor = (b - a) * (c - a); - return divident / divisor; - } - if (x == c) { - return 2 / (b - a); - } - if (c < x && x <= b) { - double divident = 2 * (b - x); - double divisor = (b - a) * (b - c); - return divident / divisor; - } - return 0; - } - - /** - * {@inheritDoc} - * - * For lower limit {@code a}, upper limit {@code b} and mode {@code c}, the - * CDF is given by - *
    - *
  • {@code 0} if {@code x < a},
  • - *
  • {@code (x - a)^2 / [(b - a) * (c - a)]} if {@code a <= x < c},
  • - *
  • {@code (c - a) / (b - a)} if {@code x = c},
  • - *
  • {@code 1 - (b - x)^2 / [(b - a) * (b - c)]} if {@code c < x <= b},
  • - *
  • {@code 1} if {@code x > b}.
  • - *
- */ - @Override - public double cumulativeProbability(double x) { - if (x < a) { - return 0; - } - if (a <= x && x < c) { - double divident = (x - a) * (x - a); - double divisor = (b - a) * (c - a); - return divident / divisor; - } - if (x == c) { - return (c - a) / (b - a); - } - if (c < x && x <= b) { - double divident = (b - x) * (b - x); - double divisor = (b - a) * (b - c); - return 1 - (divident / divisor); - } - return 1; - } - - /** - * {@inheritDoc} - * - * For lower limit {@code a}, upper limit {@code b}, and mode {@code c}, - * the mean is {@code (a + b + c) / 3}. - */ - @Override - public double getMean() { - return (a + b + c) / 3; - } - - /** - * {@inheritDoc} - * - * For lower limit {@code a}, upper limit {@code b}, and mode {@code c}, - * the variance is {@code (a^2 + b^2 + c^2 - a * b - a * c - b * c) / 18}. - */ - @Override - public double getVariance() { - return (a * a + b * b + c * c - a * b - a * c - b * c) / 18; - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is equal to the lower limit parameter - * {@code a} of the distribution. - * - * @return lower bound of the support - */ - @Override - public double getSupportLowerBound() { - return a; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is equal to the upper limit parameter - * {@code b} of the distribution. - * - * @return upper bound of the support - */ - @Override - public double getSupportUpperBound() { - return b; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } - - /** {@inheritDoc} */ - @Override - public double inverseCumulativeProbability(double p) { - if (p < 0 || - p > 1) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, p, 0, 1); - } - if (p == 0) { - return a; - } - if (p == 1) { - return b; - } - if (p < (c - a) / (b - a)) { - return a + Math.sqrt(p * (b - a) * (c - a)); - } - return b - Math.sqrt((1 - p) * (b - a) * (b - c)); - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/UniformContinuousDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/UniformContinuousDistribution.java deleted file mode 100644 index da5abf748..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/UniformContinuousDistribution.java +++ /dev/null @@ -1,161 +0,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. - */ - -package org.apache.commons.statistics.distribution; - -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.ContinuousSampler; -import org.apache.commons.rng.sampling.distribution.ContinuousUniformSampler; - -/** - * Implementation of the uniform distribution. - */ -public class UniformContinuousDistribution extends AbstractContinuousDistribution { - /** Lower bound of this distribution (inclusive). */ - private final double lower; - /** Upper bound of this distribution (exclusive). */ - private final double upper; - - /** - * Creates a uniform distribution. - * - * @param lower Lower bound of this distribution (inclusive). - * @param upper Upper bound of this distribution (exclusive). - * @throws IllegalArgumentException if {@code lower >= upper}. - */ - public UniformContinuousDistribution(double lower, - double upper) { - if (lower >= upper) { - throw new DistributionException(DistributionException.TOO_LARGE, - lower, upper); - } - - this.lower = lower; - this.upper = upper; - } - - /** {@inheritDoc} */ - @Override - public double density(double x) { - if (x < lower || - x > upper) { - return 0; - } - return 1 / (upper - lower); - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(double x) { - if (x <= lower) { - return 0; - } - if (x >= upper) { - return 1; - } - return (x - lower) / (upper - lower); - } - - /** {@inheritDoc} */ - @Override - public double inverseCumulativeProbability(final double p) { - if (p < 0 || - p > 1) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, p, 0, 1); - } - return p * (upper - lower) + lower; - } - - /** - * {@inheritDoc} - * - * For lower bound {@code lower} and upper bound {@code upper}, the mean is - * {@code 0.5 * (lower + upper)}. - */ - @Override - public double getMean() { - return 0.5 * (lower + upper); - } - - /** - * {@inheritDoc} - * - * For lower bound {@code lower} and upper bound {@code upper}, the - * variance is {@code (upper - lower)^2 / 12}. - */ - @Override - public double getVariance() { - double ul = upper - lower; - return ul * ul / 12; - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is equal to the lower bound parameter - * of the distribution. - * - * @return lower bound of the support - */ - @Override - public double getSupportLowerBound() { - return lower; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is equal to the upper bound parameter - * of the distribution. - * - * @return upper bound of the support - */ - @Override - public double getSupportUpperBound() { - return upper; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } - - /** {@inheritDoc} */ - @Override - public ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng) { - return new ContinuousDistribution.Sampler() { - /** - * Uniform distribution sampler. - */ - private final ContinuousSampler sampler = - new ContinuousUniformSampler(rng, lower, upper); - - /**{@inheritDoc} */ - @Override - public double sample() { - return sampler.sample(); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/UniformDiscreteDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/UniformDiscreteDistribution.java deleted file mode 100644 index 47ffffb06..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/UniformDiscreteDistribution.java +++ /dev/null @@ -1,159 +0,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. - */ - -package org.apache.commons.statistics.distribution; - -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.DiscreteSampler; -import org.apache.commons.rng.sampling.distribution.DiscreteUniformSampler; - -/** - * Implementation of the - * uniform integer distribution. - */ -public class UniformDiscreteDistribution extends AbstractDiscreteDistribution { - /** 1 / 12 **/ - private static final double ONE_TWELFTH = 1 / 12d; - /** Lower bound (inclusive) of this distribution. */ - private final int lower; - /** Upper bound (inclusive) of this distribution. */ - private final int upper; - /** "upper" + "lower" (to avoid overflow). */ - private final double upperPlusLower; - /** "upper" - "lower" (to avoid overflow). */ - private final double upperMinusLower; - - /** - * Creates a new uniform integer distribution using the given lower and - * upper bounds (both inclusive). - * - * @param lower Lower bound (inclusive) of this distribution. - * @param upper Upper bound (inclusive) of this distribution. - * @throws IllegalArgumentException if {@code lower > upper}. - */ - public UniformDiscreteDistribution(int lower, - int upper) { - if (lower > upper) { - throw new DistributionException(DistributionException.TOO_LARGE, - lower, upper); - } - this.lower = lower; - this.upper = upper; - upperPlusLower = (double) upper + (double) lower; - upperMinusLower = (double) upper - (double) lower; - } - - /** {@inheritDoc} */ - @Override - public double probability(int x) { - if (x < lower || x > upper) { - return 0; - } - return 1 / (upperMinusLower + 1); - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(int x) { - if (x < lower) { - return 0; - } - if (x > upper) { - return 1; - } - return (x - lower + 1) / (upperMinusLower + 1); - } - - /** - * {@inheritDoc} - * - * For lower bound {@code lower} and upper bound {@code upper}, the mean is - * {@code 0.5 * (lower + upper)}. - */ - @Override - public double getMean() { - return 0.5 * upperPlusLower; - } - - /** - * {@inheritDoc} - * - * For lower bound {@code lower} and upper bound {@code upper}, and - * {@code n = upper - lower + 1}, the variance is {@code (n^2 - 1) / 12}. - */ - @Override - public double getVariance() { - double n = upperMinusLower + 1; - return ONE_TWELFTH * (n * n - 1); - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is equal to the lower bound parameter - * of the distribution. - * - * @return lower bound of the support - */ - @Override - public int getSupportLowerBound() { - return lower; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is equal to the upper bound parameter - * of the distribution. - * - * @return upper bound of the support - */ - @Override - public int getSupportUpperBound() { - return upper; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } - - /**{@inheritDoc} */ - @Override - public DiscreteDistribution.Sampler createSampler(final UniformRandomProvider rng) { - return new DiscreteDistribution.Sampler() { - /** - * Discrete uniform distribution sampler. - */ - private final DiscreteSampler sampler = - new DiscreteUniformSampler(rng, lower, upper); - - /**{@inheritDoc} */ - @Override - public int sample() { - return sampler.sample(); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/WeibullDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/WeibullDistribution.java deleted file mode 100644 index dd227ba06..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/WeibullDistribution.java +++ /dev/null @@ -1,220 +0,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. - */ - -package org.apache.commons.statistics.distribution; - -import org.apache.commons.numbers.gamma.LogGamma; - -/** - * Implementation of the Weibull distribution. This implementation uses the - * two parameter form of the distribution defined by - * - * Weibull Distribution, equations (1) and (2). - * - * @see Weibull distribution (Wikipedia) - * @see Weibull distribution (MathWorld) - * - * @since 1.1 - */ -public class WeibullDistribution extends AbstractContinuousDistribution { - /** The shape parameter. */ - private final double shape; - /** The scale parameter. */ - private final double scale; - - /** - * Creates a distribution. - * - * @param alpha Shape parameter. - * @param beta Scale parameter. - * @throws IllegalArgumentException if {@code alpha <= 0} or {@code beta <= 0}. - */ - public WeibullDistribution(double alpha, - double beta) { - if (alpha <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, - alpha); - } - if (beta <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, - beta); - } - scale = beta; - shape = alpha; - } - - /** - * Access the shape parameter, {@code alpha}. - * - * @return the shape parameter, {@code alpha}. - */ - public double getShape() { - return shape; - } - - /** - * Access the scale parameter, {@code beta}. - * - * @return the scale parameter, {@code beta}. - */ - public double getScale() { - return scale; - } - - /** {@inheritDoc} */ - @Override - public double density(double x) { - if (x < 0) { - return 0; - } - - final double xscale = x / scale; - final double xscalepow = Math.pow(xscale, shape - 1); - - /* - * Math.pow(x / scale, shape) = - * Math.pow(xscale, shape) = - * Math.pow(xscale, shape - 1) * xscale - */ - final double xscalepowshape = xscalepow * xscale; - - return (shape / scale) * xscalepow * Math.exp(-xscalepowshape); - } - - /** {@inheritDoc} */ - @Override - public double logDensity(double x) { - if (x < 0) { - return Double.NEGATIVE_INFINITY; - } - - final double xscale = x / scale; - final double logxscalepow = Math.log(xscale) * (shape - 1); - - /* - * Math.pow(x / scale, shape) = - * Math.pow(xscale, shape) = - * Math.pow(xscale, shape - 1) * xscale - */ - final double xscalepowshape = Math.exp(logxscalepow) * xscale; - - return Math.log(shape / scale) + logxscalepow - xscalepowshape; - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(double x) { - double ret; - if (x <= 0.0) { - ret = 0.0; - } else { - ret = 1.0 - Math.exp(-Math.pow(x / scale, shape)); - } - return ret; - } - - /** - * {@inheritDoc} - * - * Returns {@code 0} when {@code p == 0} and - * {@code Double.POSITIVE_INFINITY} when {@code p == 1}. - */ - @Override - public double inverseCumulativeProbability(double p) { - double ret; - if (p < 0 || - p > 1) { - throw new DistributionException(DistributionException.OUT_OF_RANGE, p, 0, 1); - } else if (p == 0) { - ret = 0.0; - } else if (p == 1) { - ret = Double.POSITIVE_INFINITY; - } else { - ret = scale * Math.pow(-Math.log1p(-p), 1.0 / shape); - } - return ret; - } - - /** - * {@inheritDoc} - * - * The mean is {@code scale * Gamma(1 + (1 / shape))}, where {@code Gamma()} - * is the Gamma-function. - */ - @Override - public double getMean() { - final double sh = getShape(); - final double sc = getScale(); - - return sc * Math.exp(LogGamma.value(1 + (1 / sh))); - } - - /** - * {@inheritDoc} - * - * The variance is {@code scale^2 * Gamma(1 + (2 / shape)) - mean^2} - * where {@code Gamma()} is the Gamma-function. - */ - @Override - public double getVariance() { - final double sh = getShape(); - final double sc = getScale(); - final double mn = getMean(); - - return (sc * sc) * Math.exp(LogGamma.value(1 + (2 / sh))) - - (mn * mn); - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is always 0 no matter the parameters. - * - * @return lower bound of the support (always 0) - */ - @Override - public double getSupportLowerBound() { - return 0; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is always positive infinity - * no matter the parameters. - * - * @return upper bound of the support (always - * {@code Double.POSITIVE_INFINITY}) - */ - @Override - public double getSupportUpperBound() { - return Double.POSITIVE_INFINITY; - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } -} - diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ZipfDistribution.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ZipfDistribution.java deleted file mode 100644 index 8d233fa58..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/ZipfDistribution.java +++ /dev/null @@ -1,236 +0,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. - */ - -package org.apache.commons.statistics.distribution; - -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.sampling.distribution.DiscreteSampler; -import org.apache.commons.rng.sampling.distribution.RejectionInversionZipfSampler; - -/** - * Implementation of the Zipf distribution. - *

- * Parameters: - * For a random variable {@code X} whose values are distributed according to this - * distribution, the probability mass function is given by - *

- *   P(X = k) = H(N,s) * 1 / k^s    for {@code k = 1,2,...,N}.
- * 
- * {@code H(N,s)} is the normalizing constant - * which corresponds to the generalized harmonic number of order N of s. - *
    - *
  • {@code N} is the number of elements
  • - *
  • {@code s} is the exponent
  • - *
- */ -public class ZipfDistribution extends AbstractDiscreteDistribution { - /** Number of elements. */ - private final int numberOfElements; - /** Exponent parameter of the distribution. */ - private final double exponent; - /** Cached values of the nth generalized harmonic. */ - private final double nthHarmonic; - - /** - * Creates a distribution. - * - * @param numberOfElements Number of elements. - * @param exponent Exponent. - * @exception IllegalArgumentException if {@code numberOfElements <= 0} - * or {@code exponent <= 0}. - */ - public ZipfDistribution(int numberOfElements, - double exponent) { - if (numberOfElements <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, - numberOfElements); - } - if (exponent <= 0) { - throw new DistributionException(DistributionException.NEGATIVE, - exponent); - } - - this.numberOfElements = numberOfElements; - this.exponent = exponent; - this.nthHarmonic = generalizedHarmonic(numberOfElements, exponent); - } - - /** - * Get the number of elements (e.g. corpus size) for the distribution. - * - * @return the number of elements - */ - public int getNumberOfElements() { - return numberOfElements; - } - - /** - * Get the exponent characterizing the distribution. - * - * @return the exponent - */ - public double getExponent() { - return exponent; - } - - /** {@inheritDoc} */ - @Override - public double probability(final int x) { - if (x <= 0 || x > numberOfElements) { - return 0; - } - - return (1 / Math.pow(x, exponent)) / nthHarmonic; - } - - /** {@inheritDoc} */ - @Override - public double logProbability(int x) { - if (x <= 0 || x > numberOfElements) { - return Double.NEGATIVE_INFINITY; - } - - return -Math.log(x) * exponent - Math.log(nthHarmonic); - } - - /** {@inheritDoc} */ - @Override - public double cumulativeProbability(final int x) { - if (x <= 0) { - return 0; - } else if (x >= numberOfElements) { - return 1; - } - - return generalizedHarmonic(x, exponent) / nthHarmonic; - } - - /** - * {@inheritDoc} - * - * For number of elements {@code N} and exponent {@code s}, the mean is - * {@code Hs1 / Hs}, where - *
    - *
  • {@code Hs1 = generalizedHarmonic(N, s - 1)},
  • - *
  • {@code Hs = generalizedHarmonic(N, s)}.
  • - *
- */ - @Override - public double getMean() { - final int N = getNumberOfElements(); - final double s = getExponent(); - - final double Hs1 = generalizedHarmonic(N, s - 1); - final double Hs = nthHarmonic; - - return Hs1 / Hs; - } - - /** - * {@inheritDoc} - * - * For number of elements {@code N} and exponent {@code s}, the mean is - * {@code (Hs2 / Hs) - (Hs1^2 / Hs^2)}, where - *
    - *
  • {@code Hs2 = generalizedHarmonic(N, s - 2)},
  • - *
  • {@code Hs1 = generalizedHarmonic(N, s - 1)},
  • - *
  • {@code Hs = generalizedHarmonic(N, s)}.
  • - *
- */ - @Override - public double getVariance() { - final int N = getNumberOfElements(); - final double s = getExponent(); - - final double Hs2 = generalizedHarmonic(N, s - 2); - final double Hs1 = generalizedHarmonic(N, s - 1); - final double Hs = nthHarmonic; - - return (Hs2 / Hs) - ((Hs1 * Hs1) / (Hs * Hs)); - } - - /** - * Calculates the Nth generalized harmonic number. See - * Harmonic - * Series. - * - * @param n Term in the series to calculate (must be larger than 1) - * @param m Exponent (special case {@code m = 1} is the harmonic series). - * @return the nth generalized harmonic number. - */ - private double generalizedHarmonic(final int n, final double m) { - double value = 0; - for (int k = n; k > 0; --k) { - value += 1 / Math.pow(k, m); - } - return value; - } - - /** - * {@inheritDoc} - * - * The lower bound of the support is always 1 no matter the parameters. - * - * @return lower bound of the support (always 1) - */ - @Override - public int getSupportLowerBound() { - return 1; - } - - /** - * {@inheritDoc} - * - * The upper bound of the support is the number of elements. - * - * @return upper bound of the support - */ - @Override - public int getSupportUpperBound() { - return getNumberOfElements(); - } - - /** - * {@inheritDoc} - * - * The support of this distribution is connected. - * - * @return {@code true} - */ - @Override - public boolean isSupportConnected() { - return true; - } - - /**{@inheritDoc} */ - @Override - public DiscreteDistribution.Sampler createSampler(final UniformRandomProvider rng) { - return new DiscreteDistribution.Sampler() { - /** - * Zipf distribution sampler. - */ - private final DiscreteSampler sampler = - new RejectionInversionZipfSampler(rng, numberOfElements, exponent); - - /**{@inheritDoc} */ - @Override - public int sample() { - return sampler.sample(); - } - }; - } -} diff --git a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/package-info.java b/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/package-info.java deleted file mode 100644 index 98315c627..000000000 --- a/virtdata-lib-curves4/src/main/java/org/apache/commons/statistics/distribution/package-info.java +++ /dev/null @@ -1,20 +0,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. - */ -/** - * Implementations of common discrete and continuous distributions. - */ -package org.apache.commons.statistics.distribution; diff --git a/virtdata-lib-curves4/src/test/java/io/nosqlbench/virtdata/library/curves4/continuous/RealDistributionsValuesTest.java b/virtdata-lib-curves4/src/test/java/io/nosqlbench/virtdata/library/curves4/continuous/RealDistributionsValuesTest.java index caf879a28..aeb824022 100644 --- a/virtdata-lib-curves4/src/test/java/io/nosqlbench/virtdata/library/curves4/continuous/RealDistributionsValuesTest.java +++ b/virtdata-lib-curves4/src/test/java/io/nosqlbench/virtdata/library/curves4/continuous/RealDistributionsValuesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ package io.nosqlbench.virtdata.library.curves4.continuous; import io.nosqlbench.virtdata.library.curves4.continuous.long_double.Normal; import io.nosqlbench.virtdata.library.curves4.continuous.long_double.Uniform; -import org.apache.commons.math4.stat.descriptive.DescriptiveStatistics; +import org.apache.commons.math4.legacy.stat.descriptive.DescriptiveStatistics; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.assertj.core.data.Offset; diff --git a/virtdata-lib-curves4/src/test/java/io/nosqlbench/virtdata/library/curves4/discrete/IntegerDistributionsBinomialSanity.java b/virtdata-lib-curves4/src/test/java/io/nosqlbench/virtdata/library/curves4/discrete/IntegerDistributionsBinomialSanity.java index 97bc9f6ae..915a911ab 100644 --- a/virtdata-lib-curves4/src/test/java/io/nosqlbench/virtdata/library/curves4/discrete/IntegerDistributionsBinomialSanity.java +++ b/virtdata-lib-curves4/src/test/java/io/nosqlbench/virtdata/library/curves4/discrete/IntegerDistributionsBinomialSanity.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ public class IntegerDistributionsBinomialSanity { @Test public void testBinomialMappedDist() { DiscreteLongLongSampler b85 = new DiscreteLongLongSampler(new IntegerDistributionICDSource( - new BinomialDistribution(8, 0.5D) + BinomialDistribution.of(8, 0.5D) ),false); assertThat(b85.applyAsLong(0L)).isEqualTo(0); assertThat(b85.applyAsLong(Long.MAX_VALUE)).isEqualTo(8); @@ -76,7 +76,7 @@ public class IntegerDistributionsBinomialSanity { @Test public void showBinomialICDF() { DiscreteLongLongSampler b85 = new DiscreteLongLongSampler(new IntegerDistributionICDSource( - new BinomialDistribution(8,0.5D)),false); + BinomialDistribution.of(8,0.5D)),false); for (int i = 0; i < 1000; i++) { double factor=((double) i / 1000D); long v = b85.applyAsLong((long) (factor * (double) Long.MAX_VALUE)); diff --git a/virtdata-lib-curves4/src/test/java/io/nosqlbench/virtdata/library/curves4/discrete/IntegerDistributionsConcurrencyTest.java b/virtdata-lib-curves4/src/test/java/io/nosqlbench/virtdata/library/curves4/discrete/IntegerDistributionsConcurrencyTest.java index bd2b336b0..45b5550ef 100644 --- a/virtdata-lib-curves4/src/test/java/io/nosqlbench/virtdata/library/curves4/discrete/IntegerDistributionsConcurrencyTest.java +++ b/virtdata-lib-curves4/src/test/java/io/nosqlbench/virtdata/library/curves4/discrete/IntegerDistributionsConcurrencyTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,7 +40,7 @@ public class IntegerDistributionsConcurrencyTest { @Test public void testBinomialICDR() { Offset offset = Offset.offset(0.00001d); - BinomialDistribution distribution = new BinomialDistribution(8, 0.5); + BinomialDistribution distribution = BinomialDistribution.of(8, 0.5); assertThat(distribution.probability(0)).isCloseTo(0.00390d, offset); assertThat(distribution.probability(1)).isCloseTo(0.03125d, offset); assertThat(distribution.probability(2)).isCloseTo(0.10937d, offset); diff --git a/virtdata-lib-curves4/src/test/java/io/nosqlbench/virtdata/library/curves4/discrete/IntegerDistributionsValuesTest.java b/virtdata-lib-curves4/src/test/java/io/nosqlbench/virtdata/library/curves4/discrete/IntegerDistributionsValuesTest.java index 4c8bc3a6e..88bc846b9 100644 --- a/virtdata-lib-curves4/src/test/java/io/nosqlbench/virtdata/library/curves4/discrete/IntegerDistributionsValuesTest.java +++ b/virtdata-lib-curves4/src/test/java/io/nosqlbench/virtdata/library/curves4/discrete/IntegerDistributionsValuesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 nosqlbench + * Copyright (c) 2022-2023 nosqlbench * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ package io.nosqlbench.virtdata.library.curves4.discrete; import io.nosqlbench.virtdata.library.curves4.continuous.long_double.Uniform; import io.nosqlbench.virtdata.library.curves4.discrete.long_long.Zipf; -import org.apache.commons.math4.stat.descriptive.DescriptiveStatistics; +import org.apache.commons.math4.legacy.stat.descriptive.DescriptiveStatistics; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.assertj.core.data.Offset; diff --git a/virtdata-lib-random/pom.xml b/virtdata-lib-random/pom.xml index 97da72b4d..c24738e44 100644 --- a/virtdata-lib-random/pom.xml +++ b/virtdata-lib-random/pom.xml @@ -55,11 +55,6 @@ joda-time - - org.apache.commons - commons-math3 - - com.elega9t number-to-words @@ -74,50 +69,6 @@ - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - src/main/java diff --git a/virtdata-lib-realer/pom.xml b/virtdata-lib-realer/pom.xml index 3eeda643b..19d9757a0 100644 --- a/virtdata-lib-realer/pom.xml +++ b/virtdata-lib-realer/pom.xml @@ -42,50 +42,6 @@ - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - src/main/java diff --git a/virtdata-realdata/pom.xml b/virtdata-realdata/pom.xml index 228c5945a..cd6f85189 100644 --- a/virtdata-realdata/pom.xml +++ b/virtdata-realdata/pom.xml @@ -45,10 +45,6 @@ joda-time joda-time - - org.apache.commons - commons-math3 - org.greenrobot essentials @@ -61,50 +57,6 @@ - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - - - src/main/java diff --git a/virtdata-userlibs/pom.xml b/virtdata-userlibs/pom.xml index 0dc1ba0df..09be05153 100644 --- a/virtdata-userlibs/pom.xml +++ b/virtdata-userlibs/pom.xml @@ -98,49 +98,6 @@ - - - org.jacoco - jacoco-maven-plugin - 0.8.8 - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - jacoco-check - verify - - check - - - - - BUNDLE - - - INSTRUCTION - COVEREDRATIO - 0.00 - 1.00 - - - - - - - -