Example usage for java.lang Double doubleValue

List of usage examples for java.lang Double doubleValue

Introduction

In this page you can find the example usage for java.lang Double doubleValue.

Prototype

@HotSpotIntrinsicCandidate
public double doubleValue() 

Source Link

Document

Returns the double value of this Double object.

Usage

From source file:it.eng.spagobi.engines.chart.bo.charttypes.targetcharts.SparkLine.java

@Override
public JFreeChart createChart(DatasetMap datasets) {
    logger.debug("IN");
    XYDataset dataset = (XYDataset) datasets.getDatasets().get("1");

    final JFreeChart sparkLineGraph = ChartFactory.createTimeSeriesChart(null, null, null, dataset, legend,
            false, false);//from  www.  j a  va  2 s  .  co  m
    sparkLineGraph.setBackgroundPaint(color);

    TextTitle title = setStyleTitle(name, styleTitle);
    sparkLineGraph.setTitle(title);
    if (subName != null && !subName.equals("")) {
        TextTitle subTitle = setStyleTitle(subName, styleSubTitle);
        sparkLineGraph.addSubtitle(subTitle);
    }

    sparkLineGraph.setBorderVisible(false);
    sparkLineGraph.setBorderPaint(Color.BLACK);
    XYPlot plot = sparkLineGraph.getXYPlot();
    plot.setOutlineVisible(false);
    plot.setInsets(new RectangleInsets(0.0, 0.0, 0.0, 0.0));
    plot.setBackgroundPaint(null);
    plot.setDomainGridlinesVisible(false);
    plot.setDomainCrosshairVisible(false);
    plot.setRangeGridlinesVisible(false);
    plot.setRangeCrosshairVisible(false);
    plot.setBackgroundPaint(color);

    // calculate the last marker color
    Paint colorLast = getLastPointColor();

    // Calculate average, minimum and maximum to draw plot borders.
    boolean isFirst = true;
    double avg = 0, min = Double.POSITIVE_INFINITY, max = Double.NEGATIVE_INFINITY;
    int count = 0;
    for (int i = 0; i < timeSeries.getItemCount(); i++) {
        if (timeSeries.getValue(i) != null) {
            count++;
            if (isFirst) {
                min = timeSeries.getValue(i).doubleValue();
                max = timeSeries.getValue(i).doubleValue();
                isFirst = false;
            }
            double n = timeSeries.getValue(i).doubleValue();
            //calculate avg, min, max
            avg += n;
            if (n < min)
                min = n;
            if (n > max)
                max = n;
        }
    }
    // average
    avg = avg / (double) count;

    // calculate min and max between thresholds!
    boolean isFirst2 = true;
    double lb = 0, ub = 0;
    for (Iterator iterator = thresholds.keySet().iterator(); iterator.hasNext();) {
        Double thres = (Double) iterator.next();
        if (isFirst2 == true) {
            ub = thres.doubleValue();
            lb = thres.doubleValue();
            isFirst2 = false;
        }
        if (thres.doubleValue() > ub)
            ub = thres.doubleValue();
        if (thres.doubleValue() < lb)
            lb = thres.doubleValue();
    }

    plot.getRangeAxis().setRange(new Range(Math.min(lb, min - 2), Math.max(ub, max + 2) + 2));

    addMarker(1, avg, Color.GRAY, 0.8f, plot);
    //addAvaregeSeries(series, plot);
    addPointSeries(timeSeries, plot);

    int num = 3;
    for (Iterator iterator = thresholds.keySet().iterator(); iterator.hasNext();) {
        Double thres = (Double) iterator.next();
        TargetThreshold targThres = thresholds.get(thres);
        Color color = Color.WHITE;
        if (targThres != null && targThres.getColor() != null) {
            color = targThres.getColor();
        }
        if (targThres.isVisible()) {
            addMarker(num++, thres.doubleValue(), color, 0.5f, plot);
        }
    }

    ValueAxis domainAxis = plot.getDomainAxis();
    domainAxis.setVisible(false);
    domainAxis.setUpperMargin(0.2);
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setVisible(false);

    plot.getRenderer().setSeriesPaint(0, Color.BLACK);
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false) {
        public boolean getItemShapeVisible(int _series, int item) {
            TimeSeriesDataItem tsdi = timeSeries.getDataItem(item);
            if (tsdi == null)
                return false;
            Month period = (Month) tsdi.getPeriod();
            int currMonth = period.getMonth();
            int currYear = period.getYearValue();
            int lastMonthFilled = lastMonth.getMonth();
            int lastYearFilled = lastMonth.getYearValue();
            boolean isLast = false;
            if (currYear == lastYearFilled && currMonth == lastMonthFilled) {
                isLast = true;
            }
            return isLast;
        }
    };
    renderer.setSeriesPaint(0, Color.decode("0x000000"));

    renderer.setBaseShapesVisible(true);
    renderer.setBaseShapesFilled(true);
    renderer.setDrawOutlines(true);
    renderer.setUseFillPaint(true);
    renderer.setBaseFillPaint(colorLast);
    renderer.setBaseOutlinePaint(Color.BLACK);
    renderer.setUseOutlinePaint(true);
    renderer.setSeriesShape(0, new Ellipse2D.Double(-4.0, -4.0, 8.0, 8.0));

    if (wlt_mode.doubleValue() == 0) {
        renderer.setBaseItemLabelsVisible(Boolean.FALSE, true);
    } else {
        renderer.setBaseItemLabelsVisible(Boolean.TRUE, true);
        renderer.setBaseItemLabelFont(
                new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
        renderer.setBaseItemLabelPaint(styleValueLabels.getColor());
        renderer.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator("{2}", new DecimalFormat("0.###"),
                new DecimalFormat("0.###")) {
            public String generateLabel(CategoryDataset dataset, int row, int column) {
                if (dataset.getValue(row, column) == null || dataset.getValue(row, column).doubleValue() == 0)
                    return "";
                String columnKey = (String) dataset.getColumnKey(column);
                int separator = columnKey.indexOf('-');
                String month = columnKey.substring(0, separator);
                String year = columnKey.substring(separator + 1);
                int monthNum = Integer.parseInt(month);
                if (wlt_mode.doubleValue() >= 1 && wlt_mode.doubleValue() <= 4) {
                    if (wlt_mode.doubleValue() == 2 && column % 2 == 0)
                        return "";

                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.MONTH, monthNum - 1);
                    SimpleDateFormat dataFormat = new SimpleDateFormat("MMM");
                    return dataFormat.format(calendar.getTime());
                } else
                    return "" + monthNum;
            }
        });
    }

    if (wlt_mode.doubleValue() == 3) {
        renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,
                org.jfree.ui.TextAnchor.BOTTOM_CENTER, org.jfree.ui.TextAnchor.BOTTOM_RIGHT, Math.PI / 2));
        renderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6,
                org.jfree.ui.TextAnchor.TOP_CENTER, org.jfree.ui.TextAnchor.HALF_ASCENT_LEFT, Math.PI / 2));

    } else if (wlt_mode.doubleValue() == 4) {
        renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,
                org.jfree.ui.TextAnchor.BOTTOM_CENTER, org.jfree.ui.TextAnchor.BOTTOM_RIGHT, Math.PI / 4));
        renderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6,
                org.jfree.ui.TextAnchor.TOP_CENTER, org.jfree.ui.TextAnchor.HALF_ASCENT_LEFT, Math.PI / 4));
    }

    if (legend == true) {
        LegendItemCollection collection = createThresholdLegend(plot);
        LegendItem item = new LegendItem("Avg", "Avg", "Avg", "Avg", new Rectangle(10, 10), colorAverage);
        collection.add(item);
        plot.setFixedLegendItems(collection);

    }

    plot.setRenderer(0, renderer);
    logger.debug("OUT");
    return sparkLineGraph;
}

