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

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

Introduction

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

Prototype

public ArrayRealVector(double[] v1, double[] v2) 

Source Link

Document

Construct a vector by appending one vector to another vector.

Usage

From source file:de.thkwalter.et.ortskurve.Startpunktbestimmung.java

/**
 * Diese Methode berechnet den Startpunkt aus den ersten drei Messpunkten.
 * /*from w  w w .  j  a v  a2  s  . c o m*/
 * @return Der Startpunkt. Die erste Komponente des Feldes reprsentiert die x-Komponente des Mittelpunktes, die zweite
 * Komponente die y-Komponente, die dritte Komponente den Radius.
 */
private static double[] startpunktBestimmen(Vector2D[] messpunkteZurStartpunktbestimmung) {
    // Die Felder fr die Koeffizientenmatrix und die Inhomogenitt werden definiert.
    double[][] koeffizienten = new double[3][];
    double[] inhomogenitaet = new double[3];

    // Einige Hilfsgren werden deklariert.
    double[] zeile = null;
    double x = Double.NaN;
    double y = Double.NaN;

    // In der folgenden Schleife werden die Koeffizientenmatrix und die Inhomogenitt initialisiert.
    for (int i = 0; i < 3; i++) {
        // Die x- und y-Komponente eines Punktes werden gelesen.
        x = messpunkteZurStartpunktbestimmung[i].getX();
        y = messpunkteZurStartpunktbestimmung[i].getY();

        // Eine Zeile der Koeffizientenmatrix wird initialisiert
        zeile = new double[3];
        zeile[0] = 1;
        zeile[1] = -x;
        zeile[2] = -y;
        koeffizienten[i] = zeile;

        // Eine Komponente des Inhomogenittsvektors wird initialisiert.
        inhomogenitaet[i] = -(x * x + y * y);
    }

    // Die Koeffizientenmatrix wird erzeugt.
    RealMatrix koeffizientenmatrix = new Array2DRowRealMatrix(koeffizienten);

    // Der Inhomogenittsvektor wird erzeugt.
    RealVector inhomogenitaetsvektor = new ArrayRealVector(inhomogenitaet, false);

    // Der Lsungsalgorithmus fr das lineare Gleichungssystem wird erzeugt.
    DecompositionSolver alorithmus = new LUDecomposition(koeffizientenmatrix).getSolver();

    // Das inhomogene Gleichungssystem wird gelst.
    RealVector loesung = null;
    try {
        loesung = alorithmus.solve(inhomogenitaetsvektor);
    } catch (SingularMatrixException singularMatrixException) {
        // Die Fehlermeldung fr den Entwickler wird erzeugt und protokolliert.
        String fehlermeldung = "Die Matrix aus den Punkten " + messpunkteZurStartpunktbestimmung[0] + ", "
                + messpunkteZurStartpunktbestimmung[1] + " und " + messpunkteZurStartpunktbestimmung[2]
                + " ist singulr.";
        Startpunktbestimmung.logger.severe(fehlermeldung);

        // Die Ausnahme wird erzeugt und mit der Fehlermeldung fr den Benutzer initialisiert.
        String jsfMeldung = "Eine von den Messpunkten (" + messpunkteZurStartpunktbestimmung[0].getX() + ", "
                + messpunkteZurStartpunktbestimmung[0].getY() + "), ("
                + messpunkteZurStartpunktbestimmung[1].getX() + ", "
                + messpunkteZurStartpunktbestimmung[1].getY() + ") und ("
                + messpunkteZurStartpunktbestimmung[2].getX() + ", "
                + messpunkteZurStartpunktbestimmung[2].getY() + ")" + " abhngige Matrix ist singur. Der "
                + "Berechnungsalgorithmus bentigt jedoch eine regulre Matrix! Entfernen Sie bitte einen der oben "
                + "angegebenen Messpunkte.";
        ApplicationRuntimeException applicationRuntimeException = new ApplicationRuntimeException(jsfMeldung);

        throw applicationRuntimeException;
    }

    // Der Startpunkt wird aus der Lsung des linearen Gleichungssystems bestimmt.
    double xMittelpunkt = 0.5 * loesung.getEntry(1);
    double yMittelpunkt = 0.5 * loesung.getEntry(2);
    double radius = Math.sqrt(xMittelpunkt * xMittelpunkt + yMittelpunkt * yMittelpunkt - loesung.getEntry(0));

    // Der Startpunkt wird zurckgegeben.
    return new double[] { xMittelpunkt, yMittelpunkt, radius };
}

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

