Example #1
0
  /**
   * Write a Bayesian network to an output stream in BIF format.
   *
   * @param os The output stream to write to.
   * @param network The network to write.
   */
  public static void writeBIF(OutputStream os, BayesianNetwork network) {
    WriteXML xml = new WriteXML(os);
    xml.beginDocument();
    xml.addAttribute("VERSION", "0.3");
    xml.beginTag("BIF");
    xml.beginTag("NETWORK");
    xml.addProperty("NAME", "Bayes Network, Generated by Encog");
    // write variables
    for (BayesianEvent event : network.getEvents()) {
      xml.addAttribute("TYPE", "nature");
      xml.beginTag("VARIABLE");
      xml.addProperty("NAME", event.getLabel());
      for (BayesianChoice str : event.getChoices()) {
        xml.addProperty("OUTCOME", str.getLabel());
      }
      xml.endTag();
    }

    // write relations
    for (BayesianEvent event : network.getEvents()) {
      xml.beginTag("DEFINITION");
      xml.addProperty("FOR", event.getLabel());
      for (BayesianEvent parentEvent : event.getParents()) {
        xml.addProperty("GIVEN", parentEvent.getLabel());
      }
      xml.addAttribute("TABLE", generateTable(event));
      xml.endTag();
    }

    xml.endTag();
    xml.endTag();
    xml.endDocument();
  }
  /** {@inheritDoc} */
  @Override
  public final Object read(final InputStream is) {
    final BayesianNetwork result = new BayesianNetwork();
    final EncogReadHelper in = new EncogReadHelper(is);
    EncogFileSection section;
    String queryType = "";
    String queryStr = "";
    String contentsStr = "";

    while ((section = in.readNextSection()) != null) {
      if (section.getSectionName().equals("BAYES-NETWORK")
          && section.getSubSectionName().equals("BAYES-PARAM")) {
        final Map<String, String> params = section.parseParams();
        queryType = params.get("queryType");
        queryStr = params.get("query");
        contentsStr = params.get("contents");
      }
      if (section.getSectionName().equals("BAYES-NETWORK")
          && section.getSubSectionName().equals("BAYES-TABLE")) {

        result.setContents(contentsStr);

        // first, define relationships (1st pass)
        for (String line : section.getLines()) {
          result.defineRelationship(line);
        }

        result.finalizeStructure();

        // now define the probabilities (2nd pass)
        for (String line : section.getLines()) {
          result.defineProbability(line);
        }
      }
      if (section.getSectionName().equals("BAYES-NETWORK")
          && section.getSubSectionName().equals("BAYES-PROPERTIES")) {
        final Map<String, String> params = section.parseParams();
        result.getProperties().putAll(params);
      }
    }

    // define query, if it exists
    if (queryType.length() > 0) {
      BayesianQuery query = null;
      if (queryType.equals("EnumerationQuery")) {
        query = new EnumerationQuery(result);
      } else {
        query = new SamplingQuery(result);
      }

      if (query != null && queryStr.length() > 0) {
        result.setQuery(query);
        result.defineClassificationStructure(queryStr);
      }
    }

    return result;
  }
  public void testSampling3() {
    BayesianNetwork network = new BayesianNetwork();
    BayesianEvent a = network.createEvent("a");
    BayesianEvent x1 = network.createEvent("x1");
    BayesianEvent x2 = network.createEvent("x2");
    BayesianEvent x3 = network.createEvent("x3");

    network.createDependancy(a, x1, x2, x3);
    network.finalizeStructure();

    a.getTable().addLine(0.5, true); // P(A) = 0.5
    x1.getTable().addLine(0.2, true, true); // p(x1|a) = 0.2
    x1.getTable().addLine(0.6, true, false); // p(x1|~a) = 0.6
    x2.getTable().addLine(0.2, true, true); // p(x2|a) = 0.2
    x2.getTable().addLine(0.6, true, false); // p(x2|~a) = 0.6
    x3.getTable().addLine(0.2, true, true); // p(x3|a) = 0.2
    x3.getTable().addLine(0.6, true, false); // p(x3|~a) = 0.6
    network.validate();

    SamplingQuery query = new SamplingQuery(network);
    query.defineEventType(x1, EventType.Evidence);
    query.defineEventType(x3, EventType.Outcome);
    query.setEventValue(x1, true);
    query.setEventValue(x3, true);
    query.execute();
    testPercent(query.getProbability(), 50);
  }
  public void testSampling1() {
    BayesianNetwork network = new BayesianNetwork();
    BayesianEvent a = network.createEvent("a");
    BayesianEvent b = network.createEvent("b");

    network.createDependancy(a, b);
    network.finalizeStructure();
    a.getTable().addLine(0.5, true); // P(A) = 0.5
    b.getTable().addLine(0.2, true, true); // p(b|a) = 0.2
    b.getTable().addLine(0.8, true, false); // p(b|~a) = 0.8	
    network.validate();

    SamplingQuery query = new SamplingQuery(network);
    query.defineEventType(a, EventType.Evidence);
    query.defineEventType(b, EventType.Outcome);
    query.setEventValue(b, true);
    query.setEventValue(a, true);
    query.execute();
    testPercent(query.getProbability(), 20);
  }
  /** {@inheritDoc} */
  @Override
  public final void save(final OutputStream os, final Object obj) {
    final EncogWriteHelper out = new EncogWriteHelper(os);
    final BayesianNetwork b = (BayesianNetwork) obj;
    out.addSection("BAYES-NETWORK");
    out.addSubSection("BAYES-PARAM");
    String queryType = "";
    String queryStr = b.getClassificationStructure();

    if (b.getQuery() != null) {
      queryType = b.getQuery().getClass().getSimpleName();
    }

    out.writeProperty("queryType", queryType);
    out.writeProperty("query", queryStr);
    out.writeProperty("contents", b.getContents());
    out.addSubSection("BAYES-PROPERTIES");
    out.addProperties(b.getProperties());

    out.addSubSection("BAYES-TABLE");
    for (BayesianEvent event : b.getEvents()) {
      for (TableLine line : event.getTable().getLines()) {
        if (line == null) continue;
        StringBuilder str = new StringBuilder();
        str.append("P(");

        str.append(BayesianEvent.formatEventName(event, line.getResult()));

        if (event.getParents().size() > 0) {
          str.append("|");
        }

        int index = 0;
        boolean first = true;
        for (BayesianEvent parentEvent : event.getParents()) {
          if (!first) {
            str.append(",");
          }
          first = false;
          int arg = line.getArguments()[index++];
          if (parentEvent.isBoolean()) {
            if (arg == 0) {
              str.append("+");
            } else {
              str.append("-");
            }
          }
          str.append(parentEvent.getLabel());
          if (!parentEvent.isBoolean()) {
            str.append("=");
            if (arg >= parentEvent.getChoices().size()) {
              throw new BayesianError(
                  "Argument value " + arg + " is out of range for event " + parentEvent.toString());
            }
            str.append(parentEvent.getChoice(arg));
          }
        }
        str.append(")=");
        str.append(line.getProbability());
        str.append("\n");
        out.write(str.toString());
      }
    }

    out.flush();
  }