Example usage for org.apache.commons.math3.linear RealVector getDimension

List of usage examples for org.apache.commons.math3.linear RealVector getDimension

Introduction

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

Prototype

public abstract int getDimension();

Source Link

Document

Returns the size of the vector.

Usage

From source file:edu.oregonstate.eecs.mcplan.abstraction.Experiments.java

private static void writeClustering(final MetricConstrainedKMeans kmeans, final File root, final int iter)
        throws FileNotFoundException {
    Csv.write(new PrintStream(new File(root, "M" + iter + ".csv")), kmeans.metric);
    {//from   w w  w . j  a  v  a 2s. c o m
        final Csv.Writer writer = new Csv.Writer(new PrintStream(new File(root, "mu" + iter + ".csv")));
        for (int i = 0; i < kmeans.d; ++i) {
            for (int j = 0; j < kmeans.k; ++j) {
                writer.cell(kmeans.mu()[j].getEntry(i));
            }
            writer.newline();
        }
    }
    // Lt.operate( x ) maps x to the space defined by the metric
    final RealMatrix Lt = new CholeskyDecomposition(kmeans.metric).getLT();
    {
        final Csv.Writer writer = new Csv.Writer(new PrintStream(new File(root, "X" + iter + ".csv")));
        writer.cell("cluster").cell("label");
        for (int i = 0; i < kmeans.metric.getColumnDimension(); ++i) {
            writer.cell("x" + i);
        }
        for (int i = 0; i < kmeans.metric.getColumnDimension(); ++i) {
            writer.cell("Ax" + i);
        }
        writer.newline();
        for (int cluster = 0; cluster < kmeans.k; ++cluster) {
            for (int i = 0; i < kmeans.N; ++i) {
                if (kmeans.assignments()[i] == cluster) {
                    writer.cell(cluster);
                    final RealVector phi = kmeans.X_.get(i); //Phi.get( i );
                    writer.cell("?"); // TODO: write label
                    for (int j = 0; j < phi.getDimension(); ++j) {
                        writer.cell(phi.getEntry(j));
                    }
                    final RealVector trans = Lt.operate(phi);
                    for (int j = 0; j < trans.getDimension(); ++j) {
                        writer.cell(trans.getEntry(j));
                    }
                    writer.newline();
                }
            }
        }
    }
}

From source file:com.joptimizer.optimizers.LPPrimalDualMethodNetlibTest.java

