Example usage for org.apache.commons.math3.linear ArrayRealVector mapMultiplyToSelf

List of usage examples for org.apache.commons.math3.linear ArrayRealVector mapMultiplyToSelf

Introduction

In this page you can find the example usage for org.apache.commons.math3.linear ArrayRealVector mapMultiplyToSelf.

Prototype

@Override
public RealVector mapMultiplyToSelf(double d) 

Source Link

Usage

From source file:edu.utexas.cs.tactex.subscriptionspredictors.LWRCustOldAppache.java

private ArrayRealVector createNormalizedXVector(Set<Double> xValues, double min, double max) {
    Double[] dummy1 = new Double[1]; // needed to determine the type of toArray?     
    ArrayRealVector xVector = new ArrayRealVector(xValues.toArray(dummy1));
    xVector.mapSubtractToSelf(min);/*from w ww  . j a v  a 2  s .  co m*/
    xVector.mapDivideToSelf(max - min);
    // translating [0,1]=>[0.1,0.9]
    xVector.mapMultiplyToSelf(SQUEEZE);
    xVector.mapAddToSelf(OFFSET);
    return xVector;
}

From source file:edu.utexas.cs.tactex.servercustomers.factoredcustomer.DefaultCapacityBundle.java

/**
 * sum all originator's (scaled) energies (since I believe the broker sees the
 * sum of them only). // w w  w  .  ja va  2 s  .c o m
 * @param currentTimeslot 
 * @throws Exception 
 * @throws DimensionMismatchException 
 */
@Override
public ArrayRealVector getPredictedEnergy(TariffSubscription subscription, int recordLength,
        int currentTimeslot) throws DimensionMismatchException, Exception {
    ArrayRealVector result = new ArrayRealVector(recordLength);

    // sum all originator's energies 
    for (CapacityOriginator originator : capacityOriginators) {
        ArrayRealVector originatorPredictedEnergy = originator.getPredictedEnergy(subscription, recordLength,
                currentTimeslot);
        //log.info("originatorPredictedEnergy " + Arrays.toString(originatorPredictedEnergy.toArray()));
        result = result.add(originatorPredictedEnergy);
        //log.info("bundleresult " + Arrays.toString(result.toArray()));
    }

    // normalize to 1 population member
    result.mapDivideToSelf(customerInfo.getPopulation());
    //log.info("bundleresultnormalized " + Arrays.toString(result.toArray()));

    // all predictions are positive and are adjusted in the server in
    // DefaultUtilityOptimizer.usePower() therefore we adjust the sign here,
    // the last point before returning to our shifting predictor
    double usageSign = getPowerType().isConsumption() ? +1 : -1;
    result.mapMultiplyToSelf(usageSign);

    return result;
}

From source file:automenta.vivisect.dimensionalize.HyperassociativeMap.java

