Example usage for org.jdom2 Element setAttribute

List of usage examples for org.jdom2 Element setAttribute

Introduction

In this page you can find the example usage for org.jdom2 Element setAttribute.

Prototype

public Element setAttribute(final String name, final String value) 

Source Link

Document

This sets an attribute value for this element.

Usage

From source file:delfos.results.evaluationmeasures.prediction.PredicitonErrorHistogram.java

License:Open Source License

@Override
public MeasureResult getMeasureResult(RecommendationResults recommendationResults,
        RatingsDataset<? extends Rating> testDataset, RelevanceCriteria relevanceCriteria) {

    HistogramNumbersSmart histogram = new HistogramNumbersSmart(binWidth);

    for (int idUser : testDataset.allUsers()) {
        Collection<Recommendation> recommendationList = recommendationResults.getRecommendationsForUser(idUser);
        try {//  w w  w  . j a v a 2 s  .co  m
            Map<Integer, ? extends Rating> userRated = testDataset.getUserRatingsRated(idUser);
            for (Recommendation lista : recommendationList) {
                Number rating = userRated.get(lista.getIdItem()).getRatingValue();
                Number prediction = lista.getPreference();

                if (rating != null && !Double.isNaN(rating.doubleValue())
                        && !Double.isInfinite(rating.doubleValue()) && prediction != null
                        && !Double.isNaN(prediction.doubleValue())
                        && !Double.isInfinite(prediction.doubleValue())) {
                    double error = prediction.doubleValue() - rating.doubleValue();
                    histogram.addValue(error);
                }
            }
        } catch (UserNotFound ex) {
            ERROR_CODES.USER_NOT_FOUND.exit(ex);
        }

    }
    if (histogram.getNumValues() == 0) {
        Global.showWarning("Cannot compute 'MAE' since the RS did not predicted any recommendation!!");
    }

    Element histogramElement = new Element(HISTOGRAM_ELEMENT_NAME);
    histogramElement.setAttribute(HISTOGRAM_BIN_WIDTH_ATTRIBUTE_NAME, Double.toString(binWidth));

    for (int indexBin = 0; indexBin < histogram.getNumBins(); indexBin++) {
        Element binElement = new Element(BIN_ELEMENT_NAME);

        binElement.setAttribute(BIN_MIN_VALUE_ATTRIBUTE_NAME,
                Double.toString(histogram.getBin_minBound(indexBin)));
        binElement.setAttribute(BIN_MAX_VALUE_ATTRIBUTE_NAME,
                Double.toString(histogram.getBin_maxBound(indexBin)));
        binElement.setAttribute(BIN_BIN_VALUE_ATTRIBUTE_NAME,
                Integer.toString(histogram.getBin_numValues(indexBin)));

        histogramElement.addContent(binElement);
    }

    if (Global.isVerboseAnnoying()) {
        histogram.printHistogram(System.out);
    }

    return new MeasureResult(this, 0.0f);
}

From source file:delfos.results.evaluationmeasures.PRSpace.java

License:Open Source License

