com.github.chen0040.gp.treegp.program.TreeNode Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-genetic-programming Show documentation
Show all versions of java-genetic-programming Show documentation
Genetic Programming in Java, including packages on Linear Genetic Programming
package com.github.chen0040.gp.treegp.program;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by xschen on 12/5/2017.
*/
@Getter
@Setter
public class TreeNode implements Serializable {
private static final long serialVersionUID = 350057284330815219L;
private Primitive primitive;
@Setter(AccessLevel.NONE)
private final List children = new ArrayList<>();
public TreeNode(Primitive primitive){
assert primitive != null;
this.primitive = primitive;
}
public TreeNode(){
}
public int arity(){
return primitive.arity();
}
public int length(){
int lengthSoFar = 1;
for(TreeNode node : children){
lengthSoFar+=node.length();
}
return lengthSoFar;
}
public int depth(){
return depth(this, 0);
}
private static int depth(TreeNode node, int depthSoFar){
int maxDepth = depthSoFar;
for(TreeNode child : node.children){
int depth = depth(child, depthSoFar+1);
maxDepth = Math.max(maxDepth, depth);
}
return maxDepth;
}
public double execute(Object... tags) {
int count = arity();
List inputs = new ArrayList<>();
for(int i=0; i "))
{
sb.append("if(").append(children.get(0).mathExpression())
.append(symbol.equals("if<") ? " < " : " > ").append(children.get(1).mathExpression())
.append(", ").append(children.get(2).mathExpression())
.append(", ").append(children.get(3).mathExpression())
.append(")");
}
else
{
sb.append("(").append(symbol);
sb.append(" ");
for (int i = 0; i < arity; ++i)
{
if (i != 0)
{
sb.append(", ");
}
sb.append(children.get(i).mathExpression());
}
sb.append(")");
}
}
else
{
sb.append("(").append(primitive.getSymbol());
sb.append(" ");
for (int i = 0; i < arity; ++i)
{
if (i != 0)
{
sb.append(", ");
}
sb.append(children.get(i).mathExpression());
}
sb.append(")");
}
return sb.toString();
}
}
public List flatten(){
List result = new ArrayList<>();
collect(this, result);
return result;
}
private void collect(TreeNode node, List list) {
list.add(node.primitive);
for(TreeNode child : node.children){
collect(child, list);
}
}
public int depth2Node(TreeNode node){
return depth2Node(this, node, 0);
}
public static int depth2Node(TreeNode node, TreeNode target, int depthSoFar)
{
if (node == target)
{
return depthSoFar;
}
int maxDepthOfChild = -1;
for (TreeNode child_node :node.children)
{
int d = depth2Node(child_node, target, depthSoFar + 1);
if (d > maxDepthOfChild)
{
maxDepthOfChild = d;
}
}
return maxDepthOfChild;
}
}