private void checkSolution(LPNetlibProblem problem, LPOptimizationRequest or, LPOptimizationResponse response)
        throws Exception {

    double expectedvalue = problem.optimalValue;
    log.debug("expectedvalue : " + expectedvalue);
    double[] sol = response.getSolution();
    RealVector cVector = new ArrayRealVector(or.getC().toArray());
    RealVector solVector = new ArrayRealVector(sol);
    double value = cVector.dotProduct(solVector);
    log.debug("sol   : " + ArrayUtils.toString(sol));
    log.debug("value : " + value);

    //check constraints
    assertEquals(or.getLb().size(), sol.length);
    assertEquals(or.getUb().size(), sol.length);
    RealVector x = MatrixUtils.createRealVector(sol);

    //x >= lb//from   w  w  w. j a v  a 2s.c o m
    double maxLbmx = -Double.MAX_VALUE;
    for (int i = 0; i < or.getLb().size(); i++) {
        double di = Double.isNaN(or.getLb().getQuick(i)) ? -Double.MAX_VALUE : or.getLb().getQuick(i);
        maxLbmx = Math.max(maxLbmx, di - x.getEntry(i));
        assertTrue(di <= x.getEntry(i) + or.getTolerance());
    }
    log.debug("max(lb - x): " + maxLbmx);

    //x <= ub
    double maxXmub = -Double.MAX_VALUE;
    for (int i = 0; i < or.getUb().size(); i++) {
        double di = Double.isNaN(or.getUb().getQuick(i)) ? Double.MAX_VALUE : or.getUb().getQuick(i);
        maxXmub = Math.max(maxXmub, x.getEntry(i) - di);
        assertTrue(di + or.getTolerance() >= x.getEntry(i));
    }
    log.debug("max(x - ub): " + maxXmub);

    //G.x <h
    if (or.getG() != null && or.getG().rows() > 0) {
        RealMatrix GMatrix = MatrixUtils.createRealMatrix(or.getG().toArray());
        RealVector hvector = MatrixUtils.createRealVector(or.getH().toArray());
        RealVector Gxh = GMatrix.operate(x).subtract(hvector);
        double maxGxh = -Double.MAX_VALUE;
        for (int i = 0; i < Gxh.getDimension(); i++) {
            maxGxh = Math.max(maxGxh, Gxh.getEntry(i));
            assertTrue(Gxh.getEntry(i) - or.getTolerance() <= 0);
        }
        log.debug("max(G.x - h): " + maxGxh);
    }

    //A.x = b
    if (or.getA() != null && or.getA().rows() > 0) {
        RealMatrix AMatrix = MatrixUtils.createRealMatrix(or.getA().toArray());
        RealVector bvector = MatrixUtils.createRealVector(or.getB().toArray());
        RealVector Axb = AMatrix.operate(x).subtract(bvector);
        double norm = Axb.getNorm();
        log.debug("||A.x -b||: " + norm);
        assertEquals(0., norm, or.getToleranceFeas());
    }

    double percDelta = Math.abs((expectedvalue - value) / expectedvalue);
    log.debug("percDelta: " + percDelta);
    //assertEquals(0., percDelta, or.getTolerance());
    //assertEquals(expectedvalue, value, or.getTolerance());
    assertTrue(value < expectedvalue + or.getTolerance());//can even beat other optimizers! the rebel yell...
}

From source file:edu.stanford.cfuller.colocalization3d.correction.PositionCorrector.java

/**
 * Determines the target registration error for a correction by successively leaving out each ImageObject in a set used to make a correction,
 * calculating a correction from the remaining objects, and assessing the error in correcting the object left out.
 * //w ww.java  2 s.co m
 * @param imageObjects                  A Vector containing all the ImageObjects to be used for the correction
 *                                      or in the order it appears in a multiwavelength image file.
 * @return                              The average value of the error over all objects.
 */