/**
  * LWR prediction/*from w  ww . ja v  a  2 s  . co  m*/
  * 
  * @param X
  * @param Y
  * @param x0
  * @param tau
  * @return
  */
public Double LWRPredict(ArrayRealVector X, ArrayRealVector Y, double x0, final double tau) {
    ArrayRealVector X0 = new ArrayRealVector(X.getDimension(), x0);
    ArrayRealVector delta = X.subtract(X0);
    ArrayRealVector sqDists = delta.ebeMultiply(delta);
    UnivariateFunction expTau = new UnivariateFunction() {
        @Override
        public double value(double arg0) {
            //log.info(" cp univariate tau " + tau);
            return Math.pow(Math.E, -arg0 / (2 * tau));
        }
    };
    ArrayRealVector W = sqDists.map(expTau);
    double Xt_W_X = X.dotProduct(W.ebeMultiply(X));
    if (Xt_W_X == 0.0) {
        log.error(" cp LWR cannot predict - 0 denominator returning NULL");
        log.error("Xcv is " + X.toString());
        log.error("Ycv is " + Y.toString());
        log.error("x0 is " + x0);
        return null; // <==== NOTE: a caller must be prepared for it
    }
    double theta = (1.0 / Xt_W_X) * X.ebeMultiply(W).dotProduct(Y);

    return theta * x0;
}

From source file:edu.stanford.cfuller.imageanalysistools.fitting.CentroidImageObject.java

/**
  * "Fits" this object to a position by finding its intensity-weighted
  * centroid.  Does not compute error estimates, numbers of photons, etc.
  * //www  .  jav a 2s.  co  m
  * @param p     The parameters for the current analysis.
  */
@Override
public void fitPosition(ParameterDictionary p) {

    if (this.sizeInPixels == 0) {
        this.nullifyImages();
        return;
    }

    this.fitParametersByChannel = new java.util.ArrayList<FitParameters>();
    this.fitR2ByChannel = new java.util.ArrayList<Double>();
    this.fitErrorByChannel = new java.util.ArrayList<Double>();
    this.nPhotonsByChannel = new java.util.ArrayList<Double>();

    int numChannels = 0;

    if (p.hasKey("num_wavelengths")) {
        numChannels = p.getIntValueForKey("num_wavelengths");
    } else {
        numChannels = this.parent.getDimensionSizes().get(ImageCoordinate.C);
    }

    for (int channelIndex = 0; channelIndex < numChannels; channelIndex++) {

        this.parentBoxMin.set(ImageCoordinate.C, channelIndex);
        this.parentBoxMax.set(ImageCoordinate.C, channelIndex + 1);

        this.boxImages();

        java.util.Vector<Double> x = new java.util.Vector<Double>();
        java.util.Vector<Double> y = new java.util.Vector<Double>();
        java.util.Vector<Double> z = new java.util.Vector<Double>();
        java.util.Vector<Float> f = new java.util.Vector<Float>();

        for (ImageCoordinate ic : this.parent) {
            x.add((double) ic.get(ImageCoordinate.X));
            y.add((double) ic.get(ImageCoordinate.Y));
            z.add((double) ic.get(ImageCoordinate.Z));
            if (((int) this.mask.getValue(ic)) == this.label) {
                f.add(parent.getValue(ic));
            } else {
                f.add(0.0f);
            }
        }

        xValues = new double[x.size()];
        yValues = new double[y.size()];
        zValues = new double[z.size()];
        functionValues = new double[f.size()];

        double xCentroid = 0;
        double yCentroid = 0;
        double zCentroid = 0;
        double totalCounts = 0;

        for (int i = 0; i < x.size(); i++) {

            xValues[i] = x.get(i);
            yValues[i] = y.get(i);
            zValues[i] = z.get(i);
            functionValues[i] = f.get(i);
            xCentroid += xValues[i] * functionValues[i];
            yCentroid += yValues[i] * functionValues[i];
            zCentroid += zValues[i] * functionValues[i];
            totalCounts += functionValues[i];
        }

        xCentroid /= totalCounts;
        yCentroid /= totalCounts;
        zCentroid /= totalCounts;

        RealVector position = new ArrayRealVector(3, 0.0);

        position.setEntry(0, xCentroid);
        position.setEntry(1, yCentroid);
        position.setEntry(2, zCentroid);

        this.positionsByChannel.add(position);

    }

    this.hadFittingError = false;
    this.nullifyImages();

}

From source file:gamlss.algorithm.GlimFitCG.java

