/*
Copyright (C) 1999 CERN - European Organization for Nuclear Research.
Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose
is hereby granted without fee, provided that the above copyright notice appear in all copies and
that both that copyright notice and this permission notice appear in supporting documentation.
CERN makes no representations about the suitability of this software for any purpose.
It is provided "as is" without expressed or implied warranty.
*/
package cern.colt.matrix.tfloat;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import cern.colt.list.tfloat.FloatArrayList;
import cern.colt.list.tint.IntArrayList;
import cern.colt.matrix.AbstractMatrix2D;
import cern.jet.math.tfloat.FloatFunctions;
import edu.emory.utils.ConcurrencyUtils;
/**
* Abstract base class for 2-d matrices holding float elements. First
* see the package summary and javadoc tree view to get the broad picture.
*
* A matrix has a number of rows and columns, which are assigned upon instance
* construction - The matrix's size is then rows()*columns(). Elements
* are accessed via [row,column] coordinates. Legal coordinates range
* from [0,0] to [rows()-1,columns()-1]. Any attempt to access
* an element at a coordinate
* column<0 || column>=columns() || row<0 || row>=rows()
* will throw an IndexOutOfBoundsException.
*
* Note that this implementation is not synchronized.
*
* @author wolfgang.hoschek@cern.ch
* @version 1.0, 09/24/99
*
* @author Piotr Wendykier (piotr.wendykier@gmail.com)
*
*/
public abstract class FloatMatrix2D extends AbstractMatrix2D {
private static final long serialVersionUID = 1L;
/**
* Makes this class non instantiable, but still let's others inherit from
* it.
*/
protected FloatMatrix2D() {
}
/**
* Applies a function to each cell and aggregates the results. Returns a
* value v such that v==a(size()) where
* a(i) == aggr( a(i-1), f(get(row,column)) ) and terminators are
* a(1) == f(get(0,0)), a(0)==Float.NaN.
*
* Example:
*
*
* cern.jet.math.Functions F = cern.jet.math.Functions.functions;
* 2 x 2 matrix
* 0 1
* 2 3
*
* // Sum( x[row,col]*x[row,col] )
* matrix.aggregate(F.plus,F.square);
* --> 14
*
*
*
* For further examples, see the package doc.
*
* @param aggr
* an aggregation function taking as first argument the current
* aggregation and as second argument the transformed current
* cell value.
* @param f
* a function transforming the current cell value.
* @return the aggregated measure.
* @see cern.jet.math.tfloat.FloatFunctions
*/
public float aggregate(final cern.colt.function.tfloat.FloatFloatFunction aggr,
final cern.colt.function.tfloat.FloatFunction f) {
if (size() == 0)
return Float.NaN;
float a = 0;
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (rows * columns >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
int k = rows / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstRow = j * k;
final int lastRow = (j == nthreads - 1) ? rows : firstRow + k;
futures[j] = ConcurrencyUtils.submit(new Callable() {
public Float call() throws Exception {
float a = f.apply(getQuick(firstRow, 0));
int d = 1;
for (int r = firstRow; r < lastRow; r++) {
for (int c = d; c < columns; c++) {
a = aggr.apply(a, f.apply(getQuick(r, c)));
}
d = 0;
}
return Float.valueOf(a);
}
});
}
a = ConcurrencyUtils.waitForCompletion(futures, aggr);
} else {
a = f.apply(getQuick(0, 0));
int d = 1; // first cell already done
for (int r = 0; r < rows; r++) {
for (int c = d; c < columns; c++) {
a = aggr.apply(a, f.apply(getQuick(r, c)));
}
d = 0;
}
}
return a;
}
/**
* Applies a function to each cell that satisfies a condition and aggregates
* the results.
*
* @param aggr
* an aggregation function taking as first argument the current
* aggregation and as second argument the transformed current
* cell value.
* @param f
* a function transforming the current cell value.
* @param cond
* a condition.
* @return the aggregated measure.
* @see cern.jet.math.tfloat.FloatFunctions
*/
public float aggregate(final cern.colt.function.tfloat.FloatFloatFunction aggr,
final cern.colt.function.tfloat.FloatFunction f, final cern.colt.function.tfloat.FloatProcedure cond) {
if (size() == 0)
return Float.NaN;
float a = 0;
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (rows * columns >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
int k = rows / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstRow = j * k;
final int lastRow = (j == nthreads - 1) ? rows : firstRow + k;
futures[j] = ConcurrencyUtils.submit(new Callable() {
public Float call() throws Exception {
float elem = getQuick(firstRow, 0);
float a = 0;
if (cond.apply(elem) == true) {
a = aggr.apply(a, f.apply(elem));
}
int d = 1;
for (int r = firstRow; r < lastRow; r++) {
for (int c = d; c < columns; c++) {
elem = getQuick(r, c);
if (cond.apply(elem) == true) {
a = aggr.apply(a, f.apply(elem));
}
}
d = 0;
}
return Float.valueOf(a);
}
});
}
a = ConcurrencyUtils.waitForCompletion(futures, aggr);
} else {
float elem = getQuick(0, 0);
if (cond.apply(elem) == true) {
a = aggr.apply(a, f.apply(elem));
}
int d = 1; // first cell already done
for (int r = 0; r < rows; r++) {
for (int c = d; c < columns; c++) {
elem = getQuick(r, c);
if (cond.apply(elem) == true) {
a = aggr.apply(a, f.apply(elem));
}
}
d = 0;
}
}
return a;
}
/**
*
* Applies a function to all cells with a given indexes and aggregates the
* results.
*
* @param aggr
* an aggregation function taking as first argument the current
* aggregation and as second argument the transformed current
* cell value.
* @param f
* a function transforming the current cell value.
* @param rowList
* row indexes.
* @param columnList
* column indexes.
*
* @return the aggregated measure.
* @see cern.jet.math.tfloat.FloatFunctions
*/
public float aggregate(final cern.colt.function.tfloat.FloatFloatFunction aggr,
final cern.colt.function.tfloat.FloatFunction f, final IntArrayList rowList, final IntArrayList columnList) {
if (size() == 0)
return Float.NaN;
final int size = rowList.size();
final int[] rowElements = rowList.elements();
final int[] columnElements = columnList.elements();
float a = 0;
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (size >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
int k = size / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstIdx = j * k;
final int lastIdx = (j == nthreads - 1) ? size : firstIdx + k;
futures[j] = ConcurrencyUtils.submit(new Callable() {
public Float call() throws Exception {
float a = f.apply(getQuick(rowElements[firstIdx], columnElements[firstIdx]));
float elem;
for (int i = firstIdx + 1; i < lastIdx; i++) {
elem = getQuick(rowElements[i], columnElements[i]);
a = aggr.apply(a, f.apply(elem));
}
return a;
}
});
}
a = ConcurrencyUtils.waitForCompletion(futures, aggr);
} else {
float elem;
a = f.apply(getQuick(rowElements[0], columnElements[0]));
for (int i = 1; i < size; i++) {
elem = getQuick(rowElements[i], columnElements[i]);
a = aggr.apply(a, f.apply(elem));
}
}
return a;
}
/**
* Applies a function to each corresponding cell of two matrices and
* aggregates the results. Returns a value v such that
* v==a(size()) where
* a(i) == aggr( a(i-1), f(get(row,column),other.get(row,column)) )
* and terminators are
* a(1) == f(get(0,0),other.get(0,0)), a(0)==Float.NaN.
*
* Example:
*
*
* cern.jet.math.Functions F = cern.jet.math.Functions.functions;
* x == 2 x 2 matrix
* 0 1
* 2 3
*
* y == 2 x 2 matrix
* 0 1
* 2 3
*
* // Sum( x[row,col] * y[row,col] )
* x.aggregate(y, F.plus, F.mult);
* --> 14
*
* // Sum( (x[row,col] + y[row,col])ˆ2 )
* x.aggregate(y, F.plus, F.chain(F.square,F.plus));
* --> 56
*
*
*
* For further examples, see the package doc.
*
* @param aggr
* an aggregation function taking as first argument the current
* aggregation and as second argument the transformed current
* cell values.
* @param f
* a function transforming the current cell values.
* @return the aggregated measure.
* @throws IllegalArgumentException
* if
* columns() != other.columns() || rows() != other.rows()
* @see cern.jet.math.tfloat.FloatFunctions
*/
public float aggregate(final FloatMatrix2D other, final cern.colt.function.tfloat.FloatFloatFunction aggr,
final cern.colt.function.tfloat.FloatFloatFunction f) {
checkShape(other);
if (size() == 0)
return Float.NaN;
float a = 0;
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (rows * columns >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
int k = rows / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstRow = j * k;
final int lastRow = (j == nthreads - 1) ? rows : firstRow + k;
futures[j] = ConcurrencyUtils.submit(new Callable() {
public Float call() throws Exception {
float a = f.apply(getQuick(firstRow, 0), other.getQuick(firstRow, 0));
int d = 1;
for (int r = firstRow; r < lastRow; r++) {
for (int c = d; c < columns; c++) {
a = aggr.apply(a, f.apply(getQuick(r, c), other.getQuick(r, c)));
}
d = 0;
}
return Float.valueOf(a);
}
});
}
a = ConcurrencyUtils.waitForCompletion(futures, aggr);
} else {
a = f.apply(getQuick(0, 0), other.getQuick(0, 0));
int d = 1; // first cell already done
for (int r = 0; r < rows; r++) {
for (int c = d; c < columns; c++) {
a = aggr.apply(a, f.apply(getQuick(r, c), other.getQuick(r, c)));
}
d = 0;
}
}
return a;
}
/**
* Assigns the result of a function to each cell;
* x[row,col] = function(x[row,col]).
*
* Example:
*
*
* matrix = 2 x 2 matrix
* 0.5 1.5
* 2.5 3.5
*
* // change each cell to its sine
* matrix.assign(cern.jet.math.Functions.sin);
* -->
* 2 x 2 matrix
* 0.479426 0.997495
* 0.598472 -0.350783
*
*
*
* For further examples, see the package doc.
*
* @param f
* a function object taking as argument the current cell's value.
* @return this (for convenience only).
* @see cern.jet.math.tfloat.FloatFunctions
*/
public FloatMatrix2D assign(final cern.colt.function.tfloat.FloatFunction f) {
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (rows * columns >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
int k = rows / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstRow = j * k;
final int lastRow = (j == nthreads - 1) ? rows : firstRow + k;
futures[j] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
for (int r = firstRow; r < lastRow; r++) {
for (int c = 0; c < columns; c++) {
setQuick(r, c, f.apply(getQuick(r, c)));
}
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
setQuick(r, c, f.apply(getQuick(r, c)));
}
}
}
return this;
}
/**
* Assigns the result of a function to all cells that satisfy a condition.
*
* @param cond
* a condition.
*
* @param f
* a function object.
* @return this (for convenience only).
* @see cern.jet.math.tfloat.FloatFunctions
*/
public FloatMatrix2D assign(final cern.colt.function.tfloat.FloatProcedure cond,
final cern.colt.function.tfloat.FloatFunction f) {
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (rows * columns >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
int k = rows / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstRow = j * k;
final int lastRow = (j == nthreads - 1) ? rows : firstRow + k;
futures[j] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
float elem;
for (int r = firstRow; r < lastRow; r++) {
for (int c = 0; c < columns; c++) {
elem = getQuick(r, c);
if (cond.apply(elem) == true) {
setQuick(r, c, f.apply(elem));
}
}
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
float elem;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
elem = getQuick(r, c);
if (cond.apply(elem) == true) {
setQuick(r, c, f.apply(elem));
}
}
}
}
return this;
}
/**
* Assigns a value to all cells that satisfy a condition.
*
* @param cond
* a condition.
*
* @param value
* a value.
* @return this (for convenience only).
*
*/
public FloatMatrix2D assign(final cern.colt.function.tfloat.FloatProcedure cond, final float value) {
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (rows * columns >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
int k = rows / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstRow = j * k;
final int lastRow = (j == nthreads - 1) ? rows : firstRow + k;
futures[j] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
float elem;
for (int r = firstRow; r < lastRow; r++) {
for (int c = 0; c < columns; c++) {
elem = getQuick(r, c);
if (cond.apply(elem) == true) {
setQuick(r, c, value);
}
}
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
float elem;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
elem = getQuick(r, c);
if (cond.apply(elem) == true) {
setQuick(r, c, value);
}
}
}
}
return this;
}
/**
* Sets all cells to the state specified by value.
*
* @param value
* the value to be filled into the cells.
* @return this (for convenience only).
*/
public FloatMatrix2D assign(final float value) {
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (rows * columns >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
int k = rows / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstRow = j * k;
final int lastRow = (j == nthreads - 1) ? rows : firstRow + k;
futures[j] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
for (int r = firstRow; r < lastRow; r++) {
for (int c = 0; c < columns; c++) {
setQuick(r, c, value);
}
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
setQuick(r, c, value);
}
}
}
return this;
}
/**
* Sets all cells to the state specified by values. values
* is required to have the form values[row*column] and elements
* have to be stored in a row-wise order.
*
* The values are copied. So subsequent changes in values are not
* reflected in the matrix, and vice-versa.
*
* @param values
* the values to be filled into the cells.
* @return this (for convenience only).
* @throws IllegalArgumentException
* if values.length != rows()*columns().
*/
public FloatMatrix2D assign(final float[] values) {
if (values.length != rows * columns)
throw new IllegalArgumentException("Must have same length: length=" + values.length + "rows()*columns()="
+ rows() * columns());
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (rows * columns >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
int k = rows / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstRow = j * k;
final int lastRow = (j == nthreads - 1) ? rows : firstRow + k;
futures[j] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
int idx = firstRow * columns;
for (int r = firstRow; r < lastRow; r++) {
for (int c = 0; c < columns; c++) {
setQuick(r, c, values[idx++]);
}
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
int idx = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
setQuick(r, c, values[idx++]);
}
}
}
return this;
}
/**
* Sets all cells to the state specified by values. values
* is required to have the form values[row][column] and have
* exactly the same number of rows and columns as the receiver.
*
* The values are copied. So subsequent changes in values are not
* reflected in the matrix, and vice-versa.
*
* @param values
* the values to be filled into the cells.
* @return this (for convenience only).
* @throws IllegalArgumentException
* if
* values.length != rows() || for any 0 <= row < rows(): values[row].length != columns()
* .
*/
public FloatMatrix2D assign(final float[][] values) {
if (values.length != rows)
throw new IllegalArgumentException("Must have same number of rows: rows=" + values.length + "rows()="
+ rows());
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (rows * columns >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
int k = rows / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstRow = j * k;
final int lastRow = (j == nthreads - 1) ? rows : firstRow + k;
futures[j] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
for (int r = firstRow; r < lastRow; r++) {
float[] currentRow = values[r];
if (currentRow.length != columns)
throw new IllegalArgumentException(
"Must have same number of columns in every row: columns=" + currentRow.length
+ "columns()=" + columns());
for (int c = 0; c < columns; c++) {
setQuick(r, c, currentRow[c]);
}
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
for (int r = 0; r < rows; r++) {
float[] currentRow = values[r];
if (currentRow.length != columns)
throw new IllegalArgumentException("Must have same number of columns in every row: columns="
+ currentRow.length + "columns()=" + columns());
for (int c = 0; c < columns; c++) {
setQuick(r, c, currentRow[c]);
}
}
}
return this;
}
/**
* Replaces all cell values of the receiver with the values of another
* matrix. Both matrices must have the same number of rows and columns. If
* both matrices share the same cells (as is the case if they are views
* derived from the same matrix) and intersect in an ambiguous way, then
* replaces as if using an intermediate auxiliary deep copy of
* other.
*
* @param other
* the source matrix to copy from (may be identical to the
* receiver).
* @return this (for convenience only).
* @throws IllegalArgumentException
* if
* columns() != other.columns() || rows() != other.rows()
*/
public FloatMatrix2D assign(FloatMatrix2D other) {
if (other == this)
return this;
checkShape(other);
final FloatMatrix2D source;
if (haveSharedCells(other)) {
source = other.copy();
} else {
source = other;
}
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (rows * columns >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
int k = rows / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstRow = j * k;
final int lastRow = (j == nthreads - 1) ? rows : firstRow + k;
futures[j] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
for (int r = firstRow; r < lastRow; r++) {
for (int c = 0; c < columns; c++) {
setQuick(r, c, source.getQuick(r, c));
}
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
setQuick(r, c, source.getQuick(r, c));
}
}
}
return this;
}
/**
* Assigns the result of a function to each cell;
* x[row,col] = function(x[row,col],y[row,col]).
*
* Example:
*
*
* // assign x[row,col] = x[row,col]<sup>y[row,col]</sup>
* m1 = 2 x 2 matrix
* 0 1
* 2 3
*
* m2 = 2 x 2 matrix
* 0 2
* 4 6
*
* m1.assign(m2, cern.jet.math.Functions.pow);
* -->
* m1 == 2 x 2 matrix
* 1 1
* 16 729
*
*
*
* For further examples, see the package doc.
*
* @param y
* the secondary matrix to operate on.
* @param function
* a function object taking as first argument the current cell's
* value of this, and as second argument the current
* cell's value of y,
* @return this (for convenience only).
* @throws IllegalArgumentException
* if
* columns() != other.columns() || rows() != other.rows()
* @see cern.jet.math.tfloat.FloatFunctions
*/
public FloatMatrix2D assign(final FloatMatrix2D y, final cern.colt.function.tfloat.FloatFloatFunction function) {
checkShape(y);
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (rows * columns >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
int k = rows / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstRow = j * k;
final int lastRow = (j == nthreads - 1) ? rows : firstRow + k;
futures[j] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
for (int r = firstRow; r < lastRow; r++) {
for (int c = 0; c < columns; c++) {
setQuick(r, c, function.apply(getQuick(r, c), y.getQuick(r, c)));
}
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
setQuick(r, c, function.apply(getQuick(r, c), y.getQuick(r, c)));
}
}
}
return this;
}
/**
* Assigns the result of a function to all cells with a given indexes
*
* @param y
* the secondary matrix to operate on.
* @param function
* a function object taking as first argument the current cell's
* value of this, and as second argument the current
* cell's value of y,
* @param rowList
* row indexes.
* @param columnList
* column indexes.
*
* @return this (for convenience only).
* @throws IllegalArgumentException
* if
* columns() != other.columns() || rows() != other.rows()
* @see cern.jet.math.tfloat.FloatFunctions
*/
public FloatMatrix2D assign(final FloatMatrix2D y, final cern.colt.function.tfloat.FloatFloatFunction function,
IntArrayList rowList, IntArrayList columnList) {
checkShape(y);
final int size = rowList.size();
final int[] rowElements = rowList.elements();
final int[] columnElements = columnList.elements();
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (size >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
int k = size / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstIdx = j * k;
final int lastIdx = (j == nthreads - 1) ? size : firstIdx + k;
futures[j] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
for (int i = firstIdx; i < lastIdx; i++) {
setQuick(rowElements[i], columnElements[i], function.apply(getQuick(rowElements[i],
columnElements[i]), y.getQuick(rowElements[i], columnElements[i])));
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
for (int i = 0; i < size; i++) {
setQuick(rowElements[i], columnElements[i], function.apply(getQuick(rowElements[i], columnElements[i]),
y.getQuick(rowElements[i], columnElements[i])));
}
}
return this;
}
/**
* Returns the number of cells having non-zero values; ignores tolerance.
*
* @return cardinality
*/
public int cardinality() {
int cardinality = 0;
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (rows * columns >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
Integer[] results = new Integer[nthreads];
int k = rows / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstRow = j * k;
final int lastRow = (j == nthreads - 1) ? rows : firstRow + k;
futures[j] = ConcurrencyUtils.submit(new Callable() {
public Integer call() throws Exception {
int cardinality = 0;
for (int r = firstRow; r < lastRow; r++) {
for (int c = 0; c < columns; c++) {
if (getQuick(r, c) != 0)
cardinality++;
}
}
return Integer.valueOf(cardinality);
}
});
}
try {
for (int j = 0; j < nthreads; j++) {
results[j] = (Integer) futures[j].get();
}
cardinality = results[0].intValue();
for (int j = 1; j < nthreads; j++) {
cardinality += results[j].intValue();
}
} catch (ExecutionException ex) {
ex.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
if (getQuick(r, c) != 0)
cardinality++;
}
}
}
return cardinality;
}
/**
* Constructs and returns a deep copy of the receiver.
*
* Note that the returned matrix is an independent deep copy. The
* returned matrix is not backed by this matrix, so changes in the returned
* matrix are not reflected in this matrix, and vice-versa.
*
* @return a deep copy of the receiver.
*/
public FloatMatrix2D copy() {
return like().assign(this);
}
/**
* Returns the elements of this matrix.
*
* @return the elements
*/
public abstract Object elements();
/**
* Returns whether all cells are equal to the given value.
*
* @param value
* the value to test against.
* @return true if all cells are equal to the given value,
* false otherwise.
*/
public boolean equals(float value) {
return cern.colt.matrix.tfloat.algo.FloatProperty.DEFAULT.equals(this, value);
}
/**
* Compares this object against the specified object. The result is
* true if and only if the argument is not null
* and is at least a FloatMatrix2D object that has the same
* number of columns and rows as the receiver and has exactly the same
* values at the same coordinates.
*
* @param obj
* the object to compare with.
* @return true if the objects are the same; false
* otherwise.
*/
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof FloatMatrix2D))
return false;
return cern.colt.matrix.tfloat.algo.FloatProperty.DEFAULT.equals(this, (FloatMatrix2D) obj);
}
/**
* Assigns the result of a function to each non-zero cell;
* x[row,col] = function(x[row,col]). Use this method for fast
* special-purpose iteration. If you want to modify another matrix instead
* of this (i.e. work in read-only mode), simply return the input
* value unchanged.
*
* Parameters to function are as follows: first==row,
* second==column, third==nonZeroValue.
*
* @param function
* a function object taking as argument the current non-zero
* cell's row, column and value.
* @return this (for convenience only).
*/
public FloatMatrix2D forEachNonZero(final cern.colt.function.tfloat.IntIntFloatFunction function) {
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (size() >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
int k = rows / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstRow = j * k;
final int lastRow = (j == nthreads - 1) ? rows : firstRow + k;
futures[j] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
for (int r = firstRow; r < lastRow; r++) {
for (int c = 0; c < columns; c++) {
float value = getQuick(r, c);
if (value != 0) {
float a = function.apply(r, c, value);
if (a != value)
setQuick(r, c, a);
}
}
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
float value = getQuick(r, c);
if (value != 0) {
float a = function.apply(r, c, value);
if (a != value)
setQuick(r, c, a);
}
}
}
}
return this;
}
/**
* Returns the matrix cell value at coordinate [row,column].
*
* @param row
* the index of the row-coordinate.
* @param column
* the index of the column-coordinate.
* @return the value of the specified cell.
* @throws IndexOutOfBoundsException
* if
* column<0 || column>=columns() || row<0 || row>=rows()
*/
public float get(int row, int column) {
if (column < 0 || column >= columns || row < 0 || row >= rows)
throw new IndexOutOfBoundsException("row:" + row + ", column:" + column);
return getQuick(row, column);
}
/**
* Return the maximum value of this matrix together with its location
*
* @return maximum_value, row_location, column_location };
*/
public float[] getMaxLocation() {
int rowLocation = 0;
int columnLocation = 0;
float maxValue = 0;
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (size() >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
float[][] results = new float[nthreads][2];
int k = rows / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstRow = j * k;
final int lastRow = (j == nthreads - 1) ? rows : firstRow + k;
futures[j] = ConcurrencyUtils.submit(new Callable() {
public float[] call() throws Exception {
int rowLocation = firstRow;
int columnLocation = 0;
float maxValue = getQuick(rowLocation, 0);
int d = 1;
float elem;
for (int r = firstRow; r < lastRow; r++) {
for (int c = d; c < columns; c++) {
elem = getQuick(r, c);
if (maxValue < elem) {
maxValue = elem;
rowLocation = r;
columnLocation = c;
}
}
d = 0;
}
return new float[] { maxValue, rowLocation, columnLocation };
}
});
}
try {
for (int j = 0; j < nthreads; j++) {
results[j] = (float[]) futures[j].get();
}
maxValue = results[0][0];
rowLocation = (int) results[0][1];
columnLocation = (int) results[0][2];
for (int j = 1; j < nthreads; j++) {
if (maxValue < results[j][0]) {
maxValue = results[j][0];
rowLocation = (int) results[j][1];
columnLocation = (int) results[j][2];
}
}
} catch (ExecutionException ex) {
ex.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
maxValue = getQuick(0, 0);
float elem;
int d = 1;
for (int r = 0; r < rows; r++) {
for (int c = d; c < columns; c++) {
elem = getQuick(r, c);
if (maxValue < elem) {
maxValue = elem;
rowLocation = r;
columnLocation = c;
}
}
d = 0;
}
}
return new float[] { maxValue, rowLocation, columnLocation };
}
/**
* Return the minimum value of this matrix together with its location
*
* @return minimum_value, row_location, column_location};
*/
public float[] getMinLocation() {
int rowLocation = 0;
int columnLocation = 0;
float minValue = 0;
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (size() >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
float[][] results = new float[nthreads][2];
int k = rows / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstRow = j * k;
final int lastRow = (j == nthreads - 1) ? rows : firstRow + k;
futures[j] = ConcurrencyUtils.submit(new Callable() {
public float[] call() throws Exception {
int rowLocation = firstRow;
int columnLocation = 0;
float minValue = getQuick(rowLocation, 0);
int d = 1;
float elem;
for (int r = firstRow; r < lastRow; r++) {
for (int c = d; c < columns; c++) {
elem = getQuick(r, c);
if (minValue > elem) {
minValue = elem;
rowLocation = r;
columnLocation = c;
}
}
d = 0;
}
return new float[] { minValue, rowLocation, columnLocation };
}
});
}
try {
for (int j = 0; j < nthreads; j++) {
results[j] = (float[]) futures[j].get();
}
minValue = results[0][0];
rowLocation = (int) results[0][1];
columnLocation = (int) results[0][2];
for (int j = 1; j < nthreads; j++) {
if (minValue > results[j][0]) {
minValue = results[j][0];
rowLocation = (int) results[j][1];
columnLocation = (int) results[j][2];
}
}
} catch (ExecutionException ex) {
ex.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
minValue = getQuick(0, 0);
float elem;
int d = 1;
for (int r = 0; r < rows; r++) {
for (int c = d; c < columns; c++) {
elem = getQuick(r, c);
if (minValue > elem) {
minValue = elem;
rowLocation = r;
columnLocation = c;
}
}
d = 0;
}
}
return new float[] { minValue, rowLocation, columnLocation };
}
/**
* Fills the coordinates and values of cells having negative values into the
* specified lists. Fills into the lists, starting at index 0. After this
* call returns the specified lists all have a new size, the number of
* non-zero values.
*
* @param rowList
* the list to be filled with row indexes, can have any size.
* @param columnList
* the list to be filled with column indexes, can have any size.
* @param valueList
* the list to be filled with values, can have any size.
*/
public void getNegativeValues(final IntArrayList rowList, final IntArrayList columnList,
final FloatArrayList valueList) {
rowList.clear();
columnList.clear();
valueList.clear();
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
float value = getQuick(r, c);
if (value < 0) {
rowList.add(r);
columnList.add(c);
valueList.add(value);
}
}
}
}
/**
* Fills the coordinates and values of cells having non-zero values into the
* specified lists. Fills into the lists, starting at index 0. After this
* call returns the specified lists all have a new size, the number of
* non-zero values.
*
* In general, fill order is unspecified. This implementation fills
* like for (row = 0..rows-1) for (column = 0..columns-1) do ... .
* However, subclasses are free to us any other order, even an order that
* may change over time as cell values are changed. (Of course, result lists
* indexes are guaranteed to correspond to the same cell).
*
* Example:
*
*
* 2 x 3 matrix:
* 0, 0, 8
* 0, 7, 0
* -->
* rowList = (0,1)
* columnList = (2,1)
* valueList = (8,7)
*
*
*
* In other words, get(0,2)==8, get(1,1)==7.
*
* @param rowList
* the list to be filled with row indexes, can have any size.
* @param columnList
* the list to be filled with column indexes, can have any size.
* @param valueList
* the list to be filled with values, can have any size.
*/
public void getNonZeros(final IntArrayList rowList, final IntArrayList columnList, final FloatArrayList valueList) {
rowList.clear();
columnList.clear();
valueList.clear();
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
float value = getQuick(r, c);
if (value != 0) {
rowList.add(r);
columnList.add(c);
valueList.add(value);
}
}
}
}
/**
* Fills the coordinates and values of cells having positive values into the
* specified lists. Fills into the lists, starting at index 0. After this
* call returns the specified lists all have a new size, the number of
* non-zero values.
*
* @param rowList
* the list to be filled with row indexes, can have any size.
* @param columnList
* the list to be filled with column indexes, can have any size.
* @param valueList
* the list to be filled with values, can have any size.
*/
public void getPositiveValues(final IntArrayList rowList, final IntArrayList columnList,
final FloatArrayList valueList) {
rowList.clear();
columnList.clear();
valueList.clear();
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
float value = getQuick(r, c);
if (value > 0) {
rowList.add(r);
columnList.add(c);
valueList.add(value);
}
}
}
}
/**
* Returns the matrix cell value at coordinate [row,column].
*
*
* Provided with invalid parameters this method may return invalid objects
* without throwing any exception. You should only use this method when
* you are absolutely sure that the coordinate is within bounds.
* Precondition (unchecked):
* 0 <= column < columns() && 0 <= row < rows().
*
* @param row
* the index of the row-coordinate.
* @param column
* the index of the column-coordinate.
* @return the value at the specified coordinate.
*/
public abstract float getQuick(int row, int column);
/**
* Construct and returns a new empty matrix of the same dynamic type
* as the receiver, having the same number of rows and columns. For example,
* if the receiver is an instance of type DenseFloatMatrix2D the
* new matrix must also be of type DenseFloatMatrix2D, if the
* receiver is an instance of type SparseFloatMatrix2D the new
* matrix must also be of type SparseFloatMatrix2D, etc. In
* general, the new matrix should have internal parametrization as similar
* as possible.
*
* @return a new empty matrix of the same dynamic type.
*/
public FloatMatrix2D like() {
return like(rows, columns);
}
/**
* Construct and returns a new empty matrix of the same dynamic type
* as the receiver, having the specified number of rows and columns. For
* example, if the receiver is an instance of type
* DenseFloatMatrix2D the new matrix must also be of type
* DenseFloatMatrix2D, if the receiver is an instance of type
* SparseFloatMatrix2D the new matrix must also be of type
* SparseFloatMatrix2D, etc. In general, the new matrix should have
* internal parametrization as similar as possible.
*
* @param rows
* the number of rows the matrix shall have.
* @param columns
* the number of columns the matrix shall have.
* @return a new empty matrix of the same dynamic type.
*/
public abstract FloatMatrix2D like(int rows, int columns);
/**
* Construct and returns a new 1-d matrix of the corresponding dynamic
* type, entirelly independent of the receiver. For example, if the
* receiver is an instance of type DenseFloatMatrix2D the new
* matrix must be of type DenseFloatMatrix1D, if the receiver is an
* instance of type SparseFloatMatrix2D the new matrix must be of
* type SparseFloatMatrix1D, etc.
*
* @param size
* the number of cells the matrix shall have.
* @return a new matrix of the corresponding dynamic type.
*/
public abstract FloatMatrix1D like1D(int size);
/**
* Normalizes this matrix, i.e. makes the sum of all elements equal to 1.0
* If the matrix contains negative elements then all the values are shifted
* to ensure non-negativity.
*/
public void normalize() {
float min = getMinLocation()[0];
if (min < 0) {
assign(FloatFunctions.minus(min));
}
if (getMaxLocation()[0] == 0) {
assign(1.0f / size());
} else {
float sumScaleFactor = zSum();
sumScaleFactor = 1.0f / sumScaleFactor;
assign(FloatFunctions.mult(sumScaleFactor));
}
}
/**
* Sets the matrix cell at coordinate [row,column] to the specified
* value.
*
* @param row
* the index of the row-coordinate.
* @param column
* the index of the column-coordinate.
* @param value
* the value to be filled into the specified cell.
* @throws IndexOutOfBoundsException
* if
* column<0 || column>=columns() || row<0 || row>=rows()
*/
public void set(int row, int column, float value) {
if (column < 0 || column >= columns || row < 0 || row >= rows)
throw new IndexOutOfBoundsException("row:" + row + ", column:" + column);
setQuick(row, column, value);
}
/**
* Sets the matrix cell at coordinate [row,column] to the specified
* value.
*
*
* Provided with invalid parameters this method may access illegal indexes
* without throwing any exception. You should only use this method when
* you are absolutely sure that the coordinate is within bounds.
* Precondition (unchecked):
* 0 <= column < columns() && 0 <= row < rows().
*
* @param row
* the index of the row-coordinate.
* @param column
* the index of the column-coordinate.
* @param value
* the value to be filled into the specified cell.
*/
public abstract void setQuick(int row, int column, float value);
/**
* Constructs and returns a 2-dimensional array containing the cell values.
* The returned array values has the form
* values[row][column] and has the same number of rows and columns
* as the receiver.
*
* The values are copied. So subsequent changes in values are not
* reflected in the matrix, and vice-versa.
*
* @return an array filled with the values of the cells.
*/
public float[][] toArray() {
final float[][] values = new float[rows][columns];
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (size() >= ConcurrencyUtils.getThreadsBeginN_2D())) {
nthreads = Math.min(nthreads, rows);
Future>[] futures = new Future[nthreads];
int k = rows / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstRow = j * k;
final int lastRow = (j == nthreads - 1) ? rows : firstRow + k;
futures[j] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
for (int r = firstRow; r < lastRow; r++) {
float[] currentRow = values[r];
for (int c = 0; c < columns; c++) {
currentRow[c] = getQuick(r, c);
}
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
for (int r = 0; r < rows; r++) {
float[] currentRow = values[r];
for (int c = 0; c < columns; c++) {
currentRow[c] = getQuick(r, c);
}
}
}
return values;
}
/**
* Returns a string representation using default formatting.
*
* @see cern.colt.matrix.tfloat.algo.FloatFormatter
*/
public String toString() {
return new cern.colt.matrix.tfloat.algo.FloatFormatter().toString(this);
}
/**
* Returns a vector obtained by stacking the columns of the matrix on top of
* one another.
*
* @return a vector of columns of this matrix.
*/
public abstract FloatMatrix1D vectorize();
/**
* Constructs and returns a new slice view representing the rows of
* the given column. The returned view is backed by this matrix, so changes
* in the returned view are reflected in this matrix, and vice-versa. To
* obtain a slice view on subranges, construct a sub-ranging view (
* viewPart(...)), then apply this method to the sub-range view.
*
* Example:
*
*
* 2 x 3 matrix:
* 1, 2, 3
* 4, 5, 6
* viewColumn(0) ==>
* Matrix1D of size 2:
* 1, 4
*
*
*
* @param column
* the column to fix.
* @return a new slice view.
* @throws IndexOutOfBoundsException
* if column < 0 || column >= columns().
* @see #viewRow(int)
*/
public FloatMatrix1D viewColumn(int column) {
checkColumn(column);
int viewSize = this.rows;
int viewZero = (int) index(0, column);
int viewStride = this.rowStride;
return like1D(viewSize, viewZero, viewStride);
}
/**
* Constructs and returns a new flip view along the column axis. What
* used to be column 0 is now column columns()-1, ...,
* what used to be column columns()-1 is now column 0. The
* returned view is backed by this matrix, so changes in the returned view
* are reflected in this matrix, and vice-versa.
*
* Example:
*
*
* 2 x 3 matrix:
* 1, 2, 3
* 4, 5, 6
* columnFlip ==>
* 2 x 3 matrix:
* 3, 2, 1
* 6, 5, 4
* columnFlip ==>
* 2 x 3 matrix:
* 1, 2, 3
* 4, 5, 6
*
*
*
* @return a new flip view.
* @see #viewRowFlip()
*/
public FloatMatrix2D viewColumnFlip() {
return (FloatMatrix2D) (view().vColumnFlip());
}
/**
* Constructs and returns a new dice (transposition) view; Swaps
* axes; example: 3 x 4 matrix --> 4 x 3 matrix. The view has both
* dimensions exchanged; what used to be columns become rows, what used to
* be rows become columns. In other words:
* view.get(row,column)==this.get(column,row). This is a zero-copy
* transposition, taking O(1), i.e. constant time. The returned view is
* backed by this matrix, so changes in the returned view are reflected in
* this matrix, and vice-versa. Use idioms like
* result = viewDice(A).copy() to generate an independent
* transposed matrix.
*
* Example:
*
*
* 2 x 3 matrix:
* 1, 2, 3
* 4, 5, 6
* transpose ==>
* 3 x 2 matrix:
* 1, 4
* 2, 5
* 3, 6
* transpose ==>
* 2 x 3 matrix:
* 1, 2, 3
* 4, 5, 6
*
*
*
* @return a new dice view.
*/
public FloatMatrix2D viewDice() {
return (FloatMatrix2D) (view().vDice());
}
/**
* Constructs and returns a new sub-range view that is a
* height x width sub matrix starting at [row,column].
*
* Operations on the returned view can only be applied to the restricted
* range. Any attempt to access coordinates not contained in the view will
* throw an IndexOutOfBoundsException.
*
* Note that the view is really just a range restriction: The
* returned matrix is backed by this matrix, so changes in the returned
* matrix are reflected in this matrix, and vice-versa.
*
* The view contains the cells from [row,column] to
* [row+height-1,column+width-1], all inclusive. and has
* view.rows() == height; view.columns() == width;. A view's legal
* coordinates are again zero based, as usual. In other words, legal
* coordinates of the view range from [0,0] to
* [view.rows()-1==height-1,view.columns()-1==width-1]. As usual,
* any attempt to access a cell at a coordinate
* column<0 || column>=view.columns() || row<0 || row>=view.rows()
* will throw an IndexOutOfBoundsException.
*
* @param row
* The index of the row-coordinate.
* @param column
* The index of the column-coordinate.
* @param height
* The height of the box.
* @param width
* The width of the box.
* @throws IndexOutOfBoundsException
* if
* column<0 || width<0 || column+width>columns() || row<0 || height<0 || row+height>rows()
* @return the new view.
*
*/
public FloatMatrix2D viewPart(int row, int column, int height, int width) {
return (FloatMatrix2D) (view().vPart(row, column, height, width));
}
/**
* Constructs and returns a new slice view representing the columns
* of the given row. The returned view is backed by this matrix, so changes
* in the returned view are reflected in this matrix, and vice-versa. To
* obtain a slice view on subranges, construct a sub-ranging view (
* viewPart(...)), then apply this method to the sub-range view.
*
* Example:
*
*
* 2 x 3 matrix:
* 1, 2, 3
* 4, 5, 6
* viewRow(0) ==>
* Matrix1D of size 3:
* 1, 2, 3
*
*
*
* @param row
* the row to fix.
* @return a new slice view.
* @throws IndexOutOfBoundsException
* if row < 0 || row >= rows().
* @see #viewColumn(int)
*/
public FloatMatrix1D viewRow(int row) {
checkRow(row);
int viewSize = this.columns;
int viewZero = (int) index(row, 0);
int viewStride = this.columnStride;
return like1D(viewSize, viewZero, viewStride);
}
/**
* Constructs and returns a new flip view along the row axis. What
* used to be row 0 is now row rows()-1, ..., what used to
* be row rows()-1 is now row 0. The returned view is
* backed by this matrix, so changes in the returned view are reflected in
* this matrix, and vice-versa.
*
* Example:
*
*
* 2 x 3 matrix:
* 1, 2, 3
* 4, 5, 6
* rowFlip ==>
* 2 x 3 matrix:
* 4, 5, 6
* 1, 2, 3
* rowFlip ==>
* 2 x 3 matrix:
* 1, 2, 3
* 4, 5, 6
*
*
*
* @return a new flip view.
* @see #viewColumnFlip()
*/
public FloatMatrix2D viewRowFlip() {
return (FloatMatrix2D) (view().vRowFlip());
}
/**
* Constructs and returns a new selection view that is a matrix
* holding all rows matching the given condition. Applies the
* condition to each row and takes only those row where
* condition.apply(viewRow(i)) yields true. To match
* columns, use a dice view.
*
* Example:
*
*
* // extract and view all rows which have a value < threshold in the first column (representing "age")
* final float threshold = 16;
* matrix.viewSelection(
* new FloatMatrix1DProcedure() {
* public final boolean apply(FloatMatrix1D m) { return m.get(0) < threshold; }
* }
* );
*
* // extract and view all rows with RMS < threshold
* // The RMS (Root-Mean-Square) is a measure of the average "size" of the elements of a data sequence.
* matrix = 0 1 2 3
* final float threshold = 0.5;
* matrix.viewSelection(
* new FloatMatrix1DProcedure() {
* public final boolean apply(FloatMatrix1D m) { return (float)Math.sqrt(m.aggregate(F.plus,F.square) / m.size()) < threshold; }
* }
* );
*
*
*
* For further examples, see the package doc. The returned
* view is backed by this matrix, so changes in the returned view are
* reflected in this matrix, and vice-versa.
*
* @param condition
* The condition to be matched.
* @return the new view.
*/
public FloatMatrix2D viewSelection(FloatMatrix1DProcedure condition) {
IntArrayList matches = new IntArrayList();
for (int i = 0; i < rows; i++) {
if (condition.apply(viewRow(i)))
matches.add(i);
}
matches.trimToSize();
return viewSelection(matches.elements(), null); // take all columns
}
/**
* Constructs and returns a new selection view that is a matrix
* holding the indicated cells. There holds
* view.rows() == rowIndexes.length, view.columns() == columnIndexes.length
* and view.get(i,j) == this.get(rowIndexes[i],columnIndexes[j]).
* Indexes can occur multiple times and can be in arbitrary order.
*
* Example:
*
*
* this = 2 x 3 matrix:
* 1, 2, 3
* 4, 5, 6
* rowIndexes = (0,1)
* columnIndexes = (1,0,1,0)
* -->
* view = 2 x 4 matrix:
* 2, 1, 2, 1
* 5, 4, 5, 4
*
*
*
* Note that modifying the index arguments after this call has returned has
* no effect on the view. The returned view is backed by this matrix, so
* changes in the returned view are reflected in this matrix, and
* vice-versa.
*
* To indicate "all" rows or "all columns", simply set the respective
* parameter
*
* @param rowIndexes
* The rows of the cells that shall be visible in the new view.
* To indicate that all rows shall be visible, simply set
* this parameter to null.
* @param columnIndexes
* The columns of the cells that shall be visible in the new
* view. To indicate that all columns shall be visible,
* simply set this parameter to null.
* @return the new view.
* @throws IndexOutOfBoundsException
* if !(0 <= rowIndexes[i] < rows()) for any
* i=0..rowIndexes.length()-1.
* @throws IndexOutOfBoundsException
* if !(0 <= columnIndexes[i] < columns()) for any
* i=0..columnIndexes.length()-1.
*/
public FloatMatrix2D viewSelection(int[] rowIndexes, int[] columnIndexes) {
// check for "all"
if (rowIndexes == null) {
rowIndexes = new int[rows];
for (int i = 0; i < rows; i++)
rowIndexes[i] = i;
}
if (columnIndexes == null) {
columnIndexes = new int[columns];
for (int i = 0; i < columns; i++)
columnIndexes[i] = i;
}
checkRowIndexes(rowIndexes);
checkColumnIndexes(columnIndexes);
int[] rowOffsets = new int[rowIndexes.length];
int[] columnOffsets = new int[columnIndexes.length];
for (int i = 0; i < rowIndexes.length; i++) {
rowOffsets[i] = _rowOffset(_rowRank(rowIndexes[i]));
}
for (int i = 0; i < columnIndexes.length; i++) {
columnOffsets[i] = _columnOffset(_columnRank(columnIndexes[i]));
}
return viewSelectionLike(rowOffsets, columnOffsets);
}
public FloatMatrix2D viewSelection(Set indexes) {
int n = indexes.size();
int[] rowIndexes = new int[n];
int[] columnIndexes = new int[n];
int idx = 0;
for (Iterator iterator = indexes.iterator(); iterator.hasNext();) {
int[] is = iterator.next();
rowIndexes[idx] = is[0];
columnIndexes[idx] = is[1];
idx++;
}
checkRowIndexes(rowIndexes);
checkColumnIndexes(columnIndexes);
int[] rowOffsets = new int[rowIndexes.length];
int[] columnOffsets = new int[columnIndexes.length];
for (int i = 0; i < rowIndexes.length; i++) {
rowOffsets[i] = _rowOffset(_rowRank(rowIndexes[i]));
}
for (int i = 0; i < columnIndexes.length; i++) {
columnOffsets[i] = _columnOffset(_columnRank(columnIndexes[i]));
}
return viewSelectionLike(rowOffsets, columnOffsets);
}
/**
* Sorts the matrix rows into ascending order, according to the natural
* ordering of the matrix values in the given column. This sort is
* guaranteed to be stable. For further information, see
* {@link cern.colt.matrix.tfloat.algo.FloatSorting#sort(FloatMatrix2D,int)}
* . For more advanced sorting functionality, see
* {@link cern.colt.matrix.tfloat.algo.FloatSorting}.
*
* @return a new sorted vector (matrix) view.
* @throws IndexOutOfBoundsException
* if column < 0 || column >= columns().
*/
public FloatMatrix2D viewSorted(int column) {
return cern.colt.matrix.tfloat.algo.FloatSorting.mergeSort.sort(this, column);
}
/**
* Constructs and returns a new stride view which is a sub matrix
* consisting of every i-th cell. More specifically, the view has
* this.rows()/rowStride rows and
* this.columns()/columnStride columns holding cells
* this.get(i*rowStride,j*columnStride) for all
* i = 0..rows()/rowStride - 1, j = 0..columns()/columnStride - 1.
* The returned view is backed by this matrix, so changes in the returned
* view are reflected in this matrix, and vice-versa.
*
* @param rowStride
* the row step factor.
* @param columnStride
* the column step factor.
* @return a new view.
* @throws IndexOutOfBoundsException
* if rowStride<=0 || columnStride<=0.
*/
public FloatMatrix2D viewStrides(int rowStride, int columnStride) {
return (FloatMatrix2D) (view().vStrides(rowStride, columnStride));
}
/**
* 8 neighbor stencil transformation. For efficient finite difference
* operations. Applies a function to a moving 3 x 3 window. Does
* nothing if rows() < 3 || columns() < 3.
*
*
* B[i,j] = function.apply(
* A[i-1,j-1], A[i-1,j], A[i-1,j+1],
* A[i, j-1], A[i, j], A[i, j+1],
* A[i+1,j-1], A[i+1,j], A[i+1,j+1]
* )
*
* x x x - - x x x - - - -
* x o x - - x o x - - - -
* x x x - - x x x ... - x x x
* - - - - - - - - - x o x
* - - - - - - - - - x x x
*
*
*
* Make sure that cells of this and B do not overlap. In
* case of overlapping views, behaviour is unspecified.
*
*
*
* * Example: * *
*
* final float alpha = 0.25; final float beta = 0.75; // 8 neighbors
* cern.colt.function.Float9Function f = new
* cern.colt.function.Float9Function() { public final
* float apply( float a00, float a01,
* float a02, float a10, float a11,
* float a12, float a20, float a21,
* float a22) {
* return beta*a11 +
* alpha*(a00+a01+a02 + a10+a12 + a20+a21+a22);
* } }; A.zAssign8Neighbors(B,f); // 4
* neighbors cern.colt.function.Float9Function g = new
* cern.colt.function.Float9Function() { public final
* float apply( float a00, float a01,
* float a02, float a10, float a11,
* float a12, float a20, float a21,
* float a22) { return beta*a11 +
* alpha*(a01+a10+a12+a21); } C.zAssign8Neighbors(B,g); //
* fast, even though it doesn't look like it };
*
*
*
* @param B
* the matrix to hold the results.
* @param function
* the function to be applied to the 9 cells.
* @throws NullPointerException
* if function==null.
* @throws IllegalArgumentException
* if rows() != B.rows() || columns() != B.columns().
*/
public void zAssign8Neighbors(FloatMatrix2D B, cern.colt.function.tfloat.Float9Function function) {
if (function == null)
throw new NullPointerException("function must not be null.");
checkShape(B);
if (rows < 3 || columns < 3)
return; // nothing to do
int r = rows - 1;
int c = columns - 1;
float a00, a01, a02;
float a10, a11, a12;
float a20, a21, a22;
for (int i = 1; i < r; i++) {
a00 = getQuick(i - 1, 0);
a01 = getQuick(i - 1, 1);
a10 = getQuick(i, 0);
a11 = getQuick(i, 1);
a20 = getQuick(i + 1, 0);
a21 = getQuick(i + 1, 1);
for (int j = 1; j < c; j++) {
// in each step six cells can be remembered in registers - they
// don't need to be reread from slow memory
// in each step 3 instead of 9 cells need to be read from
// memory.
a02 = getQuick(i - 1, j + 1);
a12 = getQuick(i, j + 1);
a22 = getQuick(i + 1, j + 1);
B.setQuick(i, j, function.apply(a00, a01, a02, a10, a11, a12, a20, a21, a22));
a00 = a01;
a10 = a11;
a20 = a21;
a01 = a02;
a11 = a12;
a21 = a22;
}
}
}
/**
* Linear algebraic matrix-vector multiplication; z = A * y;
* Equivalent to return A.zMult(y,z,1,0);
*/
public FloatMatrix1D zMult(FloatMatrix1D y, FloatMatrix1D z) {
return zMult(y, z, 1, 0, false);
}
/**
* Linear algebraic matrix-vector multiplication;
* z = alpha * A * y + beta*z.
* z[i] = alpha*Sum(A[i,j] * y[j]) + beta*z[i], i=0..A.rows()-1, j=0..y.size()-1
* . Where A == this. clone() and casts the result.
* * Note that the view is not a deep copy. The returned matrix is * backed by this matrix, so changes in the returned matrix are reflected in * this matrix, and vice-versa. *
* Use {@link #copy()} to construct an independent deep copy rather than a * new view. * * @return a new view of the receiver. */ protected FloatMatrix2D view() { return (FloatMatrix2D) clone(); } /** * Construct and returns a new selection view. * * @param rowOffsets * the offsets of the visible elements. * @param columnOffsets * the offsets of the visible elements. * @return a new view. */ protected abstract FloatMatrix2D viewSelectionLike(int[] rowOffsets, int[] columnOffsets); }
Ads help maintain this website.