public double determineTRE(java.util.List<ImageObject> imageObjects) {

    int referenceChannel = this.parameters.getIntValueForKey(REF_CH_PARAM);

    int channelToCorrect = this.parameters.getIntValueForKey(CORR_CH_PARAM);

    RealVector treVector = new ArrayRealVector(imageObjects.size(), 0.0);
    RealVector treXYVector = new ArrayRealVector(imageObjects.size(), 0.0);

    java.util.Deque<TREThread> startedThreads = new java.util.LinkedList<TREThread>();
    int maxThreads = 1;
    if (this.parameters.hasKey(THREAD_COUNT_PARAM)) {
        maxThreads = this.parameters.getIntValueForKey(THREAD_COUNT_PARAM);
    }
    final int threadWaitTime_ms = 1000;

    for (int removeIndex = 0; removeIndex < imageObjects.size(); removeIndex++) {

        if (removeIndex % 10 == 0) {

            java.util.logging.Logger
                    .getLogger(edu.stanford.cfuller.colocalization3d.Colocalization3DMain.LOGGER_NAME)
                    .finer("calulating TRE: point " + (removeIndex + 1) + " of " + imageObjects.size());
        }

        TREThread nextFit = new TREThread(imageObjects, referenceChannel, channelToCorrect, removeIndex, this);

        if (startedThreads.size() < maxThreads) {
            startedThreads.add(nextFit);
            nextFit.start();
        } else {
            TREThread next = startedThreads.poll();
            try {

                next.join(threadWaitTime_ms);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            while (next.isAlive()) {
                startedThreads.add(next);
                next = startedThreads.poll();

                try {

                    next.join(threadWaitTime_ms);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            treVector.setEntry(next.getRemoveIndex(), next.getTre());

            treXYVector.setEntry(next.getRemoveIndex(), next.getTreXY());

            startedThreads.add(nextFit);
            nextFit.start();
        }

    }

    java.util.List<Integer> unsuccessful_TRE = new java.util.ArrayList<Integer>();

    while (startedThreads.size() > 0) {
        TREThread next = startedThreads.poll();
        try {
            next.join();
            if (next.getSuccess()) {
                treVector.setEntry(next.getRemoveIndex(), next.getTre());
            } else {
                unsuccessful_TRE.add(next.getRemoveIndex());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    RealVector treVector_mod = new ArrayRealVector(treVector.getDimension() - unsuccessful_TRE.size());
    RealVector treXYVector_mod = new ArrayRealVector(treVector_mod.getDimension());

    int c = 0;

    //unsuccessful TRE calculation results when there is incomplete coverage in the correction dataset
    for (int i = 0; i < treVector.getDimension(); ++i) {
        if (!unsuccessful_TRE.contains(i)) {
            treVector_mod.setEntry(c, treVector.getEntry(i));
            treXYVector_mod.setEntry(c, treXYVector.getEntry(i));
            ++c;
        }
    }

    treVector = treVector_mod;
    treXYVector = treXYVector_mod;

    double tre = treVector.getL1Norm() / treVector.getDimension();
    double xy_tre = (treXYVector.getL1Norm() / treXYVector.getDimension());

    java.util.logging.Logger.getLogger(edu.stanford.cfuller.colocalization3d.Colocalization3DMain.LOGGER_NAME)
            .info("TRE: " + tre);
    java.util.logging.Logger.getLogger(edu.stanford.cfuller.colocalization3d.Colocalization3DMain.LOGGER_NAME)
            .info("x-y TRE: " + xy_tre);

    return tre;

}

From source file:edu.utexas.cs.tactex.utilityestimation.UtilityEstimatorDefaultForConsumption.java

/**
 * Core method for estimating utility/*from ww  w .j av a2 s .  c om*/
 */
public double estimateUtility(HashMap<TariffSpecification, HashMap<CustomerInfo, Integer>> tariffSubscriptions,
        HashMap<TariffSpecification, HashMap<CustomerInfo, Double>> predictedCustomerSubscriptions,
        HashMap<CustomerInfo, HashMap<TariffSpecification, Double>> customer2estimatedTariffCharges,
        HashMap<CustomerInfo, HashMap<TariffSpecification, ShiftedEnergyData>> customerTariff2ShiftedEnergy,
        HashMap<CustomerInfo, ArrayRealVector> customer2NonShiftedEnergy,
        MarketPredictionManager marketPredictionManager, CostCurvesPredictor costCurvesPredictor,
        int currentTimeslot/*, HashMap<CustomerInfo,ArrayRealVector> customer2estimatedEnergy*/) { // <= for print purposes

    log.debug(
            "estimateUtility(): currently assuming competing tariffs are not new and that my subscriptions are not going to change as a result of them");

    // accumulate the final results    
    //int expectedRecordLength = 7 * 24; // TODO use Timeservice here correctly
    double estTariffIncome = 0;
    double estTariffCosts = 0;
    double wholesaleCosts = 0;
    double balancingCosts = 0;
    double distributionCosts = 0;
    double withdrawCosts = 0;
    //double totalConsumption = 0; 
    //double totalProduction = 0; 
    final int predictionRecordLength = BrokerUtils.extractPredictionRecordLength(customerTariff2ShiftedEnergy);
    RealVector predictedEnergyRecord = new ArrayRealVector(predictionRecordLength);
    RealVector totalConsumptionEnergyRecord = new ArrayRealVector(predictionRecordLength);
    RealVector totalProductionEnergyRecord = new ArrayRealVector(predictionRecordLength);
    // for each customer get his usage prediction
    for (Entry<TariffSpecification, HashMap<CustomerInfo, Double>> entry : predictedCustomerSubscriptions
            .entrySet()) {

        TariffSpecification spec = entry.getKey();
        HashMap<CustomerInfo, Double> subscriptions = entry.getValue();

        for (Entry<CustomerInfo, Double> ce : subscriptions.entrySet()) {

            CustomerInfo customerInfo = ce.getKey();
            Double subscribedPopulation = ce.getValue();

            // Predicted total tariff cash flow. Sign is inverted since
            // evaluatedTariffs was computed from customers' perspective
            if (spec.getPowerType().isConsumption()) {
                estTariffIncome += -customer2estimatedTariffCharges.get(customerInfo).get(spec)
                        * subscribedPopulation;
            } else if (spec.getPowerType().isProduction()) {
                estTariffCosts += -customer2estimatedTariffCharges.get(customerInfo).get(spec)
                        * subscribedPopulation;
            } else {
                log.warn("Ignoring unknown powertype when computing tariffs income/costs: "
                        + spec.getPowerType());
            }

            // Predicted total energy
            RealVector energyPrediction = customerTariff2ShiftedEnergy.get(customerInfo).get(spec)
                    .getShiftedEnergy().mapMultiply(subscribedPopulation);
            predictedEnergyRecord = predictedEnergyRecord.add(energyPrediction);

            // Predicted balancing cost 
            balancingCosts += 0;
            log.debug("Ignoring balancing costs - assuming they are 0");

            // Predicted withdraw costs (currently assuming everyone will pay).
            // sign is inverted since withdraw payment is from customer's perspective
            HashMap<CustomerInfo, Integer> cust2subs = tariffSubscriptions.get(spec);
            if (cust2subs != null) {
                Integer currentSubs = cust2subs.get(customerInfo);
                if (currentSubs != null && subscribedPopulation < currentSubs) {
                    double withdraws = currentSubs - subscribedPopulation;
                    withdrawCosts += -(withdraws * spec.getEarlyWithdrawPayment());
                }
            }

            // Predicted total consumption and total production
            if (spec.getPowerType().isConsumption()) {
                totalConsumptionEnergyRecord = totalConsumptionEnergyRecord.add(energyPrediction);
            } else if (spec.getPowerType().isProduction()) {
                totalProductionEnergyRecord = totalProductionEnergyRecord.add(energyPrediction);
            } else {
                log.warn("Ignoring unknown powertype when computing distribution costs");
            }
        }
    }

    // Predicted distribution costs
    log.debug("Ignoring balancing orders and curtailment when computing distribution costs");
    distributionCosts = 0;
    double distributionFee = contextManager.getDistributionFee();
    for (int i = 0; i < totalConsumptionEnergyRecord.getDimension(); ++i) {
        double totalTimeslotConsumption = Math.abs(totalConsumptionEnergyRecord.getEntry(i));
        double totalTimeslotProduction = Math.abs(totalProductionEnergyRecord.getEntry(i));
        distributionCosts += Math.max(totalTimeslotConsumption, totalTimeslotProduction) * distributionFee;
    }

    // Predicted wholesale costs (in one of the following two methods:)
    if (configuratorFactoryService.isUseCostCurves()) {
        // TODO: might not work for non-fixed rate competitor tariffs - 
        // better to send a mapping of competitor tariffs inside
        // predictedCustomerSubscriptions, compute shifted predictions for them,
        // and use these predictions here.

        // compute energy of customers I don't have 
        RealVector predictedCompetitorsEnergyRecord = new ArrayRealVector(predictionRecordLength);
        HashMap<CustomerInfo, HashMap<TariffSpecification, Double>> map = BrokerUtils
                .revertKeyMapping(predictedCustomerSubscriptions);
        for (CustomerInfo cust : map.keySet()) {
            double subsToOthers = cust.getPopulation() - BrokerUtils.sumMapValues(map.get(cust));
            RealVector customerNonShiftedEnergy = customer2NonShiftedEnergy.get(cust).mapMultiply(subsToOthers);
            predictedCompetitorsEnergyRecord = predictedCompetitorsEnergyRecord.add(customerNonShiftedEnergy);
        }

        for (int i = 0; i < predictedEnergyRecord.getDimension(); ++i) {
            int futureTimeslot = currentTimeslot + i;
            double neededKwh = predictedEnergyRecord.getEntry(i);
            double competitorKwh = predictedCompetitorsEnergyRecord.getEntry(i);
            double unitCost = costCurvesPredictor.predictUnitCostKwh(currentTimeslot, futureTimeslot, neededKwh,
                    competitorKwh);
            // NOTE: unitCost is signed (typically negative)
            wholesaleCosts += (unitCost + costCurvesPredictor.getFudgeFactorKwh(currentTimeslot)) * neededKwh;
            log.debug("cost-curve prediction: current " + currentTimeslot + " futureTimeslot " + futureTimeslot
                    + " neededKwh " + neededKwh + " neededKwh + competitorKwh " + (neededKwh + competitorKwh)
                    + " unitCost " + unitCost);
        }
    } else {
        // compute wholesale costs using this consumption and market manager marketprices prediction
        ArrayRealVector estimatedMarketPrices = marketPredictionManager.getPricePerKwhPredictionForAbout7Days();
        // sanity check
        if (predictedEnergyRecord.getDimension() != estimatedMarketPrices.getDimension()) {
            log.error("Cannot compute utility - prediction periods of market and energy differ);");
            return 0;
        }
        wholesaleCosts = -predictedEnergyRecord.dotProduct(estimatedMarketPrices);
    }

    log.info("estTariffIncome " + estTariffIncome);
    log.info("estTariffCosts " + estTariffCosts);
    log.info("wholesaleCosts " + wholesaleCosts);
    log.info("balancingCosts " + balancingCosts);
    log.info("distributionCosts " + distributionCosts);
    //log.info("old distributionCosts " +  Math.max(totalProduction, totalConsumption) * contextManager.getDistributionFee());
    log.info("withdrawCosts " + withdrawCosts);

    return estTariffIncome + estTariffCosts + wholesaleCosts + balancingCosts + distributionCosts
            + withdrawCosts;
}

From source file:com.joptimizer.optimizers.LPPresolver.java

/**
 * This method is just for testing scope.
 */// w  w w  .j  av a2  s .  c om
private void checkProgress(DoubleMatrix1D c, DoubleMatrix2D A, DoubleMatrix1D b, DoubleMatrix1D lb,
        DoubleMatrix1D ub, DoubleMatrix1D ylb, DoubleMatrix1D yub, DoubleMatrix1D zlb, DoubleMatrix1D zub) {

    if (this.expectedSolution == null) {
        return;
    }

    if (Double.isNaN(this.expectedTolerance)) {
        //for this to work properly, this method must be called at least one time before presolving operations start
        RealVector X = MatrixUtils.createRealVector(expectedSolution);
        RealMatrix AMatrix = MatrixUtils.createRealMatrix(A.toArray());
        RealVector Bvector = MatrixUtils.createRealVector(b.toArray());
        RealVector Axb = AMatrix.operate(X).subtract(Bvector);
        double norm = Axb.getNorm();
        this.expectedTolerance = Math.max(1.e-7, 1.5 * norm);
    }

    double tolerance = this.expectedTolerance;
    log.debug("tolerance: " + tolerance);

    RealVector X = MatrixUtils.createRealVector(expectedSolution);
    RealMatrix AMatrix = MatrixUtils.createRealMatrix(A.toArray());
    RealVector Bvector = MatrixUtils.createRealVector(b.toArray());
    //logger.debug("A.X-b: " + ArrayUtils.toString(originalA.operate(X).subtract(originalB)));

    //nz rows
    for (int i = 0; i < vRowPositions.length; i++) {
        short[] vRowPositionsI = vRowPositions[i];
        for (short nzJ : vRowPositionsI) {
            if (Double.compare(A.getQuick(i, nzJ), 0.) == 0) {
                log.debug("entry " + i + "," + nzJ + " est zero: " + A.getQuick(i, nzJ));
                throw new IllegalStateException();
            }
        }
    }

    //nz columns
    for (int j = 0; j < vColPositions.length; j++) {
        short[] vColPositionsJ = vColPositions[j];
        for (short nzI : vColPositionsJ) {
            if (Double.compare(A.getQuick(nzI, j), 0.) == 0) {
                log.debug("entry (" + nzI + "," + j + ") est zero: " + A.getQuick(nzI, j));
                throw new IllegalStateException();
            }
        }
    }

    //nz Aij
    for (int i = 0; i < A.rows(); i++) {
        short[] vRowPositionsI = vRowPositions[i];
        for (int j = 0; j < A.columns(); j++) {
            if (Double.compare(Math.abs(A.getQuick(i, j)), 0.) != 0) {
                if (!ArrayUtils.contains(vRowPositionsI, (short) j)) {
                    log.debug("entry " + i + "," + j + " est non-zero: " + A.getQuick(i, j));
                    throw new IllegalStateException();
                }
                if (!ArrayUtils.contains(vColPositions[j], (short) i)) {
                    log.debug("entry " + i + "," + j + " est non-zero: " + A.getQuick(i, j));
                    throw new IllegalStateException();
                }
            }
        }
    }

    //      //boolean deepCheckA = true;
    //      boolean deepCheckA = false;
    //      if(deepCheckA){
    //         //check for 0-rows
    //         List<Integer> zeroRows = new ArrayList<Integer>();
    //         for(int i=0; i<A.rows(); i++){
    //            boolean isNotZero = false;
    //            for(int j=0;!isNotZero && j<A.columns(); j++){
    //               isNotZero = Double.compare(0., A.getQuick(i, j))!=0;
    //            }
    //            if(!isNotZero){
    //               zeroRows.add(zeroRows.size(), i);
    //            }
    //         }
    //         if(!zeroRows.isEmpty()){
    //            log.debug("All 0 entries in rows " + ArrayUtils.toString(zeroRows));
    //            //log.debug(ArrayUtils.toString(A.toArray()));
    //            throw new IllegalStateException();
    //         }
    //         
    //         //check for 0-columns
    //         List<Integer> zeroCols = new ArrayList<Integer>();
    //         for(int j=0; j<A.columns(); j++){
    //            boolean isNotZero = false;
    //            for(int i=0;!isNotZero && i<A.rows(); i++){
    //               isNotZero = Double.compare(0., A.getQuick(i, j))!=0;
    //            }
    //            if(!isNotZero){
    //               zeroCols.add(zeroCols.size(), j);
    //            }
    //         }
    //         if(!zeroCols.isEmpty()){
    //            log.debug("All 0 entries in columns " + ArrayUtils.toString(zeroCols));
    //            //log.debug(ArrayUtils.toString(A.toArray()));
    //            throw new IllegalStateException();
    //         }
    //         
    //         // check rank(A): must be A pXn with rank(A)=p < n
    //         QRSparseFactorization qr = null;
    //         boolean factOK = true;
    //         try{
    //            qr = new QRSparseFactorization((SparseDoubleMatrix2D)A);
    //            qr.factorize();
    //         }catch(Exception e){
    //            factOK = false;
    //            log.warn("Warning", e);
    //         }
    //         if(factOK){
    //            log.debug("p        : " + AMatrix.getRowDimension());
    //            log.debug("n        : " + AMatrix.getColumnDimension());
    //            log.debug("full rank: " + qr.hasFullRank());
    //            if(!(A.rows() < A.columns())){
    //               log.debug("!( p < n )");
    //               throw new IllegalStateException();
    //            }
    //            if(!qr.hasFullRank()){
    //               log.debug("not full rank A matrix");
    //               throw new IllegalStateException();
    //            }
    //         }
    //      }

    //A.x = b
    RealVector Axb = AMatrix.operate(X).subtract(Bvector);
    double norm = Axb.getNorm();
    log.debug("|| A.x-b ||: " + norm);
    if (norm > tolerance) {
        //where is the error?
        for (int i = 0; i < Axb.getDimension(); i++) {
            if (Math.abs(Axb.getEntry(i)) > tolerance) {
                log.debug("entry " + i + ": " + Axb.getEntry(i));
                throw new IllegalStateException();
            }
        }
        throw new IllegalStateException();
    }

    //upper e lower
    for (int i = 0; i < X.getDimension(); i++) {
        if (X.getEntry(i) + tolerance < lb.getQuick(i)) {
            log.debug("lower bound " + i + " not respected: lb=" + lb.getQuick(i) + ", value=" + X.getEntry(i));
            throw new IllegalStateException();
        }
        if (X.getEntry(i) > ub.getQuick(i) + tolerance) {
            log.debug("upper bound " + i + " not respected: ub=" + ub.getQuick(i) + ", value=" + X.getEntry(i));
            throw new IllegalStateException();
        }
    }
}

From source file:org.apache.predictionio.examples.java.recommendations.tutorial1.Algorithm.java

@Override
public Float predict(Model model, Query query) {
    RealVector itemVector = model.itemSimilarity.get(query.iid);
    RealVector userVector = model.userHistory.get(query.uid);
    if (itemVector == null) {
        // cold start item, can't be handled by this algo, return hard code value.
        return Float.NaN;
    } else if (userVector == null) {
        // new user, can't be handled by this algo, return hard code value.
        return Float.NaN;
    } else {//from ww w . j a  v a2 s.co  m
        //logger.info("(" + query.uid + "," + query.iid + ")");
        //logger.info(itemVector.toString());
        //logger.info(userVector.toString());
        double accum = 0.0;
        double accumSim = 0.0;
        for (int i = 0; i < itemVector.getDimension(); i++) {
            double weight = itemVector.getEntry(i);
            double rating = userVector.getEntry(i);
            if ((weight != 0) && (rating != 0)) {
                accum += weight * rating;
                accumSim += Math.abs(weight);
            }
        }

        if (accumSim == 0.0) {
            return Float.NaN;
        } else {
            return (float) (accum / accumSim);
        }
    }
}

From source file:org.apache.predictionio.examples.java.recommendations.tutorial4.CollaborativeFilteringAlgorithm.java

@Override
public Float predict(CollaborativeFilteringModel model, Query query) {
    RealVector itemVector = model.itemSimilarity.get(query.iid);
    RealVector userVector = model.userHistory.get(query.uid);
    if (itemVector == null) {
        // cold start item, can't be handled by this algo, return hard code value.
        return Float.NaN;
    } else if (userVector == null) {
        // new user, can't be handled by this algo, return hard code value.
        return Float.NaN;
    } else {/*from w  ww.j a va 2  s . c o m*/
        //logger.info("(" + query.uid + "," + query.iid + ")");
        //logger.info(itemVector.toString());
        //logger.info(userVector.toString());
        double accum = 0.0;
        double accumSim = 0.0;
        for (int i = 0; i < itemVector.getDimension(); i++) {
            double weight = itemVector.getEntry(i);
            double rating = userVector.getEntry(i);
            if ((weight != 0) && (rating != 0)) {
                accum += weight * rating;
                accumSim += Math.abs(weight);
            }
        }

        if (accumSim == 0.0) {
            return Float.NaN;
        } else {
            return (float) (accum / accumSim);
        }
    }
}

From source file:org.briljantframework.array.Matrices.java

/**
 * View the double array as a {@link RealVector}.
 *
 * @param array the array//  w w  w .j  av a 2s  .  c  o m
 * @return a real vector view
 */
public static RealVector asRealVector(DoubleArray array) {
    Check.argument(array.isVector(), CAN_ONLY_VIEW_1D_ARRAYS);
    return new RealVector() {
        @Override
        public int getDimension() {
            return array.size();
        }

        @Override
        public double getEntry(int index) throws OutOfRangeException {
            return array.get(index);
        }

        @Override
        public void setEntry(int index, double value) throws OutOfRangeException {
            array.set(index, value);
        }

        @Override
        public RealVector append(RealVector v) {
            ArrayRealVector vector = new ArrayRealVector(v.getDimension() + array.size());
            copyFromArray(vector);
            for (int i = 0; i < v.getDimension(); i++) {
                vector.setEntry(i, v.getEntry(i));
            }
            return vector;
        }

        private void copyFromArray(ArrayRealVector vector) {
            for (int i = 0; i < array.size(); i++) {
                vector.setEntry(i, array.get(i));
            }
        }

        @Override
        public RealVector append(double d) {
            ArrayRealVector vector = new ArrayRealVector(array.size() + 1);
            copyFromArray(vector);
            vector.setEntry(array.size(), d);
            return vector;
        }

        @Override
        public RealVector getSubVector(int index, int n) throws NotPositiveException, OutOfRangeException {
            return asRealVector(array.get(Range.of(index, index + n)));
        }

        @Override
        public void setSubVector(int index, RealVector v) throws OutOfRangeException {
            for (int i = 0; i < array.size(); i++) {
                array.set(i + index, v.getEntry(i));
            }
        }

        @Override
        public boolean isNaN() {
            return Arrays.any(array, Double::isNaN);
        }

        @Override
        public boolean isInfinite() {
            return Arrays.any(array, Double::isInfinite);
        }

        @Override
        public RealVector copy() {
            return asRealVector(array.copy());
        }

        @Override
        @Deprecated
        public RealVector ebeDivide(RealVector v) throws DimensionMismatchException {
            if (v.getDimension() != array.size()) {
                throw new DimensionMismatchException(v.getDimension(), array.size());
            }
            RealVector a = new ArrayRealVector(array.size());
            for (int i = 0; i < array.size(); i++) {
                a.setEntry(i, array.get(i) / v.getEntry(i));
            }
            return a;
        }

        @Override
        @Deprecated
        public RealVector ebeMultiply(RealVector v) throws DimensionMismatchException {
            if (v.getDimension() != array.size()) {
                throw new DimensionMismatchException(v.getDimension(), array.size());
            }
            RealVector a = new ArrayRealVector(array.size());
            for (int i = 0; i < array.size(); i++) {
                a.setEntry(i, array.get(i) * v.getEntry(i));
            }
            return a;
        }
    };
}

From source file:org.eclipse.dataset.LinearAlgebra.java

private static Dataset createDataset(RealVector v) {
    DoubleDataset r = new DoubleDataset(v.getDimension());
    int size = r.getSize();
    if (v instanceof ArrayRealVector) {
        double[] data = ((ArrayRealVector) v).getDataRef();
        for (int i = 0; i < size; i++) {
            r.setAbs(i, data[i]);/*  w  w  w .  ja  va 2  s. c  o m*/
        }
    } else {
        for (int i = 0; i < size; i++) {
            r.setAbs(i, v.getEntry(i));
        }
    }
    return r;
}

From source file:org.eclipse.january.dataset.LinearAlgebra.java

private static Dataset createDataset(RealVector v) {
    DoubleDataset r = DatasetFactory.zeros(DoubleDataset.class, v.getDimension());
    int size = r.getSize();
    if (v instanceof ArrayRealVector) {
        double[] data = ((ArrayRealVector) v).getDataRef();
        for (int i = 0; i < size; i++) {
            r.setAbs(i, data[i]);/*from ww w  .j a  v a 2  s . com*/
        }
    } else {
        for (int i = 0; i < size; i++) {
            r.setAbs(i, v.getEntry(i));
        }
    }
    return r;
}