public ArrayRealVector glimFitFunctionCG(GAMLSSFamilyDistribution distr, ArrayRealVector response,
        Hashtable<Integer, BlockRealMatrix> X, ArrayRealVector fv, ArrayRealVector weights,
        int whichDistParameter, double step, double offSet, double globalDeviance,
        Hashtable<String, ArrayRealVector> cgData, MakeLinkFunction makelink) {

    int itn = 0;/*from  w ww  .  j  a va  2  s. com*/
    double[] temp = new double[0];

    //G.dev.in <- G.dev+1
    //     double gDevIn = globalDeviance +1;

    //i.G.dev <- G.dev
    double gDev = globalDeviance;

    double gDevOld = globalDeviance + 1;

    //first.iter <- FALSE  
    boolean firstIter = false;

    //while ( abs(G.dev.in -i.G.dev) > i.c.crit && i.iter < i.n.cyc )
    while (FastMath.abs(gDevOld - gDev) > Controls.GLIM_CONV_CRIT && itn < Controls.GLIM_NUM_CYCLES) {

        //i.iter <- i.iter+1
        itn = itn + 1;

        //for (int i = 1; i < distr.getNumberOfDistribtionParameters()+1; i++ ){
        switch (whichDistParameter) {
        case DistributionSettings.MU:
            // whichDistParameter = DistributionSettings.MU;

            //adj.mu <- -(w.mu.sigma*(eta.sigma-eta.old.sigma)+w.mu.nu*(eta.nu-eta.old.nu)+w.mu.tau*(eta.tau-eta.old.tau))/w.mu 
            adj = setAdj(cgData.get("wMuSigma"), cgData.get("eta" + DistributionSettings.SIGMA),
                    cgData.get("etaOld" + DistributionSettings.SIGMA), cgData.get("wMuNu"),
                    cgData.get("eta" + DistributionSettings.NU), cgData.get("etaOld" + DistributionSettings.NU),
                    cgData.get("wMuTau"), cgData.get("eta" + DistributionSettings.TAU),
                    cgData.get("etaOld" + DistributionSettings.TAU), cgData.get("w" + DistributionSettings.MU));

            cgData.put("adj" + DistributionSettings.MU, adj);

            break;
        case DistributionSettings.SIGMA:
            // whichDistParameter = DistributionSettings.SIGMA;

            // adj.sigma <- -(w.mu.sigma*(eta.mu-eta.old.mu)+ w.sigma.nu*(eta.nu-eta.old.nu)+w.sigma.tau*(eta.tau-eta.old.tau))/w.sigma 
            adj = setAdj(cgData.get("wMuSigma"), cgData.get("eta" + DistributionSettings.MU),
                    cgData.get("etaOld" + DistributionSettings.MU), cgData.get("wSigmaNu"),
                    cgData.get("eta" + DistributionSettings.NU), cgData.get("etaOld" + DistributionSettings.NU),
                    cgData.get("wSigmaTau"), cgData.get("eta" + DistributionSettings.TAU),
                    cgData.get("etaOld" + DistributionSettings.TAU),
                    cgData.get("w" + DistributionSettings.SIGMA));

            cgData.put("adj" + DistributionSettings.SIGMA, adj);

            break;
        case DistributionSettings.NU:
            // whichDistParameter = DistributionSettings.NU;
            break;
        case DistributionSettings.TAU:
            // whichDistParameter = DistributionSettings.TAU;
            break;
        }

        //wv.mu  <- z.mu+adj.mu
        ArrayRealVector wv = setWV(cgData.get("z" + whichDistParameter),
                cgData.get("adj" + whichDistParameter));

        //mu.fit <<- lm.wfit(x=mu.X,y=wv.mu,w=w.mu*w,method="qr") 
        wls.newSampleData(wv, X.get(whichDistParameter).copy(),
                cgData.get("w" + whichDistParameter).ebeMultiply(weights));
        ArrayRealVector fit = (ArrayRealVector) wls.calculateFittedValues(false);

        //System.out.println(wls.calculateBeta());
        //           bettas.put(whichDistParameter, (ArrayRealVector) wls.calculateBeta());

        //mu.fit$eta <<- eta.mu <- mu.fit$fitted.values+mu.offset
        temp = new double[fit.getDimension()];
        for (int j = 0; j < temp.length; j++) {
            temp[j] = fit.getEntry(j) + offSet;
        }
        //eta = new ArrayRealVector(temp,false);
        cgData.put("eta" + whichDistParameter, new ArrayRealVector(temp, false));
        temp = null;

        //mu.fit$fv <<-    mu <<- mu.object$linkinv(eta.mu)

        ArrayRealVector dParam = makelink.linkInv(distr.getDistributionParameterLink(whichDistParameter),
                cgData.get("eta" + whichDistParameter));

        distr.setDistributionParameter(whichDistParameter, dParam);

        //mu.fit$wv <<- wv.mu
        //mu.fit$wt <<- w.mu  

        //G.dev.in <- i.G.dev
        gDevOld = gDev;

        //G.dev.incr <- eval(G.dev.expr) 
        //i.G.dev <- sum(w*G.dev.incr)
        gDev = weights.dotProduct(distr.globalDevianceIncreament(response));

        if (gDev > gDevOld && itn >= 2 && Controls.AUTO_STEP) {
            for (int i = 0; i < 5; i++) {

                //eta.mu <- (eta.mu+eta.old.mu)/2
                ArrayRealVector etaM = etaMean(cgData.get("eta" + whichDistParameter),
                        cgData.get("etaOld" + whichDistParameter));
                cgData.put("eta" + whichDistParameter, etaM);
                //mu <<- mu.object$linkinv(eta.mu) 

                distr.setDistributionParameter(whichDistParameter,
                        makelink.linkInv(distr.getDistributionParameterLink(whichDistParameter), etaM));

                //if(length(who.mu) > 0) s.mu <- (s.mu+s.mu.old)/2 
                //   }
            }
        }

        //if(i.trace)
        if (Controls.GLIM_TRACE) {
            //cat("CG inner iteration ", iter, ": Global Deviance = ",format(round(i.G.dev, 4)), " \n", sep = "")           
            System.err.println("CG inner iteration " + itn + " : Global Deviance = " + gDev);
        }
        //if (i.G.dev > (G.dev.in+gd.tol) && iter >1 )
        if (gDev > (gDevOld + Controls.GLOB_DEVIANCE_TOL) && itn > 1) {

            //stop(paste("The global deviance is increasing in the inner CG loop", "\n","Try different steps for the parameters or the model maybe inappropriate"))
            System.out.println(
                    "The global deviance is increasing in the inner CG loop, try different steps for the parameters or the model maybe inappropriate");
            break;
        }
    }

    //G.dev.old <- G.dev
    //        gDevOld = gDev;

    //G.dev.incr <- eval(G.dev.expr)   
    //G.dev <- sum(w*G.dev.incr)
    //     gDev = weights.dotProduct(distr.globalDevianceIncreament(response));

    //if (G.dev > G.dev.old && iter >= 2 && autostep == TRUE)

    return (ArrayRealVector) wls.calculateBeta();
}