From source file:org.sakaiproject.tool.gradebook.test.GradebookServiceInternalTest.java

public void testMoveExternalToInternal() throws Exception {
    // Add an external assessment score.
    gradebookExternalAssessmentService.updateExternalAssessmentScore(GRADEBOOK_UID, EXT_ID_1,
            STUDENT_IN_SECTION_UID, new String("5"));

    // Break the relationship off.
    gradebookExternalAssessmentService.setExternalAssessmentToGradebookAssignment(GRADEBOOK_UID, EXT_ID_1);

    // Make sure that the internal-access APIs work now.
    setAuthnId(INSTRUCTOR_UID);/*w  w  w.  j a  v a 2 s  .com*/
    Double score = new Double(
            gradebookService.getAssignmentScoreString(GRADEBOOK_UID, EXT_TITLE_1, STUDENT_IN_SECTION_UID));
    Assert.assertTrue(score.doubleValue() == 5.0);
    gradebookService.setAssignmentScoreString(GRADEBOOK_UID, EXT_TITLE_1, STUDENT_IN_SECTION_UID,
            new String("10"), "A Friend");
    score = new Double(
            gradebookService.getAssignmentScoreString(GRADEBOOK_UID, EXT_TITLE_1, STUDENT_IN_SECTION_UID));
    Assert.assertTrue(score.doubleValue() == 10.0);

    // Make sure that the external-management fields are nulled out.
    org.sakaiproject.service.gradebook.shared.Assignment assignmentDefinition = gradebookService
            .getAssignment(GRADEBOOK_UID, EXT_TITLE_1);
    Assert.assertTrue(!assignmentDefinition.isExternallyMaintained());
    Assert.assertTrue(assignmentDefinition.getExternalAppName() == null);

    // Make sure that the external-management APIs don't work any more.
    try {
        gradebookExternalAssessmentService.updateExternalAssessmentScore(GRADEBOOK_UID, EXT_ID_1,
                STUDENT_IN_SECTION_UID, new String("5"));
        fail();
    } catch (AssessmentNotFoundException e) {
    }
}

