001/* 002 * Java Genetic Algorithm Library (jenetics-7.0.0). 003 * Copyright (c) 2007-2022 Franz Wilhelmstötter 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 * 017 * Author: 018 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com) 019 */ 020package io.jenetics.prog.op; 021 022import static java.lang.String.format; 023import static io.jenetics.ext.internal.Names.isIdentifier; 024 025import java.io.Serial; 026import java.io.Serializable; 027import java.util.HashMap; 028import java.util.Map; 029import java.util.Objects; 030import java.util.SortedSet; 031import java.util.TreeSet; 032import java.util.regex.Matcher; 033import java.util.regex.Pattern; 034import java.util.stream.Collectors; 035 036import io.jenetics.ext.util.Tree; 037import io.jenetics.ext.util.TreeNode; 038 039/** 040 * Represents the program variables. The {@code Var} operation is a 041 * <em>terminal</em> operation, which just returns the value with the defined 042 * index of the input variable array. It is essentially an orthogonal projection 043 * of the <em>n</em>-dimensional input space to the <em>1</em>-dimensional 044 * result space. 045 * 046 * <pre>{@code 047 * final ISeq<? extends Op<Double>> operations = ISeq.of(...); 048 * final ISeq<? extends Op<Double>> terminals = ISeq.of( 049 * Var.of("x", 0), Var.of("y", 1) 050 * ); 051 * }</pre> 052 * 053 * The example above shows how to define the terminal operations for a GP, which 054 * tries to optimize a 2-dimensional function. 055 * 056 * <pre>{@code 057 * static double error(final ProgramChromosome<Double> program) { 058 * final double x = ...; 059 * final double y = ...; 060 * final double result = program.eval(x, y); 061 * ... 062 * return ...; 063 * } 064 * }</pre> 065 * 066 * @implNote 067 * The {@code Var} object is comparable according it's name. 068 * 069 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> 070 * @version 7.0 071 * @since 3.9 072 */ 073public final class Var<T> implements Op<T>, Comparable<Var<T>>, Serializable { 074 075 @Serial 076 private static final long serialVersionUID = 1L; 077 078 private final String _name; 079 private final int _index; 080 081 /** 082 * Create a new variable with the given {@code name} and projection 083 * {@code index}. 084 * 085 * @param name the variable name. Used when printing the operation tree 086 * (program) 087 * @param index the projection index 088 * @throws IllegalArgumentException if the given {@code name} is not a valid 089 * Java identifier 090 * @throws IndexOutOfBoundsException if the projection {@code index} is 091 * smaller than zero 092 * @throws NullPointerException if the given variable {@code name} is 093 * {@code null} 094 */ 095 private Var(final String name, final int index) { 096 if (!isIdentifier(name)) { 097 throw new IllegalArgumentException(format( 098 "'%s' is not a valid identifier.", name 099 )); 100 } 101 if (index < 0) { 102 throw new IndexOutOfBoundsException( 103 "Index smaller than zero: " + index 104 ); 105 } 106 107 _name = name; 108 _index = index; 109 } 110 111 /** 112 * The projection index of the variable. 113 * 114 * @return the projection index of the variable 115 */ 116 public int index() { 117 return _index; 118 } 119 120 @Override 121 public String name() { 122 return _name; 123 } 124 125 @Override 126 public int arity() { 127 return 0; 128 } 129 130 @Override 131 public T apply(final T[] variables) { 132 return variables[_index]; 133 } 134 135 @Override 136 public int compareTo(final Var<T> o) { 137 return _name.compareTo(o._name); 138 } 139 140 @Override 141 public int hashCode() { 142 return Objects.hashCode(_name); 143 } 144 145 @Override 146 public boolean equals(final Object obj) { 147 return obj == this || 148 obj instanceof Var<?> other && 149 Objects.equals(other._name, _name); 150 } 151 152 @Override 153 public String toString() { 154 return _name; 155 } 156 157 /** 158 * Create a new variable with the given {@code name} and projection 159 * {@code index}. 160 * 161 * @see #parse(String) 162 * 163 * @param name the variable name. Used when printing the operation tree 164 * (program) 165 * @param index the projection index 166 * @param <T> the variable type 167 * @return a new variable with the given {@code name} and projection 168 * {@code index} 169 * @throws IllegalArgumentException if the given {@code name} is not a valid 170 * Java identifier 171 * @throws IndexOutOfBoundsException if the projection {@code index} is 172 * smaller than zero 173 * @throws NullPointerException if the given variable {@code name} is 174 * {@code null} 175 */ 176 public static <T> Var<T> of(final String name, final int index) { 177 return new Var<>(name, index); 178 } 179 180 /** 181 * Create a new variable with the given {@code name}. The projection index 182 * is set to zero. Always prefer to create new variables with 183 * {@link #of(String, int)}, especially when you define your terminal 184 * operation for your GP problem. 185 * 186 * @see #parse(String) 187 * 188 * @param name the variable name. Used when printing the operation tree 189 * (program) 190 * @param <T> the variable type 191 * @return a new variable with the given {@code name} and projection index 192 * zero 193 * @throws IllegalArgumentException if the given {@code name} is not a valid 194 * Java identifier 195 * @throws NullPointerException if the given variable {@code name} is 196 * {@code null} 197 */ 198 public static <T> Var<T> of(final String name) { 199 return new Var<>(name, 0); 200 } 201 202 private static final Pattern VAR_INDEX = Pattern.compile("(.+)\\[\\s*(\\d+)\\s*]"); 203 204 /** 205 * Parses the given variable string to its name and index. The expected 206 * format is <em>var_name</em>[<em>index</em>]. 207 * 208 * <pre> {@code 209 * x[0] 210 * y[3] 211 * my_var[4] 212 * }</pre> 213 * 214 * If no variable <em>index</em> is encoded in the name, a variable with 215 * index 0 is created. 216 * 217 * @see #of(String, int) 218 * 219 * @param name the variable name + index 220 * @param <T> the operation type 221 * @return a new variable parsed from the input string 222 * @throws IllegalArgumentException if the given variable couldn't be parsed 223 * and the given {@code name} is not a valid Java identifier 224 * @throws NullPointerException if the given variable {@code name} is 225 * {@code null} 226 */ 227 public static <T> Var<T> parse(final String name) { 228 final Matcher matcher = VAR_INDEX.matcher(name); 229 230 return matcher.matches() 231 ? of(matcher.group(1), Integer.parseInt(matcher.group(2))) 232 : of(name, 0); 233 } 234 235 /** 236 * Re-indexes the variables of the given operation {@code tree}. If the 237 * operation tree is created from it's string representation, the indices 238 * of the variables ({@link Var}), are all set to zero, since it needs the 239 * whole tree for setting the indices correctly. The mapping from the node 240 * string to the {@link Op} object, on the other hand, is a <em>local</em> 241 * operation. This method gives you the possibility to fix the indices of 242 * the variables. The indices of the variables are assigned according it's 243 * <em>natural</em> order. 244 * 245 * <pre>{@code 246 * final TreeNode<Op<Double>> tree = TreeNode.parse( 247 * "add(mul(x,y),sub(y,x))", 248 * MathOp::toMathOp 249 * ); 250 * 251 * assert Program.eval(tree, 10.0, 5.0) == 100.0; // wrong result 252 * Var.reindex(tree); 253 * assert Program.eval(tree, 10.0, 5.0) == 45.0; // correct result 254 * }</pre> 255 * The example above shows a use-case of this method. If you parse a tree 256 * string and convert it to an operation tree, you have to re-index the 257 * variables first. If not, you will get the wrong result when evaluating 258 * the tree. After the re-indexing you will get the correct result of 45.0. 259 * 260 * @since 5.0 261 * 262 * @see MathOp#toMathOp(String) 263 * @see Program#eval(Tree, Object[]) 264 * 265 * @param tree the tree where the variable indices needs to be fixed 266 * @param <V> the operation value type 267 */ 268 public static <V> void reindex(final TreeNode<Op<V>> tree) { 269 final SortedSet<Var<V>> vars = tree.stream() 270 .filter(node -> node.value() instanceof Var) 271 .map(node -> (Var<V>)node.value()) 272 .collect(Collectors.toCollection(TreeSet::new)); 273 274 int index = 0; 275 final Map<Var<V>, Integer> indexes = new HashMap<>(); 276 for (Var<V> var : vars) { 277 indexes.put(var, index++); 278 } 279 280 reindex(tree, indexes); 281 } 282 283 /** 284 * Re-indexes the variables of the given operation {@code tree}. If the 285 * operation tree is created from it's string representation, the indices 286 * of the variables ({@link Var}), are all set to zero, since it needs the 287 * whole tree for setting the indices correctly. 288 * 289 * <pre>{@code 290 * final TreeNode<Op<Double>> tree = TreeNode.parse( 291 * "add(mul(x,y),sub(y,x))", 292 * MathOp::toMathOp 293 * ); 294 * 295 * assert Program.eval(tree, 10.0, 5.0) == 100.0; // wrong result 296 * final Map<Var<Double>, Integer> indexes = new HashMap<>(); 297 * indexes.put(Var.of("x"), 0); 298 * indexes.put(Var.of("y"), 1); 299 * Var.reindex(tree, indexes); 300 * assert Program.eval(tree, 10.0, 5.0) == 45.0; // correct result 301 * }</pre> 302 * The example above shows a use-case of this method. If you parse a tree 303 * string and convert it to an operation tree, you have to re-index the 304 * variables first. If not, you will get the wrong result when evaluating 305 * the tree. After the re-indexing you will get the correct result of 45.0. 306 * 307 * @since 5.0 308 * 309 * @see MathOp#toMathOp(String) 310 * @see BoolOp#toBoolOp(String) 311 * @see Program#eval(Tree, Object[]) 312 * 313 * @param tree the tree where the variable indices needs to be fixed 314 * @param indexes the variable to index mapping 315 * @param <V> the operation value type 316 */ 317 public static <V> void reindex( 318 final TreeNode<Op<V>> tree, 319 final Map<Var<V>, Integer> indexes 320 ) { 321 for (TreeNode<Op<V>> node : tree) { 322 final Op<V> op = node.value(); 323 if (op instanceof Var) { 324 node.value(Var.of(op.name(), indexes.get(op))); 325 } 326 } 327 } 328 329}