Changeset 9601
- Timestamp:
- 06/10/13 15:48:19 (12 years ago)
- Location:
- branches/Robocode/HeuristicLab.Problems.Robocode
- Files:
-
- 3 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/Robocode/HeuristicLab.Problems.Robocode/Interpreter.cs
r9565 r9601 1 1 using System; 2 using System.Collections.Generic; 2 using System.Diagnostics; 3 using System.IO; 3 4 using System.Linq; 4 5 using System.Text; 5 using System. Threading.Tasks;6 using System.IO;6 using System.Xml; 7 using HeuristicLab.Core; 7 8 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; 8 using System.Xml; 9 using System.Diagnostics; 10 using HeuristicLab.PluginInfrastructure; 11 using HeuristicLab.Core; 12 using System.Threading; 13 14 namespace HeuristicLab.Problems.Robocode 15 { 16 public class Interpreter 17 { 18 19 private struct TankStats 20 { 21 public int moves , shots; 22 public TankStats(int moves, int shots) 23 { 24 this.moves = moves; 25 this.shots = shots; 26 } 9 10 namespace HeuristicLab.Problems.Robocode { 11 public class Interpreter { 12 13 private struct TankStats { 14 public int moves, shots; 15 public TankStats(int moves, int shots) { 16 this.moves = moves; 17 this.shots = shots; 18 } 19 } 20 static string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 21 22 public static string BuildTankProgram(ISymbolicExpressionTree tree) { 23 XmlDocument solutionCandidateRoot = new XmlDocument(); 24 solutionCandidateRoot.Load("../tank.xml"); 25 26 TankStats tankStats = EvaluateTankProgram(tree.Root, solutionCandidateRoot.FirstChild, null); 27 return solutionCandidateRoot.InnerText; 28 } 29 30 public static double EvaluateTankProgram(ISymbolicExpressionTree tree, XmlNode solutionCandidateRoot, string path) { 31 //TankStats tankStats = EvaluateTankProgram(tree.Root, solutionCandidateRoot, null); 32 //Evaluator.tankStatLog += "\r\n" + tankStats.shots + " / " + tankStats.moves; 33 string interpretedProgram = InterpretProgramTree(tree.Root); 34 Random random = new Random(); 35 string formattedPath = path.Replace("/", "\\"); 36 string outputname = ""; 37 string output = ""; 38 bool noError = true; 39 do { 40 try { 41 outputname = new string(Enumerable.Repeat(chars, 8).Select(s => s[random.Next(s.Length)]).ToArray()); 42 output = /*solutionCandidateRoot.InnerText*/interpretedProgram.Replace("class output", "class " + outputname); 43 File.WriteAllText(path + "/robots/Evaluation/" + outputname + ".java", output, System.Text.Encoding.Default); 44 noError = true; 27 45 } 28 static string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 29 30 public static string BuildTankProgram(ISymbolicExpressionTree tree) 31 { 32 XmlDocument solutionCandidateRoot = new XmlDocument(); 33 solutionCandidateRoot.Load("../tank.xml"); 34 35 TankStats tankStats = EvaluateTankProgram(tree.Root, solutionCandidateRoot.FirstChild, null); 36 return solutionCandidateRoot.InnerText; 46 catch (Exception e) { noError = false; } 47 } while (!noError); 48 49 //string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); 50 //path.Replace("\\", "\\\\"); 51 //path.Replace(" ", "\\ "); 52 #region Compile code file 53 54 ProcessStartInfo javaCompileInfo = new ProcessStartInfo(); 55 javaCompileInfo.FileName = "cmd.exe"; 56 javaCompileInfo.Arguments = "/C javac -cp " + formattedPath + "\\libs\\robocode.jar " + formattedPath + "\\robots\\Evaluation\\" + outputname + ".java"; 57 javaCompileInfo.RedirectStandardOutput = true; 58 javaCompileInfo.RedirectStandardError = true; 59 javaCompileInfo.UseShellExecute = false; 60 javaCompileInfo.CreateNoWindow = true; 61 62 Process javaCompile = new Process(); 63 javaCompile.StartInfo = javaCompileInfo; 64 javaCompile.Start(); 65 66 /*Evaluator.tankStatLog = "=====================================================\r\n"; 67 Evaluator.tankStatLog += "Tree Compilation Output: \r\n"; 68 Evaluator.tankStatLog += "=====================================================\r\n";*/ 69 70 string cmdOutput = javaCompile.StandardOutput.ReadToEnd(); 71 cmdOutput += javaCompile.StandardError.ReadToEnd(); 72 //Evaluator.tankStatLog += cmdOutput; 73 //Console.WriteLine(cmdOutput); 74 //Console.ReadLine(); 75 76 /*Evaluator.tankStatLog = "=====================================================\r\n"; 77 Evaluator.tankStatLog += "End of Tree Compilation Output: \r\n"; 78 Evaluator.tankStatLog += "=====================================================\r\n";*/ 79 80 javaCompile.WaitForExit(); 81 #endregion 82 83 84 try { File.Delete(path + "/robots/robot.database"); } 85 catch (Exception e) { } 86 87 #region evaluate code 88 89 ProcessStartInfo evaluateCodeInfo = new ProcessStartInfo(); 90 evaluateCodeInfo.FileName = "cmd.exe"; 91 //javaCompileInfo.Arguments = "/C javac -cp C:\\robocode\\libs\\robocode.jar \"" + path + "\\Spaced Up\\output.java\""; 92 evaluateCodeInfo.Arguments = "/C java -classpath " + formattedPath + "\\libs;" + formattedPath + "\\libs\\robocode.core-1.8.1.0.jar;" + formattedPath + "\\libs\\robocode.jar;" + formattedPath + "\\libs\\picocontainer-2.14.2.jar BattleRunner Evaluation." + outputname + "* false"; 93 //Console.WriteLine(javaCompileInfo.Arguments); 94 evaluateCodeInfo.RedirectStandardOutput = true; 95 evaluateCodeInfo.RedirectStandardError = true; 96 evaluateCodeInfo.UseShellExecute = false; 97 evaluateCodeInfo.CreateNoWindow = true; 98 99 Process evaluateCode = new Process(); 100 evaluateCode.StartInfo = evaluateCodeInfo; 101 evaluateCode.Start(); 102 103 // instead of p.WaitForExit(), do 104 StringBuilder q = new StringBuilder(); 105 string scoreString = ""; 106 while (!evaluateCode.HasExited) { 107 scoreString = evaluateCode.StandardOutput.ReadToEnd().Split( 108 new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).Last(); 109 q.Append("Output: " + scoreString + "\r\n"); 110 q.Append("Error: " + evaluateCode.StandardError.ReadToEnd() + "\r\n"); 111 } 112 cmdOutput += q.ToString(); 113 114 #endregion 115 116 double evaluation = -900; 117 try { 118 File.Delete(path + "/robots/Evaluation/" + outputname + ".java"); 119 File.Delete(path + "/robots/Evaluation/" + outputname + ".class"); 120 evaluation = Double.Parse(scoreString); 121 } 122 catch (Exception e) { evaluation = -900; } 123 Random rand = new Random(); 124 evaluation += rand.NextDouble() / 100; 125 126 /*Evaluator.tankStatLog = "=====================================================\r\n"; 127 Evaluator.tankStatLog += "START OF TREE - Score: " + evaluation + " (" + tankStats.shots + "/" + tankStats.moves + ")" + "\r\n" + " Compilation Output: " + cmdOutput + "\r\n"; 128 Evaluator.tankStatLog += "=====================================================\r\n"; 129 130 Evaluator.tankStatLog += solutionCandidateRoot.InnerText + "\r\n"; 131 132 Evaluator.tankStatLog += "=====================================================\r\n"; 133 Evaluator.tankStatLog += "END OF TREE\r\n"; 134 Evaluator.tankStatLog += "=====================================================\r\n"; 135 136 File.AppendAllText("../TankLog.txt", Evaluator.tankStatLog);*/ 137 return evaluation; 138 } 139 140 public static double EvaluateTankProgram(ISymbolicExpressionTree tree, ScopeList coevolutionIndividuals, XmlNode solutionCandidateRoot, string path) { 141 Random random = new Random(); 142 string formattedPath = path.Replace("/", "\\"); 143 144 // Interpret and compile main tree 145 //XmlNode mainTreeNode = solutionCandidateRoot.Clone(); 146 //EvaluateTankProgram(tree.Root, mainTreeNode, null); 147 string interpretedMainTree = InterpretProgramTree(tree.Root); 148 string mainTreeName = writeTreeToFile(interpretedMainTree, path, random); 149 compileCodefile(/*mainTreeName,*/ mainTreeName, formattedPath); 150 151 // Interpret and compile coevolutionIndividuals 152 String[] coevolutionIndividualsNames = new String[coevolutionIndividuals.Count]; 153 for (int i = 0; i < coevolutionIndividuals.Count; i++) { 154 //XmlNode individualTreeNode = solutionCandidateRoot.Clone(); 155 //EvaluateTankProgram(((ISymbolicExpressionTree)coevolutionIndividuals[i].Variables.ToArray()[0].Value).Root, individualTreeNode, null); 156 string interpretedIndividual = InterpretProgramTree(((ISymbolicExpressionTree)coevolutionIndividuals[i].Variables.ToArray()[0].Value).Root); 157 coevolutionIndividualsNames[i] = writeTreeToFile(/*individualTreeNode,*/ interpretedIndividual, path, random); 158 compileCodefile(coevolutionIndividualsNames[i], formattedPath); 159 } 160 161 // Force Robocode to update its robot database by deleting the existing one 162 try { File.Delete(path + "/robots/robot.database"); } 163 catch (Exception e) { } 164 165 // Run evaluator 166 double evaluation = runEvaluator(mainTreeName, coevolutionIndividualsNames, formattedPath); 167 try { 168 File.Delete(path + "/robots/Evaluation/" + mainTreeName + ".java"); 169 File.Delete(path + "/robots/Evaluation/" + mainTreeName + ".class"); 170 foreach (string s in coevolutionIndividualsNames) { 171 File.Delete(path + "/robots/Evaluation/" + s + ".java"); 172 File.Delete(path + "/robots/Evaluation/" + s + ".class"); 37 173 } 38 39 public static double EvaluateTankProgram(ISymbolicExpressionTree tree, XmlNode solutionCandidateRoot, string path) 40 { 41 //TankStats tankStats = EvaluateTankProgram(tree.Root, solutionCandidateRoot, null); 42 //Evaluator.tankStatLog += "\r\n" + tankStats.shots + " / " + tankStats.moves; 43 string interpretedProgram = InterpretProgramTree(tree.Root); 44 Random random = new Random(); 45 string formattedPath = path.Replace("/", "\\"); 46 string outputname = ""; 47 string output = ""; 48 bool noError = true; 49 do 50 { 51 try 52 { 53 outputname = new string(Enumerable.Repeat(chars, 8).Select(s => s[random.Next(s.Length)]).ToArray()); 54 output = /*solutionCandidateRoot.InnerText*/interpretedProgram.Replace("class output", "class " + outputname); 55 File.WriteAllText(path + "/robots/Evaluation/" + outputname + ".java", output, System.Text.Encoding.Default); 56 noError = true; 57 } 58 catch (Exception e) { noError = false; } 59 } while (!noError); 60 61 //string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); 62 //path.Replace("\\", "\\\\"); 63 //path.Replace(" ", "\\ "); 64 #region Compile code file 65 66 ProcessStartInfo javaCompileInfo = new ProcessStartInfo(); 67 javaCompileInfo.FileName = "cmd.exe"; 68 javaCompileInfo.Arguments = "/C javac -cp " + formattedPath + "\\libs\\robocode.jar " + formattedPath + "\\robots\\Evaluation\\" + outputname + ".java"; 69 javaCompileInfo.RedirectStandardOutput = true; 70 javaCompileInfo.RedirectStandardError = true; 71 javaCompileInfo.UseShellExecute = false; 72 javaCompileInfo.CreateNoWindow = true; 73 74 Process javaCompile = new Process(); 75 javaCompile.StartInfo = javaCompileInfo; 76 javaCompile.Start(); 77 78 /*Evaluator.tankStatLog = "=====================================================\r\n"; 79 Evaluator.tankStatLog += "Tree Compilation Output: \r\n"; 80 Evaluator.tankStatLog += "=====================================================\r\n";*/ 81 82 string cmdOutput = javaCompile.StandardOutput.ReadToEnd(); 83 cmdOutput += javaCompile.StandardError.ReadToEnd(); 84 //Evaluator.tankStatLog += cmdOutput; 85 //Console.WriteLine(cmdOutput); 86 //Console.ReadLine(); 87 88 /*Evaluator.tankStatLog = "=====================================================\r\n"; 89 Evaluator.tankStatLog += "End of Tree Compilation Output: \r\n"; 90 Evaluator.tankStatLog += "=====================================================\r\n";*/ 91 92 javaCompile.WaitForExit(); 93 #endregion 94 95 96 try 97 { File.Delete(path + "/robots/robot.database"); } 98 catch (Exception e) { } 99 100 #region evaluate code 101 102 ProcessStartInfo evaluateCodeInfo = new ProcessStartInfo(); 103 evaluateCodeInfo.FileName = "cmd.exe"; 104 //javaCompileInfo.Arguments = "/C javac -cp C:\\robocode\\libs\\robocode.jar \"" + path + "\\Spaced Up\\output.java\""; 105 evaluateCodeInfo.Arguments = "/C java -classpath " + formattedPath + "\\libs;" + formattedPath + "\\libs\\robocode.core-1.8.1.0.jar;" + formattedPath + "\\libs\\robocode.jar;" + formattedPath + "\\libs\\picocontainer-2.14.2.jar BattleRunner Evaluation." + outputname + "* false"; 106 //Console.WriteLine(javaCompileInfo.Arguments); 107 evaluateCodeInfo.RedirectStandardOutput = true; 108 evaluateCodeInfo.RedirectStandardError = true; 109 evaluateCodeInfo.UseShellExecute = false; 110 evaluateCodeInfo.CreateNoWindow = true; 111 112 Process evaluateCode = new Process(); 113 evaluateCode.StartInfo = evaluateCodeInfo; 114 evaluateCode.Start(); 115 116 // instead of p.WaitForExit(), do 117 StringBuilder q = new StringBuilder(); 118 string scoreString = ""; 119 while (!evaluateCode.HasExited) 120 { 121 scoreString = evaluateCode.StandardOutput.ReadToEnd().Split( 122 new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).Last(); 123 q.Append("Output: " + scoreString + "\r\n"); 124 q.Append("Error: " + evaluateCode.StandardError.ReadToEnd() + "\r\n"); 125 } 126 cmdOutput += q.ToString(); 127 128 #endregion 129 130 double evaluation = -900; 131 try 132 { 133 File.Delete(path + "/robots/Evaluation/" + outputname + ".java"); 134 File.Delete(path + "/robots/Evaluation/" + outputname + ".class"); 135 evaluation = Double.Parse(scoreString); 136 } 137 catch (Exception e) 138 { evaluation = -900; } 139 Random rand = new Random(); 140 evaluation += rand.NextDouble()/100; 141 142 /*Evaluator.tankStatLog = "=====================================================\r\n"; 143 Evaluator.tankStatLog += "START OF TREE - Score: " + evaluation + " (" + tankStats.shots + "/" + tankStats.moves + ")" + "\r\n" + " Compilation Output: " + cmdOutput + "\r\n"; 144 Evaluator.tankStatLog += "=====================================================\r\n"; 145 146 Evaluator.tankStatLog += solutionCandidateRoot.InnerText + "\r\n"; 147 148 Evaluator.tankStatLog += "=====================================================\r\n"; 149 Evaluator.tankStatLog += "END OF TREE\r\n"; 150 Evaluator.tankStatLog += "=====================================================\r\n"; 151 152 File.AppendAllText("../TankLog.txt", Evaluator.tankStatLog);*/ 153 return evaluation; 174 } 175 catch (Exception e) { } 176 Random rand = new Random(); 177 evaluation += rand.NextDouble() / 100; 178 179 return evaluation; 180 } 181 182 private static string writeTreeToFile(/*XmlNode node,*/ string interpretedTree, string path, Random random) { 183 string outputName = ""; 184 string outputString = ""; 185 bool noError = true; 186 do { 187 try { 188 outputName = new string(Enumerable.Repeat(chars, 8).Select(s => s[random.Next(s.Length)]).ToArray()); 189 outputString = /*node.InnerText*/interpretedTree.Replace("class output", "class " + outputName); 190 File.WriteAllText(path + "/robots/Evaluation/" + outputName + ".java", outputString, System.Text.Encoding.Default); 191 noError = true; 154 192 } 155 156 public static double EvaluateTankProgram(ISymbolicExpressionTree tree, ScopeList coevolutionIndividuals, XmlNode solutionCandidateRoot, string path) 157 { 158 Random random = new Random(); 159 string formattedPath = path.Replace("/", "\\"); 160 161 // Interpret and compile main tree 162 //XmlNode mainTreeNode = solutionCandidateRoot.Clone(); 163 //EvaluateTankProgram(tree.Root, mainTreeNode, null); 164 string interpretedMainTree = InterpretProgramTree(tree.Root); 165 string mainTreeName = writeTreeToFile(interpretedMainTree, path, random); 166 compileCodefile(/*mainTreeName,*/ mainTreeName, formattedPath); 167 168 // Interpret and compile coevolutionIndividuals 169 String[] coevolutionIndividualsNames = new String[coevolutionIndividuals.Count]; 170 for (int i = 0; i < coevolutionIndividuals.Count; i++) 171 { 172 //XmlNode individualTreeNode = solutionCandidateRoot.Clone(); 173 //EvaluateTankProgram(((ISymbolicExpressionTree)coevolutionIndividuals[i].Variables.ToArray()[0].Value).Root, individualTreeNode, null); 174 string interpretedIndividual = InterpretProgramTree(((ISymbolicExpressionTree)coevolutionIndividuals[i].Variables.ToArray()[0].Value).Root); 175 coevolutionIndividualsNames[i] = writeTreeToFile(/*individualTreeNode,*/ interpretedIndividual, path, random); 176 compileCodefile(coevolutionIndividualsNames[i], formattedPath); 177 } 178 179 // Force Robocode to update its robot database by deleting the existing one 180 try 181 { File.Delete(path + "/robots/robot.database"); } 182 catch (Exception e) { } 183 184 // Run evaluator 185 double evaluation = runEvaluator(mainTreeName, coevolutionIndividualsNames, formattedPath); 186 try 187 { 188 File.Delete(path + "/robots/Evaluation/" + mainTreeName + ".java"); 189 File.Delete(path + "/robots/Evaluation/" + mainTreeName + ".class"); 190 foreach (string s in coevolutionIndividualsNames) 191 { 192 File.Delete(path + "/robots/Evaluation/" + s + ".java"); 193 File.Delete(path + "/robots/Evaluation/" + s + ".class"); 194 } 195 } 196 catch (Exception e) { } 197 Random rand = new Random(); 198 evaluation += rand.NextDouble() / 100; 199 200 return evaluation; 193 catch (Exception e) { noError = false; } 194 } while (!noError); 195 196 return outputName; 197 } 198 199 private static bool compileCodefile(string filename, string formattedPath) { 200 ProcessStartInfo javaCompileInfo = new ProcessStartInfo(); 201 javaCompileInfo.FileName = "cmd.exe"; 202 javaCompileInfo.Arguments = "/C javac -cp " + formattedPath + "\\libs\\robocode.jar " + formattedPath + "\\robots\\Evaluation\\" + filename + ".java"; 203 javaCompileInfo.RedirectStandardOutput = true; 204 javaCompileInfo.RedirectStandardError = true; 205 javaCompileInfo.UseShellExecute = false; 206 javaCompileInfo.CreateNoWindow = true; 207 208 Process javaCompile = new Process(); 209 javaCompile.StartInfo = javaCompileInfo; 210 javaCompile.Start(); 211 212 string cmdOutput = javaCompile.StandardOutput.ReadToEnd(); 213 cmdOutput += javaCompile.StandardError.ReadToEnd(); 214 215 javaCompile.WaitForExit(); 216 217 if (cmdOutput.Equals("")) 218 return true; 219 return false; 220 } 221 222 private static double runEvaluator(string mainTreeFilename, string[] coevolutionIndividualsNames, string formattedPath) { 223 ProcessStartInfo evaluateCodeInfo = new ProcessStartInfo(); 224 evaluateCodeInfo.FileName = "cmd.exe"; 225 //javaCompileInfo.Arguments = "/C javac -cp C:\\robocode\\libs\\robocode.jar \"" + path + "\\Spaced Up\\output.java\""; 226 evaluateCodeInfo.Arguments = "/C java -classpath " + formattedPath + "\\libs;" + formattedPath + "\\libs\\robocode.core-1.8.1.0.jar;" + formattedPath + "\\libs\\robocode.jar;" + formattedPath + "\\libs\\picocontainer-2.14.2.jar BattleRunner Evaluation." + mainTreeFilename + "* "; 227 if (coevolutionIndividualsNames != null) { 228 foreach (string s in coevolutionIndividualsNames) 229 evaluateCodeInfo.Arguments += "Evaluation." + s + "* "; 230 } else 231 evaluateCodeInfo.Arguments += "false"; 232 //Console.WriteLine(javaCompileInfo.Arguments); 233 evaluateCodeInfo.RedirectStandardOutput = true; 234 evaluateCodeInfo.RedirectStandardError = true; 235 evaluateCodeInfo.UseShellExecute = false; 236 evaluateCodeInfo.CreateNoWindow = true; 237 238 Process evaluateCode = new Process(); 239 evaluateCode.StartInfo = evaluateCodeInfo; 240 evaluateCode.Start(); 241 242 StringBuilder q = new StringBuilder(); 243 string scoreString = ""; 244 while (!evaluateCode.HasExited) { 245 scoreString = evaluateCode.StandardOutput.ReadToEnd().Split( 246 new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).Last(); 247 q.Append("Output: " + scoreString + "\r\n"); 248 q.Append("Error: " + evaluateCode.StandardError.ReadToEnd() + "\r\n"); 249 } 250 string cmdOutput = q.ToString(); 251 try { 252 double evaluation = Double.Parse(scoreString); 253 return evaluation; 254 } 255 catch (Exception e) { } 256 257 return -900; 258 } 259 260 private static TankStats EvaluateTankProgram(ISymbolicExpressionTreeNode node, XmlNode docNode, string method) { 261 TankStats tankStats = new TankStats(0, 0); 262 263 //string log = "Doing node: \r\n"; 264 /*if (node.Symbol is ProgramRootSymbol || 265 node.Symbol is StartSymbol) 266 tankStats = EvaluateTankProgram(node.GetSubtree(0), ref docNode, null); 267 else*/ 268 if (node.Symbol is Constant) 269 docNode[method]["code"].InnerText += " " + ((ConstantTreeNode)node).Value + " "; 270 else if (node.Symbol is ShotPower) 271 docNode[method]["code"].InnerText += " " + ((ShotPowerTreeNode)node).Value + " "; 272 else if (node.Symbol is LogicalValue) 273 docNode[method]["code"].InnerText += " " + ((BooleanTreeNode)node).Value.ToString().ToLower() + " "; 274 else if (node.Symbol is Block) { 275 docNode[method]["code"].InnerText += "{\r\n"; 276 foreach (ISymbolicExpressionTreeNode n in node.Subtrees) 277 EvaluateTankProgram(n, docNode, method); 278 docNode[method]["code"].InnerText += "}\r\n"; 279 } else if (node.Symbol is IfStatement) { 280 docNode[method]["code"].InnerText += "if("; 281 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 282 docNode[method]["code"].InnerText += ")\r\n"; 283 EvaluateTankProgram(node.GetSubtree(1), docNode, method); 284 if (node.SubtreeCount == 3) 285 EvaluateTankProgram(node.GetSubtree(2), docNode, method); 286 } else if (node.Symbol is ElseStatement) { 287 docNode[method]["code"].InnerText += "else\r\n"; 288 if (node.SubtreeCount == 1) 289 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 290 } else if (node.Symbol is WhileLoop) { 291 docNode[method]["code"].InnerText += "While("; 292 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 293 docNode[method]["code"].InnerText += ")\r\n"; 294 EvaluateTankProgram(node.GetSubtree(1), docNode, method); 295 } else if (node.Symbol is Ahead) { 296 docNode[method]["code"].InnerText += "setAhead("; 297 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 298 docNode[method]["code"].InnerText += ");\r\n"; 299 tankStats.moves = 1; 300 } else if (node.Symbol is Back) { 301 docNode[method]["code"].InnerText += "setBack("; 302 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 303 docNode[method]["code"].InnerText += ");\r\n"; 304 tankStats.moves = 1; 305 } else if (node.Symbol is SetAdjustGunForRobotTurn) { 306 docNode[method]["code"].InnerText += "setAdjustGunForRobotTurn("; 307 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 308 docNode[method]["code"].InnerText += ");\r\n"; 309 tankStats.moves = 1; 310 } else if (node.Symbol is SetAdjustRadarForGunTurn) { 311 docNode[method]["code"].InnerText += "setAdjustRadarForGunTurn("; 312 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 313 docNode[method]["code"].InnerText += ");\r\n"; 314 tankStats.moves = 1; 315 } else if (node.Symbol is SetAdjustRadarForRobotTurn) { 316 docNode[method]["code"].InnerText += "setAdjustRadarForRobotTurn("; 317 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 318 docNode[method]["code"].InnerText += ");\r\n"; 319 tankStats.moves = 1; 320 } else if (node.Symbol is TurnGunLeft) { 321 docNode[method]["code"].InnerText += "setTurnGunLeft("; 322 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 323 docNode[method]["code"].InnerText += ");\r\n"; 324 tankStats.moves = 1; 325 } else if (node.Symbol is TurnGunRight) { 326 docNode[method]["code"].InnerText += "setTurnGunRight("; 327 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 328 docNode[method]["code"].InnerText += ");\r\n"; 329 tankStats.moves = 1; 330 } else if (node.Symbol is TurnLeft) { 331 docNode[method]["code"].InnerText += "setTurnLeft("; 332 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 333 docNode[method]["code"].InnerText += ");\r\n"; 334 tankStats.moves = 1; 335 } else if (node.Symbol is TurnRadarLeft) { 336 docNode[method]["code"].InnerText += "setTurnRadarLeft("; 337 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 338 docNode[method]["code"].InnerText += ");\r\n"; 339 tankStats.moves = 1; 340 } else if (node.Symbol is TurnRadarRight) { 341 docNode[method]["code"].InnerText += "setTurnRadarRight("; 342 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 343 docNode[method]["code"].InnerText += ");\r\n"; 344 tankStats.moves = 1; 345 } else if (node.Symbol is TurnRight) { 346 docNode[method]["code"].InnerText += "setTurnRight("; 347 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 348 docNode[method]["code"].InnerText += ");\r\n"; 349 tankStats.moves = 1; 350 } else if (node.Symbol is Fire) { 351 docNode[method]["code"].InnerText += "setFire("; 352 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 353 docNode[method]["code"].InnerText += ");\r\n"; 354 tankStats.shots = 1; 355 } else if (node.Symbol is Run || 356 node.Symbol is OnBulletHit || 357 node.Symbol is OnBulletMissed || 358 node.Symbol is OnHitByBullet || 359 node.Symbol is OnHitRobot || 360 node.Symbol is OnHitWall || 361 node.Symbol is OnScannedRobot) { 362 tankStats = new TankStats(); 363 foreach (SymbolicExpressionTreeNode n in node.Subtrees) { 364 string methodName = node.Symbol.GetType().ToString().Split('.').Last(); 365 try { 366 var tempStats = EvaluateTankProgram(n, docNode, methodName); 367 tankStats.moves += tempStats.moves; 368 tankStats.shots += tempStats.shots; 369 } 370 catch (Exception e) { 371 //log += "NULL EXCEPTION ON:::::::: -" + methodName + "-\r\n"; 372 //foreach (XmlNode f in docNode[methodName]) 373 // log += f.Name + "\r\n"; 374 } 201 375 } 202 203 private static string writeTreeToFile(/*XmlNode node,*/ string interpretedTree, string path, Random random) 204 { 205 string outputName = ""; 206 string outputString = ""; 207 bool noError = true; 208 do 209 { 210 try 211 { 212 outputName = new string(Enumerable.Repeat(chars, 8).Select(s => s[random.Next(s.Length)]).ToArray()); 213 outputString = /*node.InnerText*/interpretedTree.Replace("class output", "class " + outputName); 214 File.WriteAllText(path + "/robots/Evaluation/" + outputName + ".java", outputString, System.Text.Encoding.Default); 215 noError = true; 216 } 217 catch (Exception e) { noError = false; } 218 } while (!noError); 219 220 return outputName; 376 } else if (node.Symbol is Tank) { 377 foreach (SymbolicExpressionTreeNode n in node.Subtrees) { 378 try { 379 var tempStats = EvaluateTankProgram(n, docNode, method); 380 tankStats.moves += tempStats.moves; 381 tankStats.shots += tempStats.shots; 382 } 383 catch (Exception e) { } 221 384 } 222 223 private static bool compileCodefile(string filename, string formattedPath) 224 { 225 ProcessStartInfo javaCompileInfo = new ProcessStartInfo(); 226 javaCompileInfo.FileName = "cmd.exe"; 227 javaCompileInfo.Arguments = "/C javac -cp " + formattedPath + "\\libs\\robocode.jar " + formattedPath + "\\robots\\Evaluation\\" + filename + ".java"; 228 javaCompileInfo.RedirectStandardOutput = true; 229 javaCompileInfo.RedirectStandardError = true; 230 javaCompileInfo.UseShellExecute = false; 231 javaCompileInfo.CreateNoWindow = true; 232 233 Process javaCompile = new Process(); 234 javaCompile.StartInfo = javaCompileInfo; 235 javaCompile.Start(); 236 237 string cmdOutput = javaCompile.StandardOutput.ReadToEnd(); 238 cmdOutput += javaCompile.StandardError.ReadToEnd(); 239 240 javaCompile.WaitForExit(); 241 242 if (cmdOutput.Equals("")) 243 return true; 244 return false; 245 } 246 247 private static double runEvaluator(string mainTreeFilename, string[] coevolutionIndividualsNames, string formattedPath) 248 { 249 ProcessStartInfo evaluateCodeInfo = new ProcessStartInfo(); 250 evaluateCodeInfo.FileName = "cmd.exe"; 251 //javaCompileInfo.Arguments = "/C javac -cp C:\\robocode\\libs\\robocode.jar \"" + path + "\\Spaced Up\\output.java\""; 252 evaluateCodeInfo.Arguments = "/C java -classpath " + formattedPath + "\\libs;" + formattedPath + "\\libs\\robocode.core-1.8.1.0.jar;" + formattedPath + "\\libs\\robocode.jar;" + formattedPath + "\\libs\\picocontainer-2.14.2.jar BattleRunner Evaluation." + mainTreeFilename + "* "; 253 if (coevolutionIndividualsNames != null) 254 { 255 foreach (string s in coevolutionIndividualsNames) 256 evaluateCodeInfo.Arguments += "Evaluation." + s + "* "; 257 } 258 else 259 evaluateCodeInfo.Arguments += "false"; 260 //Console.WriteLine(javaCompileInfo.Arguments); 261 evaluateCodeInfo.RedirectStandardOutput = true; 262 evaluateCodeInfo.RedirectStandardError = true; 263 evaluateCodeInfo.UseShellExecute = false; 264 evaluateCodeInfo.CreateNoWindow = true; 265 266 Process evaluateCode = new Process(); 267 evaluateCode.StartInfo = evaluateCodeInfo; 268 evaluateCode.Start(); 269 270 StringBuilder q = new StringBuilder(); 271 string scoreString = ""; 272 while (!evaluateCode.HasExited) 273 { 274 scoreString = evaluateCode.StandardOutput.ReadToEnd().Split( 275 new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).Last(); 276 q.Append("Output: " + scoreString + "\r\n"); 277 q.Append("Error: " + evaluateCode.StandardError.ReadToEnd() + "\r\n"); 278 } 279 string cmdOutput = q.ToString(); 280 try 281 { 282 double evaluation = Double.Parse(scoreString); 283 return evaluation; 284 } 285 catch (Exception e) { } 286 287 return -900; 288 } 289 290 private static TankStats EvaluateTankProgram(ISymbolicExpressionTreeNode node, XmlNode docNode, string method) 291 { 292 TankStats tankStats = new TankStats(0, 0); 293 294 //string log = "Doing node: \r\n"; 295 /*if (node.Symbol is ProgramRootSymbol || 296 node.Symbol is StartSymbol) 297 tankStats = EvaluateTankProgram(node.GetSubtree(0), ref docNode, null); 298 else*/ 299 if (node.Symbol is Constant) 300 docNode[method]["code"].InnerText += " " + ((ConstantTreeNode)node).Value + " "; 301 else if (node.Symbol is ShotPower) 302 docNode[method]["code"].InnerText += " " + ((ShotPowerTreeNode)node).Value + " "; 303 else if (node.Symbol is LogicalValue) 304 docNode[method]["code"].InnerText += " " + ((BooleanTreeNode)node).Value.ToString().ToLower() + " "; 305 else if (node.Symbol is Block) 306 { 307 docNode[method]["code"].InnerText += "{\r\n"; 308 foreach (ISymbolicExpressionTreeNode n in node.Subtrees) 309 EvaluateTankProgram(n, docNode, method); 310 docNode[method]["code"].InnerText += "}\r\n"; 311 } 312 else if (node.Symbol is IfStatement) 313 { 314 docNode[method]["code"].InnerText += "if("; 315 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 316 docNode[method]["code"].InnerText += ")\r\n"; 317 EvaluateTankProgram(node.GetSubtree(1), docNode, method); 318 if (node.SubtreeCount == 3) 319 EvaluateTankProgram(node.GetSubtree(2), docNode, method); 320 } 321 else if (node.Symbol is ElseStatement) 322 { 323 docNode[method]["code"].InnerText += "else\r\n"; 324 if (node.SubtreeCount == 1) 325 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 326 } 327 else if (node.Symbol is WhileLoop) 328 { 329 docNode[method]["code"].InnerText += "While("; 330 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 331 docNode[method]["code"].InnerText += ")\r\n"; 332 EvaluateTankProgram(node.GetSubtree(1), docNode, method); 333 } 334 else if (node.Symbol is Ahead) 335 { 336 docNode[method]["code"].InnerText += "setAhead("; 337 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 338 docNode[method]["code"].InnerText += ");\r\n"; 339 tankStats.moves = 1; 340 } 341 else if (node.Symbol is Back) 342 { 343 docNode[method]["code"].InnerText += "setBack("; 344 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 345 docNode[method]["code"].InnerText += ");\r\n"; 346 tankStats.moves = 1; 347 } 348 else if (node.Symbol is SetAdjustGunForRobotTurn) 349 { 350 docNode[method]["code"].InnerText += "setAdjustGunForRobotTurn("; 351 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 352 docNode[method]["code"].InnerText += ");\r\n"; 353 tankStats.moves = 1; 354 } 355 else if (node.Symbol is SetAdjustRadarForGunTurn) 356 { 357 docNode[method]["code"].InnerText += "setAdjustRadarForGunTurn("; 358 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 359 docNode[method]["code"].InnerText += ");\r\n"; 360 tankStats.moves = 1; 361 } 362 else if (node.Symbol is SetAdjustRadarForRobotTurn) 363 { 364 docNode[method]["code"].InnerText += "setAdjustRadarForRobotTurn("; 365 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 366 docNode[method]["code"].InnerText += ");\r\n"; 367 tankStats.moves = 1; 368 } 369 else if (node.Symbol is TurnGunLeft) 370 { 371 docNode[method]["code"].InnerText += "setTurnGunLeft("; 372 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 373 docNode[method]["code"].InnerText += ");\r\n"; 374 tankStats.moves = 1; 375 } 376 else if (node.Symbol is TurnGunRight) 377 { 378 docNode[method]["code"].InnerText += "setTurnGunRight("; 379 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 380 docNode[method]["code"].InnerText += ");\r\n"; 381 tankStats.moves = 1; 382 } 383 else if (node.Symbol is TurnLeft) 384 { 385 docNode[method]["code"].InnerText += "setTurnLeft("; 386 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 387 docNode[method]["code"].InnerText += ");\r\n"; 388 tankStats.moves = 1; 389 } 390 else if (node.Symbol is TurnRadarLeft) 391 { 392 docNode[method]["code"].InnerText += "setTurnRadarLeft("; 393 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 394 docNode[method]["code"].InnerText += ");\r\n"; 395 tankStats.moves = 1; 396 } 397 else if (node.Symbol is TurnRadarRight) 398 { 399 docNode[method]["code"].InnerText += "setTurnRadarRight("; 400 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 401 docNode[method]["code"].InnerText += ");\r\n"; 402 tankStats.moves = 1; 403 } 404 else if (node.Symbol is TurnRight) 405 { 406 docNode[method]["code"].InnerText += "setTurnRight("; 407 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 408 docNode[method]["code"].InnerText += ");\r\n"; 409 tankStats.moves = 1; 410 } 411 else if (node.Symbol is Fire) 412 { 413 docNode[method]["code"].InnerText += "setFire("; 414 EvaluateTankProgram(node.GetSubtree(0), docNode, method); 415 docNode[method]["code"].InnerText += ");\r\n"; 416 tankStats.shots = 1; 417 } 418 else if (node.Symbol is Run || 419 node.Symbol is OnBulletHit || 420 node.Symbol is OnBulletMissed || 421 node.Symbol is OnHitByBullet || 422 node.Symbol is OnHitRobot || 423 node.Symbol is OnHitWall || 424 node.Symbol is OnScannedRobot) 425 { 426 tankStats = new TankStats(); 427 foreach (SymbolicExpressionTreeNode n in node.Subtrees) 428 { 429 string methodName = node.Symbol.GetType().ToString().Split('.').Last(); 430 try 431 { 432 var tempStats = EvaluateTankProgram(n, docNode, methodName); 433 tankStats.moves += tempStats.moves; 434 tankStats.shots += tempStats.shots; 435 } 436 catch (Exception e) 437 { 438 //log += "NULL EXCEPTION ON:::::::: -" + methodName + "-\r\n"; 439 //foreach (XmlNode f in docNode[methodName]) 440 // log += f.Name + "\r\n"; 441 } 442 } 443 } 444 else if (node.Symbol is Tank) 445 { 446 foreach (SymbolicExpressionTreeNode n in node.Subtrees) 447 { 448 try 449 { 450 var tempStats = EvaluateTankProgram(n, docNode, method); 451 tankStats.moves += tempStats.moves; 452 tankStats.shots += tempStats.shots; 453 } 454 catch (Exception e) { } 455 } 456 } 457 else 458 tankStats = EvaluateTankProgram(node.GetSubtree(0), docNode, null); 459 460 //log += tankStats.shots + " / " + tankStats.moves + "\r\n"; 461 //File.AppendAllText("../TankLog.txt", log); 462 463 return tankStats; 464 } 465 466 public static string InterpretProgramTree(ISymbolicExpressionTreeNode node) 467 { 468 var tankNode = node; 469 while (!(tankNode.Symbol is Tank)) 470 tankNode = tankNode.GetSubtree(0); 471 return ((CodeNode)tankNode.Symbol).Interpret(tankNode, tankNode.Subtrees); 472 } 473 } 385 } else 386 tankStats = EvaluateTankProgram(node.GetSubtree(0), docNode, null); 387 388 //log += tankStats.shots + " / " + tankStats.moves + "\r\n"; 389 //File.AppendAllText("../TankLog.txt", log); 390 391 return tankStats; 392 } 393 394 public static string InterpretProgramTree(ISymbolicExpressionTreeNode node) { 395 var tankNode = node; 396 while (!(tankNode.Symbol is Tank)) 397 tankNode = tankNode.GetSubtree(0); 398 return ((CodeNode)tankNode.Symbol).Interpret(tankNode, tankNode.Subtrees); 399 } 400 } 474 401 } -
branches/Robocode/HeuristicLab.Problems.Robocode/Solution.cs
r9570 r9601 4 4 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 5 5 6 namespace HeuristicLab.Problems.Robocode 7 { 8 [StorableClass] 9 public sealed class Solution : NamedItem 10 { 11 //private int moves; 12 //[Storable] 13 //public int Moves 14 //{ 15 // get { return moves; } 16 // private set { this.moves = value; } 17 //} 18 //private int shots; 19 //[Storable] 20 //public int Shots 21 //{ 22 // get { return shots; } 23 // private set { this.shots = value; } 24 //} 25 private ISymbolicExpressionTree tree; 26 [Storable] 27 public ISymbolicExpressionTree Tree 28 { 29 get { return tree; } 30 private set { this.tree = value; } 31 } 6 namespace HeuristicLab.Problems.Robocode { 7 [StorableClass] 8 public sealed class Solution : NamedItem { 9 //private int moves; 10 //[Storable] 11 //public int Moves 12 //{ 13 // get { return moves; } 14 // private set { this.moves = value; } 15 //} 16 //private int shots; 17 //[Storable] 18 //public int Shots 19 //{ 20 // get { return shots; } 21 // private set { this.shots = value; } 22 //} 23 [Storable] 24 public ISymbolicExpressionTree Tree { get; set; } 32 25 33 private string path; 34 [Storable] 35 public string Path 36 { 37 get { return path; } 38 private set { this.path = value; } 39 } 26 [Storable] 27 public string Path { get; set; } 40 28 41 [StorableConstructor] 42 private Solution(bool deserializing) : base(deserializing) { } 43 private Solution(Solution original, Cloner cloner) 44 : base(original, cloner) 45 { 46 //this.moves = original.moves; 47 //this.shots = original.shots; 48 this.tree = cloner.Clone(tree); 49 } 29 [StorableConstructor] 30 private Solution(bool deserializing) : base(deserializing) { } 31 private Solution(Solution original, Cloner cloner) 32 : base(original, cloner) { 50 33 51 public Solution(ISymbolicExpressionTree tree, string path)// int moves, int shots) 52 : base("Solution", "A tank program.") 53 { 54 this.tree = tree; 55 this.path = path; 56 //this.moves = moves; 57 //this.shots = shots; 58 } 59 [StorableHook(HookType.AfterDeserialization)] 60 private void AfterDeserialization() 61 { 62 } 63 public override IDeepCloneable Clone(Cloner cloner) 64 { 65 return new Solution(this, cloner); 66 } 34 Tree = cloner.Clone(original.Tree); 35 Path = original.Path; 67 36 } 37 38 public Solution(ISymbolicExpressionTree tree, string path)// int moves, int shots) 39 : base("Solution", "A tank program.") { 40 this.Tree = tree; 41 this.Path = path; 42 //this.moves = moves; 43 //this.shots = shots; 44 } 45 46 public override IDeepCloneable Clone(Cloner cloner) { 47 return new Solution(this, cloner); 48 } 49 } 68 50 } -
branches/Robocode/HeuristicLab.Problems.Robocode/Symbols/CodeNodeView.cs
r9565 r9601 1 1 using System; 2 using System.Collections.Generic;3 using System.ComponentModel;4 using System.Drawing;5 using System.Data;6 using System.Linq;7 using System.Text;8 using System.Threading.Tasks;9 2 using System.Windows.Forms; 10 3 using HeuristicLab.Core.Views; 11 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views;12 4 using HeuristicLab.MainForm; 13 using System.Diagnostics;14 using System.IO;15 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;16 5 17 6 18 namespace HeuristicLab.Problems.Robocode 19 { 20 [View("CodeNode View")] 21 [Content(typeof(CodeNode), IsDefaultView = true)] 22 public partial class CodeNodeView : NamedItemView 23 { 24 public CodeNode Content 25 { 26 get { return (CodeNode)base.Content; } 27 set { base.Content = value; } 28 } 7 namespace HeuristicLab.Problems.Robocode { 8 [View("CodeNode View")] 9 [Content(typeof(CodeNode), IsDefaultView = true)] 10 public partial class CodeNodeView : NamedItemView { 11 public new CodeNode Content { 12 get { return (CodeNode)base.Content; } 13 set { base.Content = value; } 14 } 29 15 30 public CodeNodeView() : base()31 32 33 34 35 16 public CodeNodeView() 17 : base() { 18 InitializeComponent(); 19 //this.prefixCode.Text = Content.Prefix; 20 //this.suffixCode.Text = Content.Suffix; 21 } 36 22 37 protected override void OnContentChanged() 38 { 39 base.OnContentChanged(); 40 if (Content == null) 41 { 42 this.prefixCode.Text = ""; 43 this.suffixCode.Text = ""; 44 } 45 else 46 { 47 this.prefixCode.Text = Content.Prefix; 48 this.suffixCode.Text = Content.Suffix; 49 //Content.Prefix = this.prefixCode.Text; 50 //Content.Suffix = this.suffixCode.Text; 51 } 52 } 23 protected override void OnContentChanged() { 24 base.OnContentChanged(); 25 if (Content == null) { 26 this.prefixCode.Text = ""; 27 this.suffixCode.Text = ""; 28 } else { 29 this.prefixCode.Text = Content.Prefix; 30 this.suffixCode.Text = Content.Suffix; 31 //Content.Prefix = this.prefixCode.Text; 32 //Content.Suffix = this.suffixCode.Text; 33 } 34 } 53 35 54 private void prefixCode_Leave(object sender, EventArgs e) 55 { 56 Content.Prefix = this.prefixCode.Text; 57 } 36 private void prefixCode_Leave(object sender, EventArgs e) { 37 Content.Prefix = this.prefixCode.Text; 38 } 58 39 59 private void suffixCode_Leave(object sender, EventArgs e) 60 { 61 Content.Suffix = this.suffixCode.Text; 62 } 40 private void suffixCode_Leave(object sender, EventArgs e) { 41 Content.Suffix = this.suffixCode.Text; 63 42 } 43 } 64 44 }
Note: See TracChangeset
for help on using the changeset viewer.