IGNITE-4572 Machine Learning: Develop distributed algebra support for dense and sparse data sets.
Project: http://git-wip-us.apache.org/repos/asf/ignite/repo Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/acd21fb8 Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/acd21fb8 Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/acd21fb8 Branch: refs/heads/ignite-1561-1 Commit: acd21fb8b0d1c7f274d50d30da292c96ede7515c Parents: 1f867c6 Author: Yury Babak <[email protected]> Authored: Fri Apr 14 18:50:30 2017 +0300 Committer: Anton Vinogradov <[email protected]> Committed: Fri Apr 14 18:50:30 2017 +0300 ---------------------------------------------------------------------- examples/pom-standalone-lgpl.xml | 6 + examples/pom-standalone.xml | 6 + examples/pom.xml | 6 + .../CholeskyDecompositionExample.java | 80 ++ .../EigenDecompositionExample.java | 69 ++ .../decompositions/LUDecompositionExample.java | 83 ++ .../SingularValueDecompositionExample.java | 70 ++ .../java8/math/decompositions/package-info.java | 22 + .../java8/math/matrix/CacheMatrixExample.java | 91 ++ .../java8/math/matrix/ExampleMatrixStorage.java | 162 +++ .../math/matrix/MatrixCustomStorageExample.java | 141 +++ .../java8/math/matrix/MatrixExample.java | 79 ++ .../java8/math/matrix/MatrixExampleUtil.java | 52 + .../java8/math/matrix/OffHeapMatrixExample.java | 84 ++ .../matrix/SparseDistributedMatrixExample.java | 65 + .../java8/math/matrix/SparseMatrixExample.java | 84 ++ .../java8/math/matrix/package-info.java | 22 + .../examples/java8/math/package-info.java | 22 + .../java8/math/tracer/TracerExample.java | 63 + .../java8/math/tracer/package-info.java | 22 + .../java8/math/vector/CacheVectorExample.java | 102 ++ .../java8/math/vector/ExampleVectorStorage.java | 126 ++ .../java8/math/vector/OffHeapVectorExample.java | 78 ++ .../java8/math/vector/SparseVectorExample.java | 80 ++ .../math/vector/VectorCustomStorageExample.java | 124 ++ .../java8/math/vector/VectorExample.java | 75 ++ .../java8/math/vector/package-info.java | 22 + modules/math/README.txt | 15 + modules/math/licenses/apache-2.0.txt | 202 ++++ modules/math/licenses/mit.txt | 7 + modules/math/pom.xml | 109 ++ .../java/org/apache/ignite/math/Algebra.java | 571 +++++++++ .../java/org/apache/ignite/math/Constants.java | 42 + .../org/apache/ignite/math/Destroyable.java | 30 + .../apache/ignite/math/IdentityValueMapper.java | 53 + .../java/org/apache/ignite/math/KeyMapper.java | 33 + .../java/org/apache/ignite/math/Matrix.java | 518 ++++++++ .../org/apache/ignite/math/MatrixKeyMapper.java | 30 + .../org/apache/ignite/math/MatrixStorage.java | 58 + .../org/apache/ignite/math/MetaAttributes.java | 76 ++ .../java/org/apache/ignite/math/MurmurHash.java | 246 ++++ .../apache/ignite/math/StorageConstants.java | 49 + .../apache/ignite/math/StorageOpsMetrics.java | 49 + .../java/org/apache/ignite/math/Tracer.java | 456 +++++++ .../org/apache/ignite/math/ValueMapper.java | 27 + .../java/org/apache/ignite/math/Vector.java | 498 ++++++++ .../org/apache/ignite/math/VectorKeyMapper.java | 29 + .../org/apache/ignite/math/VectorStorage.java | 53 + .../decompositions/CholeskyDecomposition.java | 306 +++++ .../decompositions/DecompositionSupport.java | 105 ++ .../math/decompositions/EigenDecomposition.java | 923 +++++++++++++++ .../math/decompositions/LUDecomposition.java | 366 ++++++ .../math/decompositions/QRDecomposition.java | 186 +++ .../SingularValueDecomposition.java | 620 ++++++++++ .../math/decompositions/package-info.java | 22 + .../math/exceptions/CardinalityException.java | 38 + .../math/exceptions/ColumnIndexException.java | 35 + .../ignite/math/exceptions/IndexException.java | 35 + .../NonPositiveDefiniteMatrixException.java | 20 + .../exceptions/NonSymmetricMatrixException.java | 18 + .../math/exceptions/RowIndexException.java | 35 + .../exceptions/SingularMatrixException.java | 30 + .../exceptions/UnknownProviderException.java | 35 + .../UnsupportedOperationException.java | 44 + .../ignite/math/exceptions/package-info.java | 22 + .../apache/ignite/math/functions/Functions.java | 136 +++ .../ignite/math/functions/IgniteBiConsumer.java | 12 + .../ignite/math/functions/IgniteBiFunction.java | 29 + .../ignite/math/functions/IgniteConsumer.java | 29 + .../math/functions/IgniteDoubleFunction.java | 29 + .../ignite/math/functions/IgniteFunction.java | 30 + .../math/functions/IntDoubleToVoidFunction.java | 25 + .../functions/IntIntDoubleToVoidFunction.java | 28 + .../math/functions/IntIntToDoubleFunction.java | 24 + .../ignite/math/functions/package-info.java | 22 + .../apache/ignite/math/impls/CacheUtils.java | 356 ++++++ .../math/impls/matrix/AbstractMatrix.java | 880 ++++++++++++++ .../ignite/math/impls/matrix/CacheMatrix.java | 158 +++ .../impls/matrix/DenseLocalOffHeapMatrix.java | 90 ++ .../impls/matrix/DenseLocalOnHeapMatrix.java | 86 ++ .../math/impls/matrix/DiagonalMatrix.java | 101 ++ .../math/impls/matrix/FunctionMatrix.java | 95 ++ .../ignite/math/impls/matrix/MatrixView.java | 84 ++ .../math/impls/matrix/PivotedMatrixView.java | 243 ++++ .../ignite/math/impls/matrix/RandomMatrix.java | 97 ++ .../impls/matrix/SparseDistributedMatrix.java | 155 +++ .../impls/matrix/SparseLocalOnHeapMatrix.java | 72 ++ .../math/impls/matrix/TransposedMatrixView.java | 84 ++ .../ignite/math/impls/matrix/package-info.java | 22 + .../apache/ignite/math/impls/package-info.java | 22 + .../storage/matrix/ArrayMatrixStorage.java | 161 +++ .../storage/matrix/CacheMatrixStorage.java | 180 +++ .../matrix/DenseOffHeapMatrixStorage.java | 197 ++++ .../storage/matrix/DiagonalMatrixStorage.java | 136 +++ .../storage/matrix/FunctionMatrixStorage.java | 175 +++ .../storage/matrix/MatrixDelegateStorage.java | 205 ++++ .../storage/matrix/PivotedMatrixStorage.java | 256 ++++ .../storage/matrix/RandomMatrixStorage.java | 176 +++ .../matrix/SparseDistributedMatrixStorage.java | 283 +++++ .../matrix/SparseLocalOnHeapMatrixStorage.java | 226 ++++ .../math/impls/storage/matrix/package-info.java | 22 + .../storage/vector/ArrayVectorStorage.java | 135 +++ .../storage/vector/CacheVectorStorage.java | 175 +++ .../storage/vector/ConstantVectorStorage.java | 133 +++ .../storage/vector/DelegateVectorStorage.java | 157 +++ .../vector/DenseLocalOffHeapVectorStorage.java | 172 +++ .../storage/vector/FunctionVectorStorage.java | 141 +++ .../storage/vector/MatrixVectorStorage.java | 185 +++ .../storage/vector/PivotedVectorStorage.java | 175 +++ .../storage/vector/RandomVectorStorage.java | 152 +++ .../SingleElementVectorDelegateStorage.java | 145 +++ .../vector/SingleElementVectorStorage.java | 143 +++ .../vector/SparseLocalOffHeapVectorStorage.java | 148 +++ .../vector/SparseLocalOnHeapVectorStorage.java | 152 +++ .../math/impls/storage/vector/package-info.java | 22 + .../impls/vector/AbstractReadOnlyVector.java | 108 ++ .../math/impls/vector/AbstractVector.java | 903 ++++++++++++++ .../ignite/math/impls/vector/CacheVector.java | 140 +++ .../math/impls/vector/ConstantVector.java | 84 ++ .../math/impls/vector/DelegatingVector.java | 391 ++++++ .../impls/vector/DenseLocalOffHeapVector.java | 89 ++ .../impls/vector/DenseLocalOnHeapVector.java | 104 ++ .../math/impls/vector/FunctionVector.java | 112 ++ .../math/impls/vector/MatrixVectorView.java | 139 +++ .../math/impls/vector/PivotedVectorView.java | 163 +++ .../ignite/math/impls/vector/RandomVector.java | 128 ++ .../math/impls/vector/SingleElementVector.java | 102 ++ .../impls/vector/SingleElementVectorView.java | 97 ++ .../impls/vector/SparseLocalOffHeapVector.java | 47 + .../math/impls/vector/SparseLocalVector.java | 71 ++ .../ignite/math/impls/vector/VectorView.java | 85 ++ .../ignite/math/impls/vector/package-info.java | 22 + .../org/apache/ignite/math/package-info.java | 22 + .../apache/ignite/math/d3-matrix-template.html | 128 ++ .../apache/ignite/math/d3-vector-template.html | 111 ++ .../org/apache/ignite/math/ExternalizeTest.java | 66 ++ .../math/MathImplDistributedTestSuite.java | 39 + .../ignite/math/MathImplLocalTestSuite.java | 123 ++ .../ignite/math/MathImplMainTestSuite.java | 33 + .../java/org/apache/ignite/math/TracerTest.java | 195 +++ .../ignite/math/benchmark/MathBenchmark.java | 205 ++++ .../math/benchmark/MathBenchmarkSelfTest.java | 100 ++ .../ignite/math/benchmark/ResultsWriter.java | 127 ++ .../math/benchmark/VectorBenchmarkTest.java | 138 +++ .../ignite/math/benchmark/package-info.java | 18 + .../CholeskyDecompositionTest.java | 158 +++ .../decompositions/EigenDecompositionTest.java | 193 +++ .../decompositions/LUDecompositionTest.java | 250 ++++ .../decompositions/QRDecompositionTest.java | 139 +++ .../SingularValueDecompositionTest.java | 120 ++ .../ignite/math/impls/MathTestConstants.java | 88 ++ .../math/impls/matrix/CacheMatrixTest.java | 369 ++++++ .../DenseLocalOffHeapMatrixConstructorTest.java | 65 + .../DenseLocalOnHeapMatrixConstructorTest.java | 71 ++ .../math/impls/matrix/DiagonalMatrixTest.java | 209 ++++ .../matrix/FunctionMatrixConstructorTest.java | 113 ++ .../math/impls/matrix/MatrixAttributeTest.java | 156 +++ .../matrix/MatrixImplementationFixtures.java | 381 ++++++ .../impls/matrix/MatrixImplementationsTest.java | 1113 ++++++++++++++++++ .../impls/matrix/MatrixKeyMapperForTests.java | 69 ++ .../impls/matrix/MatrixViewConstructorTest.java | 114 ++ .../PivotedMatrixViewConstructorTest.java | 128 ++ .../matrix/RandomMatrixConstructorTest.java | 71 ++ .../matrix/SparseDistributedMatrixTest.java | 265 +++++ .../SparseLocalOnHeapMatrixConstructorTest.java | 53 + .../impls/matrix/TransposedMatrixViewTest.java | 87 ++ .../storage/matrix/MatrixArrayStorageTest.java | 63 + .../storage/matrix/MatrixBaseStorageTest.java | 89 ++ .../matrix/MatrixOffHeapStorageTest.java | 39 + .../storage/matrix/MatrixStorageFixtures.java | 141 +++ .../matrix/MatrixStorageImplementationTest.java | 73 ++ .../SparseDistributedMatrixStorageTest.java | 126 ++ .../RandomAccessSparseVectorStorageTest.java | 60 + .../SparseLocalOffHeapVectorStorageTest.java | 78 ++ .../storage/vector/VectorArrayStorageTest.java | 58 + .../storage/vector/VectorBaseStorageTest.java | 69 ++ .../vector/VectorOffheapStorageTest.java | 73 ++ .../math/impls/vector/AbstractVectorTest.java | 543 +++++++++ .../math/impls/vector/CacheVectorTest.java | 417 +++++++ .../vector/ConstantVectorConstructorTest.java | 52 + .../vector/DelegatingVectorConstructorTest.java | 62 + .../DenseLocalOffHeapVectorConstructorTest.java | 59 + .../DenseLocalOnHeapVectorConstructorTest.java | 163 +++ .../vector/FunctionVectorConstructorTest.java | 121 ++ .../math/impls/vector/MatrixVectorViewTest.java | 209 ++++ .../PivotedVectorViewConstructorTest.java | 211 ++++ .../vector/RandomVectorConstructorTest.java | 145 +++ .../SingleElementVectorConstructorTest.java | 159 +++ .../SingleElementVectorViewConstructorTest.java | 137 +++ .../SparseLocalVectorConstructorTest.java | 54 + .../math/impls/vector/VectorAttributesTest.java | 217 ++++ .../math/impls/vector/VectorFoldMapTest.java | 122 ++ .../vector/VectorImplementationsFixtures.java | 655 +++++++++++ .../impls/vector/VectorImplementationsTest.java | 860 ++++++++++++++ .../math/impls/vector/VectorIterableTest.java | 376 ++++++ .../math/impls/vector/VectorNormTest.java | 247 ++++ .../math/impls/vector/VectorToMatrixTest.java | 291 +++++ .../math/impls/vector/VectorViewTest.java | 162 +++ pom.xml | 7 + 199 files changed, 29228 insertions(+) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/pom-standalone-lgpl.xml ---------------------------------------------------------------------- diff --git a/examples/pom-standalone-lgpl.xml b/examples/pom-standalone-lgpl.xml index d9e630b..f9d8a2c 100644 --- a/examples/pom-standalone-lgpl.xml +++ b/examples/pom-standalone-lgpl.xml @@ -73,6 +73,12 @@ <dependency> <groupId>org.apache.ignite</groupId> + <artifactId>ignite-math</artifactId> + <version>to_be_replaced_by_ignite_version</version> + </dependency> + + <dependency> + <groupId>org.apache.ignite</groupId> <artifactId>ignite-spring-data</artifactId> <version>to_be_replaced_by_ignite_version</version> </dependency> http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/pom-standalone.xml ---------------------------------------------------------------------- diff --git a/examples/pom-standalone.xml b/examples/pom-standalone.xml index fe559f8..f48b74f 100644 --- a/examples/pom-standalone.xml +++ b/examples/pom-standalone.xml @@ -78,6 +78,12 @@ </dependency> <dependency> + <groupId>org.apache.ignite</groupId> + <artifactId>ignite-math</artifactId> + <version>to_be_replaced_by_ignite_version</version> + </dependency> + + <dependency> <groupId>com.google.code.simple-spring-memcached</groupId> <artifactId>spymemcached</artifactId> <version>2.7.3</version> http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/pom.xml ---------------------------------------------------------------------- diff --git a/examples/pom.xml b/examples/pom.xml index cdb72ca..bed361b 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -107,6 +107,12 @@ </dependency> <dependency> + <groupId>org.apache.ignite</groupId> + <artifactId>ignite-math</artifactId> + <version>${project.version}</version> + </dependency> + + <dependency> <groupId>org.gridgain</groupId> <artifactId>ignite-shmem</artifactId> <version>1.0.0</version> http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/CholeskyDecompositionExample.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/CholeskyDecompositionExample.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/CholeskyDecompositionExample.java new file mode 100644 index 0000000..9a68e28 --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/CholeskyDecompositionExample.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.examples.java8.math.decompositions; + +import org.apache.ignite.math.Matrix; +import org.apache.ignite.math.Tracer; +import org.apache.ignite.math.decompositions.CholeskyDecomposition; +import org.apache.ignite.math.impls.matrix.DenseLocalOnHeapMatrix; + +/** + * Example of using {@link CholeskyDecomposition}. + */ +public class CholeskyDecompositionExample { + /** + * Executes example. + * + * @param args Command line arguments, none required. + */ + public static void main(String[] args) { + System.out.println(">>> Cholesky decomposition example started."); + // Let's compute a Cholesky decomposition of Hermitian matrix m: + // m = l l^{*}, where + // l is a lower triangular matrix + // l^{*} is its conjugate transpose + + DenseLocalOnHeapMatrix m = new DenseLocalOnHeapMatrix(new double[][] { + {2.0d, -1.0d, 0.0d}, + {-1.0d, 2.0d, -1.0d}, + {0.0d, -1.0d, 2.0d} + }); + System.out.println("\n>>> Matrix m for decomposition: "); + Tracer.showAscii(m); + + // This decomposition is useful when dealing with systems of linear equations of the form + // m x = b where m is a Hermitian matrix. + // For such systems Cholesky decomposition provides + // more effective method of solving compared to LU decomposition. + // Suppose we want to solve system + // m x = b for various bs. Then after we computed Cholesky decomposition, we can feed various bs + // as a matrix of the form + // (b1, b2, ..., bm) + // to the method Cholesky::solve which returns solutions in the form + // (sol1, sol2, ..., solm) + CholeskyDecomposition dec = new CholeskyDecomposition(m); + System.out.println("\n>>> Made decomposition m = l * l^{*}."); + System.out.println(">>> Matrix l is "); + Tracer.showAscii(dec.getL()); + System.out.println(">>> Matrix l^{*} is "); + Tracer.showAscii(dec.getLT()); + + Matrix bs = new DenseLocalOnHeapMatrix(new double[][] { + {4.0, -6.0, 7.0}, + {1.0, 1.0, 1.0} + }).transpose(); + System.out.println("\n>>> Solving systems of linear equations of the form m x = b for various bs represented by columns of matrix"); + Tracer.showAscii(bs); + Matrix sol = dec.solve(bs); + + System.out.println("\n>>> List of solutions: "); + for (int i = 0; i < sol.columnSize(); i++) + Tracer.showAscii(sol.viewColumn(i)); + + System.out.println("\n>>> Cholesky decomposition example completed."); + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/EigenDecompositionExample.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/EigenDecompositionExample.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/EigenDecompositionExample.java new file mode 100644 index 0000000..e11d642 --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/EigenDecompositionExample.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.examples.java8.math.decompositions; + +import org.apache.ignite.math.Tracer; +import org.apache.ignite.math.decompositions.EigenDecomposition; +import org.apache.ignite.math.functions.Functions; +import org.apache.ignite.math.impls.matrix.DenseLocalOnHeapMatrix; + +/** + * Example of using {@link EigenDecomposition}. + */ +public class EigenDecompositionExample { + /** + * Executes example. + * + * @param args Command line arguments, none required. + */ + public static void main(String[] args) { + System.out.println(">>> Eigen decomposition example started."); + + // Let's compute EigenDecomposition for some square (n x n) matrix m with real eigenvalues: + // m = v d v^{-1}, where d is diagonal matrix having eigenvalues of m on diagonal + // and v is matrix where i-th column is eigenvector for i-th eigenvalue (i from 0 to n - 1) + DenseLocalOnHeapMatrix m = new DenseLocalOnHeapMatrix(new double[][] { + {1.0d, 0.0d, 0.0d, 0.0d}, + {0.0d, 1.0d, 0.0d, 0.0d}, + {0.0d, 0.0d, 2.0d, 0.0d}, + {1.0d, 1.0d, 0.0d, 2.0d} + }); + System.out.println("\n>>> Matrix m for decomposition: "); + Tracer.showAscii(m); + + EigenDecomposition dec = new EigenDecomposition(m); + System.out.println("\n>>> Made decomposition."); + System.out.println(">>> Matrix getV is "); + Tracer.showAscii(dec.getV()); + System.out.println(">>> Matrix getD is "); + Tracer.showAscii(dec.getD()); + + // From this decomposition we, for example, can easily compute determinant of matrix m + // det (m) = det (v d v^{-1}) = + // det(v) det (d) det(v^{-1}) = + // det(v) det(v)^{-1} det(d) = + // det (d) = + // product of diagonal elements of d = + // product of eigenvalues + double det = dec.getRealEigenValues().foldMap(Functions.MULT, Functions.IDENTITY, 1.0); + System.out.println("\n>>> Determinant is " + det); + + System.out.println("\n>>> Eigen decomposition example completed."); + } + +} http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/LUDecompositionExample.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/LUDecompositionExample.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/LUDecompositionExample.java new file mode 100644 index 0000000..bf005ec --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/LUDecompositionExample.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.examples.java8.math.decompositions; + +import org.apache.ignite.math.Matrix; +import org.apache.ignite.math.Tracer; +import org.apache.ignite.math.decompositions.LUDecomposition; +import org.apache.ignite.math.impls.matrix.DenseLocalOnHeapMatrix; + +/** + * Example of using {@link LUDecomposition}. + */ +public class LUDecompositionExample { + /** + * Executes example. + * + * @param args Command line arguments, none required. + */ + public static void main(String[] args) { + System.out.println(">>> LU decomposition example started."); + // Let's compute a LU decomposition for some (n x n) matrix m: + // m = p l u, where + // p is an (n x n) is a row-permutation matrix + // l is a (n x n) lower triangular matrix + // u is a (n x n) upper triangular matrix + + DenseLocalOnHeapMatrix m = new DenseLocalOnHeapMatrix(new double[][] { + {1.0d, 1.0d, -1.0d}, + {1.0d, -2.0d, 3.0d}, + {2.0d, 3.0d, 1.0d} + }); + System.out.println("\n>>> Matrix m for decomposition: "); + Tracer.showAscii(m); + + // This decomposition is useful when dealing with systems of linear equations. + // (see https://en.wikipedia.org/wiki/LU_decomposition) + // suppose we want to solve system + // m x = b for various bs. Then after we computed LU decomposition, we can feed various bs + // as a matrix of the form + // (b1, b2, ..., bm) + // to the method LUDecomposition::solve which returns solutions in the form + // (sol1, sol2, ..., solm) + + LUDecomposition dec = new LUDecomposition(m); + System.out.println("\n>>> Made decomposition."); + System.out.println(">>> Matrix getL is "); + Tracer.showAscii(dec.getL()); + System.out.println(">>> Matrix getU is "); + Tracer.showAscii(dec.getU()); + System.out.println(">>> Matrix getP is "); + Tracer.showAscii(dec.getP()); + + Matrix bs = new DenseLocalOnHeapMatrix(new double[][] { + {4.0, -6.0, 7.0}, + {1.0, 1.0, 1.0} + }); + System.out.println("\n>>> Matrix to solve: "); + Tracer.showAscii(bs); + + Matrix sol = dec.solve(bs.transpose()); + + System.out.println("\n>>> List of solutions: "); + for (int i = 0; i < sol.columnSize(); i++) + Tracer.showAscii(sol.viewColumn(i)); + + System.out.println("\n>>> LU decomposition example completed."); + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/SingularValueDecompositionExample.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/SingularValueDecompositionExample.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/SingularValueDecompositionExample.java new file mode 100644 index 0000000..1b2998f --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/SingularValueDecompositionExample.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.examples.java8.math.decompositions; + +import org.apache.ignite.math.Tracer; +import org.apache.ignite.math.decompositions.SingularValueDecomposition; +import org.apache.ignite.math.impls.matrix.DenseLocalOnHeapMatrix; + +/** + * Example of using {@link SingularValueDecomposition}. + */ +public class SingularValueDecompositionExample { + /** + * Executes example. + * + * @param args Command line arguments, none required. + */ + public static void main(String[] args) { + System.out.println(">>> Singular value decomposition (SVD) example started."); + + // Let's compute a SVD of (l x k) matrix m. This decomposition can be thought as extension of EigenDecomposition to + // rectangular matrices. The factorization we get is following: + // m = u * s * v^{*}, where + // u is a real or complex unitary matrix + // s is a rectangular diagonal matrix with non-negative real numbers on diagonal (this numbers are singular values of m) + // v is a real or complex unitary matrix + // If m is real then u and v are also real. + // Complex case is not supported for the moment. + DenseLocalOnHeapMatrix m = new DenseLocalOnHeapMatrix(new double[][] { + {1.0d, 0.0d, 0.0d, 0.0d, 2.0d}, + {0.0d, 0.0d, 3.0d, 0.0d, 0.0d}, + {0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, + {0.0d, 2.0d, 0.0d, 0.0d, 0.0d} + }); + System.out.println("\n>>> Matrix m for decomposition: "); + Tracer.showAscii(m); + + SingularValueDecomposition dec = new SingularValueDecomposition(m); + System.out.println("\n>>> Made decomposition m = u * s * v^{*}."); + System.out.println(">>> Matrix u is "); + Tracer.showAscii(dec.getU()); + System.out.println(">>> Matrix s is "); + Tracer.showAscii(dec.getS()); + System.out.println(">>> Matrix v is "); + Tracer.showAscii(dec.getV()); + + // This decomposition can in particular help with solving problem of finding x minimizing 2-norm of m x such + // that 2-norm of x is 1. It appears that it is the right singular vector corresponding to minimal singular + // value, which is always last. + System.out.println("\n>>> Vector x minimizing 2-norm of m x such that 2 norm of x is 1: "); + Tracer.showAscii(dec.getV().viewColumn(dec.getSingularValues().length - 1)); + + System.out.println("\n>>> Singular value decomposition (SVD) example completed."); + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/package-info.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/package-info.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/package-info.java new file mode 100644 index 0000000..cd02b21 --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/decompositions/package-info.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * <!-- Package description. --> + * Core algebra decomposition examples. + */ +package org.apache.ignite.examples.java8.math.decompositions; http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/CacheMatrixExample.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/CacheMatrixExample.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/CacheMatrixExample.java new file mode 100644 index 0000000..44f97d2 --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/CacheMatrixExample.java @@ -0,0 +1,91 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.examples.java8.math.matrix; + +import org.apache.ignite.Ignite; +import org.apache.ignite.IgniteCache; +import org.apache.ignite.Ignition; +import org.apache.ignite.configuration.CacheConfiguration; +import org.apache.ignite.math.IdentityValueMapper; +import org.apache.ignite.math.MatrixKeyMapper; +import org.apache.ignite.math.ValueMapper; +import org.apache.ignite.math.functions.Functions; +import org.apache.ignite.math.impls.matrix.CacheMatrix; + +/** */ +public class CacheMatrixExample { + /** */ private static final String CACHE_NAME = CacheMatrixExample.class.getSimpleName(); + /** */ private static final int ROWS = 3; + /** */ private static final int COLS = 3; + + /** + * Executes example. + * + * @param args Command line arguments, none required. + */ + public static void main(String[] args) { + try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { + System.out.println(); + System.out.println(">>> CacheMatrix example started."); + + CacheConfiguration<Integer, Double> cfg = new CacheConfiguration<>(); + + cfg.setName(CACHE_NAME); + + try (IgniteCache<Integer, Double> cache = ignite.getOrCreateCache(cfg)) { + double[][] testValues = {{1.0, 0.0, 0.0}, {1.0, 1.0, 0.0}, {1.0, 1.0, 1.0}}; + + ValueMapper valMapper = new IdentityValueMapper(); + + // Map matrix element indices to cache keys. + MatrixKeyMapper<Integer> keyMapper = new MatrixKeyMapper<Integer>() { + @Override public Integer apply(int x, int y) { + return x * COLS + y; + } + + @Override public boolean isValid(Integer integer) { + return integer >= 0 && integer < COLS * ROWS; + } + }; + + // Create cache matrix. + CacheMatrix<Integer, Double> cacheMatrix = new CacheMatrix<>(ROWS, COLS, cache, keyMapper, valMapper); + + cacheMatrix.assign(testValues); + + // Find all positive elements. + Integer nonZeroes = cacheMatrix.foldMap((o, aDouble) -> { + if (aDouble > 0) + return o + 1; + return o; + }, Functions.IDENTITY, 0); + + assert nonZeroes.equals(6); + + System.out.println(">>>"); + System.out.println(">>> Finished executing Ignite \"CacheMatrix\" example."); + System.out.println(">>> Lower triangular matrix 3x3 have only 6 positive elements."); + System.out.println(">>>"); + } + finally { + // Distributed cache could be removed from cluster only by #destroyCache() call. + ignite.destroyCache(CACHE_NAME); + } + } + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/ExampleMatrixStorage.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/ExampleMatrixStorage.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/ExampleMatrixStorage.java new file mode 100644 index 0000000..260f62d --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/ExampleMatrixStorage.java @@ -0,0 +1,162 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.examples.java8.math.matrix; + +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectOutput; +import java.util.Arrays; + +import org.apache.ignite.math.MatrixStorage; + +/** + * Example matrix storage, modeled after {@link org.apache.ignite.math.impls.storage.matrix.ArrayMatrixStorage}. + */ +class ExampleMatrixStorage implements MatrixStorage { + /** Backing data array. */ + private double[][] data; + /** Amount of rows in a matrix storage. */ + private int rows; + /** Amount of columns in a matrix storage. */ + private int cols; + + /** + * + */ + public ExampleMatrixStorage() { + // No-op. + } + + /** + * @param rows Amount of rows in a matrix storage. + * @param cols Amount of columns in a matrix storage. + */ + ExampleMatrixStorage(int rows, int cols) { + assert rows > 0; + assert cols > 0; + + this.data = new double[rows][cols]; + this.rows = rows; + this.cols = cols; + } + + /** + * @param data Backing data array. + */ + ExampleMatrixStorage(double[][] data) { + assert data != null; + assert data[0] != null; + + this.data = data; + this.rows = data.length; + this.cols = data[0].length; + + assert rows > 0; + assert cols > 0; + } + + /** {@inheritDoc} */ + @Override public double get(int x, int y) { + return data[x][y]; + } + + /** {@inheritDoc} */ + @Override public boolean isSequentialAccess() { + return false; + } + + /** {@inheritDoc} */ + @Override public boolean isDense() { + return true; + } + + /** {@inheritDoc} */ + @Override public boolean isRandomAccess() { + return true; + } + + /** {@inheritDoc} */ + @Override public boolean isDistributed() { + return false; + } + + /** {@inheritDoc} */ + @Override public void set(int x, int y, double v) { + data[x][y] = v; + } + + /** {@inheritDoc} */ + @Override public int columnSize() { + return cols; + } + + /** {@inheritDoc} */ + @Override public int rowSize() { + return rows; + } + + /** {@inheritDoc} */ + @Override public boolean isArrayBased() { + return true; + } + + /** {@inheritDoc} */ + @Override public double[][] data() { + return data; + } + + /** {@inheritDoc */ + @Override public void writeExternal(ObjectOutput out) throws IOException { + out.writeInt(rows); + out.writeInt(cols); + + out.writeObject(data); + } + + /** {@inheritDoc */ + @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { + rows = in.readInt(); + cols = in.readInt(); + + data = (double[][])in.readObject(); + } + + /** {@inheritDoc} */ + @Override public int hashCode() { + int res = 1; + + res += res * 37 + rows; + res += res * 37 + cols; + res += res * 37 + Arrays.deepHashCode(data); + + return res; + } + + /** {@inheritDoc} */ + @Override public boolean equals(Object o) { + if (this == o) + return true; + + if (o == null || getClass() != o.getClass()) + return false; + + ExampleMatrixStorage that = (ExampleMatrixStorage)o; + + return Arrays.deepEquals(data, that.data); + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/MatrixCustomStorageExample.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/MatrixCustomStorageExample.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/MatrixCustomStorageExample.java new file mode 100644 index 0000000..637b2b4 --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/MatrixCustomStorageExample.java @@ -0,0 +1,141 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.examples.java8.math.matrix; + +import org.apache.ignite.math.Matrix; +import org.apache.ignite.math.MatrixStorage; +import org.apache.ignite.math.Vector; +import org.apache.ignite.math.impls.matrix.AbstractMatrix; +import org.apache.ignite.math.impls.vector.DenseLocalOnHeapVector; + +/** + * This example shows how to use {@link Matrix} API based on custom {@link MatrixStorage}. + */ +public final class MatrixCustomStorageExample { + /** + * Executes example. + * + * @param args Command line arguments, none required. + */ + public static void main(String[] args) { + System.out.println(); + System.out.println(">>> Matrix API usage example started."); + + System.out.println("\n>>> Creating a matrix to be transposed."); + double[][] data = new double[][] {{1, 2, 3}, {4, 5, 6}}; + Matrix m = new MatrixCustomStorage(data); + Matrix transposed = m.transpose(); + + System.out.println(">>> Matrix: "); + MatrixExampleUtil.print(m); + System.out.println(">>> Transposed matrix: "); + MatrixExampleUtil.print(transposed); + + MatrixExampleUtil.verifyTransposition(m, transposed); + + System.out.println("\n>>> Creating matrices to be multiplied."); + double[][] data1 = new double[][] {{1, 2}, {3, 4}}; + double[][] data2 = new double[][] {{5, 6}, {7, 8}}; + + Matrix m1 = new MatrixCustomStorage(data1); + Matrix m2 = new MatrixCustomStorage(data2); + Matrix mult = m1.times(m2); + + System.out.println(">>> First matrix: "); + MatrixExampleUtil.print(m1); + System.out.println(">>> Second matrix: "); + MatrixExampleUtil.print(m2); + System.out.println(">>> Matrix product: "); + MatrixExampleUtil.print(mult); + + System.out.println("\n>>> Calculating matrices determinants."); + double det1 = m1.determinant(); + double det2 = m2.determinant(); + double detMult = mult.determinant(); + boolean detMultIsAsExp = Math.abs(detMult - det1 * det2) < 0.0001d; + + System.out.println(">>> First matrix determinant: [" + det1 + "]."); + System.out.println(">>> Second matrix determinant: [" + det2 + "]."); + System.out.println(">>> Matrix product determinant: [" + detMult + + "], equals product of two other matrices determinants: [" + detMultIsAsExp + "]."); + + assert detMultIsAsExp : "Determinant of product matrix [" + detMult + + "] should be equal to product of determinants [" + (det1 * det2) + "]."; + + System.out.println("\n>>> Matrix API usage example completed."); + } + + /** + * Example of vector with custom storage, modeled after + * {@link org.apache.ignite.math.impls.matrix.DenseLocalOnHeapMatrix}. + */ + static class MatrixCustomStorage extends AbstractMatrix { + /** + * + */ + public MatrixCustomStorage() { + // No-op. + } + + /** + * @param rows Amount of rows in a matrix. + * @param cols Amount of columns in a matrix. + */ + MatrixCustomStorage(int rows, int cols) { + assert rows > 0; + assert cols > 0; + + setStorage(new ExampleMatrixStorage(rows, cols)); + } + + /** + * @param mtx Source matrix. + */ + MatrixCustomStorage(double[][] mtx) { + assert mtx != null; + + setStorage(new ExampleMatrixStorage(mtx)); + } + + /** + * @param orig original matrix to be copied. + */ + private MatrixCustomStorage(MatrixCustomStorage orig) { + assert orig != null; + + setStorage(new ExampleMatrixStorage(orig.rowSize(), orig.columnSize())); + + assign(orig); + } + + /** {@inheritDoc} */ + @Override public Matrix copy() { + return new MatrixCustomStorage(this); + } + + /** {@inheritDoc} */ + @Override public Matrix like(int rows, int cols) { + return new MatrixCustomStorage(rows, cols); + } + + /** {@inheritDoc} */ + @Override public Vector likeVector(int crd) { + return new DenseLocalOnHeapVector(crd); + } + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/MatrixExample.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/MatrixExample.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/MatrixExample.java new file mode 100644 index 0000000..58cedab --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/MatrixExample.java @@ -0,0 +1,79 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.examples.java8.math.matrix; + +import org.apache.ignite.math.Matrix; +import org.apache.ignite.math.impls.matrix.DenseLocalOnHeapMatrix; + +/** + * This example shows how to use {@link Matrix} API. + */ +public final class MatrixExample { + /** + * Executes example. + * + * @param args Command line arguments, none required. + */ + public static void main(String[] args) { + System.out.println(); + System.out.println(">>> Basic Matrix API usage example started."); + + System.out.println("\n>>> Creating a matrix to be transposed."); + double[][] data = new double[][] {{1, 2, 3}, {4, 5, 6}}; + Matrix m = new DenseLocalOnHeapMatrix(data); + Matrix transposed = m.transpose(); + + System.out.println(">>> Matrix: "); + MatrixExampleUtil.print(m); + System.out.println(">>> Transposed matrix: "); + MatrixExampleUtil.print(transposed); + + MatrixExampleUtil.verifyTransposition(m, transposed); + + System.out.println("\n>>> Creating matrices to be multiplied."); + double[][] data1 = new double[][] {{1, 2}, {3, 4}}; + double[][] data2 = new double[][] {{5, 6}, {7, 8}}; + + Matrix m1 = new DenseLocalOnHeapMatrix(data1); + Matrix m2 = new DenseLocalOnHeapMatrix(data2); + Matrix mult = m1.times(m2); + + System.out.println(">>> First matrix: "); + MatrixExampleUtil.print(m1); + System.out.println(">>> Second matrix: "); + MatrixExampleUtil.print(m2); + System.out.println(">>> Matrix product: "); + MatrixExampleUtil.print(mult); + + System.out.println("\n>>> Calculating matrices determinants."); + double det1 = m1.determinant(); + double det2 = m2.determinant(); + double detMult = mult.determinant(); + boolean detMultIsAsExp = Math.abs(detMult - det1 * det2) < 0.0001d; + + System.out.println(">>> First matrix determinant: [" + det1 + "]."); + System.out.println(">>> Second matrix determinant: [" + det2 + "]."); + System.out.println(">>> Matrix product determinant: [" + detMult + + "], equals product of two other matrices determinants: [" + detMultIsAsExp + "]."); + + assert detMultIsAsExp : "Determinant of product matrix [" + detMult + + "] should be equal to product of determinants [" + (det1 * det2) + "]."; + + System.out.println("\n>>> Basic Matrix API usage example completed."); + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/MatrixExampleUtil.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/MatrixExampleUtil.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/MatrixExampleUtil.java new file mode 100644 index 0000000..f3b4a62 --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/MatrixExampleUtil.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.examples.java8.math.matrix; + +import org.apache.ignite.math.Matrix; +import org.apache.ignite.math.Tracer; + +/** + * Utility functions for {@link Matrix} API examples. + */ +class MatrixExampleUtil { + /** + * Verifies matrix transposition. + * + * @param m Original matrix. + * @param transposed Transposed matrix. + */ + static void verifyTransposition(Matrix m, Matrix transposed) { + for (int row = 0; row < m.rowSize(); row++) + for (int col = 0; col < m.columnSize(); col++) { + double val = m.get(row, col); + double valTransposed = transposed.get(col, row); + + assert val == valTransposed : "Values not equal at (" + row + "," + col + + "), original: " + val + " transposed: " + valTransposed; + } + } + + /** + * Prints matrix values to console. + * + * @param m Matrix to print. + */ + static void print(Matrix m) { + Tracer.showAscii(m); + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/OffHeapMatrixExample.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/OffHeapMatrixExample.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/OffHeapMatrixExample.java new file mode 100644 index 0000000..bf99da1 --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/OffHeapMatrixExample.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.examples.java8.math.matrix; + +import org.apache.ignite.math.Matrix; +import org.apache.ignite.math.impls.matrix.DenseLocalOffHeapMatrix; + +/** + * This example shows how to use off-heap {@link Matrix} API. + */ +public final class OffHeapMatrixExample { + /** + * Executes example. + * + * @param args Command line arguments, none required. + */ + public static void main(String[] args) { + System.out.println(); + System.out.println(">>> Off-heap matrix API usage example started."); + + System.out.println("\n>>> Creating a matrix to be transposed."); + double[][] data = new double[][] {{1, 2, 3}, {4, 5, 6}}; + Matrix m = new DenseLocalOffHeapMatrix(data.length, data[0].length); + m.assign(data); + Matrix transposed = m.transpose(); + + System.out.println(">>> Matrix: "); + MatrixExampleUtil.print(m); + System.out.println(">>> Transposed matrix: "); + MatrixExampleUtil.print(transposed); + + MatrixExampleUtil.verifyTransposition(m, transposed); + + System.out.println("\n>>> Creating matrices to be multiplied."); + double[][] data1 = new double[][] {{1, 2}, {3, 4}}; + double[][] data2 = new double[][] {{5, 6}, {7, 8}}; + + Matrix m1 = new DenseLocalOffHeapMatrix(data1.length, data1[0].length); + Matrix m2 = new DenseLocalOffHeapMatrix(data2.length, data2[0].length); + + m1.assign(data1); + m2.assign(data2); + + Matrix mult = m1.times(m2); + + System.out.println(">>> First matrix: "); + MatrixExampleUtil.print(m1); + System.out.println(">>> Second matrix: "); + MatrixExampleUtil.print(m2); + System.out.println(">>> Matrix product: "); + MatrixExampleUtil.print(mult); + + System.out.println("\n>>> Calculating matrices determinants."); + double det1 = m1.determinant(); + double det2 = m2.determinant(); + double detMult = mult.determinant(); + boolean detMultIsAsExp = Math.abs(detMult - det1 * det2) < 0.0001d; + + System.out.println(">>> First matrix determinant: [" + det1 + "]."); + System.out.println(">>> Second matrix determinant: [" + det2 + "]."); + System.out.println(">>> Matrix product determinant: [" + detMult + + "], equals product of two other matrices determinants: [" + detMultIsAsExp + "]."); + + assert detMultIsAsExp : "Determinant of product matrix [" + detMult + + "] should be equal to product of determinants [" + (det1 * det2) + "]."; + + System.out.println("\n>>> Off-heap matrix API usage example completed."); + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/SparseDistributedMatrixExample.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/SparseDistributedMatrixExample.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/SparseDistributedMatrixExample.java new file mode 100644 index 0000000..7e71eb0 --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/SparseDistributedMatrixExample.java @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.ignite.examples.java8.math.matrix; + +import org.apache.ignite.Ignite; +import org.apache.ignite.Ignition; +import org.apache.ignite.math.StorageConstants; +import org.apache.ignite.math.impls.matrix.SparseDistributedMatrix; +import org.apache.ignite.thread.IgniteThread; + +/** + * This example shows how to use {@link SparseDistributedMatrix} API. + */ +public class SparseDistributedMatrixExample { + /** + * Executes example. + * + * @param args Command line arguments, none required. + */ + public static void main(String[] args) throws InterruptedException { + System.out.println(); + System.out.println(">>> Sparse distributed matrix API usage example started."); + // Start ignite grid. + try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { + System.out.println(">>> Ignite grid started."); + // Create IgniteThread, we must work with SparseDistributedMatrix inside IgniteThread + // because we create ignite cache internally. + IgniteThread igniteThread = new IgniteThread(ignite.configuration().getIgniteInstanceName(), SparseDistributedMatrixExample.class.getSimpleName(), () -> { + + double[][] testValues = {{1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 0.0, 1.0}}; + + System.out.println(">>> Create new SparseDistributedMatrix inside IgniteThread."); + // Create SparseDistributedMatrix, new cache will be created automagically. + SparseDistributedMatrix distributedMatrix = new SparseDistributedMatrix(testValues.length, testValues[0].length, + StorageConstants.ROW_STORAGE_MODE, StorageConstants.RANDOM_ACCESS_MODE); + + distributedMatrix.assign(testValues); + + assert distributedMatrix.sum() == 3.0; + + System.out.println(">>> Destroy SparseDistributedMatrix after using."); + // Destroy internal cache. + distributedMatrix.destroy(); + }); + + igniteThread.start(); + + igniteThread.join(); + } + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/SparseMatrixExample.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/SparseMatrixExample.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/SparseMatrixExample.java new file mode 100644 index 0000000..ba4e72b --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/SparseMatrixExample.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.examples.java8.math.matrix; + +import org.apache.ignite.math.Matrix; +import org.apache.ignite.math.impls.matrix.SparseLocalOnHeapMatrix; + +/** + * This example shows how to use sparse {@link Matrix} API. + */ +public final class SparseMatrixExample { + /** + * Executes example. + * + * @param args Command line arguments, none required. + */ + public static void main(String[] args) { + System.out.println(); + System.out.println(">>> Sparse matrix API usage example started."); + + System.out.println("\n>>> Creating a matrix to be transposed."); + double[][] data = new double[][] {{1, 2, 3}, {4, 5, 6}}; + Matrix m = new SparseLocalOnHeapMatrix(data.length, data[0].length); + m.assign(data); + Matrix transposed = m.transpose(); + + System.out.println(">>> Matrix: "); + MatrixExampleUtil.print(m); + System.out.println(">>> Transposed matrix: "); + MatrixExampleUtil.print(transposed); + + MatrixExampleUtil.verifyTransposition(m, transposed); + + System.out.println("\n>>> Creating matrices to be multiplied."); + double[][] data1 = new double[][] {{1, 2}, {3, 4}}; + double[][] data2 = new double[][] {{5, 6}, {7, 8}}; + + Matrix m1 = new SparseLocalOnHeapMatrix(data1.length, data1[0].length); + Matrix m2 = new SparseLocalOnHeapMatrix(data2.length, data2[0].length); + + m1.assign(data1); + m2.assign(data2); + + Matrix mult = m1.times(m2); + + System.out.println(">>> First matrix: "); + MatrixExampleUtil.print(m1); + System.out.println(">>> Second matrix: "); + MatrixExampleUtil.print(m2); + System.out.println(">>> Matrix product: "); + MatrixExampleUtil.print(mult); + + System.out.println("\n>>> Calculating matrices determinants."); + double det1 = m1.determinant(); + double det2 = m2.determinant(); + double detMult = mult.determinant(); + boolean detMultIsAsExp = Math.abs(detMult - det1 * det2) < 0.0001d; + + System.out.println(">>> First matrix determinant: [" + det1 + "]."); + System.out.println(">>> Second matrix determinant: [" + det2 + "]."); + System.out.println(">>> Matrix product determinant: [" + detMult + + "], equals product of two other matrices determinants: [" + detMultIsAsExp + "]."); + + assert detMultIsAsExp : "Determinant of product matrix [" + detMult + + "] should be equal to product of determinants [" + (det1 * det2) + "]."; + + System.out.println("\n>>> Sparse matrix API usage example completed."); + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/package-info.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/package-info.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/package-info.java new file mode 100644 index 0000000..9154518 --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/matrix/package-info.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * <!-- Package description. --> + * Core algebra matrix examples. + */ +package org.apache.ignite.examples.java8.math.matrix; http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/package-info.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/package-info.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/package-info.java new file mode 100644 index 0000000..90dae33 --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/package-info.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * <!-- Package description. --> + * Core algebra examples. + */ +package org.apache.ignite.examples.java8.math; http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/tracer/TracerExample.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/tracer/TracerExample.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/tracer/TracerExample.java new file mode 100644 index 0000000..f6e1baa --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/tracer/TracerExample.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.examples.java8.math.tracer; + +import java.awt.Color; +import java.io.IOException; +import org.apache.ignite.math.Tracer; +import org.apache.ignite.math.impls.matrix.DenseLocalOnHeapMatrix; + +/** + * Example of using {@link Tracer} utility API. + */ +public class TracerExample { + /** + * Double to color mapper example. + */ + private static final Tracer.ColorMapper COLOR_MAPPER = d -> { + if (d <= 0.33) + return Color.RED; + else if (d <= 0.66) + return Color.GREEN; + else + return Color.BLUE; + }; + + /** + * Executes example. + * + * @param args Command line arguments, none required. + */ + public static void main(String[] args) throws IOException { + System.out.println(">>> Tracer utility example started."); + + // Tracer is a simple utility class that allows pretty-printing of matrices/vectors + DenseLocalOnHeapMatrix m = new DenseLocalOnHeapMatrix(new double[][] { + {1.12345, 2.12345}, + {3.12345, 4.12345} + }); + + System.out.println("\n>>> Tracer output to console in ASCII."); + Tracer.showAscii(m, "%.3g"); + + System.out.println("\n>>> Tracer output to browser in HTML."); + Tracer.showHtml(m, COLOR_MAPPER); + + System.out.println("\n>>> Tracer utility example completed."); + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/tracer/package-info.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/tracer/package-info.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/tracer/package-info.java new file mode 100644 index 0000000..5a08504 --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/tracer/package-info.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * <!-- Package description. --> + * Core algebra tracer example. + */ +package org.apache.ignite.examples.java8.math.tracer; http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/vector/CacheVectorExample.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/vector/CacheVectorExample.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/vector/CacheVectorExample.java new file mode 100644 index 0000000..dd0fcb3 --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/vector/CacheVectorExample.java @@ -0,0 +1,102 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.examples.java8.math.vector; + +import org.apache.ignite.Ignite; +import org.apache.ignite.IgniteCache; +import org.apache.ignite.Ignition; +import org.apache.ignite.configuration.CacheConfiguration; +import org.apache.ignite.math.IdentityValueMapper; +import org.apache.ignite.math.ValueMapper; +import org.apache.ignite.math.VectorKeyMapper; +import org.apache.ignite.math.impls.vector.CacheVector; + +/** + * This example shows how to use {@link CacheVector} API. + */ +public class CacheVectorExample { + /** */ private static final String CACHE_NAME = CacheVectorExample.class.getSimpleName(); + /** */ private static final int CARDINALITY = 10; + + /** + * Executes example. + * + * @param args Command line arguments, none required. + */ + public static void main(String[] args) { + try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { + System.out.println(); + System.out.println(">>> CacheVector example started."); + + CacheConfiguration<Integer, Double> cfg = new CacheConfiguration<>(); + + cfg.setName(CACHE_NAME); + + try (IgniteCache<Integer, Double> cache = ignite.getOrCreateCache(cfg)) { + double[] testValues1 = {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; + double[] testValues2 = {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; + + ValueMapper valMapper = new IdentityValueMapper(); + + // Map vector element index to cache keys. + VectorKeyMapper<Integer> keyMapper1 = new VectorKeyMapper<Integer>() { + @Override public Integer apply(int i) { + return i; + } + + @Override public boolean isValid(Integer integer) { + return integer >= 0 && CARDINALITY > integer; + } + }; + + // Map vector element index to cache keys with shift. + VectorKeyMapper<Integer> keyMapper2 = new VectorKeyMapper<Integer>() { + @Override public Integer apply(int i) { + return i + CARDINALITY; + } + + @Override public boolean isValid(Integer integer) { + return integer >= 0 && CARDINALITY > integer; + } + }; + + // Create two cache vectors over one cache. + CacheVector cacheVector1 = new CacheVector(CARDINALITY, cache, keyMapper1, valMapper); + System.out.println(">>> First cache vector created."); + + CacheVector cacheVector2 = new CacheVector(CARDINALITY, cache, keyMapper2, valMapper); + System.out.println(">>> Second cache vector created."); + + cacheVector1.assign(testValues1); + cacheVector2.assign(testValues2); + + // Dot product for orthogonal vectors is 0.0. + assert cacheVector1.dot(cacheVector2) == 0.0; + + System.out.println(">>>"); + System.out.println(">>> Finished executing Ignite \"CacheVector\" example."); + System.out.println(">>> Dot product is 0.0 for orthogonal vectors."); + System.out.println(">>>"); + } + finally { + // Distributed cache could be removed from cluster only by #destroyCache() call. + ignite.destroyCache(CACHE_NAME); + } + } + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/vector/ExampleVectorStorage.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/vector/ExampleVectorStorage.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/vector/ExampleVectorStorage.java new file mode 100644 index 0000000..3b88e0a --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/vector/ExampleVectorStorage.java @@ -0,0 +1,126 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.examples.java8.math.vector; + +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectOutput; +import java.util.Arrays; + +import org.apache.ignite.math.VectorStorage; + +/** + * Example vector storage, modeled after {@link org.apache.ignite.math.impls.storage.vector.ArrayVectorStorage}. + */ +class ExampleVectorStorage implements VectorStorage { + /** */ + private double[] data; + + /** + * IMPL NOTE required by Externalizable + */ + public ExampleVectorStorage() { + // No-op. + } + + /** + * @param data backing data array. + */ + ExampleVectorStorage(double[] data) { + assert data != null; + + this.data = data; + } + + /** {@inheritDoc} */ + @Override public int size() { + return data == null ? 0 : data.length; + } + + /** {@inheritDoc} */ + @Override public double get(int i) { + return data[i]; + } + + /** {@inheritDoc} */ + @Override public void set(int i, double v) { + data[i] = v; + } + + /** {@inheritDoc}} */ + @Override public boolean isArrayBased() { + return true; + } + + /** {@inheritDoc} */ + @Override public double[] data() { + return data; + } + + /** {@inheritDoc} */ + @Override public boolean isSequentialAccess() { + return true; + } + + /** {@inheritDoc} */ + @Override public boolean isDense() { + return true; + } + + /** {@inheritDoc} */ + @Override public boolean isRandomAccess() { + return true; + } + + /** {@inheritDoc} */ + @Override public boolean isDistributed() { + return false; + } + + /** {@inheritDoc} */ + @Override public void writeExternal(ObjectOutput out) throws IOException { + out.writeObject(data); + } + + /** {@inheritDoc} */ + @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { + data = (double[])in.readObject(); + } + + /** {@inheritDoc} */ + @Override public int hashCode() { + int res = 1; + + res = res * 37 + Arrays.hashCode(data); + + return res; + } + + /** {@inheritDoc} */ + @Override public boolean equals(Object obj) { + if (this == obj) + return true; + + if (obj == null || getClass() != obj.getClass()) + return false; + + ExampleVectorStorage that = (ExampleVectorStorage)obj; + + return Arrays.equals(data, (that.data)); + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/vector/OffHeapVectorExample.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/vector/OffHeapVectorExample.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/vector/OffHeapVectorExample.java new file mode 100644 index 0000000..7184245 --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/vector/OffHeapVectorExample.java @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.examples.java8.math.vector; + +import java.util.Arrays; +import org.apache.ignite.math.Vector; +import org.apache.ignite.math.impls.vector.DenseLocalOffHeapVector; + +/** + * This example shows how to use off-heap {@link Vector} API. + */ +public final class OffHeapVectorExample { + /** + * Executes example. + * + * @param args Command line arguments, none required. + */ + public static void main(String[] args) { + System.out.println(); + System.out.println(">>> Off-heap vector API usage example started."); + + System.out.println("\n>>> Creating perpendicular off-heap vectors."); + double[] data1 = new double[] {1, 0, 3, 0, 5, 0}; + double[] data2 = new double[] {0, 2, 0, 4, 0, 6}; + + Vector v1 = new DenseLocalOffHeapVector(data1.length); + Vector v2 = new DenseLocalOffHeapVector(data2.length); + + v1.assign(data1); + v2.assign(data2); + + System.out.println(">>> First vector: " + Arrays.toString(data1)); + System.out.println(">>> Second vector: " + Arrays.toString(data2)); + + double dotProduct = v1.dot(v2); + boolean dotProductIsAsExp = dotProduct == 0; + + System.out.println("\n>>> Dot product of vectors: [" + dotProduct + + "], it is 0 as expected: [" + dotProductIsAsExp + "]."); + + assert dotProductIsAsExp : "Expect dot product of perpendicular vectors to be 0."; + + Vector hypotenuse = v1.plus(v2); + + System.out.println("\n>>> Hypotenuse (sum of vectors): " + Arrays.toString(hypotenuse.getStorage().data())); + + double lenSquared1 = v1.getLengthSquared(); + double lenSquared2 = v2.getLengthSquared(); + double lenSquaredHypotenuse = hypotenuse.getLengthSquared(); + + boolean lenSquaredHypotenuseIsAsExp = lenSquaredHypotenuse == lenSquared1 + lenSquared2; + + System.out.println(">>> Squared length of first vector: [" + lenSquared1 + "]."); + System.out.println(">>> Squared length of second vector: [" + lenSquared2 + "]."); + System.out.println(">>> Squared length of hypotenuse: [" + lenSquaredHypotenuse + + "], equals sum of squared lengths of two original vectors as expected: [" + + lenSquaredHypotenuseIsAsExp + "]."); + + assert lenSquaredHypotenuseIsAsExp : "Expect squared length of hypotenuse to be as per Pythagorean theorem."; + + System.out.println("\n>>> Off-heap vector API usage example completed."); + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/acd21fb8/examples/src/main/java8/org/apache/ignite/examples/java8/math/vector/SparseVectorExample.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java8/org/apache/ignite/examples/java8/math/vector/SparseVectorExample.java b/examples/src/main/java8/org/apache/ignite/examples/java8/math/vector/SparseVectorExample.java new file mode 100644 index 0000000..79e0567 --- /dev/null +++ b/examples/src/main/java8/org/apache/ignite/examples/java8/math/vector/SparseVectorExample.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.examples.java8.math.vector; + +import java.util.Arrays; +import org.apache.ignite.math.Vector; +import org.apache.ignite.math.impls.vector.SparseLocalVector; + +import static org.apache.ignite.math.StorageConstants.RANDOM_ACCESS_MODE; + +/** + * This example shows how to use sparse {@link Vector} API. + */ +public final class SparseVectorExample { + /** + * Executes example. + * + * @param args Command line arguments, none required. + */ + public static void main(String[] args) { + System.out.println(); + System.out.println(">>> Sparse vector API usage example started."); + + System.out.println("\n>>> Creating perpendicular sparse vectors."); + double[] data1 = new double[] {1, 0, 3, 0, 5, 0}; + double[] data2 = new double[] {0, 2, 0, 4, 0, 6}; + + Vector v1 = new SparseLocalVector(data1.length, RANDOM_ACCESS_MODE); + Vector v2 = new SparseLocalVector(data2.length, RANDOM_ACCESS_MODE); + + v1.assign(data1); + v2.assign(data2); + + System.out.println(">>> First vector: " + Arrays.toString(data1)); + System.out.println(">>> Second vector: " + Arrays.toString(data2)); + + double dotProduct = v1.dot(v2); + boolean dotProductIsAsExp = dotProduct == 0; + + System.out.println("\n>>> Dot product of vectors: [" + dotProduct + + "], it is 0 as expected: [" + dotProductIsAsExp + "]."); + + assert dotProductIsAsExp : "Expect dot product of perpendicular vectors to be 0."; + + Vector hypotenuse = v1.plus(v2); + + System.out.println("\n>>> Hypotenuse (sum of vectors): " + Arrays.toString(hypotenuse.getStorage().data())); + + double lenSquared1 = v1.getLengthSquared(); + double lenSquared2 = v2.getLengthSquared(); + double lenSquaredHypotenuse = hypotenuse.getLengthSquared(); + + boolean lenSquaredHypotenuseIsAsExp = lenSquaredHypotenuse == lenSquared1 + lenSquared2; + + System.out.println(">>> Squared length of first vector: [" + lenSquared1 + "]."); + System.out.println(">>> Squared length of second vector: [" + lenSquared2 + "]."); + System.out.println(">>> Squared length of hypotenuse: [" + lenSquaredHypotenuse + + "], equals sum of squared lengths of two original vectors as expected: [" + + lenSquaredHypotenuseIsAsExp + "]."); + + assert lenSquaredHypotenuseIsAsExp : "Expect squared length of hypotenuse to be as per Pythagorean theorem."; + + System.out.println("\n>>> Sparse vector API usage example completed."); + } +}