From source file:hivemall.anomaly.ChangeFinder2D.java

@Nonnull
private ArrayRealVector parseX(final Object arg) throws UDFArgumentException {
    ArrayRealVector xVec = xRing.head();
    if (xVec == null) {
        double[] data = HiveUtils.asDoubleArray(arg, listOI, elemOI);
        if (data.length == 0) {
            throw new UDFArgumentException("Dimension of x SHOULD be more than zero");
        }//from w ww  . j a v  a 2 s. c o m
        xVec = new ArrayRealVector(data, false);
    } else {
        double[] ref = xVec.getDataRef();
        HiveUtils.toDoubleArray(arg, listOI, elemOI, ref, 0.d);
    }
    return xVec;
}

From source file:gamlss.distributions.PE.java

/** Calculate and set initial value of sigma.
 * @param y - vector of values of response variable
 * @return vector of initial values of sigma
 */// ww  w  .  j ava 2s  .  co  m
private ArrayRealVector setSigmaInitial(final ArrayRealVector y) {
    //sigma.initial = expression( sigma <- (abs(y-mean(y))+sd(y))/2 )   
    final double mean = new Mean().evaluate(y.getDataRef());
    final double sd = new StandardDeviation().evaluate(y.getDataRef());
    size = y.getDimension();
    double[] out = new double[size];
    for (int i = 0; i < size; i++) {
        out[i] = (FastMath.abs(y.getEntry(i) - mean) + sd) / 2;
    }
    return new ArrayRealVector(out, false);
}

From source file:gamlss.distributions.GA.java

/**  First derivative dldm = dl/dmu,
* where l - log-likelihood function.// w w  w  .  jav  a2 s.  c om
* @param y - vector of values of response variable
* @return  a vector of first derivative dldm = dl/dmu
*/
private ArrayRealVector dldm(final ArrayRealVector y) {
    //dldm = function(y,mu,sigma) (y-mu)/((sigma^2)*(mu^2)),
    double[] out = new double[size];
    for (int i = 0; i < size; i++) {
        out[i] = (y.getEntry(i) - muV.getEntry(i)) / (tempV2.getEntry(i) * muV.getEntry(i) * muV.getEntry(i));
    }
    return new ArrayRealVector(out, false);
}

