/** {@inheritDoc} */
  @Override
  public final void write(final double[] input, final double[] ideal, final double significance) {
    final StringBuilder builder = new StringBuilder();
    builder.append("1");
    builder.append(":");
    builder.append(this.inputCount + this.idealCount);
    this.xmlOut.addAttribute("spans", builder.toString());
    this.xmlOut.addAttribute("r", "" + (this.row++));
    this.xmlOut.beginTag("row");
    int index = 0;
    for (int i = 0; i < this.inputCount; i++) {
      this.xmlOut.addAttribute("r", toColumn(index++));
      this.xmlOut.beginTag("c");
      this.xmlOut.beginTag("v");
      this.xmlOut.addText(CSVFormat.EG_FORMAT.format(input[i], Encog.DEFAULT_PRECISION));
      this.xmlOut.endTag();
      this.xmlOut.endTag();
    }

    for (int i = 0; i < this.idealCount; i++) {
      this.xmlOut.addAttribute("r", toColumn(index++));
      this.xmlOut.beginTag("c");
      this.xmlOut.beginTag("v");
      this.xmlOut.addText(CSVFormat.EG_FORMAT.format(ideal[i], Encog.DEFAULT_PRECISION));
      this.xmlOut.endTag();
      this.xmlOut.endTag();
    }

    this.xmlOut.endTag();
  }
 /**
  * Generate a table, in BIF format.
  *
  * @param event The event to write.
  * @return The string form of the table.
  */
 public static String generateTable(BayesianEvent event) {
   StringBuilder s = new StringBuilder();
   int tableIndex = 0;
   int[] args = new int[event.getParents().size()];
   do {
     for (int result = 0; result < event.getChoices().size(); result++) {
       TableLine line = event.getTable().findLine(result, args);
       if (s.length() > 0) {
         s.append(" ");
       }
       s.append(CSVFormat.EG_FORMAT.format(line.getProbability(), Encog.DEFAULT_PRECISION));
     }
   } while (BIFUtil.rollArgs(event, args));
   return s.toString();
 }
  private String renderNode(ProgramNode node) {
    StringBuilder result = new StringBuilder();

    for (int i = 0; i < node.getChildNodes().size(); i++) {
      ProgramNode childNode = node.getChildNode(i);
      result.append(renderNode(childNode));
    }

    result.append('[');
    result.append(node.getName());
    result.append(':');
    result.append(node.getTemplate().getChildNodeCount());

    for (int i = 0; i < node.getTemplate().getDataSize(); i++) {
      result.append(':');
      ValueType t = node.getData()[i].getExpressionType();
      if (t == ValueType.booleanType) {
        result.append(node.getData()[i].toBooleanValue() ? 't' : 'f');
      } else if (t == ValueType.floatingType) {
        result.append(
            CSVFormat.EG_FORMAT.format(node.getData()[i].toFloatValue(), Encog.DEFAULT_PRECISION));
      } else if (t == ValueType.intType) {
        result.append(node.getData()[i].toIntValue());
      } else if (t == ValueType.enumType) {
        result.append(node.getData()[i].getEnumType());
        result.append("#");
        result.append(node.getData()[i].toIntValue());
      } else if (t == ValueType.stringType) {
        result.append("\"");
        result.append(node.getData()[i].toStringValue());
        result.append("\"");
      }
    }
    result.append(']');

    return result.toString().trim();
  }
  /**
   * Define a probability.
   *
   * @param line The line to define the probability.
   */
  public void defineProbability(String line) {
    int index = line.lastIndexOf('=');
    boolean error = false;
    double prob = 0.0;
    String left = "";
    String right = "";

    if (index != -1) {
      left = line.substring(0, index);
      right = line.substring(index + 1);

      try {
        prob = CSVFormat.EG_FORMAT.parse(right);
      } catch (NumberFormatException ex) {
        error = true;
      }
    }

    if (error || index == -1) {
      throw new BayesianError(
          "Probability must be of the form \"P(event|condition1,condition2,etc.)=0.5\".  Conditions are optional.");
    }
    defineProbability(left, prob);
  }