/** vertices is passed as a list because the Set iterator from JGraphT is slow */
public ArrayRealVector align(V nodeToAlign, ObjectDoubleHashMap<V> neighbors, V[] vertices) {

    double nodeSpeed = getSpeedFactor(nodeToAlign);

    ArrayRealVector originalPosition = new ArrayRealVector(new double[2], true);
    //getPosition(nodeToAlign);
    //getCurrentPosition(nodeToAlign);
    getPosition(nodeToAlign, originalPosition.getDataRef());

    if (nodeSpeed == 0)
        return originalPosition;

    // calculate equilibrium with neighbors
    ArrayRealVector position = (ArrayRealVector) originalPosition.mapMultiplyToSelf(1.0 / scale);

    getNeighbors(nodeToAlign, neighbors);

    ArrayRealVector delta = newVector();

    double radius = getRadius(nodeToAlign);
    double targetDistance = radius + equilibriumDistance;
    double learningRate = this.learningRate;

    ArrayRealVector tmpAttractVector = newVector();

    // align with neighbours
    neighbors.forEachKeyValue((neighbor, distToNeighbor) -> {

        ArrayRealVector attractVector = getThePosition(neighbor, tmpAttractVector).combineToSelf(1, -1,
                position);/*from w  w w  . j a  va  2s  .co m*/

        double oldDistance = magnitude(attractVector);

        double newDistance;
        double factor = 0;
        double deltaDist = oldDistance - distToNeighbor;
        if (oldDistance > distToNeighbor) {
            newDistance = Math.pow(deltaDist, attractionStrength);

        } else {

            newDistance = -targetDistance * atanh((-deltaDist) / distToNeighbor);

            if (Math.abs(newDistance) > (Math.abs(deltaDist))) {
                newDistance = -targetDistance * (-deltaDist);
            }

        }

        newDistance *= learningRate;
        if (oldDistance != 0) {
            factor = newDistance / oldDistance;
        }

        add(delta, attractVector, factor);
    });

    ArrayRealVector repelVector = newVector();
    double maxEffectiveDistance = targetDistance * maxRepulsionDistance;

    ArrayRealVector nodePos = newVector();

    // calculate repulsion with all non-neighbors

    DistanceMetric distanceFunction = this.distanceFunction;
    double minDistance = this.minDistance;
    double repulsiveWeakness = this.repulsiveWeakness;

    for (V node : vertices) {

        if (node == null)
            continue;

        //vertices.forEach((Consumer<N>)node -> {
        //for (final N node : vertices) {
        if ((node == nodeToAlign) || (neighbors.containsKey(node)))
            continue;

        double oldDistance = distanceFunction.subtractIfLessThan(getThePosition(node, nodePos), position,
                repelVector, maxEffectiveDistance);

        if (oldDistance == Double.POSITIVE_INFINITY)
            continue; //too far to matter

        if (oldDistance < minDistance)
            oldDistance = minDistance; //continue;
        //throw new RuntimeException("invalid oldDistance");

        double newDistance = -targetDistance * Math.pow(oldDistance, -repulsiveWeakness);

        if (Math.abs(newDistance) > targetDistance) {
            newDistance = Math.copySign(targetDistance, newDistance);
        }
        newDistance *= learningRate;

        add(delta, repelVector, newDistance / oldDistance);
    }

    /*if (normalizeRepulsion)
    nodeSpeed/=delta.getNorm(); //TODO check when norm = 0*/

    if (nodeSpeed != 1.0) {
        delta.mapMultiplyToSelf(nodeSpeed);
    }

    double moveDistance = magnitude(delta);
    if (!Double.isFinite(moveDistance))
        throw new RuntimeException("invalid magnitude");

    if (moveDistance > targetDistance * acceptableMaxDistanceFactor) {
        double newLearningRate = ((targetDistance * acceptableMaxDistanceFactor) / moveDistance);
        if (newLearningRate < learningRate) {
            this.learningRate = newLearningRate;
        } else {
            this.learningRate *= LEARNING_RATE_INCREASE_FACTOR / vertices.length;
        }

        moveDistance = DEFAULT_TOTAL_MOVEMENT;
    } else {
        add(position, delta);
    }

    if (moveDistance > maxMovement) {
        maxMovement = moveDistance;
    }
    totalMovement += moveDistance;

    originalPosition.mapMultiplyToSelf(scale);
    move(nodeToAlign, originalPosition.getEntry(0), originalPosition.getEntry(1));
    return originalPosition;
}

From source file:org.eclipse.dawnsci.analysis.dataset.roi.fitting.EllipseCoordinatesFunction.java

/**
 * least-squares using algebraic cost function
 * <p>/*ww  w . j av a 2s . c om*/
 * This uses the method in "Numerically stable direct least squares fitting of ellipses"
 * by R. Halir and J. Flusser, Proceedings of the 6th International Conference in Central Europe
 * on Computer Graphics and Visualization. WSCG '98. CZ, Pilsen 1998, pp 125-132. 
 * <p>
 * @param ix
 * @param iy
 * @return geometric parameters
 */