From source file:msi.gama.util.matrix.GamaFloatMatrix.java

@Override
public boolean _removeAll(final IScope scope, final IContainer<?, Double> list) {
    // TODO Exception if o == null
    for (final Double o : list.iterable(scope)) {
        removeAll(o.doubleValue());
    }//w  w  w  . j av  a  2 s  . co m
    // TODO Make a test to verify the return
    return true;
}

From source file:org.sakaiproject.tool.gradebook.test.GradebookServiceInternalTest.java

public void testAddAssignment() throws Exception {
    setAuthnId(INSTRUCTOR_UID);//from w  ww .  ja  v a 2s  . c o m

    // Create an assignment definition.
    String assignmentName = "Client-Created Quiz";
    Assignment assignmentDefinition = new Assignment();
    assignmentDefinition.setName(assignmentName);
    assignmentDefinition.setPoints(new Double(50));
    gradebookService.addAssignment(GRADEBOOK_UID, assignmentDefinition);

    // Make sure it's there and we can grade it.
    gradebookService.setAssignmentScoreString(GRADEBOOK_UID, assignmentName, STUDENT_IN_SECTION_UID,
            new String("49"), "Service Test");
    Double score = new Double(
            gradebookService.getAssignmentScoreString(GRADEBOOK_UID, assignmentName, STUDENT_IN_SECTION_UID));
    Assert.assertTrue(score.doubleValue() == 49.0);

    // Make sure we can't add duplicate names.
    assignmentDefinition.setPoints(new Double(40));
    try {
        gradebookService.addAssignment(GRADEBOOK_UID, assignmentDefinition);
        fail();
    } catch (ConflictingAssignmentNameException e) {
    }

    // Can we add one with trailing spaces?
    try {
        assignmentDefinition.setName(assignmentName + " ");
        gradebookService.addAssignment(GRADEBOOK_UID, assignmentDefinition);
        fail("Did not catch attempt to save assignment with the same name but trailing whitespace");
    } catch (ConflictingAssignmentNameException e) {
    }

    // Make sure we don't accept zero-score assignments (at present).
    assignmentDefinition.setName("Illegal Assignment");
    assignmentDefinition.setPoints(new Double(0));
    try {
        gradebookService.addAssignment(GRADEBOOK_UID, assignmentDefinition);
        fail();
    } catch (AssignmentHasIllegalPointsException e) {
    }

    // Make sure we don't panic about unreal assignments.
    assignmentDefinition = gradebookService.getAssignment(GRADEBOOK_UID, "No Such Assignment");
    Assert.assertTrue(assignmentDefinition == null);
}