@Override
public MeasureResult getMeasureResult(RecommendationResults recommendationResults,
        RatingsDataset<? extends Rating> testDataset, RelevanceCriteria relevanceCriteria) {

    int maxLength = 0;
    for (int idUser : testDataset.allUsers()) {
        Collection<Recommendation> lr = recommendationResults.getRecommendationsForUser(idUser);

        if (lr.size() > maxLength) {
            maxLength = lr.size();// www  . j  a v a  2 s.  c o  m
        }
    }

    Map<Integer, ConfusionMatricesCurve> allUsersCurves = new TreeMap<>();

    for (int idUser : testDataset.allUsers()) {

        List<Boolean> resultados = new ArrayList<>(recommendationResults.usersWithRecommendations().size());
        Collection<Recommendation> recommendationList = recommendationResults.getRecommendationsForUser(idUser);

        try {
            Map<Integer, ? extends Rating> userRatings = testDataset.getUserRatingsRated(idUser);
            for (Recommendation r : recommendationList) {

                int idItem = r.getIdItem();
                resultados.add(relevanceCriteria.isRelevant(userRatings.get(idItem).getRatingValue()));
            }
        } catch (UserNotFound ex) {
            ERROR_CODES.USER_NOT_FOUND.exit(ex);
        }

        try {
            allUsersCurves.put(idUser, new ConfusionMatricesCurve(resultados));
        } catch (IllegalArgumentException iae) {
            Global.showWarning("User " + idUser + ": " + iae.getMessage());
        }
    }

    ConfusionMatricesCurve agregada = ConfusionMatricesCurve.mergeCurves(allUsersCurves.values());

    double areaUnderPR = agregada.getAreaPRSpace();

    Element element = new Element(this.getName());
    element.setAttribute(EvaluationMeasure.VALUE_ATTRIBUTE_NAME, Double.toString(areaUnderPR));
    element.setContent(ConfusionMatricesCurveXML.getElement(agregada));

    Map<String, Double> detailedResult = new TreeMap<>();
    for (int i = 0; i < agregada.size(); i++) {
        double precisionAt = agregada.getPrecisionAt(i);
        detailedResult.put("Precision@" + i, precisionAt);
    }

    return new MeasureResult(this, areaUnderPR);
}

From source file:delfos.results.evaluationmeasures.roccurve.AreaUnderROC.java

License:Open Source License

@Override
public MeasureResult getMeasureResult(RecommendationResults recommendationResults,
        RatingsDataset<? extends Rating> testDataset, RelevanceCriteria relevanceCriteria) {
    List<ConfusionMatrix> matrices = new LinkedList<>();
    int maxLength = 0;

    for (Integer idUser : recommendationResults.usersWithRecommendations()) {
        Collection<Recommendation> recommendations = recommendationResults.getRecommendationsForUser(idUser);

        if (recommendations.size() > maxLength) {
            maxLength = recommendations.size();
        }//from   w w w  .j  a  v a 2s  .  c  om
    }

    if (maxLength == 0) {
        return new MeasureResult(this, 0);
    }

    List<List<Boolean>> resultados = new ArrayList<>(recommendationResults.usersWithRecommendations().size());
    for (int idUser : testDataset.allUsers()) {
        Collection<Recommendation> recommendationList = recommendationResults.getRecommendationsForUser(idUser);
        List<Boolean> listaTransformada = new ArrayList<>(recommendationList.size());

        try {
            Map<Integer, ? extends Rating> userRatings = testDataset.getUserRatingsRated(idUser);
            recommendationList.stream().map((r) -> r.getIdItem()).map((idItem) -> {
                return idItem;
            }).forEach((idItem) -> {
                listaTransformada.add(relevanceCriteria.isRelevant(userRatings.get(idItem).getRatingValue()));
            });
            resultados.add(listaTransformada);
        } catch (UserNotFound ex) {
            ERROR_CODES.USER_NOT_FOUND.exit(ex);
        }
    }

    Collection<Integer> allUsers = testDataset.allUsers();
    if (allUsers.isEmpty()) {
        throw new IllegalArgumentException("Cannot work without users.");
    }

    int truePositive = 0;
    int falseNegative = 0;
    int falsePositive = 0;
    int trueNegative = 0;
    int count = 0;

    //Inicialmente supone que todos son no recomendados
    if (Global.isVerboseAnnoying()) {
        Global.showInfoMessage("ROC with length " + 0 + " of " + maxLength + ".");
    }
    for (List<Boolean> recom : resultados) {
        for (Boolean recom1 : recom) {
            if (recom1) {
                falseNegative++;
            } else {
                trueNegative++;
            }
        }
        count++;
        if (allUsers.size() > 11 && (count % (allUsers.size() / 10.0) == 0)) {
            if (Global.isVerboseAnnoying()) {
                Global.showInfoMessage(" " + count * 100 / allUsers.size() + "% of users analysed.\n");
            }
        }
    }

    //calculada la matriz de confusin para tamao 0, se aade a la curva.
    matrices.add(new ConfusionMatrix(falsePositive, falseNegative, truePositive, trueNegative));

    Chronometer c = new Chronometer();
    c.reset();
    for (int kActual = 1; kActual < maxLength; kActual++) {
        if (Global.isVerboseAnnoying()) {
            Global.showInfoMessage("ROC with length " + kActual + " of " + maxLength + ".");
        }

        //            count = 0;
        for (List<Boolean> recom : resultados) {
            if (kActual < recom.size()) {
                if (recom.get(kActual)) {
                    truePositive++;
                    falseNegative--;
                } else {
                    falsePositive++;
                    trueNegative--;
                }
            }
        }
        //calculada la matriz de confusin para longitud kActual
        matrices.add(new ConfusionMatrix(falsePositive, falseNegative, truePositive, trueNegative));
        if (Global.isVerboseAnnoying()) {
            Global.showInfoMessage(" in " + c.printPartialElapsed() + "\n");
        }
    }

    ConfusionMatricesCurve curve = new ConfusionMatricesCurve(matrices.toArray(new ConfusionMatrix[1]));

    if (Global.isVerboseAnnoying()) {
        Global.showInfoMessage("------------- Receiver Operator Characteristic --------------" + "\n");
        Global.showInfoMessage(curve.toString() + "\n");
    }

    double areaUnderROC = curve.getAreaPRSpace();

    Element element = new Element(this.getName());
    element.setAttribute(EvaluationMeasure.VALUE_ATTRIBUTE_NAME, Double.toString(areaUnderROC));
    element.setContent(ConfusionMatricesCurveXML.getElement(curve));

    return new MeasureResult(this, areaUnderROC);
}