private static double[] quickfit(IDataset ix, IDataset iy) {
    Dataset x = DatasetUtils.convertToDataset(ix);
    Dataset y = DatasetUtils.convertToDataset(iy);
    final Dataset xx = Maths.square(x);
    final Dataset yy = Maths.square(y);
    final Dataset xxx = Maths.multiply(xx, x);
    final Dataset yyy = Maths.multiply(yy, y);
    final Dataset xy = Maths.multiply(x, y);

    Matrix S1 = new Matrix(3, 3);
    S1.set(0, 0, LinearAlgebra.dotProduct(xx, xx).getDouble());
    S1.set(0, 1, LinearAlgebra.dotProduct(xxx, y).getDouble());
    S1.set(0, 2, LinearAlgebra.dotProduct(xx, yy).getDouble());

    S1.set(1, 0, S1.get(0, 1));
    S1.set(1, 1, S1.get(0, 2));
    S1.set(1, 2, LinearAlgebra.dotProduct(x, yyy).getDouble());

    S1.set(2, 0, S1.get(0, 2));
    S1.set(2, 1, S1.get(1, 2));
    S1.set(2, 2, LinearAlgebra.dotProduct(yy, yy).getDouble());

    Matrix S2 = new Matrix(3, 3);
    S2.set(0, 0, ((Number) xxx.sum()).doubleValue());
    S2.set(0, 1, LinearAlgebra.dotProduct(xx, y).getDouble());
    S2.set(0, 2, ((Number) xx.sum()).doubleValue());

    S2.set(1, 0, S2.get(0, 1));
    S2.set(1, 1, LinearAlgebra.dotProduct(x, yy).getDouble());
    S2.set(1, 2, ((Number) xy.sum()).doubleValue());

    S2.set(2, 0, S2.get(1, 1));
    S2.set(2, 1, ((Number) yyy.sum()).doubleValue());
    S2.set(2, 2, ((Number) yy.sum()).doubleValue());

    Matrix S3 = new Matrix(3, 3);
    S3.set(0, 0, S2.get(0, 2));
    S3.set(0, 1, S2.get(1, 2));
    S3.set(0, 2, ((Number) x.sum()).doubleValue());

    S3.set(1, 0, S3.get(0, 1));
    S3.set(1, 1, S2.get(2, 2));
    S3.set(1, 2, ((Number) y.sum()).doubleValue());

    S3.set(2, 0, S3.get(0, 2));
    S3.set(2, 1, S3.get(1, 2));
    S3.set(2, 2, x.getSize());

    Matrix T = S3.solve(S2.transpose()).uminus();

    Matrix M = S1.plus(S2.times(T));

    Matrix Cinv = new Matrix(new double[] { 0, 0, 0.5, 0, -1.0, 0, 0.5, 0, 0 }, 3);
    Matrix Mp = Cinv.times(M);

    //      System.err.println("M " + Arrays.toString(Mp.getRowPackedCopy()));
    Matrix V = Mp.eig().getV();
    //      System.err.println("V " + Arrays.toString(V.getRowPackedCopy()));
    double[][] mv = V.getArray();
    ArrayRealVector v1 = new ArrayRealVector(mv[0]);
    ArrayRealVector v2 = new ArrayRealVector(mv[1]);
    ArrayRealVector v3 = new ArrayRealVector(mv[2]);

    v1.mapMultiplyToSelf(4);

    ArrayRealVector v = v1.ebeMultiply(v3).subtract(v2.ebeMultiply(v2));
    double[] varray = v.getDataRef();
    int i = 0;
    for (; i < 3; i++) {
        if (varray[i] > 0)
            break;
    }
    if (i == 3) {
        throw new IllegalArgumentException("Could not find solution that satifies constraint");
    }

    v = new ArrayRealVector(new double[] { mv[0][i], mv[1][i], mv[2][i] });
    varray = v.getDataRef();
    final double ca = varray[0];
    final double cb = varray[1];
    final double cc = varray[2];
    Array2DRowRealMatrix mt = new Array2DRowRealMatrix(T.getArray(), false);
    varray = mt.operate(varray);
    final double cd = varray[0];
    final double ce = varray[1];
    final double cf = varray[2];

    //      System.err.println(String.format("Algebraic: %g, %g, %g, %g, %g, %g", ca, cb, cc, cd, ce, cf));
    final double disc = cb * cb - 4. * ca * cc;
    if (disc >= 0) {
        throw new IllegalArgumentException("Solution is not an ellipse");
    }

    if (cb == 0) {
        throw new IllegalArgumentException("Solution is a circle");
    }

    double[] qparameters = new double[PARAMETERS];
    qparameters[3] = (2. * cc * cd - cb * ce) / disc;
    qparameters[4] = (2. * ca * ce - cb * cd) / disc;

    final double sqrt = Math.sqrt((ca - cc) * (ca - cc) + cb * cb);
    qparameters[0] = -2. * (ca * ce * ce + cc * cd * cd + cf * cb * cb - cb * cd * ce - 4. * ca * cc * cf)
            / disc;
    qparameters[1] = qparameters[0] / (ca + cc + sqrt);
    qparameters[0] /= (ca + cc - sqrt);
    qparameters[0] = Math.sqrt(qparameters[0]);
    qparameters[1] = Math.sqrt(qparameters[1]);
    if (cb == 0) {
        qparameters[2] = 0.;
    } else {
        qparameters[2] = 0.5 * Math.atan2(cb, ca - cc);
    }
    if (qparameters[0] < qparameters[1]) {
        final double t = qparameters[0];
        qparameters[0] = qparameters[1];
        qparameters[1] = t;
    } else {
        qparameters[2] += Math.PI * 0.5;
    }

    return qparameters;
}