From source file:org.pentaho.di.scoring.WekaScoringData.java

/**
 * Helper method that constructs an Instance to input to the Weka model based
 * on incoming Kettle fields and pre-constructed attribute-to-field mapping
 * data.//from www  . j  a  v a 2 s  .  c o  m
 * 
 * @param inputMeta a <code>RowMetaInterface</code> value
 * @param inputRow an <code>Object</code> value
 * @param mappingIndexes an <code>int</code> value
 * @param model a <code>WekaScoringModel</code> value
 * @return an <code>Instance</code> value
 */
private Instance constructInstance(RowMetaInterface inputMeta, Object[] inputRow, int[] mappingIndexes,
        WekaScoringModel model, boolean freshVector) {

    Instances header = model.getHeader();

    // Re-use this array (unless told otherwise) to avoid an object creation
    if (m_vals == null || freshVector) {
        m_vals = new double[header.numAttributes()];
    }

    for (int i = 0; i < header.numAttributes(); i++) {

        if (mappingIndexes[i] >= 0) {
            try {
                Object inputVal = inputRow[mappingIndexes[i]];

                Attribute temp = header.attribute(i);
                ValueMetaInterface tempField = inputMeta.getValueMeta(mappingIndexes[i]);
                int fieldType = tempField.getType();

                // Check for missing value (null or empty string)
                if (tempField.isNull(inputVal)) {
                    m_vals[i] = Utils.missingValue();
                    continue;
                }

                switch (temp.type()) {
                case Attribute.NUMERIC: {
                    if (fieldType == ValueMetaInterface.TYPE_BOOLEAN) {
                        Boolean b = tempField.getBoolean(inputVal);
                        if (b.booleanValue()) {
                            m_vals[i] = 1.0;
                        } else {
                            m_vals[i] = 0.0;
                        }
                    } else if (fieldType == ValueMetaInterface.TYPE_INTEGER) {
                        Long t = tempField.getInteger(inputVal);
                        m_vals[i] = t.longValue();
                    } else {
                        Double n = tempField.getNumber(inputVal);
                        m_vals[i] = n.doubleValue();
                    }
                }
                    break;
                case Attribute.NOMINAL: {
                    String s = tempField.getString(inputVal);
                    // now need to look for this value in the attribute
                    // in order to get the correct index
                    int index = temp.indexOfValue(s);
                    if (index < 0) {
                        // set to missing value
                        m_vals[i] = Utils.missingValue();
                    } else {
                        m_vals[i] = index;
                    }
                }
                    break;
                case Attribute.STRING: {
                    String s = tempField.getString(inputVal);
                    // Set the attribute in the header to contain just this string value
                    temp.setStringValue(s);
                    m_vals[i] = 0.0;
                    break;
                }
                default:
                    m_vals[i] = Utils.missingValue();
                }
            } catch (Exception e) {
                m_vals[i] = Utils.missingValue();
            }
        } else {
            // set to missing value
            m_vals[i] = Utils.missingValue();
        }
    }

    Instance newInst = new DenseInstance(1.0, m_vals);
    newInst.setDataset(header);
    return newInst;
}

From source file:de.unibayreuth.bayeos.goat.table.MassenTableModel.java