From source file:delfos.results.MeasureResult.java

License:Open Source License

public Element getXMLElement() {
    Element measureElement = new Element(evaluationMeasure.getAlias());
    measureElement.setAttribute(EvaluationMeasure.VALUE_ATTRIBUTE_NAME, Double.toString(value));
    return measureElement;
}

From source file:delfos.web.DelfosWebConfiguration.java

public static String printXML(String xmlPath) {
    DelfosWebConfiguration.setConfiguration();
    File xml = new File(xmlPath);
    if (!xml.exists()) {
        ERROR_CODES.CONFIG_FILE_NOT_EXISTS.exit(
                new FileNotFoundException("Configuration file '" + xml.getAbsolutePath() + "' not found"));
    }/*from  www.  j  ava 2s  .  c o  m*/
    Global.showMessageTimestamped("Loading config file " + xml.getAbsolutePath());
    SAXBuilder builder = new SAXBuilder();
    Document doc = null;
    try {
        doc = builder.build(xml);
    } catch (JDOMException | IOException ex) {
        Global.showError(ex);
        ERROR_CODES.CANNOT_LOAD_CONFIG_FILE.exit(ex);
        throw new IllegalStateException(ex);
    }
    Element config = doc.getRootElement();
    config.setAttribute("configurationFilePath", xml.getAbsolutePath());
    XMLOutputter outputter = new XMLOutputter(Constants.getXMLFormat());
    return outputter.outputString(doc);
}

From source file:docubricks.data.Brick.java