Exemple #5
0
 /**
  * Set a property as a double.
  *
  * @param name The name of the property.
  * @param d The value of the property.
  */
 @Override
 public void setProperty(final String name, final double d) {
   this.properties.put(name, "" + CSVFormat.EG_FORMAT.format(d, Encog.DEFAULT_PRECISION));
   updateProperties();
 }
  /** {@inheritDoc} */
  @Override
  public Object read(final InputStream is) {
    final BasicNetwork result = new BasicNetwork();
    final FlatNetwork flat = new FlatNetwork();
    final EncogReadHelper in = new EncogReadHelper(is);
    EncogFileSection section;

    while ((section = in.readNextSection()) != null) {
      if (section.getSectionName().equals("BASIC")
          && section.getSubSectionName().equals("PARAMS")) {
        final Map<String, String> params = section.parseParams();
        result.getProperties().putAll(params);
      }
      if (section.getSectionName().equals("BASIC")
          && section.getSubSectionName().equals("NETWORK")) {
        final Map<String, String> params = section.parseParams();

        flat.setBeginTraining(EncogFileSection.parseInt(params, BasicNetwork.TAG_BEGIN_TRAINING));
        flat.setConnectionLimit(
            EncogFileSection.parseDouble(params, BasicNetwork.TAG_CONNECTION_LIMIT));
        flat.setContextTargetOffset(
            EncogFileSection.parseIntArray(params, BasicNetwork.TAG_CONTEXT_TARGET_OFFSET));
        flat.setContextTargetSize(
            EncogFileSection.parseIntArray(params, BasicNetwork.TAG_CONTEXT_TARGET_SIZE));
        flat.setEndTraining(EncogFileSection.parseInt(params, BasicNetwork.TAG_END_TRAINING));
        flat.setHasContext(EncogFileSection.parseBoolean(params, BasicNetwork.TAG_HAS_CONTEXT));
        flat.setInputCount(EncogFileSection.parseInt(params, PersistConst.INPUT_COUNT));
        flat.setLayerCounts(EncogFileSection.parseIntArray(params, BasicNetwork.TAG_LAYER_COUNTS));
        flat.setLayerFeedCounts(
            EncogFileSection.parseIntArray(params, BasicNetwork.TAG_LAYER_FEED_COUNTS));
        flat.setLayerContextCount(
            EncogFileSection.parseIntArray(params, BasicNetwork.TAG_LAYER_CONTEXT_COUNT));
        flat.setLayerIndex(EncogFileSection.parseIntArray(params, BasicNetwork.TAG_LAYER_INDEX));
        flat.setLayerOutput(section.parseDoubleArray(params, PersistConst.OUTPUT));
        flat.setLayerSums(new double[flat.getLayerOutput().length]);
        flat.setOutputCount(EncogFileSection.parseInt(params, PersistConst.OUTPUT_COUNT));
        flat.setWeightIndex(EncogFileSection.parseIntArray(params, BasicNetwork.TAG_WEIGHT_INDEX));
        flat.setWeights(section.parseDoubleArray(params, PersistConst.WEIGHTS));
        flat.setBiasActivation(section.parseDoubleArray(params, BasicNetwork.TAG_BIAS_ACTIVATION));
      } else if (section.getSectionName().equals("BASIC")
          && section.getSubSectionName().equals("ACTIVATION")) {
        int index = 0;

        flat.setActivationFunctions(new ActivationFunction[flat.getLayerCounts().length]);

        for (final String line : section.getLines()) {
          ActivationFunction af = null;
          final List<String> cols = EncogFileSection.splitColumns(line);

          // if this is a class name with a path, then do not default to inside of the Encog
          // package.
          String name;
          if (cols.get(0).indexOf('.') != -1) {
            name = cols.get(0);
          } else {
            name = "org.encog.engine.network.activation." + cols.get(0);
          }

          try {
            final Class<?> clazz = Class.forName(name);
            af = (ActivationFunction) clazz.newInstance();
          } catch (final ClassNotFoundException e) {
            throw new PersistError(e);
          } catch (final InstantiationException e) {
            throw new PersistError(e);
          } catch (final IllegalAccessException e) {
            throw new PersistError(e);
          }

          for (int i = 0; i < af.getParamNames().length; i++) {
            af.setParam(i, CSVFormat.EG_FORMAT.parse(cols.get(i + 1)));
          }

          flat.getActivationFunctions()[index++] = af;
        }
      }
    }

    result.getStructure().setFlat(flat);
    result.updateProperties();
    return result;
  }
  @Override
  public Object read(final InputStream is) {
    long nextInnovationID = 0;
    long nextGeneID = 0;

    final NEATPopulation result = new NEATPopulation();
    final NEATInnovationList innovationList = new NEATInnovationList();
    innovationList.setPopulation(result);
    result.setInnovations(innovationList);
    final EncogReadHelper in = new EncogReadHelper(is);
    EncogFileSection section;

    while ((section = in.readNextSection()) != null) {
      if (section.getSectionName().equals("NEAT-POPULATION")
          && section.getSubSectionName().equals("INNOVATIONS")) {
        for (final String line : section.getLines()) {
          final List<String> cols = EncogFileSection.splitColumns(line);
          final NEATInnovation innovation = new NEATInnovation();
          final int innovationID = Integer.parseInt(cols.get(1));
          innovation.setInnovationID(innovationID);
          innovation.setNeuronID(Integer.parseInt(cols.get(2)));
          result.getInnovations().getInnovations().put(cols.get(0), innovation);
          nextInnovationID = Math.max(nextInnovationID, innovationID + 1);
        }
      } else if (section.getSectionName().equals("NEAT-POPULATION")
          && section.getSubSectionName().equals("SPECIES")) {
        NEATGenome lastGenome = null;
        BasicSpecies lastSpecies = null;

        for (final String line : section.getLines()) {
          final List<String> cols = EncogFileSection.splitColumns(line);

          if (cols.get(0).equalsIgnoreCase("s")) {
            lastSpecies = new BasicSpecies();
            lastSpecies.setPopulation(result);
            lastSpecies.setAge(Integer.parseInt(cols.get(1)));
            lastSpecies.setBestScore(CSVFormat.EG_FORMAT.parse(cols.get(2)));
            lastSpecies.setGensNoImprovement(Integer.parseInt(cols.get(3)));
            result.getSpecies().add(lastSpecies);
          } else if (cols.get(0).equalsIgnoreCase("g")) {
            final boolean isLeader = lastGenome == null;
            lastGenome = new NEATGenome();
            lastGenome.setInputCount(result.getInputCount());
            lastGenome.setOutputCount(result.getOutputCount());
            lastGenome.setSpecies(lastSpecies);
            lastGenome.setAdjustedScore(CSVFormat.EG_FORMAT.parse(cols.get(1)));
            lastGenome.setScore(CSVFormat.EG_FORMAT.parse(cols.get(2)));
            lastGenome.setBirthGeneration(Integer.parseInt(cols.get(3)));
            lastSpecies.add(lastGenome);
            if (isLeader) {
              lastSpecies.setLeader(lastGenome);
            }
          } else if (cols.get(0).equalsIgnoreCase("n")) {
            final NEATNeuronGene neuronGene = new NEATNeuronGene();
            final int geneID = Integer.parseInt(cols.get(1));
            neuronGene.setId(geneID);

            final ActivationFunction af = EncogFileSection.parseActivationFunction(cols.get(2));
            neuronGene.setActivationFunction(af);

            neuronGene.setNeuronType(PersistNEATPopulation.stringToNeuronType(cols.get(3)));
            neuronGene.setInnovationId(Integer.parseInt(cols.get(4)));
            lastGenome.getNeuronsChromosome().add(neuronGene);
            nextGeneID = Math.max(geneID + 1, nextGeneID);
          } else if (cols.get(0).equalsIgnoreCase("l")) {
            final NEATLinkGene linkGene = new NEATLinkGene();
            linkGene.setId(Integer.parseInt(cols.get(1)));
            linkGene.setEnabled(Integer.parseInt(cols.get(2)) > 0);
            linkGene.setFromNeuronID(Integer.parseInt(cols.get(3)));
            linkGene.setToNeuronID(Integer.parseInt(cols.get(4)));
            linkGene.setWeight(CSVFormat.EG_FORMAT.parse(cols.get(5)));
            linkGene.setInnovationId(Integer.parseInt(cols.get(6)));
            lastGenome.getLinksChromosome().add(linkGene);
          }
        }

      } else if (section.getSectionName().equals("NEAT-POPULATION")
          && section.getSubSectionName().equals("CONFIG")) {
        final Map<String, String> params = section.parseParams();

        final String afStr = params.get(NEATPopulation.PROPERTY_NEAT_ACTIVATION);

        if (afStr.equalsIgnoreCase(PersistNEATPopulation.TYPE_CPPN)) {
          HyperNEATGenome.buildCPPNActivationFunctions(result.getActivationFunctions());
        } else {
          result.setNEATActivationFunction(
              EncogFileSection.parseActivationFunction(
                  params, NEATPopulation.PROPERTY_NEAT_ACTIVATION));
        }

        result.setActivationCycles(
            EncogFileSection.parseInt(params, PersistConst.ACTIVATION_CYCLES));
        result.setInputCount(EncogFileSection.parseInt(params, PersistConst.INPUT_COUNT));
        result.setOutputCount(EncogFileSection.parseInt(params, PersistConst.OUTPUT_COUNT));
        result.setPopulationSize(
            EncogFileSection.parseInt(params, NEATPopulation.PROPERTY_POPULATION_SIZE));
        result.setSurvivalRate(
            EncogFileSection.parseDouble(params, NEATPopulation.PROPERTY_SURVIVAL_RATE));
        result.setActivationCycles(
            EncogFileSection.parseInt(params, NEATPopulation.PROPERTY_CYCLES));
      }
    }

    // set factories
    if (result.isHyperNEAT()) {
      result.setGenomeFactory(new FactorHyperNEATGenome());
      result.setCODEC(new HyperNEATCODEC());
    } else {
      result.setGenomeFactory(new FactorNEATGenome());
      result.setCODEC(new NEATCODEC());
    }

    // set the next ID's
    result.getInnovationIDGenerate().setCurrentID(nextInnovationID);
    result.getGeneIDGenerate().setCurrentID(nextGeneID);

    // find first genome, which should be the best genome
    if (result.getSpecies().size() > 0) {
      final Species species = result.getSpecies().get(0);
      if (species.getMembers().size() > 0) {
        result.setBestGenome(species.getMembers().get(0));
      }
    }

    return result;
  }
  /** {@inheritDoc} */
  @Override
  public Object read(final InputStream is) {
    final RBFNetwork result = new RBFNetwork();
    final FlatNetworkRBF flat = (FlatNetworkRBF) result.getFlat();

    final EncogReadHelper in = new EncogReadHelper(is);
    EncogFileSection section;

    while ((section = in.readNextSection()) != null) {
      if (section.getSectionName().equals("RBF-NETWORK")
          && section.getSubSectionName().equals("PARAMS")) {
        final Map<String, String> params = section.parseParams();
        result.getProperties().putAll(params);
      }
      if (section.getSectionName().equals("RBF-NETWORK")
          && section.getSubSectionName().equals("NETWORK")) {
        final Map<String, String> params = section.parseParams();

        flat.setBeginTraining(EncogFileSection.parseInt(params, BasicNetwork.TAG_BEGIN_TRAINING));
        flat.setConnectionLimit(
            EncogFileSection.parseDouble(params, BasicNetwork.TAG_CONNECTION_LIMIT));
        flat.setContextTargetOffset(
            EncogFileSection.parseIntArray(params, BasicNetwork.TAG_CONTEXT_TARGET_OFFSET));
        flat.setContextTargetSize(
            EncogFileSection.parseIntArray(params, BasicNetwork.TAG_CONTEXT_TARGET_SIZE));
        flat.setEndTraining(EncogFileSection.parseInt(params, BasicNetwork.TAG_END_TRAINING));
        flat.setHasContext(EncogFileSection.parseBoolean(params, BasicNetwork.TAG_HAS_CONTEXT));
        flat.setInputCount(EncogFileSection.parseInt(params, PersistConst.INPUT_COUNT));
        flat.setLayerCounts(EncogFileSection.parseIntArray(params, BasicNetwork.TAG_LAYER_COUNTS));
        flat.setLayerFeedCounts(
            EncogFileSection.parseIntArray(params, BasicNetwork.TAG_LAYER_FEED_COUNTS));
        flat.setLayerContextCount(
            EncogFileSection.parseIntArray(params, BasicNetwork.TAG_LAYER_CONTEXT_COUNT));
        flat.setLayerIndex(EncogFileSection.parseIntArray(params, BasicNetwork.TAG_LAYER_INDEX));
        flat.setLayerOutput(section.parseDoubleArray(params, PersistConst.OUTPUT));
        flat.setLayerSums(new double[flat.getLayerOutput().length]);
        flat.setOutputCount(EncogFileSection.parseInt(params, PersistConst.OUTPUT_COUNT));
        flat.setWeightIndex(EncogFileSection.parseIntArray(params, BasicNetwork.TAG_WEIGHT_INDEX));
        flat.setWeights(section.parseDoubleArray(params, PersistConst.WEIGHTS));
        flat.setBiasActivation(section.parseDoubleArray(params, BasicNetwork.TAG_BIAS_ACTIVATION));
      } else if (section.getSectionName().equals("RBF-NETWORK")
          && section.getSubSectionName().equals("ACTIVATION")) {
        int index = 0;

        flat.setActivationFunctions(new ActivationFunction[flat.getLayerCounts().length]);

        for (final String line : section.getLines()) {
          ActivationFunction af = null;
          final List<String> cols = EncogFileSection.splitColumns(line);
          final String name = "org.encog.engine.network.activation." + cols.get(0);
          try {
            final Class<?> clazz = Class.forName(name);
            af = (ActivationFunction) clazz.newInstance();
          } catch (final ClassNotFoundException e) {
            throw new PersistError(e);
          } catch (final InstantiationException e) {
            throw new PersistError(e);
          } catch (final IllegalAccessException e) {
            throw new PersistError(e);
          }

          for (int i = 0; i < af.getParamNames().length; i++) {
            af.setParam(i, CSVFormat.EG_FORMAT.parse(cols.get(i + 1)));
          }

          flat.getActivationFunctions()[index++] = af;
        }

      } else if (section.getSectionName().equals("RBF-NETWORK")
          && section.getSubSectionName().equals("RBF")) {
        int index = 0;

        final int hiddenCount = flat.getLayerCounts()[1];
        final int inputCount = flat.getLayerCounts()[2];

        flat.setRBF(new RadialBasisFunction[hiddenCount]);

        for (final String line : section.getLines()) {
          RadialBasisFunction rbf = null;
          final List<String> cols = EncogFileSection.splitColumns(line);
          final String name = "org.encog.mathutil.rbf." + cols.get(0);
          try {
            final Class<?> clazz = Class.forName(name);
            rbf = (RadialBasisFunction) clazz.newInstance();
          } catch (final ClassNotFoundException e) {
            throw new PersistError(e);
          } catch (final InstantiationException e) {
            throw new PersistError(e);
          } catch (final IllegalAccessException e) {
            throw new PersistError(e);
          }

          rbf.setWidth(CSVFormat.EG_FORMAT.parse(cols.get(1)));
          rbf.setPeak(CSVFormat.EG_FORMAT.parse(cols.get(2)));
          rbf.setCenters(new double[inputCount]);

          for (int i = 0; i < inputCount; i++) {
            rbf.getCenters()[i] = CSVFormat.EG_FORMAT.parse(cols.get(i + 3));
          }

          flat.getRBF()[index++] = rbf;
        }
      }
    }

    return result;
  }