public boolean addRow(ObjektNode objektNode, Vector values) {
    boolean bol = false;
    try {/*from  w  ww .jav a2 s.  c o m*/

        // Update display values 

        java.util.Date von = (java.util.Date) values.elementAt(0);
        Double wert = (Double) values.elementAt(1);
        Integer status = (Integer) values.elementAt(2);

        Vector params = new Vector();

        params.add(objektNode.getId());
        params.add(von);
        params.add(wert);
        params.add(status);

        bol = ((Boolean) xmlClient.execute("MassenTableHandler.addRow", params)).booleanValue();

        vonList.add((int) (von.getTime() / 1000));
        wertList.add(wert.doubleValue());
        statusList.add(status.byteValue());

        fireTableDataChanged();

    } catch (XmlRpcException x) {
        MsgBox.error(x.getMessage());
        return false;
    }

    return bol;

}

From source file:org.rhq.plugins.script.ScriptServerComponent.java

/**
 * Executes the CLI and based on the measurement property, collects the appropriate measurement value.
 * This supports measurement data and traits.
 * A metric property can be a string that is assumed the arguments to pass to the CLI. However, if
 * the property is in the form "{arguments}|regex", the arguments are passed to the CLI and the metric
 * value is taken from the regex match. Examples of metric properties:
 *  /*w  w w .  ja  va 2 s  . c  o m*/
 * <ul>
 * <li>"-a --arg2=123" - passes that string as the arguments list, the metric value is the output of the CLI</li> 
 * <li>"{}|exitcode" - no arguments are passed to the CLI and the metric value is the exit code of the CLI</li>
 * <li>"{-a}|[lL]abel(\p{Digit}+)[\r\n]*" - "-a" is the argument passed to the CLI and the metric value is the digits following the label of the output</li>
 * <li>"{}|[ABC]+" - no arguments are passed and the value is the output of the CLI assuming it matches the regex</li>
 * <li>"{--foobar}|foobar (.*) blah" - passes "--foobar" as the argument and the metric value is the string that matches the regex group</li>
 * </ul>
 * 
 * @see MeasurementFacet#getValues(MeasurementReport, Set)
 */
public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> requests) {
    Map<String, ProcessExecutionResults> exeResultsCache = new HashMap<String, ProcessExecutionResults>();

    for (MeasurementScheduleRequest request : requests) {
        String metricPropertyName = request.getName();
        boolean dataMustBeNumeric;

        if (request.getDataType() == DataType.MEASUREMENT) {
            dataMustBeNumeric = true;
        } else if (request.getDataType() == DataType.TRAIT) {
            dataMustBeNumeric = false;
        } else {
            log.error("Plugin does not support metric [" + metricPropertyName + "] of type ["
                    + request.getDataType() + "]");
            continue;
        }

        try {

            // determine how to execute the CLI for this metric
            Map<String, String> argsRegex = parseMetricProperty(metricPropertyName);
            Object dataValue;

            if (argsRegex == null) {
                continue; // this metric's property was invalid, skip this one and move on to the next
            }

            String arguments = argsRegex.get(METRIC_PROPERTY_ARGUMENTS);
            String regex = argsRegex.get(METRIC_PROPERTY_REGEX);
            boolean valueIsExitCode = METRIC_PROPERTY_EXITCODE.equals(regex);

            // if we already executed it with the same arguments, don't bother doing it again
            ProcessExecutionResults exeResults = exeResultsCache.get((arguments == null) ? "" : arguments);
            if (exeResults == null) {
                boolean captureOutput = !valueIsExitCode; // don't need output if we need to just check exit code
                exeResults = executeExecutable(arguments, MAX_WAIT_TIME, captureOutput);
                exeResultsCache.put((arguments == null) ? "" : arguments, exeResults);
            }

            // don't report a metric value if the CLI failed to execute
            if (exeResults.getError() != null) {
                log.error("Cannot collect CLI metric [" + metricPropertyName + "]. Cause: "
                        + ThrowableUtil.getAllMessages(exeResults.getError()));
                continue;
            }

            // set dataValue to the appropriate value based on how the metric property defined it
            if (valueIsExitCode) {
                dataValue = exeResults.getExitCode();
                if (dataValue == null) {
                    log.error("Could not determine exit code for metric property [" + metricPropertyName
                            + "] - metric will not be collected");
                    continue;
                }
            } else if (regex != null) {
                final String output = exeResults.getCapturedOutput();
                if (output == null) {
                    log.error("Could not get output for metric property [" + metricPropertyName
                            + "] -- metric will not be collected");
                    continue;
                }

                Pattern pattern = Pattern.compile(regex);
                Matcher match = pattern.matcher(output);
                if (match.find()) {
                    if (match.groupCount() > 0) {
                        dataValue = match.group(1);
                    } else {
                        dataValue = output;
                    }
                } else {
                    log.error("Output did not match metric property [" + metricPropertyName
                            + "] - metric will not be collected: " + truncateString(output));
                    continue;
                }
            } else {
                dataValue = exeResults.getCapturedOutput();
                if (dataValue == null) {
                    log.error("Could not get output for metric property [" + metricPropertyName
                            + "] - metric will not be collected");
                    continue;
                }
            }

            // add the metric value to the measurement report
            if (dataMustBeNumeric) {
                Double numeric = Double.parseDouble(dataValue.toString().trim());
                report.addData(new MeasurementDataNumeric(request, numeric.doubleValue()));
            } else {
                report.addData(new MeasurementDataTrait(request, dataValue.toString().trim()));
            }
        } catch (Exception e) {
            log.error("Failed to obtain measurement [" + metricPropertyName + "]. Cause: " + e);
        }
    }

    exeResultsCache.clear(); // help out the garbage collector, since this could be alot of data
    exeResultsCache = null;

    return;
}