From source file:gamlss.distributions.BCPE.java

/**  Calculates initial value of mu, by assumption these 
 * values lie between observed data and the trend line.
 * @param y - vector of values of response variable
 * @return  a vector of initial values of mu
 *//* w ww . j ava 2  s .c o  m*/
private ArrayRealVector setMuInitial(final ArrayRealVector y) {
    //mu.initial =  expression(mu <- (y+mean(y))/2)
    size = y.getDimension();
    double[] out = new double[size];
    Mean mean = new Mean();
    double yMean = mean.evaluate(y.getDataRef());
    for (int i = 0; i < size; i++) {
        out[i] = (y.getEntry(i) + yMean) / 2;
    }
    return new ArrayRealVector(out, false);
}

From source file:edu.stanford.cfuller.imageanalysistools.fitting.GaussianFitter3DWithCovariance.java

private static double logFactorial(int n) {

    if (n < 0)
        return 0;

    if (n <= maxLogFactorialPrecalculated) {
        return logFactorialLookups.getEntry(n);
    }//from  ww w . java 2  s .  co m

    synchronized (GaussianFitter3D.class) {

        if (n > maxLogFactorialPrecalculated) {

            if (n >= logFactorialLookups.getDimension()) {

                int sizeDiff = n + 1 - logFactorialLookups.getDimension();

                RealVector toAppend = new ArrayRealVector(sizeDiff, 0.0);

                RealVector newLookups = logFactorialLookups.append(toAppend);

                logFactorialLookups = newLookups;

            }

            for (int i = maxLogFactorialPrecalculated + 1; i <= n; i++) {

                if (i == 0) {
                    logFactorialLookups.setEntry(i, 0);
                } else {
                    logFactorialLookups.setEntry(i, logFactorialLookups.getEntry(i - 1) + Math.log(i));
                }
            }

            maxLogFactorialPrecalculated = n;

        }

    }

    return logFactorialLookups.getEntry(n);

}

From source file:edu.utexas.cs.tactex.UtilityEstimatorTest.java