public Element toXML(File basepath) throws IOException {
    Element eroot = new Element("brick");
    eroot.setAttribute("id", "" + id);

    //kicking out <description> - no need for one more section

    eroot.addContent(elWithContent("name", name));
    eroot.addContent(elWithContent("abstract", vabstract));
    eroot.addContent(elWithContent("long_description", longdesc));
    eroot.addContent(elWithContent("notes", notes));
    eroot.addContent(elWithContent("license", license)); //Note: done very differently in spec!

    eroot.addContent(media.toXML(basepath));

    eroot.addContent(asmInstruction.toXML(basepath));
    for (Author a : authors)
        if (a != null) {
            Element e = new Element("author");
            e.setAttribute("id", a.id);
            eroot.addContent(e);/*from   w w  w .  jav  a2 s .  c om*/
        }
    for (Function p : functions)
        if (p != null)
            eroot.addContent(p.toXML(basepath));

    for (StepByStepInstruction instr : instructions) {
        Element e = instr.toXML(basepath);
        e.setName("instruction");
        //EEEEW!
        e.setAttribute("name", instr.name);
        eroot.addContent(e);
    }

    return eroot;
}

From source file:domainapp.app.services.export.ExportToWordMenu.java

License:Apache License

private static void addPara(final Element body, final String id, final String clazz, final String text) {
    final Element p = new Element("p");
    body.addContent(p);/*from   w  w  w.j a va2  s . c o  m*/
    p.setAttribute("id", id);
    p.setAttribute("class", clazz);
    p.setText(text);
}

From source file:domainapp.app.services.export.ExportToWordMenu.java

License:Apache License

private static Element addList(final Element body, final String id) {
    final Element ul = new Element("ul");
    body.addContent(ul);//  w w  w  .jav  a  2  s.c  om
    ul.setAttribute("id", id);
    return ul;
}

From source file:domainapp.app.services.export.ExportToWordMenu.java

License:Apache License

private static Element addTable(final Element body, final String id) {
    final Element table = new Element("table");
    body.addContent(table);//from   w  ww .  ja v a2  s  .com
    table.setAttribute("id", id);
    return table;
}

From source file:edu.ucla.loni.server.ServerUtils.java

License:Open Source License

/**
 * Updates a Document (XML file) with all the attributes from a Pipefile
 * @throws Exception //w  w w .j av a 2s  . co  m
 */
public static Document updateXML(Document doc, Pipefile pipe) throws Exception {
    Element main = getMainElement(doc);

    // Update name (attribute)
    main.setAttribute("name", pipe.name);
    // Update package (attribute)
    main.setAttribute("package", pipe.packageName);
    // Update description (attribute)
    main.setAttribute("description", pipe.description);

    // Update the tags (children)
    main.removeChildren("tag"); // Remove all old tags
    String tags = pipe.tags;
    if (tags != null && tags.length() > 0) {
        String[] tagArray = tags.split(",");
        for (String tag : tagArray) {
            Element child = new Element("tag");
            child.setText(tag);
            main.addContent(child);
        }
    }

    if (pipe.type.equals("Data")) {
        // Update values (values child => children)
        Element valuesElement = main.getChild("values");
        if (valuesElement == null) {
            valuesElement = new Element("values");
            main.addContent(valuesElement);
        }

        valuesElement.removeChildren("value"); // Remove all old values

        String values = pipe.values;
        if (values != null && values.length() > 0) {
            String[] valueArray = values.split("\n");
            for (String value : valueArray) {
                Element valueElement = new Element("value");
                valueElement.setText(value);
                valuesElement.addContent(valueElement);
            }
        }

        // Update formatType (output child => format child => attribute)
        Element output = main.getChild("output");
        if (output == null) {
            output = new Element("output");
            main.addContent(output);
        }

        Element format = output.getChild("format");
        if (format == null) {
            format = new Element("format");
            main.addContent(format);
        }

        format.setAttribute("type", pipe.formatType);
    }

    if (pipe.type.equals("Modules")) {
        // Update location (attribute)
        main.setAttribute("location", pipe.location);
    }

    if (pipe.type.equals("Modules") || pipe.type.equals("Groups")) {
        // Update uri (child)
        Element uri = main.getChild("uri");

        // If child not present, create
        if (uri == null) {
            uri = new Element("uri");
            main.addContent(uri);
        }

        uri.setText(pipe.uri);
    }

    return doc;
}