From source file:ca.mcgill.cs.creco.logic.ScoredAttribute.java

private void setRank(List<Double> pValues) {
    double previousValue = 0;
    boolean notFirst = false;
    int rank = 1;
    for (Double val : pValues) {
        if (notFirst) {
            if (previousValue != val.doubleValue()) {
                if (aNumericValueRank.containsKey(val)) {
                    LOG.error("setNumericStats sort error in Attribute " + aAttributeID + "in Category "
                            + aCategory.getId());
                } else {
                    aNumericValueRank.put(val, rank);
                    previousValue = val.doubleValue();
                }/*from w  ww. j a va2 s .c  o m*/
            }
        } else//It is the first Item
        {
            aNumericValueRank.put(val, rank);
            previousValue = val.doubleValue();
            notFirst = true;
        }
        rank++;
    }
}

From source file:ch.epfl.lsir.xin.algorithm.core.UserBasedCF.java

/**
 * This function predicts a user's rating to an item
 * @param: index of the user/*from   ww  w.j  a  va 2  s  .  c om*/
 * @param: index of the item
 * @param: is the predicted rating for rating prediction or ranking?
 * @return: the predicted rating
 * */
public double predict(int userIndex, int itemIndex, boolean rank) {
    ArrayList<SUser> similarUsers = new ArrayList<SUser>();
    int neighbors = this.config.getInt("NEIGHBOUR_SIZE");
    //find the similar users
    for (int i = 0; i < this.ratingMatrix.getRow(); i++) {
        Double value = this.ratingMatrix.getRatingMatrix().get(i).get(itemIndex);
        //this user also rated the target item
        if (value != null && this.similarityMatrix[userIndex][i] > 0) {
            //get the similarity information
            SUser su = new SUser(i, value.doubleValue(), this.similarityMatrix[userIndex][i]);
            similarUsers.add(su);
        }
    }

    //collaborative filtering cannot work: first user-average and then global-average
    if (similarUsers.size() < 1) {
        double userM = this.ratingMatrix.getUsersMean().get(userIndex);
        if (!Double.isNaN(userM)) {
            return userM;
        } else {
            return this.ratingMatrix.getAverageRating();
        }
    }
    Collections.sort(similarUsers);

    double totalSimilarity = 0;
    double prediction = 0;
    int counter = 0;
    for (int i = similarUsers.size() - 1; i >= 0; i--) {
        totalSimilarity = totalSimilarity + Math.abs(similarUsers.get(i).getSimilarity());
        prediction = prediction + similarUsers.get(i).getSimilarity() * (similarUsers.get(i).getRating()
                - this.ratingMatrix.getUsersMean().get(similarUsers.get(i).getUserIndex()));
        counter++;
        if (counter == neighbors)
            break;
    }
    if (Double.isNaN(totalSimilarity) || totalSimilarity == 0) {
        double userM = this.ratingMatrix.getUsersMean().get(userIndex);
        if (!Double.isNaN(userM)) {
            return userM;
        } else {
            return this.ratingMatrix.getAverageRating();
        }
    }
    if (rank) {
        //         prediction = prediction / totalSimilarity;   
        //         return this.getPredictionRanking(userIndex, itemIndex);
        return totalSimilarity;
    } else {
        prediction = prediction / totalSimilarity;
        prediction = prediction + this.ratingMatrix.getUsersMean().get(userIndex);
    }
    return prediction;
}