@Test
public void testUtilityEstimation() {
    CustomerInfo customer1 = new CustomerInfo("Austin", 2);
    CustomerInfo customer2 = new CustomerInfo("Dallas", 4);

    TariffSpecification spec1 = new TariffSpecification(brokerContext.getBroker(), PowerType.CONSUMPTION);
    TariffSpecification spec2 = new TariffSpecification(brokerContext.getBroker(), PowerType.CONSUMPTION);

    ArrayRealVector energy1 = new ArrayRealVector(7 * 24, 6.0);
    ArrayRealVector energy2 = new ArrayRealVector(7 * 24, 8.0);

    // allocate data structures used for utility computation
    HashMap<CustomerInfo, HashMap<TariffSpecification, Double>> customer2estimatedTariffCharges = new HashMap<CustomerInfo, HashMap<TariffSpecification, Double>>();

    HashMap<CustomerInfo, ArrayRealVector> customer2energy = new HashMap<CustomerInfo, ArrayRealVector>();

    HashMap<TariffSpecification, HashMap<CustomerInfo, Integer>> currentCustomerSubscriptions = new HashMap<TariffSpecification, HashMap<CustomerInfo, Integer>>();

    HashMap<TariffSpecification, HashMap<CustomerInfo, Double>> predictedCustomerSubscriptions = new HashMap<TariffSpecification, HashMap<CustomerInfo, Double>>();

    customer2estimatedTariffCharges.put(customer1, new HashMap<TariffSpecification, Double>());
    customer2estimatedTariffCharges.put(customer2, new HashMap<TariffSpecification, Double>());

    currentCustomerSubscriptions.put(spec1, new HashMap<CustomerInfo, Integer>());
    currentCustomerSubscriptions.put(spec2, new HashMap<CustomerInfo, Integer>());

    predictedCustomerSubscriptions.put(spec1, new HashMap<CustomerInfo, Double>());
    predictedCustomerSubscriptions.put(spec2, new HashMap<CustomerInfo, Double>());

    // populate data structures with data from above

    // tariff charges - customer2 has 2x consumption so we did
    // 2x (it's probably not necessary for testing purposes)
    // remember that charge is per single population member of a customer
    customer2estimatedTariffCharges.get(customer1).put(spec1, -10.0);
    customer2estimatedTariffCharges.get(customer1).put(spec2, -20.0);
    customer2estimatedTariffCharges.get(customer2).put(spec1, -30.0);
    customer2estimatedTariffCharges.get(customer2).put(spec2, -40.0);

    // energy consumption vector of customers
    customer2energy.put(customer1, energy1);
    customer2energy.put(customer2, energy2);

    // tests: incrementally update the following subscriptions and check
    // utility/*  ww  w . j  ava 2s .  c  om*/
    //tariffSubscriptions.get(spec1).put(customer1, 1);
    //tariffSubscriptions.get(spec2).put(customer1, 1);
    //tariffSubscriptions.get(spec1).put(customer2, 2);
    //tariffSubscriptions.get(spec2).put(customer2, 2);

    HashMap<CustomerInfo, HashMap<TariffSpecification, ShiftedEnergyData>> customerTariff2ShiftedEnergy = shiftingPredictor
            .updateEstimatedEnergyWithShifting(customer2energy, predictedCustomerSubscriptions, 0);

    // test: empty subscriptions
    double u = utilityEstimatorDefault.estimateUtility(currentCustomerSubscriptions,
            predictedCustomerSubscriptions, customer2estimatedTariffCharges, customerTariff2ShiftedEnergy,
            customer2energy, marketPredictionManager, costCurvesPredictor, 0);
    // test for both cost-curves and old method (avg) should give same result
    when(configuratorFactoryService.isUseCostCurves()).thenReturn(true);
    assertEquals("utility of empty subscriptions", 0, u, 1e-6);
    when(configuratorFactoryService.isUseCostCurves()).thenReturn(false);
    assertEquals("utility of empty subscriptions", 0, u, 1e-6);

    // test: update subscription, verify utility
    predictedCustomerSubscriptions.get(spec1).put(customer1, 1.0);
    customerTariff2ShiftedEnergy = shiftingPredictor.updateEstimatedEnergyWithShifting(customer2energy,
            predictedCustomerSubscriptions, 0);

    double expectedTariffIncome = 1 * -(-10.0); // 1 customer x estimated charge of -10.0 per customer
    double expectedMarketCharges = -1 * (7 * 24 * 6.0) * 100; // -(1 customer x total-energy x energy price)
    double expectedBalancing = 0; // currently estimated as 0
    double expectedDistribution = 1 * (7 * 24 * 6.0) * -1.5; // 1 customer x total-energy x distribution-fee
    double expectedWithdrawFees = 0; // the above tariffs don't have withdraw fees
    double expected = expectedTariffIncome + expectedMarketCharges + expectedBalancing + expectedDistribution
            + expectedWithdrawFees;

    u = utilityEstimatorDefault.estimateUtility(currentCustomerSubscriptions, predictedCustomerSubscriptions,
            customer2estimatedTariffCharges, customerTariff2ShiftedEnergy, customer2energy,
            marketPredictionManager, costCurvesPredictor, 0);
    // test for both cost-curves and old method (avg) should give same result
    when(configuratorFactoryService.isUseCostCurves()).thenReturn(true);
    assertEquals("utility of spec1->customer1(1)", expected, u, 1e-6);
    when(configuratorFactoryService.isUseCostCurves()).thenReturn(false);
    assertEquals("utility of spec1->customer1(1)", expected, u, 1e-6);

    // test: update subscription, verify utility
    predictedCustomerSubscriptions.get(spec2).put(customer1, 1.0);
    customerTariff2ShiftedEnergy = shiftingPredictor.updateEstimatedEnergyWithShifting(customer2energy,
            predictedCustomerSubscriptions, 0);

    expectedTariffIncome += 1 * -(-20.0); // 1 customer x estimated charge of -20.0 per customer
    expectedMarketCharges += -1 * (7 * 24 * 6.0) * 100; // -(1 customer x total-energy x energy price)
    expectedBalancing += 0; // currently estimated as 0
    expectedDistribution += 1 * (7 * 24 * 6.0) * -1.5; // 1 customer x total-energy x distribution-fee
    expectedWithdrawFees += 0; // the above tariffSubscriptions don't have withdraw fees
    expected = expectedTariffIncome + expectedMarketCharges + expectedBalancing + expectedDistribution
            + expectedWithdrawFees;

    u = utilityEstimatorDefault.estimateUtility(currentCustomerSubscriptions, predictedCustomerSubscriptions,
            customer2estimatedTariffCharges, customerTariff2ShiftedEnergy, customer2energy,
            marketPredictionManager, costCurvesPredictor, 0);
    // test for both cost-curves and old method (avg) should give same result
    when(configuratorFactoryService.isUseCostCurves()).thenReturn(true);
    assertEquals("utility of spec2->customer1(1)", expected, u, 1e-6);
    when(configuratorFactoryService.isUseCostCurves()).thenReturn(false);
    assertEquals("utility of spec2->customer1(1)", expected, u, 1e-6);

    // test: update subscription, verify utility
    predictedCustomerSubscriptions.get(spec1).put(customer2, 2.0);
    customerTariff2ShiftedEnergy = shiftingPredictor.updateEstimatedEnergyWithShifting(customer2energy,
            predictedCustomerSubscriptions, 0);

    expectedTariffIncome += 2 * -(-30.0); // 2 customer x estimated charge of -30.0 per customer
    expectedMarketCharges += -2 * (7 * 24 * 8.0) * 100; // -(2 customer x total-energy x energy price)
    expectedBalancing += 0; // currently estimated as 0
    expectedDistribution += 2 * (7 * 24 * 8.0) * -1.5; // 2 customer x total-energy x distribution-fee
    expectedWithdrawFees += 0; // the above tariffSubscriptions don't have withdraw fees
    expected = expectedTariffIncome + expectedMarketCharges + expectedBalancing + expectedDistribution
            + expectedWithdrawFees;

    u = utilityEstimatorDefault.estimateUtility(currentCustomerSubscriptions, predictedCustomerSubscriptions,
            customer2estimatedTariffCharges, customerTariff2ShiftedEnergy, customer2energy,
            marketPredictionManager, costCurvesPredictor, 0);
    // test for both cost-curves and old method (avg) should give same result
    when(configuratorFactoryService.isUseCostCurves()).thenReturn(true);
    assertEquals("utility of spec1->customer2(2)", expected, u, 1e-6);
    when(configuratorFactoryService.isUseCostCurves()).thenReturn(false);
    assertEquals("utility of spec1->customer2(2)", expected, u, 1e-6);

    // test: update subscription, verify utility
    predictedCustomerSubscriptions.get(spec2).put(customer2, 2.0);
    customerTariff2ShiftedEnergy = shiftingPredictor.updateEstimatedEnergyWithShifting(customer2energy,
            predictedCustomerSubscriptions, 0);

    expectedTariffIncome += 2 * -(-40.0); // 2 customer x estimated charge of -40.0 per customer
    expectedMarketCharges += -2 * (7 * 24 * 8.0) * 100; // -(2 customer x total-energy x energy price)
    expectedBalancing += 0; // currently estimated as 0
    expectedDistribution += 2 * (7 * 24 * 8.0) * -1.5; // 2 customer x total-energy x distribution-fee
    expectedWithdrawFees += 0; // the above tariffSubscriptions don't have withdraw fees
    expected = expectedTariffIncome + expectedMarketCharges + expectedBalancing + expectedDistribution
            + expectedWithdrawFees;

    u = utilityEstimatorDefault.estimateUtility(currentCustomerSubscriptions, predictedCustomerSubscriptions,
            customer2estimatedTariffCharges, customerTariff2ShiftedEnergy, customer2energy,
            marketPredictionManager, costCurvesPredictor, 0);
    // test for both cost-curves and old method (avg) should give same result
    when(configuratorFactoryService.isUseCostCurves()).thenReturn(true);
    assertEquals("utility of spec2->customer2(2)", expected, u, 1e-6);
    when(configuratorFactoryService.isUseCostCurves()).thenReturn(false);
    assertEquals("utility of spec2->customer2(2)", expected, u, 1e-6);

    // test: changing prediction method works market prediction decreased by
    // half for costCurvesPredictor only
    when(costCurvesPredictor.predictUnitCostKwh(any(Integer.class), any(Integer.class), any(Double.class),
            any(Double.class))).thenReturn(-50.0);
    when(configuratorFactoryService.isUseCostCurves()).thenReturn(true);
    u = utilityEstimatorDefault.estimateUtility(currentCustomerSubscriptions, predictedCustomerSubscriptions,
            customer2estimatedTariffCharges, customerTariff2ShiftedEnergy, customer2energy,
            marketPredictionManager, costCurvesPredictor, 0);
    assertEquals("setting predictions method using a boolean - curves",
            expected + 0.5 * Math.abs(expectedMarketCharges), u, 1e-6);
    when(configuratorFactoryService.isUseCostCurves()).thenReturn(false);
    u = utilityEstimatorDefault.estimateUtility(currentCustomerSubscriptions, predictedCustomerSubscriptions,
            customer2estimatedTariffCharges, customerTariff2ShiftedEnergy, customer2energy,
            marketPredictionManager, costCurvesPredictor, 0);
    assertEquals("setting predictions method using a boolean - mkt-avg", expected, u, 1e-6);

    // ======================
    // test for withdraw fees
    // ======================

    // testing from scratch, re-allocating everything
    customer1 = new CustomerInfo("Austin", 2);
    customer2 = new CustomerInfo("Dallas", 4);

    // creating tariffs with early withdraw payments.
    // The minDuration is set to 0 so that if we ever account
    // for subscription durations in our utility architecture,
    // this test will fail. The reason is that a min duration of
    // 0 should cause no payment, but currently we 
    // assume any migration from revoked tariff pays and 
    // ignore the min duration. 
    spec1 = new TariffSpecification(brokerContext.getBroker(), PowerType.CONSUMPTION)
            .withEarlyWithdrawPayment(-1.234).withMinDuration(0);
    spec2 = new TariffSpecification(brokerContext.getBroker(), PowerType.CONSUMPTION)
            .withEarlyWithdrawPayment(-2.345).withMinDuration(0);

    energy1 = new ArrayRealVector(7 * 24, 0.0); // no consumption, we only test fees
    energy2 = new ArrayRealVector(7 * 24, 0.0); // no consumption, we only test fees

    // allocate data structures used for utility computation
    customer2estimatedTariffCharges = new HashMap<CustomerInfo, HashMap<TariffSpecification, Double>>();

    customer2energy = new HashMap<CustomerInfo, ArrayRealVector>();

    currentCustomerSubscriptions = new HashMap<TariffSpecification, HashMap<CustomerInfo, Integer>>();

    predictedCustomerSubscriptions = new HashMap<TariffSpecification, HashMap<CustomerInfo, Double>>();

    customer2estimatedTariffCharges.put(customer1, new HashMap<TariffSpecification, Double>());
    customer2estimatedTariffCharges.put(customer2, new HashMap<TariffSpecification, Double>());

    // initializing current subscriptions to:
    // spec1: customer1=>2, customer2=>0
    // spec2: customer1=>0, customer2=>1
    // 2 and 1 to break symmetry when testing 
    currentCustomerSubscriptions.put(spec1, new HashMap<CustomerInfo, Integer>());
    currentCustomerSubscriptions.put(spec2, new HashMap<CustomerInfo, Integer>());
    //
    currentCustomerSubscriptions.get(spec1).put(customer1, 2);
    currentCustomerSubscriptions.get(spec1).put(customer2, 0);
    currentCustomerSubscriptions.get(spec2).put(customer1, 0);
    currentCustomerSubscriptions.get(spec2).put(customer2, 1);

    // initializing predicted subscriptions to:
    // spec1: customer1=>0, customer2=>1
    // spec2: customer1=>2, customer2=>0
    predictedCustomerSubscriptions.put(spec1, new HashMap<CustomerInfo, Double>());
    predictedCustomerSubscriptions.put(spec2, new HashMap<CustomerInfo, Double>());
    //
    predictedCustomerSubscriptions.get(spec1).put(customer1, 0.0);
    predictedCustomerSubscriptions.get(spec1).put(customer2, 1.0);
    predictedCustomerSubscriptions.get(spec2).put(customer1, 2.0);
    predictedCustomerSubscriptions.get(spec2).put(customer2, 0.0);

    // populate data structures with data from above

    // estimated tariff charges per customer are 0 - we only test fees
    customer2estimatedTariffCharges.get(customer1).put(spec1, 0.0);
    customer2estimatedTariffCharges.get(customer1).put(spec2, 0.0);
    customer2estimatedTariffCharges.get(customer2).put(spec1, 0.0);
    customer2estimatedTariffCharges.get(customer2).put(spec2, 0.0);

    // energy consumption vector of customers
    customer2energy.put(customer1, energy1);
    customer2energy.put(customer2, energy2);

    customerTariff2ShiftedEnergy = shiftingPredictor.updateEstimatedEnergyWithShifting(customer2energy,
            predictedCustomerSubscriptions, 0);

    // test: migration => fee payments
    when(configuratorFactoryService.isUseCostCurves()).thenReturn(false);
    u = utilityEstimatorDefault.estimateUtility(currentCustomerSubscriptions, predictedCustomerSubscriptions,
            customer2estimatedTariffCharges, customerTariff2ShiftedEnergy, customer2energy,
            marketPredictionManager, costCurvesPredictor, 0);
    // 2/1 migration from tariff, '-' is to convert to broker perspective
    expected = -(2 * -1.234 - 2.345);
    assertEquals("utility of withdraw fees ", expected, u, 1e-6);

}