From f03b10f4498f4af700d1a3f326090a9844a19aa2 Mon Sep 17 00:00:00 2001 From: AlexisDrogoul Date: Thu, 15 Apr 2021 08:46:48 +0700 Subject: [PATCH] Reorganizes maths/stats operators and types in their plugins Moves Apache Commons Maths out of ext and to the maths plugin. --- .../msi/gama/util/matrix/GamaFloatMatrix.java | 274 ++----------- .../msi/gama/util/matrix/GamaIntMatrix.java | 258 +++---------- .../src/msi/gama/util/matrix/GamaMatrix.java | 169 +-------- .../gama/util/matrix/GamaObjectMatrix.java | 69 ++-- .../src/msi/gama/util/matrix/IMatrix.java | 111 +----- .../src/msi/gama/util/random/GamaRNG.java | 42 +- .../src/msi/gaml/operators/Material.java | 32 -- .../src/msi/gaml/operators/Random.java | 359 ++---------------- .../src/msi/gaml/types/GamaMaterialType.java | 34 +- msi.gama.ext/.classpath | 1 - msi.gama.ext/META-INF/MANIFEST.MF | 32 -- msi.gama.ext/build.properties | 1 - .../license/LICENSE-2.0.txt | 202 ---------- .../models/Data/Data Analysis/.project | 18 - ummisco.gaml.extensions.maths/.classpath | 3 +- .../.settings/org.eclipse.jdt.core.prefs | 9 + .../META-INF/MANIFEST.MF | 10 +- .../build.properties | 3 +- .../lib}/commons-math3-3.6.1.jar | Bin .../Diffusion in a cuve (Cycle length).gaml | 1 + .../maths/matrix/MatrixOperators.java | 236 ++++++++++++ .../maths/random/ForwardingGenerator.java | 71 ++++ .../gaml/extensions/maths/random/Random2.java | 323 ++++++++++++++++ .../META-INF/MANIFEST.MF | 3 +- .../models/Clustering Algorithms}/.project | 3 +- .../Clustering Algorithms}/Clustering.gaml | 0 .../Spatial Clustering.gaml | 0 .../models/Spatial Statistics}/.project | 3 +- .../Spatial Statistics}/includes/CLC00_06.dbf | Bin .../Spatial Statistics}/includes/CLC00_06.prj | 0 .../Spatial Statistics}/includes/CLC00_06.shp | Bin .../Spatial Statistics}/includes/CLC00_06.shx | Bin .../models/Raster Map Comparison.gaml | 0 .../models/Vector Map Comparison.gaml | 0 .../models}/Statistics/.project | 3 +- .../models}/Statistics/Regression.gaml | 0 .../Statistics/Statistic Operators.gaml | 0 .../gaml/extensions/stats}/MapComparison.java | 91 ++--- .../ummisco/gaml/extensions/stats/Stats.java | 1 + 39 files changed, 892 insertions(+), 1470 deletions(-) delete mode 100644 msi.gama.core/src/msi/gaml/operators/Material.java delete mode 100644 msi.gama.ext/commons-math3-3.6.1/license/LICENSE-2.0.txt delete mode 100644 msi.gama.models/models/Data/Data Analysis/.project rename {msi.gama.ext/commons-math3-3.6.1/jars => ummisco.gaml.extensions.maths/lib}/commons-math3-3.6.1.jar (100%) create mode 100644 ummisco.gaml.extensions.maths/src/ummisco/gaml/extensions/maths/matrix/MatrixOperators.java create mode 100644 ummisco.gaml.extensions.maths/src/ummisco/gaml/extensions/maths/random/ForwardingGenerator.java create mode 100644 ummisco.gaml.extensions.maths/src/ummisco/gaml/extensions/maths/random/Random2.java rename {msi.gama.models/models/Data/Data Analysis/Clustering => ummisco.gaml.extensions.stats/models/Clustering Algorithms}/.project (79%) rename {msi.gama.models/models/Data/Data Analysis/Clustering => ummisco.gaml.extensions.stats/models/Clustering Algorithms}/Clustering.gaml (100%) rename {msi.gama.models/models/Data/Data Analysis/Clustering => ummisco.gaml.extensions.stats/models/Clustering Algorithms}/Spatial Clustering.gaml (100%) rename {msi.gama.models/models/Data/Data Analysis/Map Comparison => ummisco.gaml.extensions.stats/models/Spatial Statistics}/.project (79%) rename {msi.gama.models/models/Data/Data Analysis/Map Comparison => ummisco.gaml.extensions.stats/models/Spatial Statistics}/includes/CLC00_06.dbf (100%) rename {msi.gama.models/models/Data/Data Analysis/Map Comparison => ummisco.gaml.extensions.stats/models/Spatial Statistics}/includes/CLC00_06.prj (100%) rename {msi.gama.models/models/Data/Data Analysis/Map Comparison => ummisco.gaml.extensions.stats/models/Spatial Statistics}/includes/CLC00_06.shp (100%) rename {msi.gama.models/models/Data/Data Analysis/Map Comparison => ummisco.gaml.extensions.stats/models/Spatial Statistics}/includes/CLC00_06.shx (100%) rename {msi.gama.models/models/Data/Data Analysis/Map Comparison => ummisco.gaml.extensions.stats/models/Spatial Statistics}/models/Raster Map Comparison.gaml (100%) rename {msi.gama.models/models/Data/Data Analysis/Map Comparison => ummisco.gaml.extensions.stats/models/Spatial Statistics}/models/Vector Map Comparison.gaml (100%) rename {msi.gama.models/models/Data/Data Analysis => ummisco.gaml.extensions.stats/models}/Statistics/.project (79%) rename {msi.gama.models/models/Data/Data Analysis => ummisco.gaml.extensions.stats/models}/Statistics/Regression.gaml (100%) rename {msi.gama.models/models/Data/Data Analysis => ummisco.gaml.extensions.stats/models}/Statistics/Statistic Operators.gaml (100%) rename {msi.gama.core/src/msi/gaml/operators => ummisco.gaml.extensions.stats/src/ummisco/gaml/extensions/stats}/MapComparison.java (92%) diff --git a/msi.gama.core/src/msi/gama/util/matrix/GamaFloatMatrix.java b/msi.gama.core/src/msi/gama/util/matrix/GamaFloatMatrix.java index 7f2b27d252..277b7caf63 100644 --- a/msi.gama.core/src/msi/gama/util/matrix/GamaFloatMatrix.java +++ b/msi.gama.core/src/msi/gama/util/matrix/GamaFloatMatrix.java @@ -16,14 +16,9 @@ import java.util.List; import org.apache.commons.lang.ArrayUtils; -import org.apache.commons.math3.exception.DimensionMismatchException; -import org.apache.commons.math3.linear.Array2DRowRealMatrix; -import org.apache.commons.math3.linear.EigenDecomposition; -import org.apache.commons.math3.linear.LUDecomposition; -import org.apache.commons.math3.linear.RealMatrix; +import org.locationtech.jts.index.quadtree.IntervalSize; import com.google.common.primitives.Doubles; -import org.locationtech.jts.index.quadtree.IntervalSize; import msi.gama.common.util.RandomUtils; import msi.gama.metamodel.shape.GamaPoint; @@ -45,33 +40,23 @@ public class GamaFloatMatrix extends GamaMatrix { static public GamaFloatMatrix from(final IScope scope, final IMatrix m) { - if (m instanceof GamaFloatMatrix) { return (GamaFloatMatrix) m; } - if (m instanceof GamaObjectMatrix) { + if (m instanceof GamaFloatMatrix) return (GamaFloatMatrix) m; + if (m instanceof GamaObjectMatrix) return new GamaFloatMatrix(scope, m.getCols(scope), m.getRows(scope), ((GamaObjectMatrix) m).getMatrix()); - } - if (m instanceof GamaIntMatrix) { + if (m instanceof GamaIntMatrix) return new GamaFloatMatrix(m.getCols(scope), m.getRows(scope), ((GamaIntMatrix) m).matrix); - } return null; } static public GamaFloatMatrix from(final IScope scope, final int c, final int r, final IMatrix m) { - if (m instanceof GamaFloatMatrix) { return new GamaFloatMatrix(c, r, ((GamaFloatMatrix) m).getMatrix()); } - if (m instanceof GamaObjectMatrix) { - return new GamaFloatMatrix(scope, c, r, ((GamaObjectMatrix) m).getMatrix()); - } - if (m instanceof GamaIntMatrix) { return new GamaFloatMatrix(c, r, ((GamaIntMatrix) m).matrix); } + if (m instanceof GamaFloatMatrix) return new GamaFloatMatrix(c, r, ((GamaFloatMatrix) m).getMatrix()); + if (m instanceof GamaObjectMatrix) return new GamaFloatMatrix(scope, c, r, ((GamaObjectMatrix) m).getMatrix()); + if (m instanceof GamaIntMatrix) return new GamaFloatMatrix(c, r, ((GamaIntMatrix) m).matrix); return null; } private double[] matrix; - public GamaFloatMatrix(final RealMatrix rm) { - super(rm.getColumnDimension(), rm.getRowDimension(), Types.FLOAT); - matrix = new double[rm.getColumnDimension() * rm.getRowDimension()]; - updateMatrix(rm); - } - public GamaFloatMatrix(final double[] mat) { super(1, mat.length, Types.FLOAT); setMatrix(mat); @@ -151,7 +136,7 @@ public boolean _contains(final IScope scope, final Object o) { if (o instanceof Double) { final Double d = (Double) o; for (int i = 0; i < getMatrix().length; i++) { - if (IntervalSize.isZeroWidth(getMatrix()[i], d)) { return true; } + if (IntervalSize.isZeroWidth(getMatrix()[i], d)) return true; } } return false; @@ -159,13 +144,13 @@ public boolean _contains(final IScope scope, final Object o) { @Override public Double _first(final IScope scope) { - if (getMatrix().length == 0) { return 0d; } + if (getMatrix().length == 0) return 0d; return getMatrix()[0]; } @Override public Double _last(final IScope scope) { - if (getMatrix().length == 0) { return 0d; } + if (getMatrix().length == 0) return 0d; return getMatrix()[getMatrix().length - 1]; } @@ -182,20 +167,9 @@ public Integer _length(final IScope scope) { * matrix to concatenate * @return the matrix concatenated */ - // @Override - // @operator(value = IKeyword.APPEND_VERTICALLY, content_type = - // ITypeProvider.BOTH, category={IOperatorCategory.MATRIX}) - public IMatrix _opAppendVertically(final IScope scope, final IMatrix b) { - final GamaFloatMatrix a = this; - final double[] ma = a.getMatrix(); - final double[] mb = ((GamaFloatMatrix) b).getMatrix(); - final double[] mab = ArrayUtils.addAll(ma, mb); - - final GamaFloatMatrix fl = new GamaFloatMatrix(a.getCols(scope), a.getRows(scope) + b.getRows(scope), mab); - - // throw GamaRuntimeException.error("ATTENTION : Matrix additions not - // implemented. Returns nil for the moment"); - return fl; + public GamaFloatMatrix _opAppendVertically(final IScope scope, final GamaFloatMatrix b) { + final double[] mab = ArrayUtils.addAll(getMatrix(), b.getMatrix()); + return new GamaFloatMatrix(numCols, numRows + b.getRows(scope), mab); } /** @@ -206,70 +180,18 @@ public IMatrix _opAppendVertically(final IScope scope, final IMatrix b) { * matrix to concatenate * @return the matrix concatenated */ - // @Override - // @operator(value = IKeyword.APPEND_HORYZONTALLY, content_type = - // ITypeProvider.BOTH, category={IOperatorCategory.MATRIX}) - public IMatrix _opAppendHorizontally(final IScope scope, final IMatrix b) { - final GamaFloatMatrix a = this; - // GamaFloatMatrix aprime = new GamaFloatMatrix(a.getRows(scope), - // a.getCols(scope)); - final GamaFloatMatrix aprime = (GamaFloatMatrix) a._reverse(scope); - // DEBUG.LOG("aprime = " + aprime); - // GamaFloatMatrix bprime = new GamaFloatMatrix(b.getRows(scope), - // b.getCols(scope)); - final GamaFloatMatrix bprime = (GamaFloatMatrix) ((GamaFloatMatrix) b)._reverse(scope); - // DEBUG.LOG("bprime = " + bprime); - final GamaFloatMatrix c = (GamaFloatMatrix) aprime.opAppendVertically(scope, bprime); - // DEBUG.LOG("c = " + c); - final GamaFloatMatrix cprime = (GamaFloatMatrix) c._reverse(scope); - // DEBUG.LOG("cprime = " + cprime); + public IMatrix _opAppendHorizontally(final IScope scope, final GamaFloatMatrix b) { + final GamaFloatMatrix aprime = _reverse(scope); + final GamaFloatMatrix bprime = b._reverse(scope); + final GamaFloatMatrix c = aprime._opAppendVertically(scope, bprime); + final GamaFloatMatrix cprime = c._reverse(scope); return cprime; } - // @Override - // public Double _max(final IScope scope) { - // Double max = -Double.MAX_VALUE; - // for ( int i = 0; i < matrix.length; i++ ) { - // if ( matrix[i] > max ) { - // max = Double.valueOf(matrix[i]); - // } - // } - // return max; - // } - // - // @Override - // public Double _min(final IScope scope) { - // Double min = Double.MAX_VALUE; - // for ( int i = 0; i < matrix.length; i++ ) { - // if ( matrix[i] < min ) { - // min = Double.valueOf(matrix[i]); - // } - // } - // return min; - // } - // - // @Override - // public Double _product(final IScope scope) { - // double result = 1.0; - // for ( int i = 0, n = matrix.length; i < n; i++ ) { - // result *= matrix[i]; - // } - // return result; - // } - // - // @Override - // public Double _sum(final IScope scope) { - // double result = 0.0; - // for ( int i = 0, n = matrix.length; i < n; i++ ) { - // result += matrix[i]; - // } - // return result; - // } - // @Override public boolean _isEmpty(final IScope scope) { for (int i = 0; i < getMatrix().length; i++) { - if (getMatrix()[i] != 0d) { return false; } + if (getMatrix()[i] != 0d) return false; } return true; } @@ -281,7 +203,7 @@ protected IMatrix _matrixValue(final IScope scope, final ILocation preferredSize } @Override - public IMatrix _reverse(final IScope scope) throws GamaRuntimeException { + public GamaFloatMatrix _reverse(final IScope scope) throws GamaRuntimeException { final GamaFloatMatrix result = new GamaFloatMatrix(numRows, numCols); for (int i = 0; i < numCols; i++) { for (int j = 0; j < numRows; j++) { @@ -295,19 +217,18 @@ public IMatrix _reverse(final IScope scope) throws GamaRuntimeException { @Override public GamaFloatMatrix copy(final IScope scope, final ILocation size, final boolean copy) { if (size == null) { - if (copy) { + if (copy) return new GamaFloatMatrix(numCols, numRows, Arrays.copyOf(getMatrix(), matrix.length)); - } else { + else return this; - } } return new GamaFloatMatrix((int) size.getX(), (int) size.getY(), Arrays.copyOf(getMatrix(), matrix.length)); } @Override public boolean equals(final Object m) { - if (this == m) { return true; } - if (!(m instanceof GamaFloatMatrix)) { return false; } + if (this == m) return true; + if (!(m instanceof GamaFloatMatrix)) return false; final GamaFloatMatrix mat = (GamaFloatMatrix) m; return Arrays.equals(this.getMatrix(), mat.getMatrix()); } @@ -327,24 +248,16 @@ public void _putAll(final IScope scope, final Object o) throws GamaRuntimeExcept @Override public Double get(final IScope scope, final int col, final int row) { - if (col >= numCols || col < 0 || row >= numRows || row < 0) { return 0d; } + if (col >= numCols || col < 0 || row >= numRows || row < 0) return 0d; return getMatrix()[row * numCols + col]; } - // public void put(final int col, final int row, final double obj) { - // if ( !(col >= numCols || col < 0 || row >= numRows || row < 0) ) { - // matrix[row * numCols + col] = obj; - // } - // } - @Override public void set(final IScope scope, final int col, final int row, final Object obj) throws GamaRuntimeException { if (!(col >= numCols || col < 0 || row >= numRows || row < 0)) { final double val = Cast.asFloat(scope, obj); getMatrix()[row * numCols + col] = val; } - // put(col, row, Cast.asFloat(GAMA.getDefaultScope(), - // obj).doubleValue()); } private boolean remove(final double o) { @@ -365,7 +278,7 @@ public boolean _removeFirst(final IScope scope, final Double o) throws GamaRunti @Override public Double remove(final IScope scope, final int col, final int row) { - if (col >= numCols || col < 0 || row >= numRows || row < 0) { return 0d; } + if (col >= numCols || col < 0 || row >= numRows || row < 0) return 0d; final double o = getMatrix()[row * numCols + col]; getMatrix()[row * numCols + col] = 0d; return o; @@ -384,11 +297,9 @@ private boolean removeAll(final double o) { @Override public boolean _removeAll(final IScope scope, final IContainer list) { - // TODO Exception if o == null for (final Double o : list.iterable(scope)) { removeAll(o.doubleValue()); } - // TODO Make a test to verify the return return true; } @@ -404,28 +315,14 @@ public String toString() { for (int row = 0; row < numRows; row++) { for (int col = 0; col < numCols; col++) { sb.append(get(null, col, row)); - if (col < numCols - 1) { - sb.append(','); - } - } - if (row < numRows - 1) { - sb.append(';'); + if (col < numCols - 1) { sb.append(','); } } + if (row < numRows - 1) { sb.append(';'); } } sb.append(']'); return sb.toString(); } - /** - * Method iterator() - * - * @see msi.gama.util.matrix.GamaMatrix#iterator() - */ - // @Override - // public Iterator iterator() { - // return Doubles.asList(getMatrix()).iterator(); - // } - @Override public java.lang.Iterable iterable(final IScope scope) { return Doubles.asList(getMatrix()); @@ -439,26 +336,8 @@ void setMatrix(final double[] matrix) { this.matrix = matrix; } - RealMatrix getRealMatrix() { - final RealMatrix realMatrix = new Array2DRowRealMatrix(this.numRows, this.numCols); - for (int i = 0; i < this.numRows; i++) { - for (int j = 0; j < this.numCols; j++) { - realMatrix.setEntry(i, j, this.get(null, j, i)); - } - } - return realMatrix; - } - - void updateMatrix(final RealMatrix realMatrix) { - for (int i = 0; i < this.numRows; i++) { - for (int j = 0; j < this.numCols; j++) { - getMatrix()[i * numCols + j] = realMatrix.getEntry(i, j); - } - } - } - @Override - public IMatrix plus(final IScope scope, final IMatrix other) throws GamaRuntimeException { + public GamaFloatMatrix plus(final IScope scope, final IMatrix other) throws GamaRuntimeException { final GamaFloatMatrix matb = from(scope, other); if (matb != null && this.numCols == matb.numCols && this.numRows == matb.numRows) { final GamaFloatMatrix nm = new GamaFloatMatrix(this.numCols, this.numRows); @@ -471,7 +350,7 @@ public IMatrix plus(final IScope scope, final IMatrix other) throws GamaRuntimeE } @Override - public IMatrix times(final IScope scope, final IMatrix other) throws GamaRuntimeException { + public GamaFloatMatrix times(final IScope scope, final IMatrix other) throws GamaRuntimeException { final GamaFloatMatrix matb = from(scope, other); if (matb != null && this.numCols == matb.numCols && this.numRows == matb.numRows) { final GamaFloatMatrix nm = new GamaFloatMatrix(this.numCols, this.numRows); @@ -484,7 +363,7 @@ public IMatrix times(final IScope scope, final IMatrix other) throws GamaRuntime } @Override - public IMatrix minus(final IScope scope, final IMatrix other) throws GamaRuntimeException { + public GamaFloatMatrix minus(final IScope scope, final IMatrix other) throws GamaRuntimeException { final GamaFloatMatrix matb = from(scope, other); if (matb != null && this.numCols == matb.numCols && this.numRows == matb.numRows) { final GamaFloatMatrix nm = new GamaFloatMatrix(this.numCols, this.numRows); @@ -497,7 +376,7 @@ public IMatrix minus(final IScope scope, final IMatrix other) throws GamaRuntime } @Override - public IMatrix times(final Double val) throws GamaRuntimeException { + public GamaFloatMatrix times(final Double val) throws GamaRuntimeException { final GamaFloatMatrix nm = new GamaFloatMatrix(this.numCols, this.numRows); for (int i = 0; i < matrix.length; i++) { nm.matrix[i] = matrix[i] * val; @@ -506,7 +385,7 @@ public IMatrix times(final Double val) throws GamaRuntimeException { } @Override - public IMatrix times(final Integer val) throws GamaRuntimeException { + public GamaFloatMatrix times(final Integer val) throws GamaRuntimeException { final GamaFloatMatrix nm = new GamaFloatMatrix(this.numCols, this.numRows); for (int i = 0; i < matrix.length; i++) { nm.matrix[i] = matrix[i] * val; @@ -515,7 +394,7 @@ public IMatrix times(final Integer val) throws GamaRuntimeException { } @Override - public IMatrix divides(final Double val) throws GamaRuntimeException { + public GamaFloatMatrix divides(final Double val) throws GamaRuntimeException { final GamaFloatMatrix nm = new GamaFloatMatrix(this.numCols, this.numRows); for (int i = 0; i < matrix.length; i++) { nm.matrix[i] = matrix[i] / val; @@ -524,7 +403,7 @@ public IMatrix divides(final Double val) throws GamaRuntimeException { } @Override - public IMatrix divides(final Integer val) throws GamaRuntimeException { + public GamaFloatMatrix divides(final Integer val) throws GamaRuntimeException { final GamaFloatMatrix nm = new GamaFloatMatrix(this.numCols, this.numRows); for (int i = 0; i < matrix.length; i++) { nm.matrix[i] = matrix[i] / val; @@ -533,7 +412,7 @@ public IMatrix divides(final Integer val) throws GamaRuntimeException { } @Override - public IMatrix divides(final IScope scope, final IMatrix other) throws GamaRuntimeException { + public GamaFloatMatrix divides(final IScope scope, final IMatrix other) throws GamaRuntimeException { final GamaFloatMatrix matb = from(scope, other); if (matb != null && this.numCols == matb.numCols && this.numRows == matb.numRows) { final GamaFloatMatrix nm = new GamaFloatMatrix(this.numCols, this.numRows); @@ -546,18 +425,7 @@ public IMatrix divides(final IScope scope, final IMatrix other) throws GamaRunti } @Override - public IMatrix matrixMultiplication(final IScope scope, final IMatrix other) throws GamaRuntimeException { - final GamaFloatMatrix matb = from(scope, other); - try { - if (matb != null) { return new GamaFloatMatrix(getRealMatrix().multiply(matb.getRealMatrix())); } - } catch (final DimensionMismatchException e) { - throw GamaRuntimeException.error("The dimensions of the matrices do not correspond", scope); - } - return null; - } - - @Override - public IMatrix plus(final Double val) throws GamaRuntimeException { + public GamaFloatMatrix plus(final Double val) throws GamaRuntimeException { final GamaFloatMatrix nm = new GamaFloatMatrix(this.numCols, this.numRows); for (int i = 0; i < matrix.length; i++) { nm.matrix[i] = matrix[i] + val; @@ -566,7 +434,7 @@ public IMatrix plus(final Double val) throws GamaRuntimeException { } @Override - public IMatrix plus(final Integer val) throws GamaRuntimeException { + public GamaFloatMatrix plus(final Integer val) throws GamaRuntimeException { final GamaFloatMatrix nm = new GamaFloatMatrix(this.numCols, this.numRows); for (int i = 0; i < matrix.length; i++) { nm.matrix[i] = matrix[i] + val; @@ -575,7 +443,7 @@ public IMatrix plus(final Integer val) throws GamaRuntimeException { } @Override - public IMatrix minus(final Double val) throws GamaRuntimeException { + public GamaFloatMatrix minus(final Double val) throws GamaRuntimeException { final GamaFloatMatrix nm = new GamaFloatMatrix(this.numCols, this.numRows); for (int i = 0; i < matrix.length; i++) { nm.matrix[i] = matrix[i] - val; @@ -584,7 +452,7 @@ public IMatrix minus(final Double val) throws GamaRuntimeException { } @Override - public IMatrix minus(final Integer val) throws GamaRuntimeException { + public GamaFloatMatrix minus(final Integer val) throws GamaRuntimeException { final GamaFloatMatrix nm = new GamaFloatMatrix(this.numCols, this.numRows); for (int i = 0; i < matrix.length; i++) { nm.matrix[i] = matrix[i] - val; @@ -594,8 +462,8 @@ public IMatrix minus(final Integer val) throws GamaRuntimeException { @Override public Double getNthElement(final Integer index) { - if (index == null) { return 0d; } - if (index > getMatrix().length) { return 0d; } + if (index == null) return 0d; + if (index > getMatrix().length) return 0d; return getMatrix()[index]; } @@ -604,57 +472,6 @@ protected void setNthElement(final IScope scope, final int index, final Object v getMatrix()[index] = Cast.asFloat(scope, value); } - public RealMatrix toApacheMatrix(final IScope scope) { - final RealMatrix rm = new Array2DRowRealMatrix(numRows, numCols); - for (int i = 0; i < numCols; i++) { - for (int j = 0; j < numRows; j++) { - final double val = get(scope, i, j); - rm.setEntry(j, i, val); - } - } - return rm; - } - - public IMatrix fromApacheMatrix(final IScope scope, final RealMatrix rm) { - if (rm == null) { return null; } - final GamaFloatMatrix matrix = new GamaFloatMatrix(rm.getColumnDimension(), rm.getRowDimension()); - for (int i = 0; i < numCols; i++) { - for (int j = 0; j < numRows; j++) { - matrix.set(scope, i, j, rm.getEntry(j, i)); - } - } - return matrix; - - } - - @Override - public Double getDeterminant(final IScope scope) throws GamaRuntimeException { - final RealMatrix rm = toApacheMatrix(scope); - final LUDecomposition ld = new LUDecomposition(rm); - return ld.getDeterminant(); - } - - @Override - public Double getTrace(final IScope scope) throws GamaRuntimeException { - final RealMatrix rm = toApacheMatrix(scope); - return rm.getTrace(); - } - - @Override - public IList getEigen(final IScope scope) throws GamaRuntimeException { - final RealMatrix rm = toApacheMatrix(scope); - final EigenDecomposition ed = new EigenDecomposition(rm); - return fromApacheMatrixtoDiagList(scope, ed.getD()); - } - - IList fromApacheMatrixtoDiagList(final IScope scope, final RealMatrix rm) { - final IList vals = GamaListFactory.create(Types.FLOAT); - for (int i = 0; i < rm.getColumnDimension(); i++) { - vals.add(rm.getEntry(i, i)); - } - return vals; - } - @Override public String serialize(final boolean includingBuiltIn) { return "matrix(" + getRowsList(null).serialize(includingBuiltIn) + ")"; @@ -665,13 +482,6 @@ public IContainerType getGamlType() { return Types.MATRIX.of(Types.FLOAT); } - @Override - public IMatrix inverse(final IScope scope) throws GamaRuntimeException { - final RealMatrix rm = toApacheMatrix(scope); - final LUDecomposition ld = new LUDecomposition(rm); - return fromApacheMatrix(scope, ld.getSolver().getInverse()); - } - @Override public StreamEx stream(final IScope scope) { return DoubleStreamEx.of(matrix).boxed(); diff --git a/msi.gama.core/src/msi/gama/util/matrix/GamaIntMatrix.java b/msi.gama.core/src/msi/gama/util/matrix/GamaIntMatrix.java index f342526bfa..9d36497936 100644 --- a/msi.gama.core/src/msi/gama/util/matrix/GamaIntMatrix.java +++ b/msi.gama.core/src/msi/gama/util/matrix/GamaIntMatrix.java @@ -14,11 +14,6 @@ import java.util.List; import org.apache.commons.lang.ArrayUtils; -import org.apache.commons.math3.exception.DimensionMismatchException; -import org.apache.commons.math3.linear.Array2DRowRealMatrix; -import org.apache.commons.math3.linear.EigenDecomposition; -import org.apache.commons.math3.linear.LUDecomposition; -import org.apache.commons.math3.linear.RealMatrix; import com.google.common.primitives.Ints; @@ -44,22 +39,18 @@ public class GamaIntMatrix extends GamaMatrix { static public GamaIntMatrix from(final IScope scope, final IMatrix m) { - if (m instanceof GamaIntMatrix) { return (GamaIntMatrix) m; } - if (m instanceof GamaObjectMatrix) { + if (m instanceof GamaIntMatrix) return (GamaIntMatrix) m; + if (m instanceof GamaObjectMatrix) return new GamaIntMatrix(scope, m.getCols(scope), m.getRows(scope), ((GamaObjectMatrix) m).getMatrix()); - } - if (m instanceof GamaFloatMatrix) { + if (m instanceof GamaFloatMatrix) return new GamaIntMatrix(m.getCols(scope), m.getRows(scope), ((GamaFloatMatrix) m).getMatrix()); - } return null; } static public GamaIntMatrix from(final IScope scope, final int c, final int r, final IMatrix m) { - if (m instanceof GamaIntMatrix) { return new GamaIntMatrix(c, r, ((GamaIntMatrix) m).getMatrix()); } - if (m instanceof GamaObjectMatrix) { - return new GamaIntMatrix(scope, c, r, ((GamaObjectMatrix) m).getMatrix()); - } - if (m instanceof GamaFloatMatrix) { return new GamaIntMatrix(c, r, ((GamaFloatMatrix) m).getMatrix()); } + if (m instanceof GamaIntMatrix) return new GamaIntMatrix(c, r, ((GamaIntMatrix) m).getMatrix()); + if (m instanceof GamaObjectMatrix) return new GamaIntMatrix(scope, c, r, ((GamaObjectMatrix) m).getMatrix()); + if (m instanceof GamaFloatMatrix) return new GamaIntMatrix(c, r, ((GamaFloatMatrix) m).getMatrix()); return null; } @@ -137,12 +128,6 @@ public GamaIntMatrix(final IScope scope, final Object[] mat) { } } - public GamaIntMatrix(final RealMatrix rm) { - super(rm.getColumnDimension(), rm.getRowDimension(), Types.INT); - matrix = new int[rm.getColumnDimension() * rm.getRowDimension()]; - updateMatrix(rm); - } - // public GamaIntMatrix(final GamaMatrix rm) { // super(rm.numCols, rm.numRows); // matrix = new int[rm.numCols * rm.numRows]; @@ -162,20 +147,20 @@ protected void _putAll(final IScope scope, final Object o) throws GamaRuntimeExc @Override protected boolean _contains(final IScope scope, final Object o) { for (final int element : matrix) { - if (o instanceof Integer && element == ((Integer) o).intValue()) { return true; } + if (o instanceof Integer && element == ((Integer) o).intValue()) return true; } return false; } @Override public Integer _first(final IScope scope) { - if (matrix.length == 0) { return 0; } + if (matrix.length == 0) return 0; return matrix[0]; } @Override public Integer _last(final IScope scope) { - if (matrix.length == 0) { return 0; } + if (matrix.length == 0) return 0; return matrix[matrix.length - 1]; } @@ -192,20 +177,9 @@ public Integer _length(final IScope scope) { * matrix to concatenate * @return the matrix concatenated */ - // @Override - // @operator(value = IKeyword.APPEND_VERTICALLY, content_type = - // ITypeProvider.BOTH, - // category={IOperatorCategory.MATRIX}) - public IMatrix _opAppendVertically(final IScope scope, final IMatrix b) { - final GamaIntMatrix a = this; - final int[] ma = a.getMatrix(); - final int[] mb = ((GamaIntMatrix) b).getMatrix(); - final int[] mab = ArrayUtils.addAll(ma, mb); - - return new GamaIntMatrix(a.getCols(scope), a.getRows(scope) + b.getRows(scope), mab); - - // throw GamaRuntimeException.error("ATTENTION : Matrix additions not - // implemented. Returns nil for the moment"); + public GamaIntMatrix _opAppendVertically(final IScope scope, final GamaIntMatrix b) { + final int[] mab = ArrayUtils.addAll(getMatrix(), b.getMatrix()); + return new GamaIntMatrix(numCols, numRows + b.getRows(scope), mab); } /** @@ -217,67 +191,18 @@ public IMatrix _opAppendVertically(final IScope scope, final IMatrix b) { * @return the matrix concatenated */ - // @Override - // @operator(value = IKeyword.APPEND_HORYZONTALLY, content_type = - // ITypeProvider.BOTH, - // category={IOperatorCategory.MATRIX}) - public IMatrix _opAppendHorizontally(final IScope scope, final IMatrix b) { - final GamaIntMatrix a = this; - final GamaIntMatrix aprime = (GamaIntMatrix) a._reverse(scope); - // DEBUG.LOG("aprime = " + aprime); - final GamaIntMatrix bprime = (GamaIntMatrix) ((GamaIntMatrix) b)._reverse(scope); - // DEBUG.LOG("bprime = " + bprime); - final GamaIntMatrix c = (GamaIntMatrix) aprime.opAppendVertically(scope, bprime); - // DEBUG.LOG("c = " + c); - final GamaIntMatrix cprime = (GamaIntMatrix) c._reverse(scope); - // DEBUG.LOG("cprime = " + cprime); + public GamaIntMatrix _opAppendHorizontally(final IScope scope, final GamaIntMatrix b) { + final GamaIntMatrix aprime = _reverse(scope); + final GamaIntMatrix bprime = b._reverse(scope); + final GamaIntMatrix c = aprime._opAppendVertically(scope, bprime); + final GamaIntMatrix cprime = c._reverse(scope); return cprime; } - // @Override - // public Integer _max(final IScope scope) { - // Integer max = Integer.MIN_VALUE; - // for ( int i = 0; i < matrix.length; i++ ) { - // if ( matrix[i] > max ) { - // max = Integer.valueOf(matrix[i]); - // } - // } - // return max; - // } - // - // @Override - // public Integer _min(final IScope scope) { - // Integer min = Integer.MAX_VALUE; - // for ( int i = 0; i < matrix.length; i++ ) { - // if ( matrix[i] < min ) { - // min = Integer.valueOf(matrix[i]); - // } - // } - // return min; - // } - // - // @Override - // public Double _product(final IScope scope) { - // double result = 1.0; - // for ( int i = 0, n = matrix.length; i < n; i++ ) { - // result *= matrix[i]; - // } - // return result; - // } - // - // @Override - // public Integer _sum(final IScope scope) { - // int result = 0; - // for ( int i = 0, n = matrix.length; i < n; i++ ) { - // result += matrix[i]; - // } - // return result; - // } - @Override public boolean _isEmpty(final IScope scope) { for (final int element : matrix) { - if (element != 0) { return false; } + if (element != 0) return false; } return true; } @@ -295,8 +220,8 @@ protected IMatrix _matrixValue(final IScope scope, final ILocation preferredSize } @Override - public IMatrix _reverse(final IScope scope) throws GamaRuntimeException { - final IMatrix result = new GamaIntMatrix(numRows, numCols); + public GamaIntMatrix _reverse(final IScope scope) throws GamaRuntimeException { + final GamaIntMatrix result = new GamaIntMatrix(numRows, numCols); for (int i = 0; i < numCols; i++) { for (int j = 0; j < numRows; j++) { result.set(scope, j, i, get(scope, i, j)); @@ -308,21 +233,19 @@ public IMatrix _reverse(final IScope scope) throws GamaRuntimeException { @Override public GamaIntMatrix copy(final IScope scope, final ILocation preferredSize, final boolean copy) { if (preferredSize == null) { - if (copy) { + if (copy) return new GamaIntMatrix(numCols, numRows, Arrays.copyOf(matrix, matrix.length)); - } else { + else return this; - } - } else { + } else return new GamaIntMatrix((int) preferredSize.getX(), (int) preferredSize.getX(), Arrays.copyOf(matrix, matrix.length)); - } } @Override public boolean equals(final Object m) { - if (this == m) { return true; } - if (!(m instanceof GamaIntMatrix)) { return false; } + if (this == m) return true; + if (!(m instanceof GamaIntMatrix)) return false; final GamaIntMatrix mat = (GamaIntMatrix) m; return Arrays.equals(this.matrix, mat.matrix); } @@ -338,7 +261,7 @@ public void fillWith(final int o) { @Override public Integer get(final IScope scope, final int col, final int row) { - if (col >= numCols || col < 0 || row >= numRows || row < 0) { return 0; } + if (col >= numCols || col < 0 || row >= numRows || row < 0) return 0; return matrix[row * numCols + col]; } @@ -348,13 +271,13 @@ public double getSize() { // @Override public void set(final IScope scope, final int col, final int row, final int obj) { - if (col >= numCols || col < 0 || row >= numRows || row < 0) { return; } + if (col >= numCols || col < 0 || row >= numRows || row < 0) return; matrix[row * numCols + col] = obj; } @Override public void set(final IScope scope, final int col, final int row, final Object obj) { - if (col >= numCols || col < 0 || row >= numRows || row < 0) { return; } + if (col >= numCols || col < 0 || row >= numRows || row < 0) return; matrix[row * numCols + col] = Cast.asInt(scope, obj); } @@ -370,7 +293,7 @@ public boolean remove(final int o) { @Override public Integer remove(final IScope scope, final int col, final int row) { - if (col >= numCols || col < 0 || row >= numRows || row < 0) { return 0; } + if (col >= numCols || col < 0 || row >= numRows || row < 0) return 0; final int o = matrix[row * numCols + col]; matrix[row * numCols + col] = 0; return o; @@ -421,13 +344,9 @@ public void process(final IScope scope) { for (int row = 0; row < numRows; row++) { for (int col = 0; col < numCols; col++) { sb.append(get(scope, col, row)); - if (col < numCols - 1) { - sb.append(','); - } - } - if (row < numRows - 1) { - sb.append(';'); + if (col < numCols - 1) { sb.append(','); } } + if (row < numRows - 1) { sb.append(';'); } } } }); @@ -446,24 +365,6 @@ public java.lang.Iterable iterable(final IScope scope) { return Ints.asList(matrix); } - RealMatrix getRealMatrix() { - final RealMatrix realMatrix = new Array2DRowRealMatrix(this.numRows, this.numCols); - for (int i = 0; i < this.numRows; i++) { - for (int j = 0; j < this.numCols; j++) { - realMatrix.setEntry(i, j, Cast.asFloat(null, this.get(null, j, i))); - } - } - return realMatrix; - } - - void updateMatrix(final RealMatrix realMatrix) { - for (int i = 0; i < this.numRows; i++) { - for (int j = 0; j < this.numCols; j++) { - getMatrix()[i * numCols + j] = Cast.asInt(null, realMatrix.getEntry(i, j)); - } - } - } - // void fillMatrix(final GamaMatrix matrix2) { // for ( int i = 0; i < this.numRows; i++ ) { // for ( int j = 0; j < this.numCols; j++ ) { @@ -473,7 +374,7 @@ void updateMatrix(final RealMatrix realMatrix) { // } @Override - public IMatrix plus(final IScope scope, final IMatrix other) throws GamaRuntimeException { + public GamaIntMatrix plus(final IScope scope, final IMatrix other) throws GamaRuntimeException { final GamaIntMatrix matb = from(scope, other); if (matb != null && this.numCols == matb.numCols && this.numRows == matb.numRows) { final GamaIntMatrix nm = new GamaIntMatrix(this.numCols, this.numRows); @@ -486,7 +387,7 @@ public IMatrix plus(final IScope scope, final IMatrix other) throws GamaRuntimeE } @Override - public IMatrix times(final IScope scope, final IMatrix other) throws GamaRuntimeException { + public GamaIntMatrix times(final IScope scope, final IMatrix other) throws GamaRuntimeException { final GamaIntMatrix matb = from(scope, other); if (matb != null && this.numCols == matb.numCols && this.numRows == matb.numRows) { final GamaIntMatrix nm = new GamaIntMatrix(this.numCols, this.numRows); @@ -499,7 +400,7 @@ public IMatrix times(final IScope scope, final IMatrix other) throws GamaRuntime } @Override - public IMatrix minus(final IScope scope, final IMatrix other) throws GamaRuntimeException { + public GamaIntMatrix minus(final IScope scope, final IMatrix other) throws GamaRuntimeException { final GamaIntMatrix matb = from(scope, other); if (matb != null && this.numCols == matb.numCols && this.numRows == matb.numRows) { final GamaIntMatrix nm = new GamaIntMatrix(this.numCols, this.numRows); @@ -512,7 +413,7 @@ public IMatrix minus(final IScope scope, final IMatrix other) throws GamaRuntime } @Override - public IMatrix times(final Double val) throws GamaRuntimeException { + public GamaFloatMatrix times(final Double val) throws GamaRuntimeException { final GamaFloatMatrix nm = new GamaFloatMatrix(this.numCols, this.numRows); final double[] mm = nm.getMatrix(); for (int i = 0; i < matrix.length; i++) { @@ -522,7 +423,7 @@ public IMatrix times(final Double val) throws GamaRuntimeException { } @Override - public IMatrix times(final Integer val) throws GamaRuntimeException { + public GamaIntMatrix times(final Integer val) throws GamaRuntimeException { final GamaIntMatrix nm = new GamaIntMatrix(this.numCols, this.numRows); for (int i = 0; i < matrix.length; i++) { nm.matrix[i] = matrix[i] * val; @@ -531,7 +432,7 @@ public IMatrix times(final Integer val) throws GamaRuntimeException { } @Override - public IMatrix divides(final Double val) throws GamaRuntimeException { + public GamaFloatMatrix divides(final Double val) throws GamaRuntimeException { final GamaFloatMatrix nm = new GamaFloatMatrix(this.numCols, this.numRows); final double[] mm = nm.getMatrix(); for (int i = 0; i < matrix.length; i++) { @@ -541,7 +442,7 @@ public IMatrix divides(final Double val) throws GamaRuntimeException { } @Override - public IMatrix divides(final Integer val) throws GamaRuntimeException { + public GamaFloatMatrix divides(final Integer val) throws GamaRuntimeException { final GamaFloatMatrix nm = new GamaFloatMatrix(this.numCols, this.numRows); final double[] mm = nm.getMatrix(); for (int i = 0; i < matrix.length; i++) { @@ -551,7 +452,7 @@ public IMatrix divides(final Integer val) throws GamaRuntimeException { } @Override - public IMatrix divides(final IScope scope, final IMatrix other) throws GamaRuntimeException { + public GamaIntMatrix divides(final IScope scope, final IMatrix other) throws GamaRuntimeException { final GamaIntMatrix matb = from(scope, other); if (matb != null && this.numCols == matb.numCols && this.numRows == matb.numRows) { final GamaIntMatrix nm = new GamaIntMatrix(this.numCols, this.numRows); @@ -564,18 +465,7 @@ public IMatrix divides(final IScope scope, final IMatrix other) throws GamaRunti } @Override - public IMatrix matrixMultiplication(final IScope scope, final IMatrix other) throws GamaRuntimeException { - final GamaIntMatrix matb = from(scope, other); - try { - if (matb != null) { return new GamaIntMatrix(getRealMatrix().multiply(matb.getRealMatrix())); } - } catch (final DimensionMismatchException e) { - throw GamaRuntimeException.error(" The dimensions of the matrices do not correspond", scope); - } - return null; - } - - @Override - public IMatrix plus(final Double val) throws GamaRuntimeException { + public GamaFloatMatrix plus(final Double val) throws GamaRuntimeException { final GamaFloatMatrix nm = new GamaFloatMatrix(this.numCols, this.numRows); final double[] mm = nm.getMatrix(); for (int i = 0; i < matrix.length; i++) { @@ -585,7 +475,7 @@ public IMatrix plus(final Double val) throws GamaRuntimeException { } @Override - public IMatrix plus(final Integer val) throws GamaRuntimeException { + public GamaIntMatrix plus(final Integer val) throws GamaRuntimeException { final GamaIntMatrix nm = new GamaIntMatrix(this.numCols, this.numRows); for (int i = 0; i < matrix.length; i++) { nm.matrix[i] = matrix[i] + val; @@ -594,7 +484,7 @@ public IMatrix plus(final Integer val) throws GamaRuntimeException { } @Override - public IMatrix minus(final Double val) throws GamaRuntimeException { + public GamaFloatMatrix minus(final Double val) throws GamaRuntimeException { final GamaFloatMatrix nm = new GamaFloatMatrix(this.numCols, this.numRows); final double[] mm = nm.getMatrix(); for (int i = 0; i < matrix.length; i++) { @@ -604,7 +494,7 @@ public IMatrix minus(final Double val) throws GamaRuntimeException { } @Override - public IMatrix minus(final Integer val) throws GamaRuntimeException { + public GamaIntMatrix minus(final Integer val) throws GamaRuntimeException { final GamaIntMatrix nm = new GamaIntMatrix(this.numCols, this.numRows); for (int i = 0; i < matrix.length; i++) { nm.matrix[i] = matrix[i] - val; @@ -614,8 +504,8 @@ public IMatrix minus(final Integer val) throws GamaRuntimeException { @Override public Integer getNthElement(final Integer index) { - if (index == null) { return 0; } - if (index > getMatrix().length) { return 0; } + if (index == null) return 0; + if (index > getMatrix().length) return 0; return getMatrix()[index]; } @@ -624,69 +514,11 @@ protected void setNthElement(final IScope scope, final int index, final Object v getMatrix()[index] = Cast.asInt(scope, value); } - @Override - public Double getDeterminant(final IScope scope) throws GamaRuntimeException { - final RealMatrix rm = toApacheMatrix(scope); - final LUDecomposition ld = new LUDecomposition(rm); - return ld.getDeterminant(); - } - - @Override - public Double getTrace(final IScope scope) throws GamaRuntimeException { - final RealMatrix rm = toApacheMatrix(scope); - return rm.getTrace(); - } - - @Override - public IList getEigen(final IScope scope) throws GamaRuntimeException { - final RealMatrix rm = toApacheMatrix(scope); - final EigenDecomposition ed = new EigenDecomposition(rm); - return fromApacheMatrixtoDiagList(scope, ed.getD()); - } - @Override public String serialize(final boolean includingBuiltIn) { return "matrix(" + getRowsList(null).serialize(includingBuiltIn) + ")"; } - IList fromApacheMatrixtoDiagList(final IScope scope, final RealMatrix rm) { - final IList vals = GamaListFactory.create(Types.FLOAT); - for (int i = 0; i < rm.getColumnDimension(); i++) { - vals.add(rm.getEntry(i, i)); - } - return vals; - } - - public RealMatrix toApacheMatrix(final IScope scope) { - final RealMatrix rm = new Array2DRowRealMatrix(numRows, numCols); - for (int i = 0; i < numCols; i++) { - for (int j = 0; j < numRows; j++) { - final int val = get(scope, i, j); - rm.setEntry(j, i, val); - } - } - return rm; - } - - public IMatrix fromApacheMatrix(final IScope scope, final RealMatrix rm) { - if (rm == null) { return null; } - final GamaFloatMatrix matrix = new GamaFloatMatrix(rm.getColumnDimension(), rm.getRowDimension()); - for (int i = 0; i < numCols; i++) { - for (int j = 0; j < numRows; j++) { - matrix.set(scope, i, j, rm.getEntry(j, i)); - } - } - return matrix; - - } - - @Override - public IMatrix inverse(final IScope scope) throws GamaRuntimeException { - final RealMatrix rm = toApacheMatrix(scope); - final LUDecomposition ld = new LUDecomposition(rm); - return fromApacheMatrix(scope, ld.getSolver().getInverse()); - } - @Override public StreamEx stream(final IScope scope) { return IntStreamEx.of(matrix).boxed(); diff --git a/msi.gama.core/src/msi/gama/util/matrix/GamaMatrix.java b/msi.gama.core/src/msi/gama/util/matrix/GamaMatrix.java index 29c5ca0056..d694483636 100644 --- a/msi.gama.core/src/msi/gama/util/matrix/GamaMatrix.java +++ b/msi.gama.core/src/msi/gama/util/matrix/GamaMatrix.java @@ -12,16 +12,9 @@ import java.util.List; -import msi.gama.common.interfaces.IKeyword; import msi.gama.common.util.RandomUtils; import msi.gama.metamodel.shape.GamaPoint; import msi.gama.metamodel.shape.ILocation; -import msi.gama.precompiler.GamlAnnotations.doc; -import msi.gama.precompiler.GamlAnnotations.example; -import msi.gama.precompiler.GamlAnnotations.operator; -import msi.gama.precompiler.IConcept; -import msi.gama.precompiler.IOperatorCategory; -import msi.gama.precompiler.ITypeProvider; import msi.gama.runtime.IScope; import msi.gama.runtime.exceptions.GamaRuntimeException; import msi.gama.util.GamaListFactory; @@ -92,7 +85,7 @@ public static IList getColumns(final IScope scope, final IMatrix m) { public static IList getColumn(final IScope scope, final IMatrix m, final Integer num_col) { final IList result = GamaListFactory.create(m.getGamlType().getContentType()); - if (num_col >= m.getCols(scope) || num_col < 0) { return result; } + if (num_col >= m.getCols(scope) || num_col < 0) return result; for (int i = 0; i < m.getRows(scope); i++) { result.add(m.get(scope, num_col, i)); } @@ -101,7 +94,7 @@ public static IList getColumn(final IScope scope, final IMatrix m, final Integer public static IList getLine(final IScope scope, final IMatrix m, final Integer num_line) { final IList result = GamaListFactory.create(m.getGamlType().getContentType()); - if (num_line >= m.getRows(scope) || num_line < 0) { return result; } + if (num_line >= m.getRows(scope) || num_line < 0) return result; for (int i = 0; i < m.getCols(scope); i++) { result.add(m.get(scope, i, num_line)); } @@ -190,126 +183,34 @@ protected GamaMatrix(final IScope scope, final List objects, final ILocation pre this.type = Types.MATRIX.of(contentsType); } - /** - * Take two matrices (with the same number of columns) and create a big matrix putting the second matrix under the - * first matrix - * - * @param two - * matrix to concatenate - * @return the matrix concatenated - */ - - @Override - @operator ( - value = IKeyword.APPEND_VERTICALLY, - content_type = ITypeProvider.BOTH, - category = { IOperatorCategory.MATRIX }, - concept = { IConcept.MATRIX }) - @doc ( - value = "A matrix resulting from the concatenation of the columns of the two given matrices. ", - masterDoc = false, - examples = { @example ( - value = "matrix([[1,2],[3,4]]) append_vertically matrix([[1,2],[3,4]])", - equals = "matrix([[1,2,1,2],[3,4,3,4]])") }) - public IMatrix opAppendVertically(final IScope scope, final IMatrix b) { - if (this instanceof GamaIntMatrix && b instanceof GamaIntMatrix) { - return ((GamaIntMatrix) this)._opAppendVertically(scope, b); - } - if (this instanceof GamaFloatMatrix && b instanceof GamaFloatMatrix) { - return ((GamaFloatMatrix) this)._opAppendVertically(scope, b); - } - if (this instanceof GamaIntMatrix && b instanceof GamaFloatMatrix) { - return new GamaFloatMatrix(((GamaIntMatrix) this).getRealMatrix())._opAppendVertically(scope, b); - } - if (this instanceof GamaFloatMatrix && b instanceof GamaIntMatrix) { - return ((GamaFloatMatrix) this)._opAppendVertically(scope, - new GamaFloatMatrix(((GamaIntMatrix) b).getRealMatrix())); - } - if (this instanceof GamaObjectMatrix && b instanceof GamaObjectMatrix) { - return ((GamaObjectMatrix) this)._opAppendVertically(scope, b); - } - /* - * Object[] ma = this.getMatrix(); Object[] mb = b.getMatrix(); Object[] mab = ArrayUtils.addAll(ma, mb); - * - * GamaObjectMatrix fl = new GamaObjectMatrix(a.getCols(scope), a.getRows(scope) + b.getRows(scope), mab); - */ - // throw GamaRuntimeException.error("ATTENTION : Matrix additions not - // implemented. Returns nil for the moment"); - return this; - } - - /** - * Take two matrices (with the same number of rows) and create a big matrix putting the second matrix on the right - * side of the first matrix - * - * @param two - * matrix to concatenate - * @return the matrix concatenated - */ - - @Override - @operator ( - value = IKeyword.APPEND_HORIZONTALLY, - content_type = ITypeProvider.BOTH, - category = { IOperatorCategory.MATRIX }, - concept = { IConcept.MATRIX }) - @doc ( - value = "A matrix resulting from the concatenation of the rows of the two given matrices.", - masterDoc = false) - public IMatrix opAppendHorizontally(final IScope scope, final IMatrix b) { - if (this instanceof GamaIntMatrix && b instanceof GamaIntMatrix) { - return ((GamaIntMatrix) this)._opAppendHorizontally(scope, b); - } - if (this instanceof GamaFloatMatrix && b instanceof GamaFloatMatrix) { - return ((GamaFloatMatrix) this)._opAppendHorizontally(scope, b); - } - if (this instanceof GamaIntMatrix && b instanceof GamaFloatMatrix) { - return new GamaFloatMatrix(((GamaIntMatrix) this).getRealMatrix())._opAppendHorizontally(scope, b); - } - if (this instanceof GamaFloatMatrix && b instanceof GamaIntMatrix) { - return ((GamaFloatMatrix) this)._opAppendHorizontally(scope, - new GamaFloatMatrix(((GamaIntMatrix) b).getRealMatrix())); - } - if (this instanceof GamaObjectMatrix && b instanceof GamaObjectMatrix) { - return ((GamaObjectMatrix) this)._opAppendHorizontally(scope, b); - } - - return this; - } - @Override public T get(final IScope scope, final ILocation p) { final double px = p.getX(); final double py = p.getY(); - if (px > numCols - 1 || px < 0) { + if (px > numCols - 1 || px < 0) throw GamaRuntimeException.error("Access to a matrix element out of its bounds: " + px, scope); - } - if (py > numRows - 1 || py < 0) { + if (py > numRows - 1 || py < 0) throw GamaRuntimeException.error("Access to a matrix element out of its bounds: " + py, scope); - } return get(scope, (int) px, (int) py); } @Override public T getFromIndicesList(final IScope scope, final IList indices) throws GamaRuntimeException { - if (indices == null || indices.isEmpty()) { return null; } + if (indices == null || indices.isEmpty()) return null; final int size = indices.size(); if (size == 1) { final Object index = indices.get(0); - if (index instanceof GamaPoint) { + if (index instanceof GamaPoint) return get(scope, (GamaPoint) index); - } else { + else return this.getNthElement(Cast.asInt(scope, index)); - } } final int px = Cast.asInt(scope, indices.get(0)); final int py = Cast.asInt(scope, indices.get(1)); - if (px > numCols - 1 || px < 0) { + if (px > numCols - 1 || px < 0) throw GamaRuntimeException.error("Access to a matrix element out of its bounds: " + px, scope); - } - if (py > numRows - 1 || py < 0) { + if (py > numRows - 1 || py < 0) throw GamaRuntimeException.error("Access to a matrix element out of its bounds: " + py, scope); - } return get(scope, px, py); } @@ -339,9 +240,7 @@ public final String stringValue(final IScope scope) throws GamaRuntimeException for (int line = 0; line < numRows; line++) { for (int col = 0; col < numCols; col++) { sb.append(Cast.asString(scope, get(scope, col, line))); - if (col != numCols - 1) { - sb.append(';'); - } + if (col != numCols - 1) { sb.append(';'); } } sb.append(java.lang.System.getProperty("line.separator")); } @@ -384,7 +283,7 @@ public final IMatrix copy(final IScope scope) { public static boolean isFlat(final List val) { for (final Object element : val) { - if (element instanceof List) { return false; } + if (element instanceof List) return false; } return true; } @@ -403,9 +302,9 @@ public final boolean checkBounds(final IScope scope, final Object object, final return x >= 0 && x < numCols && y >= 0 && y < numRows; } else if (object instanceof IContainer) { for (final Object o : ((IContainer) object).iterable(scope)) { - if (!checkBounds(scope, o, forAdding)) { return false; } + if (!checkBounds(scope, o, forAdding)) return false; } - } else if (object instanceof Integer) { return (Integer) object < numCols * numRows; } + } else if (object instanceof Integer) return (Integer) object < numCols * numRows; return false; } @@ -555,19 +454,19 @@ public void setAllValues(final IScope scope, final T value) { } @Override - public void removeValue(final IScope scope, final Object value) {}; + public void removeValue(final IScope scope, final Object value) {} @Override - public void removeIndex(final IScope scope, final Object index) {}; + public void removeIndex(final IScope scope, final Object index) {} @Override public void removeIndexes(final IScope scope, final IContainer indexes) {} @Override - public void removeValues(final IScope scope, final IContainer values) {}; + public void removeValues(final IScope scope, final IContainer values) {} @Override - public void removeAllOccurrencesOfValue(final IScope scope, final Object value) {}; + public void removeAllOccurrencesOfValue(final IScope scope, final Object value) {} /* * (non-Javadoc) @@ -577,10 +476,9 @@ public void removeIndexes(final IScope scope, final IContainer indexes) {} @Override public final IList listValue(final IScope scope, final IType contentsType, final boolean copy) { final IType originalContentsType = type.getContentType(); - if (!GamaType.requiresCasting(contentsType, originalContentsType)) { - // no need to take "copy" into account as the list is created anyway + if (!GamaType.requiresCasting(contentsType, originalContentsType)) // no need to take "copy" into account as the + // list is created anyway return _listValue(scope, originalContentsType, false); - } return _listValue(scope, contentsType, true); // for ( int i = 0, n = result.size(); i < n; i++ ) { // result.set(i, contentsType.cast(scope, result.get(i), null, false)); @@ -718,11 +616,6 @@ public IMatrix divides(final IScope scope, final IMatrix other) throws GamaRunti return this; } - @Override - public IMatrix matrixMultiplication(final IScope scope, final IMatrix other) throws GamaRuntimeException { - return this; - } - @Override public IMatrix times(final Double val) throws GamaRuntimeException { return this; @@ -763,28 +656,4 @@ public IMatrix minus(final Integer val) throws GamaRuntimeException { return this; } - @Override - public Double getDeterminant(final IScope scope) throws GamaRuntimeException { - throw GamaRuntimeException.error("Only usable for int and float matrices", scope); - } - - @Override - public Double getTrace(final IScope scope) throws GamaRuntimeException { - throw GamaRuntimeException.error("Only usable for int and float matrices", scope); - } - - @Override - public IList getEigen(final IScope scope) throws GamaRuntimeException { - throw GamaRuntimeException.error("Only usable for int and float matrices", scope); - } - - @Override - public IMatrix inverse(final IScope scope) throws GamaRuntimeException { - throw GamaRuntimeException.error("Only usable for int and float matrices", scope); - } - - @Override - public IMatrix transpose(final IScope scope) throws GamaRuntimeException { - return reverse(scope); - } } diff --git a/msi.gama.core/src/msi/gama/util/matrix/GamaObjectMatrix.java b/msi.gama.core/src/msi/gama/util/matrix/GamaObjectMatrix.java index 42aa7e1821..fd8014e525 100644 --- a/msi.gama.core/src/msi/gama/util/matrix/GamaObjectMatrix.java +++ b/msi.gama.core/src/msi/gama/util/matrix/GamaObjectMatrix.java @@ -36,14 +36,12 @@ public class GamaObjectMatrix extends GamaMatrix { static public GamaObjectMatrix from(final int c, final int r, final IMatrix m) { - if (m instanceof GamaFloatMatrix) { return new GamaObjectMatrix(c, r, ((GamaFloatMatrix) m).getMatrix()); } - if (m instanceof GamaObjectMatrix) { + if (m instanceof GamaFloatMatrix) return new GamaObjectMatrix(c, r, ((GamaFloatMatrix) m).getMatrix()); + if (m instanceof GamaObjectMatrix) return new GamaObjectMatrix(c, r, ((GamaObjectMatrix) m).getMatrix(), m.getGamlType().getContentType()); - } - if (m instanceof GamaIntMatrix) { return new GamaObjectMatrix(c, r, ((GamaIntMatrix) m).matrix); } - if (m instanceof GamaSpatialMatrix) { + if (m instanceof GamaIntMatrix) return new GamaObjectMatrix(c, r, ((GamaIntMatrix) m).matrix); + if (m instanceof GamaSpatialMatrix) return new GamaObjectMatrix(c, r, ((GamaSpatialMatrix) m).getMatrix(), m.getGamlType().getContentType()); - } return null; } @@ -118,20 +116,20 @@ public void _clear() { @Override public boolean _contains(final IScope scope, final Object o) { for (int i = 0; i < getMatrix().length; i++) { - if (getMatrix()[i].equals(o)) { return true; } + if (getMatrix()[i].equals(o)) return true; } return false; } @Override public Object _first(final IScope scope) { - if (getMatrix().length == 0) { return null; } + if (getMatrix().length == 0) return null; return getMatrix()[0]; } @Override public Object _last(final IScope scope) { - if (getMatrix().length == 0) { return null; } + if (getMatrix().length == 0) return null; return getMatrix()[getMatrix().length - 1]; } @@ -149,21 +147,11 @@ public Integer _length(final IScope scope) { * @return the matrix concatenated */ - // @Override - // @operator(value = IKeyword.APPEND_VERTICALLY, content_type = - // ITypeProvider.CONTENT_TYPE_AT_INDEX + 1, category={IOperatorCategory.MATRIX}) public IMatrix _opAppendVertically(final IScope scope, final IMatrix b) { - final GamaObjectMatrix a = this; - final Object[] ma = a.getMatrix(); - final Object[] mb = ((GamaObjectMatrix) b).getMatrix(); - final Object[] mab = ArrayUtils.addAll(ma, mb); + final Object[] mab = ArrayUtils.addAll(getMatrix(), ((GamaObjectMatrix) b).getMatrix()); final IType newContentsType = GamaType.findCommonType(getGamlType().getContentType(), b.getGamlType().getContentType()); - final IMatrix fl = - new GamaObjectMatrix(a.getCols(scope), a.getRows(scope) + b.getRows(scope), mab, newContentsType); - - // throw GamaRuntimeException.error("ATTENTION : Matrix additions not - // implemented. Returns nil for the moment"); + final IMatrix fl = new GamaObjectMatrix(numCols, numRows + b.getRows(scope), mab, newContentsType); return fl; } @@ -176,19 +164,11 @@ public IMatrix _opAppendVertically(final IScope scope, final IMatrix b) { * @return the matrix concatenated */ - // @Override - // @operator(value = IKeyword.APPEND_HORYZONTALLY, content_type = - // ITypeProvider.CONTENT_TYPE_AT_INDEX + 1, category={IOperatorCategory.MATRIX}) public GamaObjectMatrix _opAppendHorizontally(final IScope scope, final IMatrix b) { - // GamaObjectMatrix a = this; final GamaObjectMatrix aprime = _reverse(scope); - // DEBUG.LOG("aprime = " + aprime); final GamaObjectMatrix bprime = GamaObjectMatrix.from(b.getCols(scope), b.getRows(scope), b)._reverse(scope); - // DEBUG.LOG("bprime = " + bprime); - final GamaObjectMatrix c = (GamaObjectMatrix) aprime.opAppendVertically(scope, bprime); - // DEBUG.LOG("c = " + c); + final GamaObjectMatrix c = (GamaObjectMatrix) aprime._opAppendVertically(scope, bprime); final GamaObjectMatrix cprime = c._reverse(scope); - // DEBUG.LOG("cprime = " + cprime); return cprime; } @@ -243,7 +223,7 @@ public GamaObjectMatrix _opAppendHorizontally(final IScope scope, final IMatrix< @Override public boolean _isEmpty(final IScope scope) { for (int i = 0; i < getMatrix().length; i++) { - if (getMatrix()[i] != null) { return false; } + if (getMatrix()[i] != null) return false; } return true; } @@ -274,12 +254,11 @@ public GamaObjectMatrix _reverse(final IScope scope) throws GamaRuntimeException @Override public GamaObjectMatrix copy(final IScope scope, final ILocation size, final boolean copy) { if (size == null) { - if (copy) { + if (copy) return new GamaObjectMatrix(numCols, numRows, Arrays.copyOf(matrix, matrix.length), getGamlType().getContentType()); - } else { + else return this; - } } return new GamaObjectMatrix((int) size.getX(), (int) size.getY(), Arrays.copyOf(matrix, matrix.length), getGamlType().getContentType()); @@ -287,8 +266,8 @@ public GamaObjectMatrix copy(final IScope scope, final ILocation size, final boo @Override public boolean equals(final Object m) { - if (this == m) { return true; } - if (!(m instanceof GamaObjectMatrix)) { return false; } + if (this == m) return true; + if (!(m instanceof GamaObjectMatrix)) return false; final GamaObjectMatrix mat = (GamaObjectMatrix) m; return Arrays.equals(this.getMatrix(), mat.getMatrix()); } @@ -319,19 +298,19 @@ public void fillWith(final IScope scope, final Object o) { @Override public Object get(final IScope scope, final int col, final int row) { - if (col >= numCols || col < 0 || row >= numRows || row < 0) { return null; } + if (col >= numCols || col < 0 || row >= numRows || row < 0) return null; return getMatrix()[row * numCols + col]; } @Override public void set(final IScope scope, final int col, final int row, final Object obj) { - if (col >= numCols || col < 0 || row >= numRows || row < 0) { return; } + if (col >= numCols || col < 0 || row >= numRows || row < 0) return; getMatrix()[row * numCols + col] = GamaType.toType(scope, obj, getGamlType().getContentType(), false); } @Override public Object remove(final IScope scope, final int col, final int row) { - if (col >= numCols || col < 0 || row >= numRows || row < 0) { return null; } + if (col >= numCols || col < 0 || row >= numRows || row < 0) return null; final Object o = getMatrix()[row * numCols + col]; getMatrix()[row * numCols + col] = null; return o; @@ -377,13 +356,9 @@ public void process(final IScope scope) { for (int row = 0; row < numRows; row++) { for (int col = 0; col < numCols; col++) { sb.append(get(scope, col, row)); - if (col < numCols - 1) { - sb.append(','); - } - } - if (row < numRows - 1) { - sb.append(';'); + if (col < numCols - 1) { sb.append(','); } } + if (row < numRows - 1) { sb.append(';'); } } } }); @@ -422,8 +397,8 @@ protected void setNthElement(final IScope scope, final int index, final Object v */ @Override public Object getNthElement(final Integer index) { - if (index == null) { return null; } - if (index > getMatrix().length) { return null; } + if (index == null) return null; + if (index > getMatrix().length) return null; return getMatrix()[index]; } diff --git a/msi.gama.core/src/msi/gama/util/matrix/IMatrix.java b/msi.gama.core/src/msi/gama/util/matrix/IMatrix.java index 3ccb9df839..0e7040ac45 100644 --- a/msi.gama.core/src/msi/gama/util/matrix/IMatrix.java +++ b/msi.gama.core/src/msi/gama/util/matrix/IMatrix.java @@ -19,7 +19,6 @@ import msi.gama.precompiler.GamlAnnotations.getter; import msi.gama.precompiler.GamlAnnotations.operator; import msi.gama.precompiler.GamlAnnotations.test; -import msi.gama.precompiler.GamlAnnotations.usage; import msi.gama.precompiler.GamlAnnotations.variable; import msi.gama.precompiler.GamlAnnotations.vars; import msi.gama.precompiler.IConcept; @@ -163,21 +162,6 @@ public interface IMatrix @test ("matrix([[1,2],[3,4]]) / matrix([[1,2],[3,4]]) = matrix([[1,1],[1,1]])") IMatrix divides(IScope scope, IMatrix other) throws GamaRuntimeException; - @operator ( - value = ".", - can_be_const = true, - content_type = ITypeProvider.CONTENT_TYPE_AT_INDEX + 1, - category = { IOperatorCategory.MATRIX }, - concept = { IConcept.MATRIX }) - @doc ( - usages = @usage ( - value = "if both operands are matrix, returns the dot product of them", - examples = @example ( - value = "matrix([[1,1],[1,2]]) . matrix([[1,1],[1,2]])", - equals = "matrix([[2,3],[3,5]])"))) - @test ("matrix([[1,1],[1,2]]) . matrix([[1,1],[1,2]]) = matrix([[2,3],[3,5]])") - IMatrix matrixMultiplication(IScope scope, IMatrix other) throws GamaRuntimeException; - @operator ( value = IKeyword.MINUS, can_be_const = true, @@ -272,98 +256,6 @@ public interface IMatrix void set(IScope scope, final int col, final int row, final Object obj) throws GamaRuntimeException; - @operator ( - value = IKeyword.APPEND_HORIZONTALLY, - content_type = ITypeProvider.BOTH, - category = { IOperatorCategory.MATRIX }, - concept = { IConcept.MATRIX }) - @doc ( - value = "A matrix resulting from the concatenation of the rows of the two given matrices. If not both numerical or both object matrices, returns the first matrix.", - masterDoc = true, - examples = { @example ( - value = "matrix([[1.0,2.0],[3.0,4.0]]) append_horizontally matrix([[1,2],[3,4]])", - equals = "matrix([[1.0,2.0],[3.0,4.0],[1.0,2.0],[3.0,4.0]])") }) - IMatrix opAppendHorizontally(final IScope scope, final IMatrix b); - - @operator ( - value = IKeyword.APPEND_VERTICALLY, - content_type = ITypeProvider.BOTH, - category = { IOperatorCategory.MATRIX }, - concept = { IConcept.MATRIX }) - @doc ( - value = "A matrix resulting from the concatenation of the columns of the two given matrices. If not both numerical or both object matrices, returns the first matrix.", - masterDoc = true, - examples = { @example ( - value = "matrix([[1,2],[3,4]]) append_vertically matrix([[1,2],[3,4]])", - equals = "matrix([[1,2,1,2],[3,4,3,4]])") }) - IMatrix opAppendVertically(final IScope scope, final IMatrix b); - - @operator ( - value = { "determinant", "det" }, - category = { IOperatorCategory.MATRIX }, - concept = { IConcept.MATRIX }) - @doc ( - value = "The determinant of the given matrix", - masterDoc = true, - examples = { @example ( - value = "determinant(matrix([[1,2],[3,4]]))", - equals = "-2") }) - Double getDeterminant(IScope scope) throws GamaRuntimeException; - - @operator ( - value = "trace", - category = { IOperatorCategory.MATRIX }, - concept = { IConcept.MATRIX }) - @doc ( - value = "The trace of the given matrix (the sum of the elements on the main diagonal).", - masterDoc = true, - examples = { @example ( - value = "trace(matrix([[1,2],[3,4]]))", - equals = "5") }) - Double getTrace(IScope scope) throws GamaRuntimeException; - - @operator ( - value = "eigenvalues", - content_type = IType.FLOAT, - category = { IOperatorCategory.MATRIX }, - concept = { IConcept.MATRIX }) - @doc ( - value = "The list of the eigen values of the given matrix", - masterDoc = true, - examples = { @example ( - value = "eigenvalues(matrix([[5,-3],[6,-4]]))", - equals = "[2.0000000000000004,-0.9999999999999998]") }) - IList getEigen(IScope scope) throws GamaRuntimeException; - - @operator ( - value = "transpose", - can_be_const = true, - content_type = ITypeProvider.CONTENT_TYPE_AT_INDEX + 1, - category = { IOperatorCategory.MATRIX }, - concept = { IConcept.MATRIX }) - @doc ( - value = "The transposition of the given matrix", - masterDoc = true, - examples = { @example ( - value = "transpose(matrix([[5,-3],[6,-4]]))", - equals = "matrix([[5,6],[-3,-4]])") }) - IMatrix transpose(IScope scope) throws GamaRuntimeException; - - @operator ( - value = "inverse", - can_be_const = true, - content_type = IType.FLOAT, - // ITypeProvider.CONTENT_TYPE_AT_INDEX + 1, - category = { IOperatorCategory.MATRIX }, - concept = { IConcept.MATRIX }) - @doc ( - value = "The inverse matrix of the given matrix. If no inverse exists, returns a matrix that has properties that resemble that of an inverse.", - masterDoc = true, - examples = { @example ( - value = "inverse(matrix([[4,3],[3,2]]))", - equals = "matrix([[-2.0,3.0],[3.0,-4.0]])") }) - IMatrix inverse(IScope scope) throws GamaRuntimeException; - @Override StreamEx stream(final IScope scope); @@ -385,4 +277,7 @@ default boolean containsKey(final IScope scope, final Object o) { IMatrix copy(IScope scope, ILocation preferredSize, boolean copy); + @Override + IMatrix reverse(final IScope scope) throws GamaRuntimeException; + } \ No newline at end of file diff --git a/msi.gama.core/src/msi/gama/util/random/GamaRNG.java b/msi.gama.core/src/msi/gama/util/random/GamaRNG.java index 18177eb84a..18d3763eea 100644 --- a/msi.gama.core/src/msi/gama/util/random/GamaRNG.java +++ b/msi.gama.core/src/msi/gama/util/random/GamaRNG.java @@ -1,36 +1,33 @@ /******************************************************************************************************* * - * msi.gama.util.random.GamaRNG.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) + * msi.gama.util.random.GamaRNG.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and + * simulation platform (v. 1.8.1) * * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.util.random; import java.util.Random; -import org.apache.commons.math3.random.RandomGenerator; -import org.apache.commons.math3.random.RandomGeneratorFactory; - /** * Class GamaRNG. * * @author drogoul * @since 4 juin 2015 + * @modified april 2021 for removing the dependency towards Apache Commons Maths * */ -public abstract class GamaRNG extends Random implements RandomGenerator { +public abstract class GamaRNG extends Random { // Mask for casting a byte to an int, bit-by-bit (with // bitwise AND) with no special consideration for the sign bit. public static final int BITWISE_BYTE_TO_INT = 0x000000FF; /** - * @return The seed data used to initialise this pseudo-random number - * generator. + * @return The seed data used to initialise this pseudo-random number generator. */ abstract byte[] getSeed(); @@ -59,9 +56,9 @@ public void setUsage(final int usage) { } /** - * Take four bytes from the specified position in the specified block and - * convert them into a 32-bit int, using the big-endian convention. - * + * Take four bytes from the specified position in the specified block and convert them into a 32-bit int, using the + * big-endian convention. + * * @param bytes * The data to read from. * @param offset @@ -74,18 +71,16 @@ public static int convertBytesToInt(final byte[] bytes, final int offset) { } /** - * Convert an array of bytes into an array of ints. 4 bytes from the input - * data map to a single int in the output data. - * + * Convert an array of bytes into an array of ints. 4 bytes from the input data map to a single int in the output + * data. + * * @param bytes * The data to read from. * @return An array of 32-bit integers constructed from the data. * @since 1.1 */ public static int[] convertBytesToInts(final byte[] bytes) { - if (bytes.length % 4 != 0) { - throw new IllegalArgumentException("Number of input bytes must be a multiple of 4."); - } + if (bytes.length % 4 != 0) throw new IllegalArgumentException("Number of input bytes must be a multiple of 4."); final int[] ints = new int[bytes.length / 4]; for (int i = 0; i < ints.length; i++) { ints[i] = convertBytesToInt(bytes, i * 4); @@ -93,15 +88,4 @@ public static int[] convertBytesToInts(final byte[] bytes) { return ints; } - @Override - public void setSeed(int seed) { - super.setSeed(Integer.toUnsignedLong(seed)); - - } - - @Override - public void setSeed(int[] seed) { - setSeed(RandomGeneratorFactory.convertToLong(seed)); - } - } diff --git a/msi.gama.core/src/msi/gaml/operators/Material.java b/msi.gama.core/src/msi/gaml/operators/Material.java deleted file mode 100644 index 924de87979..0000000000 --- a/msi.gama.core/src/msi/gaml/operators/Material.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************************************* - * - * msi.gaml.operators.Material.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) - * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners - * - * Visit https://github.com/gama-platform/gama for license information and contacts. - * - ********************************************************************************************************/ -package msi.gaml.operators; - -import msi.gama.precompiler.GamlAnnotations.*; -import msi.gama.util.*; - -/** - * Written by mazarsju - * - * @todo Description - * - */ -public class Material { - - @operator(value = "material", can_be_const = true, category = { /*TODO*/ }, concept = { /*TODO*/ }) - @doc( - value = "Returns a material defined by a given damper and reflectivity", - masterDoc = true - ) - public static GamaMaterial material(final double damper, final double reflectivity) { - return new GamaMaterial(damper,reflectivity); - } -} diff --git a/msi.gama.core/src/msi/gaml/operators/Random.java b/msi.gama.core/src/msi/gaml/operators/Random.java index 777de85f40..0474d1105a 100644 --- a/msi.gama.core/src/msi/gaml/operators/Random.java +++ b/msi.gama.core/src/msi/gaml/operators/Random.java @@ -10,11 +10,6 @@ ********************************************************************************************************/ package msi.gaml.operators; -import org.apache.commons.math3.distribution.GammaDistribution; -import org.apache.commons.math3.distribution.LogNormalDistribution; -import org.apache.commons.math3.distribution.WeibullDistribution; - -import msi.gama.common.interfaces.IKeyword; import msi.gama.common.util.RandomUtils; import msi.gama.metamodel.shape.GamaPoint; import msi.gama.metamodel.shape.ILocation; @@ -27,7 +22,6 @@ import msi.gama.precompiler.IConcept; import msi.gama.precompiler.IOperatorCategory; import msi.gama.precompiler.ITypeProvider; -import msi.gama.precompiler.Reason; import msi.gama.runtime.IScope; import msi.gama.runtime.exceptions.GamaRuntimeException; import msi.gama.util.GamaListFactory; @@ -51,9 +45,7 @@ public class Random { public static RandomUtils RANDOM(final IScope scope) { RandomUtils r = scope.getRandom(); - if (r == null) { - r = new RandomUtils(); - } + if (r == null) { r = new RandomUtils(); } return r; } @@ -92,7 +84,7 @@ public static Double opTGauss(final IScope scope, final GamaPoint p) { "weibull_rnd", "gamma_trunc_rnd", "weibull_trunc_rnd", "lognormal_trunc_rnd" }) @test ("seed <- 1.0; truncated_gauss ([0.5, 0.2]) = 0.5671546797294768") public static Double opTGauss(final IScope scope, final IList list) { - if (list.size() < 2) { return 0d; } + if (list.size() < 2) return 0d; final double mean = Cast.asFloat(scope, list.get(0)); final double range = Cast.asFloat(scope, list.get(1)); /* @@ -230,9 +222,8 @@ public static Integer opBinomial(final IScope scope, final Integer n, final Doub see = { "reverse" }) @test ("seed <- 1.0; shuffle ([12, 13, 14]) = [12,13,14]") public static IList opShuffle(final IScope scope, final IContainer target) { - if (target == null || target.isEmpty(scope)) { + if (target == null || target.isEmpty(scope)) return GamaListFactory.create(target == null ? Types.NO_TYPE : target.getGamlType().getContentType()); - } final IList list = target.listValue(scope, target.getGamlType().getContentType(), false).copy(scope); RANDOM(scope).shuffleInPlace(list); return list; @@ -486,17 +477,13 @@ public static Integer opRndChoice(final IScope scope, final IList distribution) for (final Object eltDistrib : distribution) { final Double elt = Cast.asFloat(scope, eltDistrib); - if (elt < 0.0) { - throw GamaRuntimeException.create(new RuntimeException("Distribution elements should be positive."), - scope); - } + if (elt < 0.0) throw GamaRuntimeException + .create(new RuntimeException("Distribution elements should be positive."), scope); normalizedDistribution.add(elt); sumElt = sumElt + elt; } - if (sumElt == 0.0) { - throw GamaRuntimeException - .create(new RuntimeException("Distribution elements should not be all equal to 0"), scope); - } + if (sumElt == 0.0) throw GamaRuntimeException + .create(new RuntimeException("Distribution elements should not be all equal to 0"), scope); for (int i = 0; i < normalizedDistribution.size(); i++) { normalizedDistribution.set(i, normalizedDistribution.get(i) / sumElt); @@ -506,12 +493,12 @@ public static Integer opRndChoice(final IScope scope, final IList distribution) for (int i = 0; i < distribution.size(); i++) { randomValue = randomValue - normalizedDistribution.get(i); - if (randomValue <= 0) { return i; } + if (randomValue <= 0) return i; } return -1; } - + @operator ( value = "rnd_choice", concept = { IConcept.RANDOM }, @@ -524,7 +511,7 @@ public static Integer opRndChoice(final IScope scope, final IList distribution) test = false) }, see = { "rnd" }) @test ("seed <- 1.0; rnd_choice([\"toto\"::0.2,\"tata\"::0.5,\"tonton\"::0.3]) = \"tonton\"") - public static T opRndCoice(final IScope scope, final IMap distribution) { + public static T opRndCoice(final IScope scope, final IMap distribution) { final IList key = distribution.getKeys(); final IList normalizedDistribution = GamaListFactory.create(Types.FLOAT); Double sumElt = 0.0; @@ -532,18 +519,14 @@ public static T opRndCoice(final IScope scope, final IMap distribution) for (final T k : key) { Object eltDistrib = distribution.get(k); final Double elt = Cast.asFloat(scope, eltDistrib); - if (elt < 0.0) { - throw GamaRuntimeException.create(new RuntimeException("Distribution elements should be positive."), - scope); - } + if (elt < 0.0) throw GamaRuntimeException + .create(new RuntimeException("Distribution elements should be positive."), scope); normalizedDistribution.add(elt); sumElt = sumElt + elt; } - if (sumElt == 0.0) { - throw GamaRuntimeException - .create(new RuntimeException("Distribution elements should not be all equal to 0"), scope); - } - + if (sumElt == 0.0) throw GamaRuntimeException + .create(new RuntimeException("Distribution elements should not be all equal to 0"), scope); + for (int i = 0; i < normalizedDistribution.size(); i++) { normalizedDistribution.set(i, normalizedDistribution.get(i) / sumElt); } @@ -552,7 +535,7 @@ public static T opRndCoice(final IScope scope, final IMap distribution) for (int i = 0; i < distribution.size(); i++) { randomValue = randomValue - normalizedDistribution.get(i); - if (randomValue <= 0) { return key.get(i); } + if (randomValue <= 0) return key.get(i); } throw GamaRuntimeException.create(new RuntimeException("Malformed distribution"), scope); @@ -572,10 +555,8 @@ public static T opRndCoice(final IScope scope, final IMap distribution) test = false) }) @test ("seed <- 1.0; " + "list l1 <- sample([2,10,1],2,false);\r\n" + " list l2 <- [1,10];" + "l1 = l2") public static IList opSample(final IScope scope, final IList x, final int nb, final boolean replacement) { - if (nb < 0.0) { - throw GamaRuntimeException - .create(new RuntimeException("The number of elements of the sample should be positive."), scope); - } + if (nb < 0.0) throw GamaRuntimeException + .create(new RuntimeException("The number of elements of the sample should be positive."), scope); final IList result = GamaListFactory.create(x.getGamlType()); final IList source = replacement ? x : x.copy(scope); while (result.size() < nb && !source.isEmpty()) { @@ -605,15 +586,12 @@ public static IList opSample(final IScope scope, final IList x, final int nb, fi + " list l2 <- [10,1];\r\n" + " l1 = l2 ") public static IList opSample(final IScope scope, final IList x, final int nb, final boolean replacement, final IList weights) { - if (weights == null) { return opSample(scope, x, nb, replacement); } - if (nb < 0.0) { - throw GamaRuntimeException - .create(new RuntimeException("The number of elements of the sample should be positive."), scope); - } - if (weights.size() != x.size()) { - throw GamaRuntimeException.create(new RuntimeException( - "The number of weights should be equal to the number of elements of the source."), scope); - } + if (weights == null) return opSample(scope, x, nb, replacement); + if (nb < 0.0) throw GamaRuntimeException + .create(new RuntimeException("The number of elements of the sample should be positive."), scope); + if (weights.size() != x.size()) throw GamaRuntimeException.create( + new RuntimeException("The number of weights should be equal to the number of elements of the source."), + scope); final IList result = GamaListFactory.create(x.getGamlType()); final IList source = replacement ? x : x.copy(scope); final IList weights_s = replacement ? weights : weights.copy(scope); @@ -672,293 +650,4 @@ public static Double open_simplex_generator(final IScope scope, final double x, return OpenSimplexNoise.noise(x, y, biais); } - @operator ( - value = "gamma_rnd", - can_be_const = false, - category = { IOperatorCategory.RANDOM }, - concept = { IConcept.RANDOM }) - @doc ( - value = "returns a random value from a gamma distribution with specified values of the shape and scale parameters", - examples = { @example ( - value = "gamma_rnd(9,0.5)", - equals = "0.731", - test = false) }, - see = { "binomial", "gauss_rnd", "lognormal_rnd", "poisson", "rnd", "skew_gauss", "truncated_gauss", - "weibull_rnd", "gamma_trunc_rnd" }) - @no_test (Reason.IMPOSSIBLE_TO_TEST) - public static Double OpGammaDist(final IScope scope, final Double shape, final Double scale) - throws GamaRuntimeException { - final GammaDistribution dist = new GammaDistribution(scope.getRandom().getGenerator(), shape, scale, - GammaDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY); - return dist.sample(); - } - - @operator ( - value = "weibull_rnd", - can_be_const = false, - category = { IOperatorCategory.RANDOM }, - concept = { IConcept.RANDOM }) - @doc ( - value = "returns a random value from a Weibull distribution with specified values of the shape (alpha) and scale (beta) parameters. See https://mathworld.wolfram.com/WeibullDistribution.html for more details (equations 1 and 2). ", - examples = { @example ( - value = "weibull_rnd(2,3) ", - equals = "0.731", - test = false) }, - see = { "binomial", "gamma_rnd", "gauss_rnd", "lognormal_rnd", "poisson", "rnd", "skew_gauss", - "truncated_gauss", "weibull_trunc_rnd" }) - @no_test (Reason.IMPOSSIBLE_TO_TEST) - public static Double OpWeibullDist(final IScope scope, final Double shape, final Double scale) - throws GamaRuntimeException { - final WeibullDistribution dist = new WeibullDistribution(scope.getRandom().getGenerator(), shape, scale); - - return dist.sample(); - } - - @operator ( - value = "lognormal_rnd", - can_be_const = false, - category = { IOperatorCategory.RANDOM }, - concept = { IConcept.RANDOM }) - @doc ( - value = "returns a random value from a Log-Normal distribution with specified values of the shape (alpha) and scale (beta) parameters. See https://en.wikipedia.org/wiki/Log-normal_distribution for more details. ", - examples = { @example ( - value = "lognormal_rnd(2,3) ", - equals = "0.731", - test = false) }, - see = { "binomial", "gamma_rnd", "gauss_rnd", "poisson", "rnd", "skew_gauss", "truncated_gauss", - "weibull_rnd", "lognormal_trunc_rnd" }) - @no_test (Reason.IMPOSSIBLE_TO_TEST) - public static Double OpLogNormalDist(final IScope scope, final Double shape, final Double scale) - throws GamaRuntimeException { - final LogNormalDistribution dist = new LogNormalDistribution(scope.getRandom().getGenerator(), shape, scale); - return dist.sample(); - } - - @operator ( - value = "lognormal_trunc_rnd", - can_be_const = false, - category = { IOperatorCategory.RANDOM }, - concept = { IConcept.RANDOM }) - @doc ( - value = "returns a random value from a truncated Log-Normal distribution (in a range or given only one boundary) with specified values of the shape (alpha) and scale (beta) parameters. See https://en.wikipedia.org/wiki/Log-normal_distribution for more details. ", - usages = { @usage ( - value = "when 2 float operands are specified, they are taken as mininimum and maximum values for the result", - examples = { @example ( - value = "lognormal_trunc_rnd(2,3,0,5)", - test = false) }) }, - see = { "lognormal_rnd", "gamma_trunc_rnd", "weibull_trunc_rnd", "truncated_gauss" }) - @test ("lognormal_trunc_rnd(2,3,0,5) <= 5.0") - @test ("lognormal_trunc_rnd(2,3,0.0,5.0) >= 0.0") - public static Double OpLogNormalTruncDist(final IScope scope, final Double shape, final Double scale, - final Double min, final Double max) throws GamaRuntimeException { - double tmpResult = 0; - - do { - tmpResult = OpLogNormalDist(scope, shape, scale); - } while (tmpResult > max || tmpResult < min); - return tmpResult; - } - - @operator ( - value = "lognormal_trunc_rnd", - can_be_const = false, - category = { IOperatorCategory.RANDOM }, - concept = { IConcept.RANDOM }) - @doc ( - usages = { @usage ( - value = "when 1 float and a boolean (isMax) operands are specified, the float value represents the single boundary (max if the boolean is true, min otherwise),", - examples = { @example ( - value = "lognormal_trunc_rnd(2,3,5,true)", - test = false) }) }, - see = { "lognormal_rnd", "gamma_trunc_rnd", "weibull_trunc_rnd", "truncated_gauss" }) - @test ("lognormal_trunc_rnd(2,3,5,true) <= 5.0") - @test ("lognormal_trunc_rnd(2,3,0.0,false) >= 0.0") - public static Double OpLogNormalTruncDist(final IScope scope, final Double shape, final Double scale, - final Double minmax, final Boolean isMax) throws GamaRuntimeException { - double tmpResult = 0; - - if (isMax) { - // minmax is a max here - do { - tmpResult = OpLogNormalDist(scope, shape, scale); - } while (tmpResult > minmax); - } else { - // minmax is a min here - do { - tmpResult = OpLogNormalDist(scope, shape, scale); - } while (tmpResult < minmax); - } - return tmpResult; - } - - @operator ( - value = "weibull_trunc_rnd", - can_be_const = false, - category = { IOperatorCategory.RANDOM }, - concept = { IConcept.RANDOM }) - @doc ( - value = "returns a random value from a truncated Weibull distribution (in a range or given only one boundary) with specified values of the shape (alpha) and scale (beta) parameters. See https://mathworld.wolfram.com/WeibullDistribution.html for more details (equations 1 and 2). ", - usages = { @usage ( - value = "when 2 float operands are specified, they are taken as mininimum and maximum values for the result", - examples = { @example ( - value = "weibull_trunc_rnd(2,3,0.0,5.0)", - test = false) }) }, - see = { "weibull_rnd", "gamma_trunc_rnd", "lognormal_trunc_rnd", "truncated_gauss" }) - @test ("weibull_trunc_rnd(2,3,0,5) <= 5.0") - @test ("weibull_trunc_rnd(2,3,0.0,5.0) >= 0.0") - public static Double OpWeibullTruncDist(final IScope scope, final Double shape, final Double scale, - final Double min, final Double max) throws GamaRuntimeException { - double tmpResult = 0; - - do { - tmpResult = OpWeibullDist(scope, shape, scale); - } while (tmpResult > max || tmpResult < min); - return tmpResult; - } - - @operator ( - value = "weibull_trunc_rnd", - can_be_const = false, - category = { IOperatorCategory.RANDOM }, - concept = { IConcept.RANDOM }) - @doc ( - usages = { @usage ( - value = "when 1 float and a boolean (isMax) operands are specified, the float value represents the single boundary (max if the boolean is true, min otherwise),", - examples = { @example ( - value = "weibull_trunc_rnd(2,3,5,true)", - test = false) }) }, - see = { "weibull_rnd", "gamma_trunc_rnd", "lognormal_trunc_rnd", "truncated_gauss" }) - @test ("weibull_trunc_rnd(2,3,5,true) <= 5.0") - @test ("weibull_trunc_rnd(2,3,0.0,false) >= 0.0") - public static Double OpWeibullTruncDist(final IScope scope, final Double shape, final Double scale, - final Double minmax, final Boolean isMax) throws GamaRuntimeException { - double tmpResult = 0; - - if (isMax) { - // minmax is a max here - do { - tmpResult = OpWeibullDist(scope, shape, scale); - } while (tmpResult > minmax); - } else { - // minmax is a min here - do { - tmpResult = OpWeibullDist(scope, shape, scale); - } while (tmpResult < minmax); - } - return tmpResult; - } - - @operator ( - value = "gamma_trunc_rnd", - can_be_const = false, - category = { IOperatorCategory.RANDOM }, - concept = { IConcept.RANDOM }) - @doc ( - value = "returns a random value from a truncated gamma distribution (in a range or given only one boundary) with specified values of the shape and scale parameters.", - usages = { @usage ( - value = "when 2 float operands are specified, they are taken as mininimum and maximum values for the result", - examples = { @example ( - value = "gamma_trunc_rnd(2,3,0,5)", - test = false) }) }, - see = { "gamma_rnd", "weibull_trunc_rnd", "lognormal_trunc_rnd", "truncated_gauss" }) - @test ("gamma_trunc_rnd(2,3,0,5) <= 5.0") - @test ("gamma_trunc_rnd(2,3,0.0,5.0) >= 0.0") - public static Double OpGammaTruncDist(final IScope scope, final Double shape, final Double scale, final Double min, - final Double max) throws GamaRuntimeException { - double tmpResult = 0; - - do { - tmpResult = OpGammaDist(scope, shape, scale); - } while (tmpResult > max || tmpResult < min); - return tmpResult; - } - - @operator ( - value = "gamma_trunc_rnd", - can_be_const = false, - category = { IOperatorCategory.RANDOM }, - concept = { IConcept.RANDOM }) - @doc ( - usages = { @usage ( - value = "when 1 float and a boolean (isMax) operands are specified, the float value represents the single boundary (max if the boolean is true, min otherwise),", - examples = { @example ( - value = "gamma_trunc_rnd(2,3,5,true)", - test = false) }) }, - see = { "gamma_rnd", "weibull_trunc_rnd", "lognormal_trunc_rnd", "truncated_gauss" }) - @test ("gamma_trunc_rnd(2,3,5,true) <= 5.0") - @test ("gamma_trunc_rnd(2,3,0.0,false) >= 0.0") - public static Double OpGammaTruncDist(final IScope scope, final Double shape, final Double scale, - final Double minmax, final Boolean isMax) throws GamaRuntimeException { - double tmpResult = 0; - - if (isMax) { - // minmax is a max here - do { - tmpResult = OpGammaDist(scope, shape, scale); - } while (tmpResult > minmax); - } else { - // minmax is a min here - do { - tmpResult = OpGammaDist(scope, shape, scale); - } while (tmpResult < minmax); - } - return tmpResult; - } - - - @operator ( - value = "weibull_density", - can_be_const = false, - category = { IOperatorCategory.RANDOM }, - concept = { IConcept.RANDOM }) - @doc ( - value = "weibull_density(x,shape,scale) returns the probability density function (PDF) at the specified point x " - + "of the Weibull distribution with the given shape and scale.", - examples = { @example ( value = "weibull_rnd(1,2,3) ", equals = "0.731", test = false) }, - see = { "binomial", "gamma_rnd", "gauss_rnd", "lognormal_rnd", "poisson", "rnd", "skew_gauss", - "lognormal_density", "gamma_density"}) - @no_test (Reason.IMPOSSIBLE_TO_TEST) - public static Double OpWeibullDistDensity(final IScope scope, final Double x, final Double shape, final Double scale) - throws GamaRuntimeException { - final WeibullDistribution dist = new WeibullDistribution(scope.getRandom().getGenerator(), shape, scale); - - return dist.density(x); - } - - @operator ( - value = "lognormal_density", - can_be_const = false, - category = { IOperatorCategory.RANDOM }, - concept = { IConcept.RANDOM }) - @doc ( - value = "lognormal_density(x,shape,scale) returns the probability density function (PDF) at the specified point x " - + "of the logNormal distribution with the given shape and scale.", - examples = { @example ( value = "lognormal_density(1,2,3) ", equals = "0.731", test = false) }, - see = { "binomial", "gamma_rnd", "gauss_rnd", "poisson", "rnd", "skew_gauss", "truncated_gauss", - "weibull_rnd", "weibull_density", "gamma_density" }) - @no_test (Reason.IMPOSSIBLE_TO_TEST) - public static Double OpLogNormalDist(final IScope scope, final Double x, final Double shape, final Double scale) - throws GamaRuntimeException { - final LogNormalDistribution dist = new LogNormalDistribution(scope.getRandom().getGenerator(), shape, scale); - return dist.density(x); - } - - @operator ( - value = "gamma_density", - can_be_const = false, - category = { IOperatorCategory.RANDOM }, - concept = { IConcept.RANDOM }) - @doc ( - value = "gamma_density(x,shape,scale) returns the probability density function (PDF) at the specified point x " - + "of the Gamma distribution with the given shape and scale.", - examples = { @example ( value = "gamma_density(1,9,0.5)", equals = "0.731", test = false) }, - see = { "binomial", "gauss_rnd", "lognormal_rnd", "poisson", "rnd", "skew_gauss", "truncated_gauss", - "weibull_rnd", "weibull_density", "lognormal_density" }) - @no_test (Reason.IMPOSSIBLE_TO_TEST) - public static Double OpGammaDist(final IScope scope, final Double x, final Double shape, final Double scale) - throws GamaRuntimeException { - final GammaDistribution dist = new GammaDistribution(scope.getRandom().getGenerator(), shape, scale, - GammaDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY); - return dist.density(x); - } } diff --git a/msi.gama.core/src/msi/gaml/types/GamaMaterialType.java b/msi.gama.core/src/msi/gaml/types/GamaMaterialType.java index d066834283..6ddcc61cec 100644 --- a/msi.gama.core/src/msi/gaml/types/GamaMaterialType.java +++ b/msi.gama.core/src/msi/gaml/types/GamaMaterialType.java @@ -1,16 +1,18 @@ /******************************************************************************************************* * - * msi.gaml.types.GamaMaterialType.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) + * msi.gaml.types.GamaMaterialType.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and + * simulation platform (v. 1.8.1) * * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.types; import msi.gama.common.interfaces.IKeyword; +import msi.gama.precompiler.GamlAnnotations.doc; +import msi.gama.precompiler.GamlAnnotations.operator; import msi.gama.precompiler.GamlAnnotations.type; import msi.gama.precompiler.ISymbolKind; import msi.gama.runtime.IScope; @@ -23,13 +25,29 @@ * @todo Description * */ -@SuppressWarnings("unchecked") -@type(name = IKeyword.MATERIAL, id = IType.MATERIAL, wraps = { - GamaMaterial.class }, kind = ISymbolKind.Variable.REGULAR, concept = { /* TODO */ }) +@SuppressWarnings ("unchecked") +@type ( + name = IKeyword.MATERIAL, + id = IType.MATERIAL, + wraps = { GamaMaterial.class }, + kind = ISymbolKind.Variable.REGULAR, + concept = { /* TODO */ }) public class GamaMaterialType extends GamaType { public static GamaMaterial DEFAULT_MATERIAL = new GamaMaterial(0, 0); + @operator ( + value = "material", + can_be_const = true, + category = { /* TODO */ }, + concept = { /* TODO */ }) + @doc ( + value = "Returns a material defined by a given damper and reflectivity", + masterDoc = true) + public static GamaMaterial material(final double damper, final double reflectivity) { + return new GamaMaterial(damper, reflectivity); + } + @Override public GamaMaterial cast(final IScope scope, final Object obj, final Object param, final boolean copy) throws GamaRuntimeException { @@ -37,9 +55,7 @@ public GamaMaterial cast(final IScope scope, final Object obj, final Object para } public static GamaMaterial staticCast(final IScope scope, final Object obj, final boolean copy) { - if (obj instanceof GamaMaterial) { - return (GamaMaterial) obj; - } + if (obj instanceof GamaMaterial) return (GamaMaterial) obj; return null; } diff --git a/msi.gama.ext/.classpath b/msi.gama.ext/.classpath index 45b9ab857f..36a2eff05f 100644 --- a/msi.gama.ext/.classpath +++ b/msi.gama.ext/.classpath @@ -137,7 +137,6 @@ - diff --git a/msi.gama.ext/META-INF/MANIFEST.MF b/msi.gama.ext/META-INF/MANIFEST.MF index cccea7f6d4..4816c25db0 100644 --- a/msi.gama.ext/META-INF/MANIFEST.MF +++ b/msi.gama.ext/META-INF/MANIFEST.MF @@ -198,37 +198,6 @@ Export-Package: com.conversantmedia.util.collection, org.apache.commons.lang3.text.translate, org.apache.commons.lang3.time, org.apache.commons.lang3.tuple, - org.apache.commons.math3.distribution, - org.apache.commons.math3.exception;uses:="org.apache.commons.math3.exception.util,org.apache.commons.math3.util", - org.apache.commons.math3.geometry.euclidean.threed, - org.apache.commons.math3.linear; - uses:="org.apache.commons.math3, - new org.apache.commons.math3.linear, - org.apache.commons.math3.analysis, - org.apache.commons.math3.exception, - org.apache.commons.math3.util", - org.apache.commons.math3.ml.clustering, - org.apache.commons.math3.ml.distance, - org.apache.commons.math3.ode; - uses:="org.apache.commons.math3.ode.sampling, - org.apache.commons.math3.ode.nonstiff, - org.apache.commons.math3.ode.events, - org.apache.commons.math3.exception, - org.apache.commons.math3.analysis.solvers, - org.apache.commons.math3.linear", - org.apache.commons.math3.ode.nonstiff; - uses:="org.apache.commons.math3.ode.sampling, - org.apache.commons.math3.ode, - org.apache.commons.math3.ode.events, - org.apache.commons.math3.analysis.solvers, - org.apache.commons.math3.linear", - org.apache.commons.math3.ode.sampling;uses:="org.apache.commons.math3.ode,new org.apache.commons.math3.ode.sampling,org.apache.commons.math3.linear", - org.apache.commons.math3.random, - org.apache.commons.math3.stat.clustering, - org.apache.commons.math3.stat.descriptive, - org.apache.commons.math3.stat.descriptive.moment, - org.apache.commons.math3.stat.regression;uses:="org.apache.commons.math3.exception.util,org.apache.commons.math3.exception,org.apache.commons.math3.linear", - org.apache.commons.math3.util;uses:="org.apache.commons.math3,org.apache.commons.math3.exception.util,new org.apache.commons.math3.util", org.ejml, org.ejml.data, org.ejml.dense.block, @@ -618,7 +587,6 @@ Require-Bundle: com.google.guava;visibility:=reexport, org.eclipse.xsd;bundle-version="2.18.0" Bundle-ClassPath: ., protobuf-java-3.6.1.jar, - commons-math3-3.6.1/jars/commons-math3-3.6.1.jar, rcaller 2.5/jars/RCaller-2.5.jar, jgrapht 1.0.1/jgrapht-core-1.0.1.jar, jts 1.18.1/jts-core-1.18.1.jar, diff --git a/msi.gama.ext/build.properties b/msi.gama.ext/build.properties index aa3009905c..a8ffce10d5 100644 --- a/msi.gama.ext/build.properties +++ b/msi.gama.ext/build.properties @@ -1,6 +1,5 @@ bin.includes = .,\ META-INF/,\ - commons-math3-3.6.1/jars/commons-math3-3.6.1.jar,\ rcaller 2.5/jars/RCaller-2.5.jar,\ jgrapht 1.0.1/jgrapht-core-1.0.1.jar,\ protobuf-java-3.6.1.jar,\ diff --git a/msi.gama.ext/commons-math3-3.6.1/license/LICENSE-2.0.txt b/msi.gama.ext/commons-math3-3.6.1/license/LICENSE-2.0.txt deleted file mode 100644 index d645695673..0000000000 --- a/msi.gama.ext/commons-math3-3.6.1/license/LICENSE-2.0.txt +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/msi.gama.models/models/Data/Data Analysis/.project b/msi.gama.models/models/Data/Data Analysis/.project deleted file mode 100644 index ccdf30ff9b..0000000000 --- a/msi.gama.models/models/Data/Data Analysis/.project +++ /dev/null @@ -1,18 +0,0 @@ - - - Data Analysis - - - - - - org.eclipse.xtext.ui.shared.xtextBuilder - - - - - - org.eclipse.xtext.ui.shared.xtextNature - msi.gama.application.gamaNature - - diff --git a/ummisco.gaml.extensions.maths/.classpath b/ummisco.gaml.extensions.maths/.classpath index ddf901b473..b3d87e4bbc 100644 --- a/ummisco.gaml.extensions.maths/.classpath +++ b/ummisco.gaml.extensions.maths/.classpath @@ -1,7 +1,8 @@ - + + diff --git a/ummisco.gaml.extensions.maths/.settings/org.eclipse.jdt.core.prefs b/ummisco.gaml.extensions.maths/.settings/org.eclipse.jdt.core.prefs index 0b3561ab6b..419df1dd64 100644 --- a/ummisco.gaml.extensions.maths/.settings/org.eclipse.jdt.core.prefs +++ b/ummisco.gaml.extensions.maths/.settings/org.eclipse.jdt.core.prefs @@ -1,2 +1,11 @@ eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=11 +org.eclipse.jdt.core.compiler.compliance=11 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning org.eclipse.jdt.core.compiler.processAnnotations=enabled +org.eclipse.jdt.core.compiler.release=enabled +org.eclipse.jdt.core.compiler.source=11 diff --git a/ummisco.gaml.extensions.maths/META-INF/MANIFEST.MF b/ummisco.gaml.extensions.maths/META-INF/MANIFEST.MF index b88c398b28..dc5db39516 100644 --- a/ummisco.gaml.extensions.maths/META-INF/MANIFEST.MF +++ b/ummisco.gaml.extensions.maths/META-INF/MANIFEST.MF @@ -6,7 +6,13 @@ Bundle-Version: 1.8.1.qualifier Require-Bundle: msi.gama.core, msi.gama.ext Bundle-ActivationPolicy: lazy -Export-Package: ummisco.gaml.extensions.maths.ode.statements -Bundle-RequiredExecutionEnvironment: JavaSE-1.8 +Export-Package: org.apache.commons.math3.ml.clustering, + org.apache.commons.math3.ml.distance, + org.apache.commons.math3.random, + org.apache.commons.math3.stat.descriptive.moment, + ummisco.gaml.extensions.maths.ode.statements +Bundle-RequiredExecutionEnvironment: JavaSE-11 Automatic-Module-Name: ummisco.gaml.extensions.maths +Bundle-ClassPath: lib/commons-math3-3.6.1.jar, + . diff --git a/ummisco.gaml.extensions.maths/build.properties b/ummisco.gaml.extensions.maths/build.properties index f54ea0ed1a..302b7fb7bb 100644 --- a/ummisco.gaml.extensions.maths/build.properties +++ b/ummisco.gaml.extensions.maths/build.properties @@ -5,4 +5,5 @@ bin.includes = META-INF/,\ .,\ plugin.xml,\ models/,\ - tests/ + tests/,\ + lib/commons-math3-3.6.1.jar diff --git a/msi.gama.ext/commons-math3-3.6.1/jars/commons-math3-3.6.1.jar b/ummisco.gaml.extensions.maths/lib/commons-math3-3.6.1.jar similarity index 100% rename from msi.gama.ext/commons-math3-3.6.1/jars/commons-math3-3.6.1.jar rename to ummisco.gaml.extensions.maths/lib/commons-math3-3.6.1.jar diff --git a/ummisco.gaml.extensions.maths/models/Diffusion Statement/models/Diffusion in a cuve (Cycle length).gaml b/ummisco.gaml.extensions.maths/models/Diffusion Statement/models/Diffusion in a cuve (Cycle length).gaml index 74dd064e4f..c002499078 100644 --- a/ummisco.gaml.extensions.maths/models/Diffusion Statement/models/Diffusion in a cuve (Cycle length).gaml +++ b/ummisco.gaml.extensions.maths/models/Diffusion Statement/models/Diffusion in a cuve (Cycle length).gaml @@ -74,6 +74,7 @@ grid quick_cells height: size width: size { experiment diffusion type: gui { output { + layout #horizontal; display a type: opengl { // Display the grid with elevation grid cells elevation: phero*10 triangulation: true; diff --git a/ummisco.gaml.extensions.maths/src/ummisco/gaml/extensions/maths/matrix/MatrixOperators.java b/ummisco.gaml.extensions.maths/src/ummisco/gaml/extensions/maths/matrix/MatrixOperators.java new file mode 100644 index 0000000000..47cf312e2d --- /dev/null +++ b/ummisco.gaml.extensions.maths/src/ummisco/gaml/extensions/maths/matrix/MatrixOperators.java @@ -0,0 +1,236 @@ +package ummisco.gaml.extensions.maths.matrix; + +import org.apache.commons.math3.exception.DimensionMismatchException; +import org.apache.commons.math3.linear.Array2DRowRealMatrix; +import org.apache.commons.math3.linear.EigenDecomposition; +import org.apache.commons.math3.linear.LUDecomposition; +import org.apache.commons.math3.linear.RealMatrix; + +import msi.gama.common.interfaces.IKeyword; +import msi.gama.precompiler.GamlAnnotations.doc; +import msi.gama.precompiler.GamlAnnotations.example; +import msi.gama.precompiler.GamlAnnotations.operator; +import msi.gama.precompiler.GamlAnnotations.test; +import msi.gama.precompiler.GamlAnnotations.usage; +import msi.gama.precompiler.IConcept; +import msi.gama.precompiler.IOperatorCategory; +import msi.gama.precompiler.ITypeProvider; +import msi.gama.runtime.IScope; +import msi.gama.runtime.exceptions.GamaRuntimeException; +import msi.gama.util.GamaListFactory; +import msi.gama.util.IList; +import msi.gama.util.matrix.GamaFloatMatrix; +import msi.gama.util.matrix.GamaIntMatrix; +import msi.gama.util.matrix.GamaObjectMatrix; +import msi.gama.util.matrix.IMatrix; +import msi.gaml.operators.Cast; +import msi.gaml.types.IType; +import msi.gaml.types.Types; + +public class MatrixOperators { + + @operator ( + value = ".", + can_be_const = true, + content_type = ITypeProvider.CONTENT_TYPE_AT_INDEX + 1, + category = { IOperatorCategory.MATRIX }, + concept = { IConcept.MATRIX }) + @doc ( + usages = @usage ( + value = "if both operands are matrix, returns the dot product of them", + examples = @example ( + value = "matrix([[1,1],[1,2]]) . matrix([[1,1],[1,2]])", + equals = "matrix([[2,3],[3,5]])"))) + @test ("matrix([[1,1],[1,2]]) . matrix([[1,1],[1,2]]) = matrix([[2,3],[3,5]])") + public static IMatrix matrixMultiplication(final IScope scope, final IMatrix a, final IMatrix b) + throws GamaRuntimeException { + try { + if (a instanceof GamaIntMatrix && b instanceof GamaIntMatrix) + return toGamaIntMatrix(getRealMatrix(a).multiply(getRealMatrix(b))); + return toGamaFloatMatrix(getRealMatrix(a).multiply(getRealMatrix(b))); + } catch (final DimensionMismatchException e) { + throw GamaRuntimeException.error(" The dimensions of the matrices do not correspond", scope); + } + } + + @operator ( + value = { "determinant", "det" }, + category = { IOperatorCategory.MATRIX }, + concept = { IConcept.MATRIX }) + @doc ( + value = "The determinant of the given matrix", + masterDoc = true, + examples = { @example ( + value = "determinant(matrix([[1,2],[3,4]]))", + equals = "-2") }) + public static Double getDeterminant(final IScope scope, final IMatrix m) throws GamaRuntimeException { + return new LUDecomposition(getRealMatrix(m)).getDeterminant(); + } + + @operator ( + value = "trace", + category = { IOperatorCategory.MATRIX }, + concept = { IConcept.MATRIX }) + @doc ( + value = "The trace of the given matrix (the sum of the elements on the main diagonal).", + masterDoc = true, + examples = { @example ( + value = "trace(matrix([[1,2],[3,4]]))", + equals = "5") }) + public static Double getTrace(final IScope scope, final IMatrix m) throws GamaRuntimeException { + return getRealMatrix(m).getTrace(); + } + + @operator ( + value = "eigenvalues", + content_type = IType.FLOAT, + category = { IOperatorCategory.MATRIX }, + concept = { IConcept.MATRIX }) + @doc ( + value = "The list of the eigen values of the given matrix", + masterDoc = true, + examples = { @example ( + value = "eigenvalues(matrix([[5,-3],[6,-4]]))", + equals = "[2.0000000000000004,-0.9999999999999998]") }) + public static IList getEigen(final IScope scope, final IMatrix m) throws GamaRuntimeException { + return fromApacheMatrixtoDiagList(scope, new EigenDecomposition(getRealMatrix(m)).getD()); + } + + @operator ( + value = "transpose", + can_be_const = true, + content_type = ITypeProvider.CONTENT_TYPE_AT_INDEX + 1, + category = { IOperatorCategory.MATRIX }, + concept = { IConcept.MATRIX }) + @doc ( + value = "The transposition of the given matrix", + masterDoc = true, + examples = { @example ( + value = "transpose(matrix([[5,-3],[6,-4]]))", + equals = "matrix([[5,6],[-3,-4]])") }) + public static IMatrix transpose(final IScope scope, final IMatrix m) throws GamaRuntimeException { + return m.reverse(scope); + } + + @operator ( + value = "inverse", + can_be_const = true, + content_type = IType.FLOAT, + // ITypeProvider.CONTENT_TYPE_AT_INDEX + 1, + category = { IOperatorCategory.MATRIX }, + concept = { IConcept.MATRIX }) + @doc ( + value = "The inverse matrix of the given matrix. If no inverse exists, returns a matrix that has properties that resemble that of an inverse.", + masterDoc = true, + examples = { @example ( + value = "inverse(matrix([[4,3],[3,2]]))", + equals = "matrix([[-2.0,3.0],[3.0,-4.0]])") }) + public static IMatrix inverse(final IScope scope, final IMatrix m) throws GamaRuntimeException { + return toGamaFloatMatrix(new LUDecomposition(getRealMatrix(m)).getSolver().getInverse()); + } + + @operator ( + value = IKeyword.APPEND_VERTICALLY, + content_type = ITypeProvider.BOTH, + category = { IOperatorCategory.MATRIX }, + concept = { IConcept.MATRIX }) + @doc ( + value = "A matrix resulting from the concatenation of the columns of the two given matrices. ", + masterDoc = false, + examples = { @example ( + value = "matrix([[1,2],[3,4]]) append_vertically matrix([[1,2],[3,4]])", + equals = "matrix([[1,2,1,2],[3,4,3,4]])") }) + public static IMatrix opAppendVertically(final IScope scope, final IMatrix a, final IMatrix b) { + if (a instanceof GamaIntMatrix) { + if (b instanceof GamaIntMatrix) + return ((GamaIntMatrix) a)._opAppendVertically(scope, (GamaIntMatrix) b); + else if (b instanceof GamaFloatMatrix) + return GamaFloatMatrix.from(scope, b)._opAppendVertically(scope, (GamaFloatMatrix) b); + } else if (a instanceof GamaFloatMatrix) { + if (b instanceof GamaIntMatrix) + return ((GamaFloatMatrix) a)._opAppendVertically(scope, GamaFloatMatrix.from(scope, b)); + else if (b instanceof GamaFloatMatrix) + return ((GamaFloatMatrix) a)._opAppendVertically(scope, (GamaFloatMatrix) b); + } + if (a instanceof GamaObjectMatrix && b instanceof GamaObjectMatrix) + return ((GamaObjectMatrix) a)._opAppendVertically(scope, b); + return a; + } + + /** + * Take two matrices (with the same number of rows) and create a big matrix putting the second matrix on the right + * side of the first matrix + * + * @param two + * matrix to concatenate + * @return the matrix concatenated + */ + + @operator ( + value = IKeyword.APPEND_HORIZONTALLY, + content_type = ITypeProvider.BOTH, + category = { IOperatorCategory.MATRIX }, + concept = { IConcept.MATRIX }) + @doc ( + value = "A matrix resulting from the concatenation of the rows of the two given matrices.", + masterDoc = false) + public static IMatrix opAppendHorizontally(final IScope scope, final IMatrix a, final IMatrix b) { + if (a instanceof GamaIntMatrix) { + if (b instanceof GamaIntMatrix) + return ((GamaIntMatrix) a)._opAppendHorizontally(scope, (GamaIntMatrix) b); + else if (b instanceof GamaFloatMatrix) + return GamaFloatMatrix.from(scope, a)._opAppendHorizontally(scope, (GamaFloatMatrix) b); + } else if (a instanceof GamaFloatMatrix) { + if (b instanceof GamaIntMatrix) + return ((GamaFloatMatrix) a)._opAppendHorizontally(scope, GamaFloatMatrix.from(scope, b)); + else if (b instanceof GamaFloatMatrix) + return GamaFloatMatrix.from(scope, a)._opAppendHorizontally(scope, (GamaFloatMatrix) b); + } + if (a instanceof GamaObjectMatrix && b instanceof GamaObjectMatrix) + return ((GamaObjectMatrix) a)._opAppendHorizontally(scope, b); + return a; + } + + public static RealMatrix getRealMatrix(final IMatrix m) { + var rows = m.getRows(null); + var cols = m.getCols(null); + final RealMatrix realMatrix = new Array2DRowRealMatrix(rows, cols); + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + realMatrix.setEntry(i, j, Cast.asFloat(null, m.get(null, j, i))); + } + } + return realMatrix; + } + + public static void updateMatrix(final IMatrix m, final RealMatrix realMatrix) { + var rows = m.getRows(null); + var cols = m.getCols(null); + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + m.set(null, j, i, realMatrix.getEntry(i, j)); + } + } + } + + public static GamaIntMatrix toGamaIntMatrix(final RealMatrix m) { + GamaIntMatrix result = new GamaIntMatrix(m.getColumnDimension(), m.getRowDimension()); + updateMatrix(result, m); + return result; + } + + public static GamaFloatMatrix toGamaFloatMatrix(final RealMatrix m) { + GamaFloatMatrix result = new GamaFloatMatrix(m.getColumnDimension(), m.getRowDimension()); + updateMatrix(result, m); + return result; + } + + public static IList fromApacheMatrixtoDiagList(final IScope scope, final RealMatrix rm) { + final IList vals = GamaListFactory.create(Types.FLOAT); + for (int i = 0; i < rm.getColumnDimension(); i++) { + vals.add(rm.getEntry(i, i)); + } + return vals; + } + +} diff --git a/ummisco.gaml.extensions.maths/src/ummisco/gaml/extensions/maths/random/ForwardingGenerator.java b/ummisco.gaml.extensions.maths/src/ummisco/gaml/extensions/maths/random/ForwardingGenerator.java new file mode 100644 index 0000000000..5b7eaf488b --- /dev/null +++ b/ummisco.gaml.extensions.maths/src/ummisco/gaml/extensions/maths/random/ForwardingGenerator.java @@ -0,0 +1,71 @@ +package ummisco.gaml.extensions.maths.random; + +import org.apache.commons.math3.random.RandomGenerator; +import org.apache.commons.math3.random.RandomGeneratorFactory; + +import msi.gama.util.random.GamaRNG; + +public class ForwardingGenerator implements RandomGenerator { + + private final GamaRNG target; + + ForwardingGenerator(final GamaRNG target) { + this.target = target; + } + + @Override + public boolean nextBoolean() { + return target.nextBoolean(); + } + + @Override + public void nextBytes(final byte[] arg0) { + target.nextBytes(arg0); + } + + @Override + public double nextDouble() { + return target.nextDouble(); + } + + @Override + public float nextFloat() { + return target.nextFloat(); + } + + @Override + public double nextGaussian() { + return target.nextGaussian(); + } + + @Override + public int nextInt() { + return target.nextInt(); + } + + @Override + public int nextInt(final int arg0) { + return target.nextInt(arg0); + } + + @Override + public long nextLong() { + return target.nextLong(); + } + + @Override + public void setSeed(final int arg0) { + target.setSeed(Integer.toUnsignedLong(arg0)); + } + + @Override + public void setSeed(final int[] arg0) { + target.setSeed(RandomGeneratorFactory.convertToLong(arg0)); + } + + @Override + public void setSeed(final long arg0) { + target.setSeed(arg0); + } + +} \ No newline at end of file diff --git a/ummisco.gaml.extensions.maths/src/ummisco/gaml/extensions/maths/random/Random2.java b/ummisco.gaml.extensions.maths/src/ummisco/gaml/extensions/maths/random/Random2.java new file mode 100644 index 0000000000..dc5ab6ed2f --- /dev/null +++ b/ummisco.gaml.extensions.maths/src/ummisco/gaml/extensions/maths/random/Random2.java @@ -0,0 +1,323 @@ +package ummisco.gaml.extensions.maths.random; + +import org.apache.commons.math3.distribution.GammaDistribution; +import org.apache.commons.math3.distribution.LogNormalDistribution; +import org.apache.commons.math3.distribution.WeibullDistribution; + +import msi.gama.precompiler.GamlAnnotations.doc; +import msi.gama.precompiler.GamlAnnotations.example; +import msi.gama.precompiler.GamlAnnotations.no_test; +import msi.gama.precompiler.GamlAnnotations.operator; +import msi.gama.precompiler.GamlAnnotations.test; +import msi.gama.precompiler.GamlAnnotations.usage; +import msi.gama.precompiler.IConcept; +import msi.gama.precompiler.IOperatorCategory; +import msi.gama.precompiler.Reason; +import msi.gama.runtime.IScope; +import msi.gama.runtime.exceptions.GamaRuntimeException; + +public class Random2 { + + @operator ( + value = "gamma_rnd", + can_be_const = false, + category = { IOperatorCategory.RANDOM }, + concept = { IConcept.RANDOM }) + @doc ( + value = "returns a random value from a gamma distribution with specified values of the shape and scale parameters", + examples = { @example ( + value = "gamma_rnd(9,0.5)", + equals = "0.731", + test = false) }, + see = { "binomial", "gauss_rnd", "lognormal_rnd", "poisson", "rnd", "skew_gauss", "truncated_gauss", + "weibull_rnd", "gamma_trunc_rnd" }) + @no_test (Reason.IMPOSSIBLE_TO_TEST) + public static Double OpGammaDist(final IScope scope, final Double shape, final Double scale) + throws GamaRuntimeException { + final GammaDistribution dist = new GammaDistribution(new ForwardingGenerator(scope.getRandom().getGenerator()), + shape, scale, GammaDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY); + return dist.sample(); + } + + @operator ( + value = "weibull_rnd", + can_be_const = false, + category = { IOperatorCategory.RANDOM }, + concept = { IConcept.RANDOM }) + @doc ( + value = "returns a random value from a Weibull distribution with specified values of the shape (alpha) and scale (beta) parameters. See https://mathworld.wolfram.com/WeibullDistribution.html for more details (equations 1 and 2). ", + examples = { @example ( + value = "weibull_rnd(2,3) ", + equals = "0.731", + test = false) }, + see = { "binomial", "gamma_rnd", "gauss_rnd", "lognormal_rnd", "poisson", "rnd", "skew_gauss", + "truncated_gauss", "weibull_trunc_rnd" }) + @no_test (Reason.IMPOSSIBLE_TO_TEST) + public static Double OpWeibullDist(final IScope scope, final Double shape, final Double scale) + throws GamaRuntimeException { + final WeibullDistribution dist = + new WeibullDistribution(new ForwardingGenerator(scope.getRandom().getGenerator()), shape, scale); + + return dist.sample(); + } + + @operator ( + value = "lognormal_rnd", + can_be_const = false, + category = { IOperatorCategory.RANDOM }, + concept = { IConcept.RANDOM }) + @doc ( + value = "returns a random value from a Log-Normal distribution with specified values of the shape (alpha) and scale (beta) parameters. See https://en.wikipedia.org/wiki/Log-normal_distribution for more details. ", + examples = { @example ( + value = "lognormal_rnd(2,3) ", + equals = "0.731", + test = false) }, + see = { "binomial", "gamma_rnd", "gauss_rnd", "poisson", "rnd", "skew_gauss", "truncated_gauss", + "weibull_rnd", "lognormal_trunc_rnd" }) + @no_test (Reason.IMPOSSIBLE_TO_TEST) + public static Double OpLogNormalDist(final IScope scope, final Double shape, final Double scale) + throws GamaRuntimeException { + final LogNormalDistribution dist = + new LogNormalDistribution(new ForwardingGenerator(scope.getRandom().getGenerator()), shape, scale); + return dist.sample(); + } + + @operator ( + value = "lognormal_trunc_rnd", + can_be_const = false, + category = { IOperatorCategory.RANDOM }, + concept = { IConcept.RANDOM }) + @doc ( + value = "returns a random value from a truncated Log-Normal distribution (in a range or given only one boundary) with specified values of the shape (alpha) and scale (beta) parameters. See https://en.wikipedia.org/wiki/Log-normal_distribution for more details. ", + usages = { @usage ( + value = "when 2 float operands are specified, they are taken as mininimum and maximum values for the result", + examples = { @example ( + value = "lognormal_trunc_rnd(2,3,0,5)", + test = false) }) }, + see = { "lognormal_rnd", "gamma_trunc_rnd", "weibull_trunc_rnd", "truncated_gauss" }) + @test ("lognormal_trunc_rnd(2,3,0,5) <= 5.0") + @test ("lognormal_trunc_rnd(2,3,0.0,5.0) >= 0.0") + public static Double OpLogNormalTruncDist(final IScope scope, final Double shape, final Double scale, + final Double min, final Double max) throws GamaRuntimeException { + double tmpResult = 0; + + do { + tmpResult = OpLogNormalDist(scope, shape, scale); + } while (tmpResult > max || tmpResult < min); + return tmpResult; + } + + @operator ( + value = "lognormal_trunc_rnd", + can_be_const = false, + category = { IOperatorCategory.RANDOM }, + concept = { IConcept.RANDOM }) + @doc ( + usages = { @usage ( + value = "when 1 float and a boolean (isMax) operands are specified, the float value represents the single boundary (max if the boolean is true, min otherwise),", + examples = { @example ( + value = "lognormal_trunc_rnd(2,3,5,true)", + test = false) }) }, + see = { "lognormal_rnd", "gamma_trunc_rnd", "weibull_trunc_rnd", "truncated_gauss" }) + @test ("lognormal_trunc_rnd(2,3,5,true) <= 5.0") + @test ("lognormal_trunc_rnd(2,3,0.0,false) >= 0.0") + public static Double OpLogNormalTruncDist(final IScope scope, final Double shape, final Double scale, + final Double minmax, final Boolean isMax) throws GamaRuntimeException { + double tmpResult = 0; + + if (isMax) { + // minmax is a max here + do { + tmpResult = OpLogNormalDist(scope, shape, scale); + } while (tmpResult > minmax); + } else { + // minmax is a min here + do { + tmpResult = OpLogNormalDist(scope, shape, scale); + } while (tmpResult < minmax); + } + return tmpResult; + } + + @operator ( + value = "weibull_trunc_rnd", + can_be_const = false, + category = { IOperatorCategory.RANDOM }, + concept = { IConcept.RANDOM }) + @doc ( + value = "returns a random value from a truncated Weibull distribution (in a range or given only one boundary) with specified values of the shape (alpha) and scale (beta) parameters. See https://mathworld.wolfram.com/WeibullDistribution.html for more details (equations 1 and 2). ", + usages = { @usage ( + value = "when 2 float operands are specified, they are taken as mininimum and maximum values for the result", + examples = { @example ( + value = "weibull_trunc_rnd(2,3,0.0,5.0)", + test = false) }) }, + see = { "weibull_rnd", "gamma_trunc_rnd", "lognormal_trunc_rnd", "truncated_gauss" }) + @test ("weibull_trunc_rnd(2,3,0,5) <= 5.0") + @test ("weibull_trunc_rnd(2,3,0.0,5.0) >= 0.0") + public static Double OpWeibullTruncDist(final IScope scope, final Double shape, final Double scale, + final Double min, final Double max) throws GamaRuntimeException { + double tmpResult = 0; + + do { + tmpResult = OpWeibullDist(scope, shape, scale); + } while (tmpResult > max || tmpResult < min); + return tmpResult; + } + + @operator ( + value = "weibull_trunc_rnd", + can_be_const = false, + category = { IOperatorCategory.RANDOM }, + concept = { IConcept.RANDOM }) + @doc ( + usages = { @usage ( + value = "when 1 float and a boolean (isMax) operands are specified, the float value represents the single boundary (max if the boolean is true, min otherwise),", + examples = { @example ( + value = "weibull_trunc_rnd(2,3,5,true)", + test = false) }) }, + see = { "weibull_rnd", "gamma_trunc_rnd", "lognormal_trunc_rnd", "truncated_gauss" }) + @test ("weibull_trunc_rnd(2,3,5,true) <= 5.0") + @test ("weibull_trunc_rnd(2,3,0.0,false) >= 0.0") + public static Double OpWeibullTruncDist(final IScope scope, final Double shape, final Double scale, + final Double minmax, final Boolean isMax) throws GamaRuntimeException { + double tmpResult = 0; + + if (isMax) { + // minmax is a max here + do { + tmpResult = OpWeibullDist(scope, shape, scale); + } while (tmpResult > minmax); + } else { + // minmax is a min here + do { + tmpResult = OpWeibullDist(scope, shape, scale); + } while (tmpResult < minmax); + } + return tmpResult; + } + + @operator ( + value = "gamma_trunc_rnd", + can_be_const = false, + category = { IOperatorCategory.RANDOM }, + concept = { IConcept.RANDOM }) + @doc ( + value = "returns a random value from a truncated gamma distribution (in a range or given only one boundary) with specified values of the shape and scale parameters.", + usages = { @usage ( + value = "when 2 float operands are specified, they are taken as mininimum and maximum values for the result", + examples = { @example ( + value = "gamma_trunc_rnd(2,3,0,5)", + test = false) }) }, + see = { "gamma_rnd", "weibull_trunc_rnd", "lognormal_trunc_rnd", "truncated_gauss" }) + @test ("gamma_trunc_rnd(2,3,0,5) <= 5.0") + @test ("gamma_trunc_rnd(2,3,0.0,5.0) >= 0.0") + public static Double OpGammaTruncDist(final IScope scope, final Double shape, final Double scale, final Double min, + final Double max) throws GamaRuntimeException { + double tmpResult = 0; + + do { + tmpResult = OpGammaDist(scope, shape, scale); + } while (tmpResult > max || tmpResult < min); + return tmpResult; + } + + @operator ( + value = "gamma_trunc_rnd", + can_be_const = false, + category = { IOperatorCategory.RANDOM }, + concept = { IConcept.RANDOM }) + @doc ( + usages = { @usage ( + value = "when 1 float and a boolean (isMax) operands are specified, the float value represents the single boundary (max if the boolean is true, min otherwise),", + examples = { @example ( + value = "gamma_trunc_rnd(2,3,5,true)", + test = false) }) }, + see = { "gamma_rnd", "weibull_trunc_rnd", "lognormal_trunc_rnd", "truncated_gauss" }) + @test ("gamma_trunc_rnd(2,3,5,true) <= 5.0") + @test ("gamma_trunc_rnd(2,3,0.0,false) >= 0.0") + public static Double OpGammaTruncDist(final IScope scope, final Double shape, final Double scale, + final Double minmax, final Boolean isMax) throws GamaRuntimeException { + double tmpResult = 0; + + if (isMax) { + // minmax is a max here + do { + tmpResult = OpGammaDist(scope, shape, scale); + } while (tmpResult > minmax); + } else { + // minmax is a min here + do { + tmpResult = OpGammaDist(scope, shape, scale); + } while (tmpResult < minmax); + } + return tmpResult; + } + + @operator ( + value = "weibull_density", + can_be_const = false, + category = { IOperatorCategory.RANDOM }, + concept = { IConcept.RANDOM }) + @doc ( + value = "weibull_density(x,shape,scale) returns the probability density function (PDF) at the specified point x " + + "of the Weibull distribution with the given shape and scale.", + examples = { @example ( + value = "weibull_rnd(1,2,3) ", + equals = "0.731", + test = false) }, + see = { "binomial", "gamma_rnd", "gauss_rnd", "lognormal_rnd", "poisson", "rnd", "skew_gauss", + "lognormal_density", "gamma_density" }) + @no_test (Reason.IMPOSSIBLE_TO_TEST) + public static Double OpWeibullDistDensity(final IScope scope, final Double x, final Double shape, + final Double scale) throws GamaRuntimeException { + final WeibullDistribution dist = + new WeibullDistribution(new ForwardingGenerator(scope.getRandom().getGenerator()), shape, scale); + + return dist.density(x); + } + + @operator ( + value = "lognormal_density", + can_be_const = false, + category = { IOperatorCategory.RANDOM }, + concept = { IConcept.RANDOM }) + @doc ( + value = "lognormal_density(x,shape,scale) returns the probability density function (PDF) at the specified point x " + + "of the logNormal distribution with the given shape and scale.", + examples = { @example ( + value = "lognormal_density(1,2,3) ", + equals = "0.731", + test = false) }, + see = { "binomial", "gamma_rnd", "gauss_rnd", "poisson", "rnd", "skew_gauss", "truncated_gauss", + "weibull_rnd", "weibull_density", "gamma_density" }) + @no_test (Reason.IMPOSSIBLE_TO_TEST) + public static Double OpLogNormalDist(final IScope scope, final Double x, final Double shape, final Double scale) + throws GamaRuntimeException { + final LogNormalDistribution dist = + new LogNormalDistribution(new ForwardingGenerator(scope.getRandom().getGenerator()), shape, scale); + return dist.density(x); + } + + @operator ( + value = "gamma_density", + can_be_const = false, + category = { IOperatorCategory.RANDOM }, + concept = { IConcept.RANDOM }) + @doc ( + value = "gamma_density(x,shape,scale) returns the probability density function (PDF) at the specified point x " + + "of the Gamma distribution with the given shape and scale.", + examples = { @example ( + value = "gamma_density(1,9,0.5)", + equals = "0.731", + test = false) }, + see = { "binomial", "gauss_rnd", "lognormal_rnd", "poisson", "rnd", "skew_gauss", "truncated_gauss", + "weibull_rnd", "weibull_density", "lognormal_density" }) + @no_test (Reason.IMPOSSIBLE_TO_TEST) + public static Double OpGammaDist(final IScope scope, final Double x, final Double shape, final Double scale) + throws GamaRuntimeException { + final GammaDistribution dist = new GammaDistribution(new ForwardingGenerator(scope.getRandom().getGenerator()), + shape, scale, GammaDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY); + return dist.density(x); + } + +} diff --git a/ummisco.gaml.extensions.stats/META-INF/MANIFEST.MF b/ummisco.gaml.extensions.stats/META-INF/MANIFEST.MF index 809c1cc69d..7e1015bdae 100644 --- a/ummisco.gaml.extensions.stats/META-INF/MANIFEST.MF +++ b/ummisco.gaml.extensions.stats/META-INF/MANIFEST.MF @@ -4,7 +4,8 @@ Bundle-Name: Stats Bundle-SymbolicName: ummisco.gaml.extensions.stats;singleton:=true Bundle-Version: 1.8.1.qualifier Require-Bundle: msi.gama.core, - msi.gama.ext + ummisco.gaml.extensions.maths;bundle-version="1.8.1", + msi.gama.ext;bundle-version="1.8.1" Bundle-ActivationPolicy: lazy Export-Package: ummisco.gaml.extensions.stats Bundle-ClassPath: ., diff --git a/msi.gama.models/models/Data/Data Analysis/Clustering/.project b/ummisco.gaml.extensions.stats/models/Clustering Algorithms/.project similarity index 79% rename from msi.gama.models/models/Data/Data Analysis/Clustering/.project rename to ummisco.gaml.extensions.stats/models/Clustering Algorithms/.project index 6991e3135e..2db2470c7a 100644 --- a/msi.gama.models/models/Data/Data Analysis/Clustering/.project +++ b/ummisco.gaml.extensions.stats/models/Clustering Algorithms/.project @@ -1,7 +1,7 @@ Clustering - + stats plugin @@ -14,5 +14,6 @@ org.eclipse.xtext.ui.shared.xtextNature msi.gama.application.gamaNature + msi.gama.application.pluginNature diff --git a/msi.gama.models/models/Data/Data Analysis/Clustering/Clustering.gaml b/ummisco.gaml.extensions.stats/models/Clustering Algorithms/Clustering.gaml similarity index 100% rename from msi.gama.models/models/Data/Data Analysis/Clustering/Clustering.gaml rename to ummisco.gaml.extensions.stats/models/Clustering Algorithms/Clustering.gaml diff --git a/msi.gama.models/models/Data/Data Analysis/Clustering/Spatial Clustering.gaml b/ummisco.gaml.extensions.stats/models/Clustering Algorithms/Spatial Clustering.gaml similarity index 100% rename from msi.gama.models/models/Data/Data Analysis/Clustering/Spatial Clustering.gaml rename to ummisco.gaml.extensions.stats/models/Clustering Algorithms/Spatial Clustering.gaml diff --git a/msi.gama.models/models/Data/Data Analysis/Map Comparison/.project b/ummisco.gaml.extensions.stats/models/Spatial Statistics/.project similarity index 79% rename from msi.gama.models/models/Data/Data Analysis/Map Comparison/.project rename to ummisco.gaml.extensions.stats/models/Spatial Statistics/.project index 6378802dc0..2c5b83970f 100644 --- a/msi.gama.models/models/Data/Data Analysis/Map Comparison/.project +++ b/ummisco.gaml.extensions.stats/models/Spatial Statistics/.project @@ -1,7 +1,7 @@ Map comparison - + stats plugin @@ -14,5 +14,6 @@ org.eclipse.xtext.ui.shared.xtextNature msi.gama.application.gamaNature + msi.gama.application.pluginNature diff --git a/msi.gama.models/models/Data/Data Analysis/Map Comparison/includes/CLC00_06.dbf b/ummisco.gaml.extensions.stats/models/Spatial Statistics/includes/CLC00_06.dbf similarity index 100% rename from msi.gama.models/models/Data/Data Analysis/Map Comparison/includes/CLC00_06.dbf rename to ummisco.gaml.extensions.stats/models/Spatial Statistics/includes/CLC00_06.dbf diff --git a/msi.gama.models/models/Data/Data Analysis/Map Comparison/includes/CLC00_06.prj b/ummisco.gaml.extensions.stats/models/Spatial Statistics/includes/CLC00_06.prj similarity index 100% rename from msi.gama.models/models/Data/Data Analysis/Map Comparison/includes/CLC00_06.prj rename to ummisco.gaml.extensions.stats/models/Spatial Statistics/includes/CLC00_06.prj diff --git a/msi.gama.models/models/Data/Data Analysis/Map Comparison/includes/CLC00_06.shp b/ummisco.gaml.extensions.stats/models/Spatial Statistics/includes/CLC00_06.shp similarity index 100% rename from msi.gama.models/models/Data/Data Analysis/Map Comparison/includes/CLC00_06.shp rename to ummisco.gaml.extensions.stats/models/Spatial Statistics/includes/CLC00_06.shp diff --git a/msi.gama.models/models/Data/Data Analysis/Map Comparison/includes/CLC00_06.shx b/ummisco.gaml.extensions.stats/models/Spatial Statistics/includes/CLC00_06.shx similarity index 100% rename from msi.gama.models/models/Data/Data Analysis/Map Comparison/includes/CLC00_06.shx rename to ummisco.gaml.extensions.stats/models/Spatial Statistics/includes/CLC00_06.shx diff --git a/msi.gama.models/models/Data/Data Analysis/Map Comparison/models/Raster Map Comparison.gaml b/ummisco.gaml.extensions.stats/models/Spatial Statistics/models/Raster Map Comparison.gaml similarity index 100% rename from msi.gama.models/models/Data/Data Analysis/Map Comparison/models/Raster Map Comparison.gaml rename to ummisco.gaml.extensions.stats/models/Spatial Statistics/models/Raster Map Comparison.gaml diff --git a/msi.gama.models/models/Data/Data Analysis/Map Comparison/models/Vector Map Comparison.gaml b/ummisco.gaml.extensions.stats/models/Spatial Statistics/models/Vector Map Comparison.gaml similarity index 100% rename from msi.gama.models/models/Data/Data Analysis/Map Comparison/models/Vector Map Comparison.gaml rename to ummisco.gaml.extensions.stats/models/Spatial Statistics/models/Vector Map Comparison.gaml diff --git a/msi.gama.models/models/Data/Data Analysis/Statistics/.project b/ummisco.gaml.extensions.stats/models/Statistics/.project similarity index 79% rename from msi.gama.models/models/Data/Data Analysis/Statistics/.project rename to ummisco.gaml.extensions.stats/models/Statistics/.project index 22839270b1..760a374e81 100644 --- a/msi.gama.models/models/Data/Data Analysis/Statistics/.project +++ b/ummisco.gaml.extensions.stats/models/Statistics/.project @@ -1,7 +1,7 @@ Statistics - + stats plugin @@ -14,5 +14,6 @@ org.eclipse.xtext.ui.shared.xtextNature msi.gama.application.gamaNature + msi.gama.application.pluginNature diff --git a/msi.gama.models/models/Data/Data Analysis/Statistics/Regression.gaml b/ummisco.gaml.extensions.stats/models/Statistics/Regression.gaml similarity index 100% rename from msi.gama.models/models/Data/Data Analysis/Statistics/Regression.gaml rename to ummisco.gaml.extensions.stats/models/Statistics/Regression.gaml diff --git a/msi.gama.models/models/Data/Data Analysis/Statistics/Statistic Operators.gaml b/ummisco.gaml.extensions.stats/models/Statistics/Statistic Operators.gaml similarity index 100% rename from msi.gama.models/models/Data/Data Analysis/Statistics/Statistic Operators.gaml rename to ummisco.gaml.extensions.stats/models/Statistics/Statistic Operators.gaml diff --git a/msi.gama.core/src/msi/gaml/operators/MapComparison.java b/ummisco.gaml.extensions.stats/src/ummisco/gaml/extensions/stats/MapComparison.java similarity index 92% rename from msi.gama.core/src/msi/gaml/operators/MapComparison.java rename to ummisco.gaml.extensions.stats/src/ummisco/gaml/extensions/stats/MapComparison.java index 49102c897f..79b4f84e74 100644 --- a/msi.gama.core/src/msi/gaml/operators/MapComparison.java +++ b/ummisco.gaml.extensions.stats/src/ummisco/gaml/extensions/stats/MapComparison.java @@ -8,7 +8,9 @@ * Visit https://github.com/gama-platform/gama for license information and contacts. * ********************************************************************************************************/ -package msi.gaml.operators; +package ummisco.gaml.extensions.stats; + +import static msi.gaml.operators.Cast.asFloat; import java.util.ArrayList; import java.util.Collections; @@ -35,6 +37,8 @@ import msi.gama.util.IContainer; import msi.gama.util.IList; import msi.gama.util.matrix.GamaMatrix; +import msi.gaml.operators.Cast; +import msi.gaml.operators.Containers; import msi.gaml.types.IType; import msi.gaml.types.Types; @@ -78,9 +82,9 @@ public static double kappa(final IScope scope, final IList vals1, final equals = "0.29411764705882354") }) public static double kappa(final IScope scope, final IList vals1, final IList vals2, final IList categories, final IList weights) { - if (vals1 == null || vals2 == null) { return 1; } + if (vals1 == null || vals2 == null) return 1; final int nb = vals1.size(); - if (nb != vals2.size()) { return 0; } + if (nb != vals2.size()) return 0; final int nbCat = categories.size(); final double[] X = new double[nbCat]; final double[] Y = new double[nbCat]; @@ -99,7 +103,7 @@ public static double kappa(final IScope scope, final IList vals1, final } double total = 0; for (int i = 0; i < nb; i++) { - final double weight = weights == null ? 1.0 : Cast.asFloat(scope, weights.get(i)); + final double weight = weights == null ? 1.0 : asFloat(scope, weights.get(i)); total += weight; final Object val1 = vals1.get(i); final Object val2 = vals2.get(i); @@ -122,7 +126,7 @@ public static double kappa(final IScope scope, final IList vals1, final po += contigency[i][i]; pe += X[i] * Y[i]; } - if (pe == 1) { return 1; } + if (pe == 1) return 1; return (po - pe) / (1 - pe); } @@ -149,15 +153,16 @@ public static double kappaSimulation(final IScope scope, final IList val concept = {}) @doc ( value = "kappa simulation indicator for 2 map comparisons: kappa(list_valsInits,list_valsObs,list_valsSim, categories, weights). Reference: van Vliet, J., Bregt, A.K. & Hagen-Zanker, A. (2011). Revisiting Kappa to account for change in the accuracy assessment of land-use change models, Ecological Modelling 222(8)", - usages = {@usage(value = "kappa_sim can be used with an additional weights operand", - examples = { @example ( - value = "kappa_sim([\"cat1\",\"cat1\",\"cat2\",\"cat2\",\"cat2\"],[\"cat1\",\"cat3\",\"cat2\",\"cat1\",\"cat3\"],[\"cat1\",\"cat3\",\"cat2\",\"cat3\",\"cat1\"],[\"cat1\",\"cat2\",\"cat3\"], [1.0, 2.0, 3.0, 1.0, 5.0])", - equals = "0.2702702702702703") })}) + usages = { @usage ( + value = "kappa_sim can be used with an additional weights operand", + examples = { @example ( + value = "kappa_sim([\"cat1\",\"cat1\",\"cat2\",\"cat2\",\"cat2\"],[\"cat1\",\"cat3\",\"cat2\",\"cat1\",\"cat3\"],[\"cat1\",\"cat3\",\"cat2\",\"cat3\",\"cat1\"],[\"cat1\",\"cat2\",\"cat3\"], [1.0, 2.0, 3.0, 1.0, 5.0])", + equals = "0.2702702702702703") }) }) public static double kappaSimulation(final IScope scope, final IList valsInit, final IList valsObs, final IList valsSim, final IList categories, final IList weights) { - if (valsInit == null || valsObs == null || valsSim == null) { return 1; } + if (valsInit == null || valsObs == null || valsSim == null) return 1; final int nb = valsInit.size(); - if (nb != valsObs.size() || nb != valsSim.size()) { return 0; } + if (nb != valsObs.size() || nb != valsSim.size()) return 0; final int nbCat = categories.size(); final double[] O = new double[nbCat]; final double[][] contigency = new double[nbCat][nbCat]; @@ -210,7 +215,7 @@ public static double kappaSimulation(final IScope scope, final IList val } pe += O[j] * sum; } - if (pe == 1) { return 1; } + if (pe == 1) return 1; return (po - pe) / (1 - pe); } @@ -247,9 +252,9 @@ public static double fuzzyKappa(final IScope scope, final IAddressableContainer agents, final IList vals1, final IList vals2, final IList similarities, final IList categories, final GamaMatrix fuzzycategories, final Double distance, final IList weights) { - if (agents == null) { return 1; } + if (agents == null) return 1; final int nb = agents.length(scope); - if (nb < 1) { return 1; } + if (nb < 1) return 1; final int nbCat = categories.size(); similarities.clear(); final boolean[] sim = new boolean[nb]; @@ -274,7 +279,7 @@ public static double fuzzyKappa(final IScope scope, final Map ringsPn = GamaMapFactory.create(); final int nbRings = buildRings(scope, filter, distance, rings, ringsPn, agents); final double similarityExpected = computeExpectedSim(nbCat, X, Y, nbRings, rings, ringsPn); - if (similarityExpected == 1) { return 1; } + if (similarityExpected == 1) return 1; return (meanSimilarity - similarityExpected) / (1 - similarityExpected); } @@ -314,9 +319,9 @@ public static double fuzzyKappaSimulation(final IScope scope, final IList valsObs, final IList valsSim, final IList similarities, final IList categories, final GamaMatrix fuzzytransitions, final Double distance, final IList weights) { - if (agents == null) { return 1; } + if (agents == null) return 1; final int nb = agents.length(scope); - if (nb < 1) { return 1; } + if (nb < 1) return 1; similarities.clear(); final int nbCat = categories.size(); final double[] nbObs = new double[nbCat]; @@ -384,7 +389,7 @@ public static double fuzzyKappaSimulation(final IScope scope, } } } - if (pe == 1) { return 1; } + if (pe == 1) return 1; return (po - pe) / (1 - pe); } @@ -454,12 +459,8 @@ private static double[] computeXaXs(final IScope scope, final IAgentFilter filte final double valxstmp = fuzzyTransition(scope, fuzzytransitions, nbCat, valInitId, valObsId, valIId, valSId) * dist; - if (valxatmp > xa) { - xa = valxatmp; - } - if (valxstmp > xs) { - xs = valxstmp; - } + if (valxatmp > xa) { xa = valxatmp; } + if (valxstmp > xs) { xs = valxstmp; } } XaXs[0] = xa; @@ -510,12 +511,8 @@ private static void computeXaXsTransitions(final IScope scope, final IAgentFilte final double dist = distancesCoeff.get(ag); final double xatmp = fuzzyTransition(scope, fuzzytransitions, nbCat, i, k, i, j) * dist; final double xstmp = fuzzyTransition(scope, fuzzytransitions, nbCat, i, j, i, k) * dist; - if (xatmp > xa) { - xa = xatmp; - } - if (xstmp > xs) { - xs = xstmp; - } + if (xatmp > xa) { xa = xatmp; } + if (xstmp > xs) { xs = xstmp; } } if (xa > 0) { @@ -557,9 +554,7 @@ private static void computeXaXsTransitions(final IScope scope, final IAgentFilte private static double p(final double dist, final int a, final int b, final double[] X, final double[] Y, final Map ringsPn) { int n = 0; - if (dist > 0.0) { - n = ringsPn.get(dist); - } + if (dist > 0.0) { n = ringsPn.get(dist); } return (1 - Math.pow(1 - X[a], n)) * (1 - Math.pow(1 - Y[b], n)); } @@ -624,12 +619,8 @@ private static double computeSimilarity(final IScope scope, final IAgentFilter f final double val1 = crispVector1[id][j] * distancesCoeff.get(ag); final double val2 = crispVector2[id][j] * distancesCoeff.get(ag); - if (val1 > max1) { - max1 = val1; - } - if (val2 > max2) { - max2 = val2; - } + if (val1 > max1) { max1 = val1; } + if (val2 > max2) { max2 = val2; } } fuzzyVector1[i][j] = max1; fuzzyVector2[i][j] = max2; @@ -640,12 +631,8 @@ private static double computeSimilarity(final IScope scope, final IAgentFilter f for (int j = 0; j < nbCat; j++) { final double s1 = Math.min(fuzzyVector1[i][j], crispVector2[i][j]); final double s2 = Math.min(fuzzyVector2[i][j], crispVector1[i][j]); - if (s1 > s1Max) { - s1Max = s1; - } - if (s2 > s2Max) { - s2Max = s2; - } + if (s1 > s1Max) { s1Max = s1; } + if (s2 > s2Max) { s2Max = s2; } } similarities.add(Math.min(s1Max, s2Max)); } @@ -713,9 +700,7 @@ private static int buildRings(final IScope scope, final IAgentFilter filter, fin for (final IAgent ag : neighbors) { final double dist = centralLoc.euclidianDistanceTo(ag.getLocation()); - if (dist == 0) { - continue; - } + if (dist == 0) { continue; } if (!rings.contains(dist)) { rings.add(dist); ringsPn.put(dist, 1); @@ -747,18 +732,18 @@ private static int buildRings(final IScope scope, final IAgentFilter filter, fin equals = "20.0") }) public static double percentAbsoluteDeviation(final IScope scope, final IList vals1, final IList vals2) { - if (vals1 == null || vals2 == null) { return 1; } + if (vals1 == null || vals2 == null) return 1; final int nb = vals1.size(); - if (nb != vals2.size()) { return 0; } + if (nb != vals2.size()) return 0; double sum = 0; double coeff = 0; for (int i = 0; i < nb; i++) { - final double val1 = Cast.asFloat(scope, vals1.get(i)); - final double val2 = Cast.asFloat(scope, vals2.get(i)); + final double val1 = asFloat(scope, vals1.get(i)); + final double val2 = asFloat(scope, vals2.get(i)); coeff += val1; sum += Math.abs(val1 - val2) * 100.0; } - if (coeff == 0) { return 0; } + if (coeff == 0) return 0; return sum / coeff; } diff --git a/ummisco.gaml.extensions.stats/src/ummisco/gaml/extensions/stats/Stats.java b/ummisco.gaml.extensions.stats/src/ummisco/gaml/extensions/stats/Stats.java index a8e51b4a21..ffe79c7557 100644 --- a/ummisco.gaml.extensions.stats/src/ummisco/gaml/extensions/stats/Stats.java +++ b/ummisco.gaml.extensions.stats/src/ummisco/gaml/extensions/stats/Stats.java @@ -1050,6 +1050,7 @@ public static IList DBscanApache(final IScope scope, final IList data, fi equals = "[[0,2,3],[1]]") }) public static IList KMeansPlusplusApache(final IScope scope, final IList data, final Integer k, final Integer maxIt) throws GamaRuntimeException { + // AD 04/21 : Is it ok to use an additional generator here ? final MersenneTwister rand = new MersenneTwister(scope.getRandom().getSeed().longValue()); final List instances = new ArrayList<>();