From source file:ch.epfl.lsir.xin.algorithm.core.ItemBasedCF.java

/**
 * This function predicts a user's rating to an item
 * @param: index of the user//from  ww w . j a  va2s  . co  m
 * @param: index of the item
 * @param: if the prediction is for ranking
 * @return: the predicted rating
 * */
public double predict(int userIndex, int itemIndex, boolean rank) {
    ArrayList<SItem> similarItems = new ArrayList<SItem>();
    int neighbors = this.config.getInt("NEIGHBOUR_SIZE");
    //find the similar items
    for (int i = 0; i < this.ratingMatrix.getColumn(); i++) {
        Double value = this.ratingMatrix.getRatingMatrix().get(userIndex).get(i);
        //this item is also rated by the target user
        if (value != null && this.similarityMatrix[itemIndex][i] > 0) {
            //get the similarity information
            SItem si = new SItem(i, value.doubleValue(), this.similarityMatrix[itemIndex][i]);
            similarItems.add(si);
        }
    }

    //collaborative filtering cannot work: first user-average and then global-average
    if (similarItems.size() < 1 /*|| similarItems.get(similarItems.size()-1).getSimilarity() == 0*/ ) {
        //         System.out.println("Cannot be predicted by UserCF");
        double itemM = this.ratingMatrix.getItemMean(itemIndex);
        if (!Double.isNaN(itemM)) {
            return itemM;
        } else {
            return this.ratingMatrix.getAverageRating();
        }
    }
    Collections.sort(similarItems);

    double totalSimilarity = 0;
    double prediction = 0;
    int counter = 0;
    double simRanking = 0;
    for (int i = similarItems.size() - 1; i >= 0; i--) {
        totalSimilarity = totalSimilarity + Math.abs(similarItems.get(i).getSimilarity());
        simRanking += similarItems.get(i).getSimilarity();
        prediction = prediction + similarItems.get(i).getSimilarity() * (similarItems.get(i).getRating()
                - this.ratingMatrix.getItemsMean().get(similarItems.get(i).getItemIndex()));
        //         if(  Double.isNaN(totalSimilarity) || totalSimilarity == 0  )
        //         {
        //            System.out.println(similarItems.get(i).getSimilarity() + " ,  "
        //                  + similarItems.get(i).getRating() + " pred: " + prediction);
        //         }
        counter++;
        if (counter == neighbors)
            break;
    }
    if (Double.isNaN(totalSimilarity) || totalSimilarity == 0) {
        double itemM = this.ratingMatrix.getItemMean(itemIndex);
        if (!Double.isNaN(itemM)) {
            return itemM;
        } else {
            return this.ratingMatrix.getAverageRating();
        }
    }
    if (rank) {
        return totalSimilarity;
        //         return simRanking;
    } else {
        prediction = prediction / totalSimilarity;
        prediction = prediction + this.ratingMatrix.getItemMean(itemIndex);
    }

    return prediction;
}