├── .gitignore ├── LICENSE ├── Makefile ├── Manifest ├── NOTICE ├── PshApplet.java ├── PshEquationBuilder.java ├── PshGP.java ├── PshInspector.java ├── README.md ├── TomToDo.md ├── coevolution ├── CEFloatReg1.pushgp ├── CEFloatReg2.pushgp ├── DifficultFloatReg1.pushgp ├── DifficultFloatReg2.pushgp └── DifficultIntReg1.pushgp ├── gpsamples ├── cartcenter.pushgp ├── floatreg0.pushgp ├── floatreg1.pushgp ├── floatreg2.pushgp ├── floatreg3.pushgp ├── intreg0.pushgp ├── intreg1.pushgp ├── intreg2.pushgp ├── nodeselectiontesting.pushgp ├── standard.pushgp └── trival-gp-problemset │ ├── problemset.pushgp │ ├── regression1.pushgp │ ├── regression10.pushgp │ ├── regression2.pushgp │ ├── regression3.pushgp │ ├── regression4.pushgp │ ├── regression5.pushgp │ ├── regression6.pushgp │ ├── regression7.pushgp │ ├── regression8.pushgp │ └── regression9.pushgp ├── org └── spiderland │ └── Psh │ ├── Checkpoint.java │ ├── Coevolution │ ├── CEFloatSymbolicRegression.java │ ├── FloatRegFitPrediction.java │ ├── FloatRegFitPredictionIndividual.java │ ├── GenericPredictionIndividual.java │ ├── PredictionGA.java │ └── PredictionGAIndividual.java │ ├── GA.java │ ├── GAIndividual.java │ ├── GATestCase.java │ ├── GenericStack.java │ ├── IncludeException.java │ ├── InputPusher.java │ ├── InspectorInput.java │ ├── Instruction.java │ ├── Instructions.java │ ├── Interpreter.java │ ├── ObjectPair.java │ ├── ObjectStack.java │ ├── Params.java │ ├── ProbClass │ ├── CartCentering.java │ ├── FloatClassification.java │ ├── FloatSymbolicRegression.java │ └── IntSymbolicRegression.java │ ├── Program.java │ ├── PushGP.java │ ├── PushGPIndividual.java │ ├── Stack.java │ ├── TestCase │ ├── FloatRegTestCases1.java │ ├── FloatRegTestCases2.java │ ├── IntRegTestCases1.java │ └── TestCaseGenerator.java │ ├── booleanStack.java │ ├── floatStack.java │ ├── intStack.java │ └── test │ ├── GenericStackTest.java │ ├── InstructionTest.java │ └── ProgramTest.java ├── pushevolved ├── cartCenteringEvolved.push ├── cefloatreg2evolved.push └── factorialEvolved.push ├── pushsamples ├── exampleProgram0.push ├── exampleProgram1.push ├── exampleProgram2.push ├── exampleProgram3.push ├── instructionTesting.push └── random.push └── tools ├── InstructionListCleaner.java ├── PushInstructionSet.txt └── PushMissingInstructions.txt /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | .project 3 | .classpath 4 | /Run from CEFloatReg2 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Copyright 2009-2010 Jon Klein 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | SOURCES = *.java org/spiderland/Psh/*.java org/spiderland/Psh/ProbClass/*.java org/spiderland/Psh/Coevolution/*.java 16 | CLASSES = *.class org/spiderland/Psh/*.class org/spiderland/Psh/ProbClass/*.class org/spiderland/Psh/Coevolution/*.class 17 | 18 | .PHONY: docs 19 | 20 | all: Psh.jar docs 21 | 22 | Psh.jar: $(SOURCES) 23 | javac -source 1.6 -target 1.6 -Xlint $(SOURCES) 24 | jar cf Psh.jar Manifest LICENSE NOTICE README.md $(CLASSES) 25 | 26 | clean: 27 | rm -f org/spiderland/Psh/*.class *.class Psh.jar 28 | 29 | tilde: 30 | rm -f *~ 31 | rm -f gpsamples/*~ 32 | rm -f pushsamples/*~ 33 | rm -f tools/*~ 34 | rm -f org/spiderland/Psh/*~ 35 | 36 | test: 37 | java -cp junit-4.4.jar:. junit.textui.TestRunner org.spiderland.Psh.test.ProgramTest 38 | 39 | docs: 40 | javadoc -d docs/api org.spiderland.Psh 41 | -------------------------------------------------------------------------------- /Manifest: -------------------------------------------------------------------------------- 1 | Main-Class: Psh 2 | Manifest-Version: 1.0 3 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Psh 2 | Copyright 2009-2010 Jon Klein 3 | 4 | Portions of this software were developed at the University of Massachusetts 5 | Amherst. 6 | -------------------------------------------------------------------------------- /PshApplet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import java.applet.*; 18 | 19 | import org.spiderland.Psh.*; 20 | 21 | public class PshApplet extends Applet { 22 | public static final long serialVersionUID = 2L; 23 | 24 | 25 | Interpreter _interpreter = new Interpreter(); 26 | 27 | public void init() { 28 | try { 29 | System.out.println( Run( getParameter( "program" ) ) ); 30 | } catch( Exception e ) {}; 31 | } 32 | 33 | public String Run( String inValue ) { 34 | _interpreter.ClearStacks(); 35 | 36 | try { 37 | Program p; 38 | p = new Program( _interpreter, inValue ); 39 | 40 | _interpreter.Execute( p ); 41 | 42 | } catch( Exception e ) { 43 | 44 | }; 45 | 46 | return _interpreter.toString(); 47 | } 48 | 49 | public String GetInstructionString() { 50 | return "=> " + _interpreter.GetRegisteredInstructionsString(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /PshEquationBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import java.io.File; 18 | import java.util.ArrayList; 19 | 20 | import org.spiderland.Psh.*; 21 | 22 | /** 23 | * Used to print equations from Psh programs 24 | */ 25 | public class PshEquationBuilder { 26 | public static void main(String args[]) throws Exception { 27 | 28 | if (args.length != 1) { 29 | System.out.println("Usage: PshEquationBuilder inputfile"); 30 | System.exit(0); 31 | } 32 | 33 | File inFile = new File(args[0]); 34 | 35 | // Read fileString 36 | String fileString = Params.ReadFileString(inFile); 37 | 38 | // Get programString 39 | String programString; 40 | int indexNewline = fileString.indexOf("\n"); 41 | 42 | if (indexNewline == -1) { 43 | programString = fileString; 44 | } 45 | else{ 46 | programString = fileString.substring(0, indexNewline).trim(); 47 | } 48 | 49 | //Get rid of parentheses 50 | programString = programString.replace('(', ' '); 51 | programString = programString.replace(')', ' ').trim(); 52 | 53 | String instructions[] = programString.split("\\s+"); 54 | 55 | ArrayList stringStack = new ArrayList(); 56 | stringStack.add("x"); 57 | for(String instruction : instructions){ 58 | 59 | // (input.in0 float.+ float.- float.* float./ float.exp float.sin float.cos float.2pi) 60 | if(instruction.equals("input.in0")){ 61 | stringStack.add("x"); 62 | } 63 | else if(instruction.equals("float.+")){ 64 | if(stringStack.size() > 1){ 65 | String top = stringStack.remove(stringStack.size() - 1); 66 | String next = stringStack.remove(stringStack.size() - 1); 67 | 68 | String result = "(" + top + " + " + next + ")"; 69 | stringStack.add(result); 70 | } 71 | } 72 | else if(instruction.equals("float.-")){ 73 | if(stringStack.size() > 1){ 74 | String top = stringStack.remove(stringStack.size() - 1); 75 | String next = stringStack.remove(stringStack.size() - 1); 76 | 77 | String result = "(" + top + " - " + next + ")"; 78 | stringStack.add(result); 79 | } 80 | } 81 | else if(instruction.equals("float.*")){ 82 | if(stringStack.size() > 1){ 83 | String top = stringStack.remove(stringStack.size() - 1); 84 | String next = stringStack.remove(stringStack.size() - 1); 85 | 86 | String result = "(" + top + " * " + next + ")"; 87 | stringStack.add(result); 88 | } 89 | } 90 | else if(instruction.equals("float./")){ 91 | if(stringStack.size() > 1){ 92 | String top = stringStack.remove(stringStack.size() - 1); 93 | String next = stringStack.remove(stringStack.size() - 1); 94 | 95 | String result = "(" + top + " / " + next + ")"; 96 | stringStack.add(result); 97 | } 98 | } 99 | else if(instruction.equals("float.exp")){ 100 | if(stringStack.size() > 0){ 101 | String top = stringStack.remove(stringStack.size() - 1); 102 | 103 | String result = "(e^" + top + ")"; 104 | stringStack.add(result); 105 | } 106 | } 107 | else if(instruction.equals("float.sin")){ 108 | if(stringStack.size() > 0){ 109 | String top = stringStack.remove(stringStack.size() - 1); 110 | 111 | String result = "sin(" + top + ")"; 112 | stringStack.add(result); 113 | } 114 | } 115 | else if(instruction.equals("float.cos")){ 116 | if(stringStack.size() > 0){ 117 | String top = stringStack.remove(stringStack.size() - 1); 118 | 119 | String result = "cos(" + top + ")"; 120 | stringStack.add(result); 121 | } 122 | } 123 | else if(instruction.equals("float.2pi")){ 124 | stringStack.add("2 * pi"); 125 | } 126 | else{ 127 | throw new Exception("Unrecognized Psh instruction " + 128 | instruction +" in program."); 129 | } 130 | 131 | 132 | } 133 | 134 | System.out.println(stringStack.get(stringStack.size() - 1)); 135 | 136 | } 137 | } -------------------------------------------------------------------------------- /PshGP.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import java.io.*; 18 | 19 | import org.spiderland.Psh.*; 20 | 21 | /** 22 | * PshGP executes a genetic programming run using the given parameter file. More 23 | * information about parameter files can be found in the README. 24 | */ 25 | public class PshGP { 26 | public static void main(String args[]) throws Exception { 27 | 28 | if (args.length != 1 && args.length != 3) { 29 | System.out.println("Usage: PshGP paramfile|checkpointfile.gz [testprogram testcasenumber]"); 30 | System.exit(0); 31 | } 32 | 33 | GA ga = null; 34 | if (args[0].endsWith(".gz")) 35 | ga = GA.GAWithCheckpoint(args[0]); 36 | else 37 | ga = GA.GAWithParameters(Params.ReadFromFile(new File(args[0]))); 38 | 39 | if (args.length == 3) { 40 | // Execute a test program 41 | 42 | Program p = new Program(args[1]); 43 | ((PushGP) ga).RunTestProgram(p, Integer.parseInt(args[2])); 44 | } else { 45 | // Execute a GP run. 46 | 47 | ga.Run(); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /PshInspector.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import org.spiderland.Psh.*; 18 | 19 | /** 20 | * PshInspector pshFile 21 | * 22 | * PshInspector can be used to inspect the execution of a Psh program. 23 | * After every step of the program, the stacks of the interpreter 24 | * are displayed. The Psh program is given to PshInspector through 25 | * the file pshFile. pshFile is an input file containing the 26 | * following, separated by new lines: 27 | * 28 | * - Program: The psh program to run 29 | * - ExecutionLimit: Maximum execution steps 30 | * - Input(optional): Any inputs to be pushed before execution, 31 | * separated by spaces. Note: Only int, float, and 32 | * boolean inputs are accepted. 33 | */ 34 | public class PshInspector { 35 | public static void main(String args[]) throws Exception { 36 | 37 | if (args.length != 1) { 38 | System.out.println("Usage: PshInspector inputfile"); 39 | System.exit(0); 40 | } 41 | 42 | // _input will allow easy initialization of the interpreter. 43 | InspectorInput _input = new InspectorInput(args[0]); 44 | Interpreter _interpreter = _input.getInterpreter(); 45 | 46 | int _executionLimit = _input.getExecutionLimit(); 47 | int executed = 0; 48 | int stepsTaken = 1; 49 | String stepPrint = ""; 50 | 51 | // Print registered instructions 52 | System.out.println("Registered Instructions: " 53 | + _interpreter.GetRegisteredInstructionsString() + "\n"); 54 | 55 | // Run the Psh Inspector 56 | System.out.println("====== State after " + executed + " steps ======"); 57 | _interpreter.PrintStacks(); 58 | 59 | while (executed < _executionLimit && stepsTaken == 1) { 60 | executed += 1; 61 | 62 | // Create output string 63 | if (executed == 1) 64 | stepPrint = "====== State after " + executed + " step "; 65 | else 66 | stepPrint = "====== State after " + executed + " steps "; 67 | 68 | stepPrint += "(last step: "; 69 | Object execTop = _interpreter.execStack().top(); 70 | 71 | if (execTop instanceof Program) 72 | stepPrint += "(...)"; 73 | else 74 | stepPrint += execTop; 75 | 76 | stepPrint += ") ======"; 77 | 78 | // Execute 1 instruction 79 | stepsTaken = _interpreter.Step(1); 80 | 81 | if (stepsTaken == 1) { 82 | System.out.println(stepPrint); 83 | _interpreter.PrintStacks(); 84 | } 85 | } 86 | 87 | } 88 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > Copyright 2009-2010 Jon Klein 2 | > 3 | > Licensed under the Apache License, Version 2.0 (the "License"); 4 | > you may not use this file except in compliance with the License. 5 | > You may obtain a copy of the License at 6 | > 7 | > http://www.apache.org/licenses/LICENSE-2.0 8 | > 9 | > Unless required by applicable law or agreed to in writing, software 10 | > distributed under the License is distributed on an "AS IS" BASIS, 11 | > WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | > See the License for the specific language governing permissions and 13 | > limitations under the License. 14 | 15 | Psh 16 | === 17 | 18 | Psh is a Java implementation of the Push programming language and of PushGP. Push is a stack-based language designed for evolutionary computation, specifically genetic programming. PushGP is a genetic programming system that evolves programs in Push. More information about Push and PushGP can be found [here](http://hampshire.edu/lspector/push.html). 19 | 20 | This is v1.0 of Psh. 21 | 22 | Getting Started with Git 23 | ======================== 24 | 25 | To Get Psh 26 | ---------- 27 | $ git clone git://github.com/jonklein/Psh.git 28 | $ cd Psh 29 | 30 | To Update Psh 31 | ------------- 32 | $ cd Psh 33 | $ git pull 34 | 35 | Git References 36 | -------------- 37 | - [Pro Git](http://progit.org/book/) - A wonderful source for those new to git. 38 | - [GitHub Help](http://help.github.com/) - GitHub help pages. 39 | 40 | Getting Started with Psh 41 | ======================== 42 | 43 | Building Psh 44 | ------------ 45 | After getting Psh with get, build the package: 46 | 47 | $ make 48 | 49 | Using PshGP 50 | ---------- 51 | To run PshGP on a sample problem: 52 | 53 | $ java PshGP gpsamples/intreg1.pushgp 54 | 55 | This problem uses integer symbolic regression to solve the equation y = 12x^2 + 5. Other sample problems are available, with descriptions, in `gpsamples/`. For example, `intreg2.pushgp` uses integer symbolic regression to solve the factorial function, and `regression1.pushgp` uses float symbolic regression to solve y = 12x^2 + 5. 56 | 57 | Using PshInspector 58 | ------------------ 59 | PshInspector allows you to examine every step of a Psh program as it executes. To run PshInspector on a sample psh program: 60 | 61 | $ java PshInspector pushsamples/exampleProgram1.push 62 | 63 | This push file runs the psh program `(2994 5 integer.+)` for 100 steps after pushing the inputs `44, 22, true, 17.76`. Other sample psh programs are available in `pushsamples/`. 64 | 65 | Using Psh in Eclipse 66 | ==================== 67 | 68 | Getting Psh 69 | ----------- 70 | Use _Getting Started with Git_ above, or use [Egit](http://www.eclipse.org/egit/) with help [on this page](http://wiki.eclipse.org/EGit/User_Guide). Note on installing Egit: the link provided on the download page does not download any files directly; instead, it is meant to be pasted in Eclipse under `Help > Install New Software`. 71 | 72 | Loading Psh in Eclipse 73 | ---------------------- 74 | Start a new Java project by clicking `File > New > Java Project`. From there, select `Create project from existing source` and browse for and select the Psh project folder. Click `Finish`. 75 | 76 | Adding JUnit to the Build Path 77 | ------------------------------ 78 | JUnit, while not essential to using Psh, will allow for some automatic testing and will make Eclipse not complain about errors in Psh whenever you try to run it. JUnit can be downloaded [here](http://www.junit.org/), and should be placed wherever you want to store Java jar libraries. To add JUnit to your Psh project, click `Project > Properties`. Then select `Java Build Path` followed by the `Libraries` tab, and then click `Add External JARs...`. Select your JUnit jar file wherever you saved it, click `Open`, and then `Ok`. Now, JUnit should be added to your build path. 79 | 80 | Using PshGP from Eclipse 81 | ------------------------ 82 | Since PshGP requires command-line arguments, you must first specify them in Eclipse by setting up a Run Configuration. To do so, click `Run > Run Configurations...`. From here, click `New launch configuration` in the upper left corner. Give your configuration a name, and select the project by browsing or by typing Psh in the project line. Then, select PshGP as the main class by clicking `Search > PshGP > Ok`. Now, click the `Arguments` tab, and type in the configuration file you wish to run, for example `gpsamples/intreg1.pushgp`. From here, you can click `Run` to directly run this configuration, or `Apply` then `Close` if you don't want to run it right away. To run a run configuration, click the arrow to the right of the `Run` arrow, and select the run configuration you wish to execute. 83 | 84 | Psh In More Detail 85 | ================== 86 | 87 | Configuration Files 88 | ------------------- 89 | PshGP runs are setup using configuration files which have the extension `.pushgp`. These files contain a list of parameters in the form of 90 | 91 | param-name = value 92 | 93 | The following parameters must be defined in the configuration file, given with example values: 94 | 95 | problem-class = org.spiderland.Psh.IntSymbolicRegression 96 | 97 | max-generations = 200 98 | population-size = 1000 99 | execution-limit = 150 100 | max-points-in-program = 100 101 | max-random-code-size = 40 102 | 103 | tournament-size = 7 104 | mutation-percent = 30 105 | crossover-percent = 55 106 | simplification-percent = 5 107 | 108 | reproduction-simplifications = 25 109 | report-simplifications = 100 110 | final-simplifications = 1000 111 | 112 | test-cases = ((1 1) (2 2) (3 6) (4 24) (5 120) (6 720)) 113 | instruction-set = (registered.exec registered.boolean integer.% integer.* integer.+ integer.- integer./ integer.dup) 114 | 115 | The following parameters are optional. If not specified, the default values below will be used for these parameters, except for the parameters `mutation-mode`, `output-file`, and `push-frame-mode`, which significantly change the run when specified. Also, `target-function-string` defaults to not displaying a string, but a representative example is given below. 116 | 117 | trivial-geography-radius = 10 118 | simplify-flatten-percent = 20 119 | mutation-mode = fair 120 | fair-mutation-range = .3 121 | 122 | node-selection-mode = unbiased (others available are leaf-probability and size-tournament) 123 | node-selection-leaf-probability = 10 (only used if node-selection-mode = leaf-probability) 124 | node-selection-tournament-size = 2 (only used if node-selection-mode = size-tournament) 125 | 126 | min-random-integer = -10 127 | max-random-integer = 10 128 | random-integer-resolution = 1 129 | min-random-float = -10.0 130 | max-random-float = 10.0 131 | random-float-resolution = 0.01 132 | 133 | target-function-string = "y = x^4 - 2x + 7" 134 | 135 | interpreter-class = org.spiderland.Psh.Interpreter 136 | individual-class = org.spiderland.Psh.PushGPIndividual 137 | inputpusher-class = org.spiderland.Psh.InputPusher 138 | 139 | output-file = out.txt 140 | push-frame-mode = pushstacks 141 | 142 | PshInspector Files 143 | ------------------ 144 | In order to inspect the execution of a program, PshInspector takes a push program file with the extension `.push`. After every step of the program, the stacks of the interpreter are displayed. The input file contains the following, separated by new lines: 145 | 146 | - Program: The Psh program to run 147 | - ExecutionLimit: Maximum execution steps 148 | - Input(optional): Any inputs to be pushed before execution, separated by spaces. The inputs are pushed in the order in which they are given. Note: Only int, float, and boolean inputs are accepted. 149 | 150 | Problem Classes 151 | --------------- 152 | PshGP uses problem classes, implemented as Java classes, to determine certain aspects of the run, such as how to compute fitness values. The choice of problem class determines how test case data is interpreted, and which stacks are used for test case input and output. In addition, certain inherited methods in both GA.java and PushGP.java may be overwritten for further customization. 153 | 154 | Psh comes with a few standard problem classes. The following problem classes are currently implemented, and are in the ProbClass subpackage: 155 | 156 | - FloatSymbolicRegression.java: Maps an input floating point value to an output floating point value. Error value is computed as the difference between the desired output value and the top value on the float stack. 157 | - IntSymbolicRegression.java: Maps an input integer value to an output integer value. Error value is computed as the difference between the desired output value and the top value on the integer stack. 158 | - CartCentering.java: Maps two input floats (position and velocity) to a boolean value that represents a forward or backward force applied to a cart. The error is the amount of time required to stop the cart at the origin. For more information, see the problem class file. 159 | 160 | In order to perform runs for other types of problems, you can implement your own custom problem classes. Please note the following: 161 | 162 | - You will likely want to implement the InitFromParamenters method, which can be used to set up test cases. If so, make sure to also call its parent method. 163 | - In PshGP, the term fitness actually refers to error values, which means that lower values are considered more fit and that 0.0 represents no error. The EvaluateTestCase method must be implemented by any problem class, and should compute an individual's fitness, with lower values being better. 164 | - The InitInterpreter method must be implemented by all problem classes though many times this method is simply left empty. 165 | - There are other optional methods that can be overwritten or extended in the GA.java and PushGP.java classes. For example, the CartCentering.java problem class implements the Success method in order to override the conditions that GA uses to identify a successful run. 166 | 167 | Changelog 168 | ========= 169 | 170 | Major Changes since v1.0: 171 | ------------------------- 172 | - The parameters that affect Ephemeral Random Constant creation, such as the minimum random integer, are now available as optional configuration parameters. See Configuration Files above for more details. 173 | - Implement new instructions: integer.pow, integer.min, integer.max, float.exp, float.pow. Also, fixed a bug in float.max. 174 | - Moved problem classes and test cases to their own packages to reduce clutter. 175 | - Fixed holes in many integer and float instructions that could cause underflow, overflow, or NaN errors. 176 | - Made FloatSymbolicRegression and IntSymbolicRegression as well as co-evolved FloatSymbolicRegression work with test-case generators. 177 | - PshGP now primarily uses the mean of test case errors for an individual's error instead of the total sum of the errors. 178 | - Added optional parameter `target-function-string`, which specifies a human-readable version of the target function, which is only used in I/O. 179 | - Added many instructions that were missing from the Push 3.0 specification. 180 | - Added node-selection-mode as an optional parameter, as well as node size tournaments for node selection. 181 | 182 | Major Changes since v0.3: 183 | ------------------------- 184 | - Added new integer and float instructions: abs, neg, sin, cos, tan, max, min. 185 | - Added new boolean instructions: and, or, xor, not. 186 | - Added problem class for the cart centering problem (CartCentering.java), an optimal control problem. 187 | - Made many parameters of .pushgp files optional. This should make creating .pushgp files for new users much simpler, as many parameters are rarely (if ever) changed. Optional parameters are listed in this readme. 188 | - Change Psh over to Apache 2.0 license. 189 | - The number of fitness evaluations is now displayed during reports. 190 | 191 | Major Changes since v0.2: 192 | ------------------------- 193 | - All instructions have been converted into lower case to match Schush and other implementations. 194 | - An input stack was added, which holds all inputs. It has the following instructions: 195 | 1. input.index - Pops n off of the integer stack and pushes input[n] onto corresponding stack. If integer stack is empty, acts as a no-op. 196 | 2. input.makeinputsN - Creates N instructions called 'input.in0', 'input.in1', ..., 'input.in(N-1)' 197 | 3. input.inall - For all n in 0 to input.size, push input[n] onto the corresponding stack. 198 | 4. input.inallrev - For all n in input.size to 9, push input[n] onto the corresponding stack. 199 | 5. input.stackdepth - Puts size of stack on integer stack. 200 | - In config files, you can now include all instructions for a certain type using 'registered.type' (e.g. 'registered.integer' or 'registered.stack'). 201 | - Implemented auto-simplification, which is used during generation and final reports. Auto-simplification may also be used as a genetic operator along with mutation and crossover. 202 | 203 | Major Changes since v0.1: 204 | ------------------------- 205 | - Added problem classes for integer symbolic regression (IntSymbolicRegression.java) and integer symbolic regression without an input instruction (IntSymbolicRegressionNoInput.java). 206 | - Fixed 'code' and 'exec' stack iteration functions, which were not executing correctly according to Push 3.0 standards. 207 | - PshGP now displays the error values for the best program during the generation report. 208 | - PshInspector was created to inspect interpreter stacks of push programs as they execute. This can be used to catch errors and trace executions. To run, see Using PshInspector section above. 209 | 210 | Acknowledgement 211 | =============== 212 | This material is based upon work supported by the National Science Foundation under Grant No. 1017817. Any opinions, findings, and conclusions or recommendations expressed in this publication are those of the authors and do not necessarily reflect the views of the National Science Foundation. -------------------------------------------------------------------------------- /TomToDo.md: -------------------------------------------------------------------------------- 1 | To Do List 2 | ========== 3 | 4 | Done Major Changes 5 | ------------------ 6 | - Added problem classes for integer symbolic regression (IntSymbolicRegression.java) and integer symbolic regression without an input instruction (IntSymbolicRegressionNoInput.java). 7 | - Make PshGP display the errors for best program 8 | - Implement Psh runtime examiner to see why Schush and Psh are running code and getting different results. It likely has to do with what they push on the stacks at the beginning of a run. 9 | - Fix code.do*range. Issues: 1. Recrusive call is not surrounded by parentheses. 2. Does not leave a copy of second integer on int stack. 10 | - Check that non-code.do*range code stack iteration instructions are working correctly, i.e. have same results as with Schush 11 | - Fix Psh to make sure exec.do*range and other iterative instructions are working correctly. 12 | - Allow the inclusion of all instructions for a certain type using registered.type (e.g. registered.integer or registered.exec). 13 | - Implement Autosimplification function. Have Psh use Autosimplification after evolution. Autosimplify during reports. Make optional Autosimplification genetic operator. 14 | - Make all instructions lower case. 15 | - Implement input stack including the following instructions: 16 | 1. input.index - Pops n off of the integer stack and pushes input[n] onto corresponding stack. If integer stack is empty, acts as a no-op. 17 | 2. input.makeinputsN - Creates N instructions called 'input.in0', 'input.in1', ..., 'input.in(N-1)' 18 | 3. input.inall - For all n in 0 to input.size, push input[n] onto the corresponding stack. 19 | 4. input.inallrev - For all n in input.size to 9, push input[n] onto the corresponding stack. 20 | 5. input.stackdepth - Puts size of stack on integer stack. 21 | - Implement absolute value and negation instructions for both int and float. 22 | - Implement new problem class CartCentering.java, that is used for the Cart Centering problem described by Koza in Genetic Programming. 23 | - Change Psh over to Apache 2.0 license. 24 | - Implement new instructions: integer.pow, integer.min, integer.max, float.exp, float.pow 25 | - Create more difficult float regression example that uses many test cases, and to do so creates it's test cases using TestCaseGenerator.java. 26 | 27 | 28 | Done Minor Changes 29 | ------------------ 30 | - Fiddle with integer symbolic regression to test a different function and different input 31 | - Make list of available instructions 32 | - Implement symbolic regression for a different example (see Schush) [i.e. run trial of Factorial] 33 | - Make sure Psh prints stacks (int and float in particular) in same order as Schush 34 | - Fix parentheses pushed onto stack issue in Psh. 35 | - In PshInspector, when printing generation number, print last executed instruction on same line. 36 | - Run Factorial and make sure the returned programs are correct 37 | - Make sure trivial-geography is actually being used. It's parameter appears only in the function TournamentSelectionIndex, which is never being called. 38 | - Get working version uploaded to GitHub 39 | - Remove "//trh//" type comments, clean up things for release v0.2 40 | - Announce major changes on i3ci blog. 41 | - In README, make Major Changes section read better. 42 | - Add population, generations, and other statistics to the pre-run report of PushGP. 43 | - Add to "Problem Classes" section in README 44 | - Made many parameters of .pushgp files optional. This should make creating .pushgp files for new users much simpler, as many parameters are rarely (if ever) changed. 45 | - Add float.erc and integer.erc to their respective registered instructions (i.e. for registered.float) 46 | - The number of fitness evaluations is now displayed during reports. 47 | - Release v1.0 of Psh, including changing the README version number. 48 | - The parameters that affect Ephemeral Random Constant creation, such as the minimum random integer, are now available as optional .pushgp parameters. 49 | - Fixed a bug in float.max 50 | - Added optional parameter `target-function-string`, which specifies a human-readable version of the target function, which is only used in I/O. 51 | 52 | 53 | To Do Still 54 | ----------- 55 | - Make way to conduct multiple runs and get statistics about those runs, to compare things such as population, generations, or use of ERCs. 56 | - Add co-evolution fitness predictors. This will be a big project (make a git branch). 57 | - Many GA an PushGP methods are can be overwritten in order to implement co-evolution. 58 | - Add instructions for integer.fromfloat, float.frominteger, etc. 59 | - During Auto-simplification, instead of only flattening or removing random points, could run a subprogram for a bit, and then replace it by whatever constants are left on the stacks. This would be useful when code like "boolean.stackdepth" is used only to get a 0 on the int stack. 60 | 61 | 62 | Jon's TODO 63 | ---------- 64 | 65 | Some things TODO before a 1.0 release: 66 | 67 | - x improved reporting 68 | - x output to files 69 | - x trivial GP problem sets 70 | - x unfair mutation 71 | 72 | - documentation 73 | - x trivial geography 74 | - CSV reader 75 | - classification problems //trh//what are these? - check out Koza 76 | - parity problem //trh//semi-important 77 | - x boolean instructions //trh//important 78 | - instruction review 79 | -------------------------------------------------------------------------------- /coevolution/CEFloatReg1.pushgp: -------------------------------------------------------------------------------- 1 | # Copyright 2009-2010 Jon Klein 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # 16 | # First trials of co-evolved predictors for float symbolic regression. Evolving 17 | # symbolic regression for y = 3x^2 + 4x 18 | # 19 | # Tom Helmuth 20 | # 8/3/10 21 | # 22 | 23 | ### Setup solution GP parameters 24 | 25 | population-size = 200 26 | max-generations = 1000 27 | execution-limit = 150 28 | 29 | mutation-percent = 15 30 | crossover-percent = 75 31 | simplification-percent = 5 32 | 33 | tournament-size = 7 34 | trivial-geography-radius = 10 35 | max-points-in-program = 100 36 | mutation-mode = fair 37 | 38 | max-random-code-size = 40 39 | simplify-flatten-percent = 10 40 | 41 | reproduction-simplifications = 25 42 | report-simplifications = 100 43 | final-simplifications = 2000 44 | 45 | target-function-string = y = 3x^2 + 4x 46 | 47 | ### Setup problem class and test cases. 48 | 49 | problem-class = org.spiderland.Psh.Coevolution.CEFloatSymbolicRegression 50 | test-case-class = org.spiderland.Psh.TestCase.FloatRegTestCases1 51 | instruction-set = (registered.float input.makeinputs1) 52 | 53 | 54 | ### Setup predictor GP parameters 55 | 56 | PREDICTOR-problem-class = org.spiderland.Psh.Coevolution.FloatRegFitPrediction 57 | PREDICTOR-individual-class = org.spiderland.Psh.Coevolution.FloatRegFitPredictionIndividual 58 | PREDICTOR-population-size = 10 59 | PREDICTOR-effort-percent = 5 60 | 61 | PREDICTOR-trainer-population-size = 10 62 | PREDICTOR-generations-between-trainers = 20 63 | 64 | PREDICTOR-mutation-percent = 25 65 | PREDICTOR-crossover-percent = 70 66 | 67 | PREDICTOR-tournament-size = 2 68 | PREDICTOR-trivial-geography-radius = 0 69 | -------------------------------------------------------------------------------- /coevolution/CEFloatReg2.pushgp: -------------------------------------------------------------------------------- 1 | # Copyright 2009-2010 Jon Klein 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # 16 | # A difficult symbolic regression problem that needs many test cases. Will be 17 | # used to test TestCaseGenerator.java as well as co-evolved fitness prediction. 18 | # The problem to be solved is 19 | # y = (e ^ |x|) * sin(x) 20 | # 21 | # Tom Helmuth 22 | # 8/14/10 23 | # 24 | 25 | ### Setup solution GP parameters 26 | 27 | population-size = 150 28 | max-generations = 20000 29 | execution-limit = 200 30 | 31 | mutation-percent = 10 32 | crossover-percent = 80 33 | simplification-percent = 5 34 | 35 | tournament-size = 7 36 | trivial-geography-radius = 10 37 | max-points-in-program = 100 38 | mutation-mode = fair 39 | 40 | max-random-code-size = 40 41 | simplify-flatten-percent = 10 42 | 43 | reproduction-simplifications = 25 44 | report-simplifications = 100 45 | final-simplifications = 2000 46 | 47 | min-random-float = -10.0 48 | max-random-float = 10.0 49 | random-float-resolution = 0.001 50 | 51 | target-function-string = y = (e ^ |x|) * sin(x) 52 | 53 | ### Setup problem class and test cases. 54 | 55 | problem-class = org.spiderland.Psh.Coevolution.CEFloatSymbolicRegression 56 | test-case-class = org.spiderland.Psh.TestCase.FloatRegTestCases2 57 | 58 | #instruction-set = (registered.float input.makeinputs1) 59 | instruction-set = (input.makeinputs1 float.+ float.- float.* float./ float.exp float.sin float.cos) 60 | 61 | ### Setup predictor GP parameters 62 | 63 | PREDICTOR-problem-class = org.spiderland.Psh.Coevolution.FloatRegFitPrediction 64 | PREDICTOR-individual-class = org.spiderland.Psh.Coevolution.FloatRegFitPredictionIndividual 65 | PREDICTOR-population-size = 10 66 | PREDICTOR-effort-percent = 5 67 | 68 | PREDICTOR-trainer-population-size = 10 69 | PREDICTOR-generations-between-trainers = 20 70 | 71 | PREDICTOR-mutation-percent = 25 72 | PREDICTOR-crossover-percent = 70 73 | 74 | PREDICTOR-tournament-size = 2 75 | PREDICTOR-trivial-geography-radius = 0 76 | -------------------------------------------------------------------------------- /coevolution/DifficultFloatReg1.pushgp: -------------------------------------------------------------------------------- 1 | # Copyright 2009-2010 Jon Klein 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # 16 | # Evolving symbolic regression for y = 3x^2 + 4x 17 | # 18 | # Tom Helmuth 19 | # 8/14/10 20 | # 21 | 22 | ### Setup required parameters 23 | 24 | population-size = 200 25 | max-generations = 1000 26 | execution-limit = 150 27 | 28 | mutation-percent = 15 29 | crossover-percent = 75 30 | simplification-percent = 5 31 | 32 | tournament-size = 7 33 | max-points-in-program = 100 34 | 35 | max-random-code-size = 40 36 | simplify-flatten-percent = 10 37 | 38 | reproduction-simplifications = 25 39 | report-simplifications = 100 40 | final-simplifications = 2000 41 | 42 | ### Setup problem class and test cases. 43 | 44 | problem-class = org.spiderland.Psh.ProbClass.FloatSymbolicRegression 45 | instruction-set = (registered.float input.makeinputs1) 46 | 47 | test-case-class = org.spiderland.Psh.TestCase.FloatRegTestCases1 48 | 49 | ### Setup Optional Parameters 50 | 51 | trivial-geography-radius = 10 52 | simplify-flatten-percent = 5 53 | mutation-mode = fair 54 | fair-mutation-range = .5 55 | 56 | min-random-float = -10.0 57 | max-random-float = 10.0 58 | random-float-resolution = 0.01 59 | 60 | target-function-string = y = 3x^2 + 4x 61 | -------------------------------------------------------------------------------- /coevolution/DifficultFloatReg2.pushgp: -------------------------------------------------------------------------------- 1 | # Copyright 2009-2010 Jon Klein 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # 16 | # A difficult symbolic regression problem that needs many test cases. Will be 17 | # used to test TestCaseGenerator.java. The problem to be solved is 18 | # y = (e ^ |x|) * sin(x) 19 | # 20 | # Tom Helmuth 21 | # 8/9/10 22 | # 23 | 24 | ### Setup required parameters 25 | 26 | population-size = 150 27 | max-generations = 20000 28 | execution-limit = 200 29 | 30 | mutation-percent = 10 31 | crossover-percent = 80 32 | simplification-percent = 5 33 | 34 | tournament-size = 7 35 | max-points-in-program = 100 36 | 37 | max-random-code-size = 40 38 | simplify-flatten-percent = 10 39 | 40 | reproduction-simplifications = 25 41 | report-simplifications = 100 42 | final-simplifications = 2000 43 | 44 | ### Setup problem class and test cases. 45 | 46 | problem-class = org.spiderland.Psh.ProbClass.FloatSymbolicRegression 47 | test-case-class = org.spiderland.Psh.TestCase.FloatRegTestCases2 48 | 49 | #instruction-set = (registered.float input.makeinputs1) 50 | instruction-set = (input.makeinputs1 float.+ float.- float.* float./ float.exp float.sin float.cos) 51 | 52 | ### Setup Optional Parameters 53 | 54 | trivial-geography-radius = 10 55 | simplify-flatten-percent = 5 56 | mutation-mode = fair 57 | fair-mutation-range = .5 58 | 59 | min-random-float = -10.0 60 | max-random-float = 10.0 61 | random-float-resolution = 0.001 62 | 63 | target-function-string = y = (e ^ |x|) * sin(x) 64 | -------------------------------------------------------------------------------- /coevolution/DifficultIntReg1.pushgp: -------------------------------------------------------------------------------- 1 | # Copyright 2009-2010 Jon Klein 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # 16 | # A difficult int symbolic regression problem that needs many test cases. Will 17 | # be used to test TestCaseGenerator.java. The problem to be solved is 18 | # y = 9x^3 + 24x^2 - 3x + 10 19 | # 20 | # Tom Helmuth 21 | # 8/9/10 22 | # 23 | 24 | ### Setup required parameters 25 | 26 | population-size = 150 27 | max-generations = 20000 28 | execution-limit = 200 29 | 30 | mutation-percent = 10 31 | crossover-percent = 80 32 | simplification-percent = 5 33 | 34 | tournament-size = 7 35 | max-points-in-program = 100 36 | 37 | max-random-code-size = 40 38 | simplify-flatten-percent = 10 39 | 40 | reproduction-simplifications = 25 41 | report-simplifications = 100 42 | final-simplifications = 2000 43 | 44 | ### Setup problem class and test cases. 45 | 46 | problem-class = org.spiderland.Psh.ProbClass.IntSymbolicRegression 47 | instruction-set = (registered.integer registered.exec input.makeinputs1) 48 | 49 | test-case-class = org.spiderland.Psh.TestCase.IntRegTestCases1 50 | 51 | ### Setup Optional Parameters 52 | 53 | trivial-geography-radius = 10 54 | simplify-flatten-percent = 5 55 | mutation-mode = fair 56 | fair-mutation-range = .5 57 | 58 | min-random-integer = -100 59 | max-random-integer = 100 60 | random-integer-resolution = 1 61 | 62 | target-function-string = y = 9x^3 + 24x^2 - 3x + 10 63 | -------------------------------------------------------------------------------- /gpsamples/cartcenter.pushgp: -------------------------------------------------------------------------------- 1 | # Copyright 2009-2010 Jon Klein 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # 16 | # A sample PushGP file for testing the cart centering problem. This solves 17 | # the cart centering problem as described in John Koza's Genetic Programming, 18 | # chapter 7.1. In this problem, a cart is placed on a 1-dimensional, 19 | # frictionless track. At every time, the cart has a position and velocity on 20 | # the track. The problem is to stop the cart at the origin (within reasonable 21 | # approximations) by applying a fixed-magnitude force to accelerate the cart 22 | # in the forward or backward direction. 23 | # 24 | # Tom Helmuth 25 | # 05/20/2010 26 | # 27 | 28 | 29 | ### Set classes for the Push intepreter and individuals. These 30 | ### values can used to implement custom interpreter or individual 31 | ### behaviors. 32 | 33 | interpreter-class = org.spiderland.Psh.Interpreter 34 | inputpusher-class = org.spiderland.Psh.InputPusher 35 | individual-class = org.spiderland.Psh.PushGPIndividual 36 | 37 | ### Setup GP parameters 38 | 39 | population-size = 700 40 | max-generations = 30 41 | execution-limit = 150 42 | 43 | mutation-percent = 20 44 | crossover-percent = 70 45 | simplification-percent = 5 46 | 47 | tournament-size = 7 48 | trivial-geography-radius = 10 49 | max-points-in-program = 100 50 | mutation-mode = fair 51 | 52 | max-random-code-size = 40 53 | simplify-flatten-percent = 20 54 | 55 | reproduction-simplifications = 25 56 | report-simplifications = 100 57 | final-simplifications = 1000 58 | 59 | 60 | ### The problem class determines how test cases are setup and 61 | ### how fitness scores are computed. The CartCentering 62 | ### class uses a set of test case position-velocity pairs that are 63 | ### initial positions for the simulation 64 | 65 | problem-class = org.spiderland.Psh.ProbClass.CartCentering 66 | 67 | ### Each test case is a random pair in ([-1,1], [-1,1]). 68 | 69 | test-cases = ( (-0.294133296634 0.332170057671) (0.884483851852 0.463930712756) (-0.941108900715 -0.474550578003) (-0.2154123755 0.129190551234) (0.81059133629 -0.457220881675) (0.346539006331 -0.969663306002) (-0.958336743378 -0.862494306359) (0.262973889345 -0.0780369533455) (0.50091902012 -0.157506644573) (-0.628033696865 0.28470322712) (0.546528591363 0.97691173827) (0.945010339137 0.228957693882) (-0.431268738184 0.482249537404) (-0.277201566573 -0.348652935221) (-0.469219563194 -0.0790323397644) (-0.790678651745 -0.649224019784) (-0.707822583335 -0.215881725486) (-0.420589060752 0.257590241249) (-0.980695665536 0.0951923066897) (-0.315667389986 0.888282298712) ) 70 | 71 | ### Instruction set - either of the below sets can be used, but the second is more accurate. 72 | 73 | #instruction-set = (registered.float registered.input input.makeinputs2) 74 | instruction-set = (registered.input input.makeinputs2 float.+ float.- float.* float./ float.abs float.neg float.> float.= float.< float.% float.erc) 75 | 76 | -------------------------------------------------------------------------------- /gpsamples/floatreg0.pushgp: -------------------------------------------------------------------------------- 1 | # Copyright 2009-2010 Jon Klein 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # 16 | # A sample PushGP file for a simple test symbolic regression problem. 17 | # In this demo, the system solves the equation y = x^2 - 7, using 18 | # floating point symbolic regression 19 | # 20 | # Tom Helmuth 21 | # 06/08/2010 22 | # 23 | 24 | ### Setup required parameters 25 | 26 | problem-class = org.spiderland.Psh.ProbClass.FloatSymbolicRegression 27 | 28 | max-generations = 1000 29 | population-size = 200 30 | execution-limit = 100 31 | max-points-in-program = 50 32 | max-random-code-size = 30 33 | 34 | tournament-size = 7 35 | mutation-percent = 20 36 | crossover-percent = 70 37 | simplification-percent = 5 38 | 39 | reproduction-simplifications = 20 40 | report-simplifications = 100 41 | final-simplifications = 1000 42 | 43 | test-cases = ((-5 18) (-4 9) (-3 2) (-2 -3) (-1 -6) (0 -7) (1 -6) (2 -3) (3 2) (4 9) (5 18)) 44 | instruction-set = (float.* float.+ float.- float./ float.dup float.flush float.stackdepth float.swap float.erc input.makeinputs1) 45 | 46 | ### Setup Optional Parameters 47 | 48 | trivial-geography-radius = 10 49 | simplify-flatten-percent = 20 50 | mutation-mode = fair 51 | fair-mutation-range = .5 52 | 53 | min-random-float = -10.0 54 | max-random-float = 10.0 55 | random-float-resolution = 1.0 56 | target-function-string = y = x^2 - 7 57 | -------------------------------------------------------------------------------- /gpsamples/floatreg1.pushgp: -------------------------------------------------------------------------------- 1 | # Copyright 2009-2010 Jon Klein 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # 16 | # A sample PushGP file for a simple test symbolic regression problem. 17 | # In this demo, the system solves the equation y = 12x^2 + 5. 18 | # 19 | # Jon Klein 20 | # 06/14/2008 21 | # 22 | 23 | ### We can optionally read in some additional parameters 24 | include standard.pushgp 25 | 26 | ### Setup some standard GP parameters 27 | 28 | population-size = 2000 29 | execution-limit = 80 30 | tournament-size = 7 31 | mutation-percent = 10 32 | crossover-percent = 75 33 | max-generations = 200 34 | max-random-code-size = 40 35 | fair-mutation-range = .3 36 | 37 | ### New Parameters since version 0.1 38 | 39 | trivial-geography-radius= 10 40 | 41 | simplification-percent = 5 42 | simplify-flatten-percent= 20 43 | 44 | reproduction-simplifications = 25 45 | report-simplifications = 10 46 | final-simplifications = 1000 47 | 48 | target-function-string = y = 12x^2 + 5 49 | 50 | 51 | ### The problem class determines how test cases are setup and 52 | ### how fitness scores are computed. The FloatSymbolicRegression 53 | ### class uses a set of float inputs and a single output. 54 | 55 | problem-class = org.spiderland.Psh.ProbClass.FloatSymbolicRegression 56 | 57 | test-cases = ( ( 1 17 ) ( 2 53 ) ( 3 113 ) ( 4 197 ) ( 5 305 ) ) 58 | 59 | ### Other possible ways of defining test cases 60 | 61 | # test-case-class = Problem1Generator # at runtime from code 62 | # test-case-xml = Problem1.xml # from an XML file 63 | # test-case-csv = Problem1.csv # from a comma separated value file 64 | 65 | instruction-set = ( float.* float.+ float.% float.- float.dup float.swap float.erc input.makeinputs1 ) 66 | -------------------------------------------------------------------------------- /gpsamples/floatreg2.pushgp: -------------------------------------------------------------------------------- 1 | # Copyright 2009-2010 Jon Klein 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # 16 | # A sample PushGP file for a simple test symbolic regression problem. 17 | # In this demo, the system solves the equation y = 1.72x^2 - 0.68x^3, using 18 | # floating point symbolic regression 19 | # 20 | # Tom Helmuth 21 | # 06/08/2010 22 | # 23 | 24 | ### Setup required parameters 25 | 26 | problem-class = org.spiderland.Psh.ProbClass.FloatSymbolicRegression 27 | 28 | max-generations = 200 29 | population-size = 2000 30 | execution-limit = 150 31 | max-points-in-program = 100 32 | max-random-code-size = 40 33 | 34 | tournament-size = 7 35 | mutation-percent = 10 36 | crossover-percent = 80 37 | simplification-percent = 5 38 | 39 | reproduction-simplifications = 25 40 | report-simplifications = 100 41 | final-simplifications = 10000 42 | 43 | test-cases = ((-5 128) (-4.5 96.795) (-4 71.04) (-3.5 50.225) (-3 33.84) (-2.5 21.375) (-2 12.32) (-1.5 6.165) (-1 2.4) (-0.5 0.515) (0 0) (0.5 .345) (1 1.04) (1.5 1.575) (2 1.44) (2.5 0.125) (3 -2.88) (3.5 -8.085) (4 -16) (4.5 -27.135) (5 -42)) 44 | instruction-set = (registered.float input.makeinputs1) 45 | 46 | ### Setup Optional Parameters 47 | 48 | trivial-geography-radius = 20 49 | simplify-flatten-percent = 20 50 | mutation-mode = fair 51 | fair-mutation-range = .5 52 | 53 | min-random-float = -2.0 54 | max-random-float = 2.0 55 | random-float-resolution = 0.01 56 | 57 | target-function-string = y = 1.72x^2 - 0.68x^3 58 | -------------------------------------------------------------------------------- /gpsamples/floatreg3.pushgp: -------------------------------------------------------------------------------- 1 | # Copyright 2009-2010 Jon Klein 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # 16 | # A sample PushGP file for a simple test symbolic regression problem. 17 | # In this demo, the system solves the equation y = 2|x| - 2x^2 + x, using 18 | # floating point symbolic regression 19 | # 20 | # Tom Helmuth 21 | # 09/03/2010 22 | # 23 | 24 | ### Setup required parameters 25 | 26 | problem-class = org.spiderland.Psh.ProbClass.FloatSymbolicRegression 27 | 28 | max-generations = 500 29 | population-size = 200 30 | execution-limit = 150 31 | max-points-in-program = 100 32 | max-random-code-size = 40 33 | 34 | tournament-size = 7 35 | mutation-percent = 10 36 | crossover-percent = 80 37 | simplification-percent = 5 38 | 39 | reproduction-simplifications = 25 40 | report-simplifications = 10 41 | final-simplifications = 10000 42 | 43 | test-cases = ((-5 -20) (-4.5 -15.75) (-4 -12) (-3.5 -8.75) (-3 -6) (-2.5 -3.75) (-2 -2) (-1.5 -0.75) (-1 0) (-0.5 0.25) (0 0) (0.5 1.25) (1 2) (1.5 2.25) (2 2) (2.5 1.25) (3 0) (3.5 -1.75) (4 -4) (4.5 -6.75) (5 -10)) 44 | instruction-set = (registered.float input.makeinputs1) 45 | 46 | ### Setup Optional Parameters 47 | 48 | trivial-geography-radius = 10 49 | simplify-flatten-percent = 20 50 | mutation-mode = fair 51 | fair-mutation-range = .5 52 | 53 | min-random-float = -5.0 54 | max-random-float = 5.0 55 | random-float-resolution = 0.5 56 | 57 | target-function-string = y = 2|x| - 2x^2 + x 58 | -------------------------------------------------------------------------------- /gpsamples/intreg0.pushgp: -------------------------------------------------------------------------------- 1 | # Copyright 2009-2010 Jon Klein 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # 16 | # A sample PushGP file for a simple test symbolic regression problem. 17 | # In this demo, the system solves the equation y = x, using 18 | # integer symbolic regression. 19 | # 20 | # Tom Helmuth 21 | # 01/12/2010 22 | # 23 | 24 | ### Set classes for the Push intepreter and individuals. These 25 | ### values can used to implement custom interpreter or individual 26 | ### behaviors. 27 | 28 | interpreter-class = org.spiderland.Psh.Interpreter 29 | inputpusher-class = org.spiderland.Psh.InputPusher 30 | individual-class = org.spiderland.Psh.PushGPIndividual 31 | 32 | # push-frame-mode = pushstacks 33 | 34 | ### Setup some standard GP parameters 35 | 36 | mutation-percent = 40 37 | crossover-percent = 40 38 | simplification-percent = 10 39 | 40 | simplify-flatten-percent= 20 41 | 42 | reproduction-simplifications = 25 43 | report-simplifications = 100 44 | final-simplifications = 1000 45 | 46 | max-generations = 200 47 | tournament-size = 7 48 | trivial-geography-radius= 0 49 | max-points-in-program = 40 50 | mutation-mode = fair 51 | fair-mutation-range = .3 52 | population-size = 50 53 | execution-limit = 80 54 | max-random-code-size = 40 55 | 56 | target-function-string = y = x 57 | 58 | ### The problem class determines how test cases are setup and 59 | ### how fitness scores are computed. The IntSymbolicRegression 60 | ### class uses a set of int inputs and a single output. 61 | 62 | problem-class = org.spiderland.Psh.ProbClass.IntSymbolicRegression 63 | 64 | #This test case is for y = x 65 | test-cases = ( ( 1 1 ) ( 2 2 ) ( 5 5 ) ( 41 41 ) ( 95 95 ) ( 124 124 ) ) 66 | 67 | 68 | #Instruction set for y = x 69 | instruction-set = ( integer.% integer.* integer.+ integer.- integer./ integer.< integer.= integer.> integer.dup integer.flush integer.pop integer.rot integer.stackdepth integer.swap integer.erc boolean.dup boolean.flush boolean.pop boolean.rot boolean.stackdepth boolean.swap exec.= exec.do*count exec.do*range exec.do*times exec.dup exec.flush exec.pop exec.rot exec.stackdepth exec.swap registered.input input.makeinputs1 ) 70 | -------------------------------------------------------------------------------- /gpsamples/intreg1.pushgp: -------------------------------------------------------------------------------- 1 | # Copyright 2009-2010 Jon Klein 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # 16 | # A sample PushGP file for a simple test symbolic regression problem. 17 | # In this demo, the system solves the equation y = 12x^2 + 5, using 18 | # integer symbolic regression 19 | # 20 | # Jon Klein 21 | # 06/14/2008 22 | # 23 | # Changes by Tom Helmuth 24 | # 06/05/2010 25 | # 26 | 27 | ### Setup some standard GP parameters 28 | 29 | tournament-size = 7 30 | trivial-geography-radius= 10 31 | max-points-in-program = 100 32 | mutation-mode = fair 33 | fair-mutation-range = .5 34 | 35 | population-size = 2000 36 | mutation-percent = 10 37 | crossover-percent = 75 38 | simplification-percent = 5 39 | max-generations = 200 40 | max-random-code-size = 40 41 | 42 | execution-limit = 80 43 | 44 | reproduction-simplifications = 25 45 | report-simplifications = 100 46 | final-simplifications = 1000 47 | 48 | target-function-string = y = 12x^2 + 5 49 | 50 | 51 | ### The problem class determines how test cases are setup and 52 | ### how fitness scores are computed. The IntSymbolicRegression 53 | ### class uses a set of int inputs and a single output. 54 | 55 | problem-class = org.spiderland.Psh.ProbClass.IntSymbolicRegression 56 | 57 | #This test case is for y = 12x^2 + 5 58 | test-cases = ( ( 1 17 ) ( 2 53 ) ( 3 113 ) ( 4 197 ) ( 5 305 ) ) 59 | 60 | #Instruction set for y = 12x^2 + 5 61 | instruction-set = (registered.integer registered.input input.makeinputs1) 62 | -------------------------------------------------------------------------------- /gpsamples/intreg2.pushgp: -------------------------------------------------------------------------------- 1 | # Copyright 2009-2010 Jon Klein 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # 16 | # A sample PushGP file for a simple test symbolic regression problem. 17 | # In this demo, the system solves the factorial function using 18 | # integer symbolic regression 19 | # 20 | # Tom Helmuth 21 | # 01/17/2010 22 | # 23 | 24 | ### Set classes for the Push interpreter and individuals. These 25 | ### values can used to implement custom interpreter or individual 26 | ### behaviors. 27 | 28 | interpreter-class = org.spiderland.Psh.Interpreter 29 | inputpusher-class = org.spiderland.Psh.InputPusher 30 | individual-class = org.spiderland.Psh.PushGPIndividual 31 | 32 | ### Setup GP parameters 33 | 34 | execution-limit = 150 35 | 36 | mutation-percent = 30 37 | crossover-percent = 55 38 | simplification-percent = 5 39 | 40 | max-generations = 500 41 | tournament-size = 7 42 | trivial-geography-radius= 10 43 | max-points-in-program = 100 44 | mutation-mode = fair 45 | fair-mutation-range = .5 46 | population-size = 1000 47 | max-random-code-size = 40 48 | 49 | simplify-flatten-percent= 20 50 | 51 | reproduction-simplifications = 25 52 | report-simplifications = 100 53 | final-simplifications = 1000 54 | 55 | 56 | ### The problem class determines how test cases are setup and 57 | ### how fitness scores are computed. The IntSymbolicRegression 58 | ### class uses a set of int inputs and a single output. 59 | 60 | problem-class = org.spiderland.Psh.ProbClass.IntSymbolicRegression 61 | 62 | #This test case is for factorial 63 | test-cases = ((1 1) (2 2) (3 6) (4 24) (5 120) (6 720)) 64 | 65 | target-function-string = y = x! 66 | 67 | #Instruction set for factorial 68 | #instruction-set = (registered.integer registered.exec registered.code registered.boolean registered.input input.makeinputs1 ) 69 | instruction-set = (registered.integer input.makeinputs1) -------------------------------------------------------------------------------- /gpsamples/nodeselectiontesting.pushgp: -------------------------------------------------------------------------------- 1 | # Copyright 2009-2010 Jon Klein 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # 16 | # A sample PushGP file for a simple test symbolic regression problem. 17 | # In this demo, the system solves the equation y = 12x^2 + 5. 18 | # 19 | # Tom Helmuth 20 | # 11/20/2010 21 | # 22 | 23 | ### Setup required parameters 24 | 25 | problem-class = org.spiderland.Psh.ProbClass.FloatSymbolicRegression 26 | 27 | max-generations = 500 28 | population-size = 200 29 | execution-limit = 150 30 | max-points-in-program = 100 31 | max-random-code-size = 40 32 | 33 | tournament-size = 7 34 | mutation-percent = 20 35 | crossover-percent = 65 36 | simplification-percent = 10 37 | 38 | reproduction-simplifications = 25 39 | report-simplifications = 100 40 | final-simplifications = 10000 41 | 42 | test-cases = ((0 5) ( 1 17 ) ( 2 53 ) ( 3 113 ) ( 4 197 ) ( 5 305 ) (6 437) (7 593) (8 773) (9 977) (10 1205)) 43 | instruction-set = ( float.* float.+ float.% float.- float.dup float.swap float.erc input.makeinputs1 ) 44 | 45 | ### Setup Optional Parameters 46 | 47 | trivial-geography-radius = 10 48 | simplify-flatten-percent = 20 49 | 50 | min-random-float = -20.0 51 | max-random-float = 20.0 52 | random-float-resolution = 1.0 53 | 54 | target-function-string = y = 12x^2 + 5 55 | 56 | ### Setup optional parameters having to do with node selection and replacement 57 | 58 | #Options: unbiased, leaf-probability, size-tournament 59 | node-selection-mode = size-tournament 60 | node-selection-leaf-probability = 10 61 | node-selection-tournament-size = 2 62 | 63 | #mutation-mode = fair 64 | #fair-mutation-range = .5 65 | 66 | -------------------------------------------------------------------------------- /gpsamples/standard.pushgp: -------------------------------------------------------------------------------- 1 | # Copyright 2009-2010 Jon Klein 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # 16 | # PushGP common configuration settings 17 | # Jon Klein 18 | # 06/14/2008 19 | # 20 | 21 | ### Set classes for the Push intepreter and individuals. These 22 | ### values can used to implement custom interpreter or individual 23 | ### behaviors. 24 | 25 | interpreter-class = org.spiderland.Psh.Interpreter 26 | inputpusher-class = org.spiderland.Psh.InputPusher 27 | individual-class = org.spiderland.Psh.PushGPIndividual 28 | 29 | # push-frame-mode = pushstacks 30 | 31 | ### Reasonable default values for GP -- may be changed by problem 32 | ### specific configuration files 33 | 34 | tournament-size = 7 35 | trivial-geography-radius = 0 36 | max-points-in-program = 100 37 | mutation-mode = fair 38 | fair-mutation-range = .3 39 | -------------------------------------------------------------------------------- /gpsamples/trival-gp-problemset/problemset.pushgp: -------------------------------------------------------------------------------- 1 | # Copyright 2009-2010 Jon Klein 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # 16 | # A common PshGP config file for a set of symbolic regression problems 17 | # used in the book chapter: 18 | # 19 | # Spector, L., and J. Klein. 2005. Trivial Geography in Genetic Programming. 20 | # In Genetic Programming Theory and Practice III, edited by T. Yu, R.L. Riolo, 21 | # and B. Worzel, pp. 109-124. Boston, MA: Kluwer Academic Publishers. 22 | # 23 | # http://hampshire.edu/lspector/pubs/trivial-geography-toappear.pdf 24 | # 25 | # Though the problem sets are the same as those presented in the paper, the 26 | # PushGP parameters and PushGP implementation are different than those used 27 | # in the paper and may produce different results. 28 | # 29 | # Jon Klein 30 | # 06/14/2008 31 | # 32 | 33 | ### We can optionally read in some additional parameters 34 | include ../standard.pushgp 35 | 36 | ### Set classes for the Push intepreter and individuals. We 37 | ### can use this to implement custom interpreter behaviors. 38 | 39 | interpreter-class = org.spiderland.Psh.Interpreter 40 | individual-class = org.spiderland.Psh.PushGPIndividual 41 | 42 | ### Setup some standard GP parameters 43 | 44 | population-size = 2000 45 | execution-limit = 200 46 | tournament-size = 7 47 | mutation-percent = 20 48 | crossover-percent = 70 49 | max-generations = 200 50 | max-random-code-size = 40 51 | fair-mutation-range = .3 52 | 53 | ### New Parameters since version 0.1 54 | 55 | trivial-geography-radius= 10 56 | 57 | simplification-percent = 0 58 | simplify-flatten-percent= 20 59 | 60 | reproduction-simplifications = 25 61 | report-simplifications = 100 62 | final-simplifications = 1000 63 | 64 | 65 | ### The problem class determines how test cases are setup and 66 | ### how fitness scores are computed. The FloatSymbolicRegression 67 | ### class uses a set of float inputs and a single output. 68 | 69 | problem-class = org.spiderland.Psh.ProbClass.FloatSymbolicRegression 70 | 71 | instruction-set = ( float.* float.+ float.% float.dup float.- float.swap float.erc registered.input) 72 | -------------------------------------------------------------------------------- /gpsamples/trival-gp-problemset/regression1.pushgp: -------------------------------------------------------------------------------- 1 | 2 | include problemset.pushgp 3 | 4 | test-cases = ( ( 0 0 ) ( 1 12 ) ( 2 78 ) ( 3 246 ) ( 4 564 ) ( 5 1080 ) ( 6 1842 ) ( 7 2898 ) ( 8 4296 ) ( 9 6084 ) ) 5 | -------------------------------------------------------------------------------- /gpsamples/trival-gp-problemset/regression10.pushgp: -------------------------------------------------------------------------------- 1 | 2 | include problemset.pushgp 3 | 4 | test-cases = ( ( 0 -2 ) ( 1 -2 ) ( 2 34 ) ( 3 574 ) ( 4 3598 ) ( 5 14398 ) ( 6 44098 ) ( 7 112894 ) ( 8 254014 ) ( 9 518398 ) ) 5 | -------------------------------------------------------------------------------- /gpsamples/trival-gp-problemset/regression2.pushgp: -------------------------------------------------------------------------------- 1 | 2 | include problemset.pushgp 3 | 4 | test-cases = ( ( 0 0 ) ( 1 21 ) ( 2 78 ) ( 3 213 ) ( 4 468 ) ( 5 885 ) ( 6 1506 ) ( 7 2373 ) ( 8 3528 ) ( 9 5013 ) ) -------------------------------------------------------------------------------- /gpsamples/trival-gp-problemset/regression3.pushgp: -------------------------------------------------------------------------------- 1 | 2 | include problemset.pushgp 3 | 4 | test-cases = ( ( 0 0 ) ( 1 14 ) ( 2 82 ) ( 3 234 ) ( 4 500 ) ( 5 910 ) ( 6 1494 ) ( 7 2282 ) ( 8 3304 ) ( 9 4590 ) ) 5 | -------------------------------------------------------------------------------- /gpsamples/trival-gp-problemset/regression4.pushgp: -------------------------------------------------------------------------------- 1 | 2 | include problemset.pushgp 3 | 4 | test-cases = ( ( 0 0 ) ( 1 3 ) ( 2 14 ) ( 3 39 ) ( 4 84 ) ( 5 155 ) ( 6 258 ) ( 7 399 ) ( 8 584 ) ( 9 819 ) ) 5 | -------------------------------------------------------------------------------- /gpsamples/trival-gp-problemset/regression5.pushgp: -------------------------------------------------------------------------------- 1 | 2 | include problemset.pushgp 3 | 4 | test-cases = ( ( 0 0 ) ( 1 -2 ) ( 2 -2 ) ( 3 6 ) ( 4 28 ) ( 5 70 ) ( 6 138 ) ( 7 238 ) ( 8 376 ) ( 9 558 ) ) 5 | -------------------------------------------------------------------------------- /gpsamples/trival-gp-problemset/regression6.pushgp: -------------------------------------------------------------------------------- 1 | 2 | include problemset.pushgp 3 | 4 | test-cases = ( ( 0 6 ) ( 1 18 ) ( 2 290 ) ( 3 2040 ) ( 4 8406 ) ( 5 25406 ) ( 6 62898 ) ( 7 135540 ) ( 8 263750 ) ( 9 474666 ) ) 5 | -------------------------------------------------------------------------------- /gpsamples/trival-gp-problemset/regression7.pushgp: -------------------------------------------------------------------------------- 1 | 2 | include problemset.pushgp 3 | 4 | test-cases = ( ( 0 -3 ) ( 1 18 ) ( 2 107 ) ( 3 480 ) ( 4 1521 ) ( 5 3782 ) ( 6 7983 ) ( 7 15012 ) ( 8 25925 ) ( 9 41946 ) ) 5 | -------------------------------------------------------------------------------- /gpsamples/trival-gp-problemset/regression8.pushgp: -------------------------------------------------------------------------------- 1 | 2 | include problemset.pushgp 3 | 4 | test-cases = ( ( 0 5 ) ( 1 6 ) ( 2 233 ) ( 3 3056 ) ( 4 18165 ) ( 5 71330 ) ( 6 216761 ) ( 7 553068 ) ( 8 1242821 ) ( 9 2535710 ) 5 | -------------------------------------------------------------------------------- /gpsamples/trival-gp-problemset/regression9.pushgp: -------------------------------------------------------------------------------- 1 | 2 | include problemset.pushgp 3 | 4 | test-cases = ( ( 0 -8 ) ( 1 -4 ) ( 2 22 ) ( 3 112 ) ( 4 332 ) ( 5 772 ) ( 6 1546 ) ( 7 2792 ) ( 8 4672 ) ( 9 7372 ) ) 5 | -------------------------------------------------------------------------------- /org/spiderland/Psh/Checkpoint.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh; 18 | 19 | import java.io.Serializable; 20 | 21 | public class Checkpoint implements Serializable { 22 | private static final long serialVersionUID = 1L; 23 | int checkpointNumber; 24 | GA ga; 25 | StringBuffer report; 26 | 27 | public Checkpoint(GA ga) { 28 | checkpointNumber = 0; 29 | this.ga = ga; 30 | report = new StringBuffer(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /org/spiderland/Psh/Coevolution/CEFloatSymbolicRegression.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh.Coevolution; 18 | 19 | import java.util.ArrayList; 20 | import java.util.HashMap; 21 | 22 | import org.spiderland.Psh.GAIndividual; 23 | import org.spiderland.Psh.GATestCase; 24 | import org.spiderland.Psh.Interpreter; 25 | import org.spiderland.Psh.ObjectPair; 26 | import org.spiderland.Psh.Program; 27 | import org.spiderland.Psh.PushGP; 28 | import org.spiderland.Psh.PushGPIndividual; 29 | import org.spiderland.Psh.floatStack; 30 | import org.spiderland.Psh.TestCase.TestCaseGenerator; 31 | 32 | /** 33 | * This problem class implements symbolic regression for floating point numbers 34 | * using co-evolved prediction. The class must keep track of the amount of 35 | * effort it takes compared to the effort of the co-evolving predictor 36 | * population, and use about 95% of the effort. Effort based on the number of 37 | * evaluation executions thus far, which is tracked by the interpreter. 38 | * 39 | */ 40 | public class CEFloatSymbolicRegression extends PushGP { 41 | private static final long serialVersionUID = 1L; 42 | 43 | protected float _currentInput; 44 | 45 | protected long _effort; 46 | protected float _predictorEffortPercent; 47 | protected PredictionGA _predictorGA; 48 | 49 | private boolean _success; 50 | 51 | private float _noResultPenalty = 1000f; 52 | 53 | protected void InitFromParameters() throws Exception { 54 | super.InitFromParameters(); 55 | 56 | _effort = 0; 57 | 58 | String cases = GetParam("test-cases", true); 59 | String casesClass = GetParam("test-case-class", true); 60 | if (cases == null && casesClass == null) { 61 | throw new Exception("No acceptable test-case parameter."); 62 | } 63 | 64 | if (casesClass != null) { 65 | // Get test cases from the TestCasesClass. 66 | Class iclass = Class.forName(casesClass); 67 | Object iObject = iclass.newInstance(); 68 | if (!(iObject instanceof TestCaseGenerator)) { 69 | throw (new Exception( 70 | "test-case-class must inherit from class TestCaseGenerator")); 71 | } 72 | 73 | TestCaseGenerator testCaseGenerator = (TestCaseGenerator) iObject; 74 | int numTestCases = testCaseGenerator.TestCaseCount(); 75 | 76 | for (int i = 0; i < numTestCases; i++) { 77 | ObjectPair testCase = testCaseGenerator.TestCase(i); 78 | 79 | Float in = (Float) testCase._first; 80 | Float out = (Float) testCase._second; 81 | 82 | Print(";; Fitness case #" + i + " input: " + in + " output: " 83 | + out + "\n"); 84 | 85 | _testCases.add(new GATestCase(in, out)); 86 | } 87 | } else { 88 | // Get test cases from test-cases. 89 | Program caselist = new Program(_interpreter, cases); 90 | 91 | for (int i = 0; i < caselist.size(); i++) { 92 | Program p = (Program) caselist.peek(i); 93 | 94 | if (p.size() < 2) 95 | throw new Exception( 96 | "Not enough elements for fitness case \"" + p 97 | + "\""); 98 | 99 | Float in = new Float(p.peek(0).toString()); 100 | Float out = new Float(p.peek(1).toString()); 101 | 102 | Print(";; Fitness case #" + i + " input: " + in + " output: " 103 | + out + "\n"); 104 | 105 | _testCases.add(new GATestCase(in, out)); 106 | } 107 | } 108 | 109 | // Create and initialize predictors 110 | _predictorEffortPercent = GetFloatParam("PREDICTOR-effort-percent", 111 | true); 112 | _predictorGA = PredictionGA.PredictionGAWithParameters(this, 113 | GetPredictorParameters(_parameters)); 114 | 115 | } 116 | 117 | protected void InitInterpreter(Interpreter inInterpreter) { 118 | } 119 | 120 | @Override 121 | protected void BeginGeneration() throws Exception { 122 | //trh Temporary solution, needs to actually use effort info 123 | if(_generationCount % 2 == 1){ 124 | _predictorGA.Run(1); 125 | } 126 | } 127 | 128 | /** 129 | * Evaluates a solution individual using the best predictor so far. 130 | */ 131 | protected void PredictIndividual(GAIndividual inIndividual, 132 | boolean duringSimplify) { 133 | 134 | FloatRegFitPredictionIndividual predictor = (FloatRegFitPredictionIndividual) _predictorGA.GetBestPredictor(); 135 | float fitness = predictor.PredictSolutionFitness((PushGPIndividual) inIndividual); 136 | 137 | inIndividual.SetFitness(fitness); 138 | inIndividual.SetErrors(new ArrayList()); 139 | } 140 | 141 | public float EvaluateTestCase(GAIndividual inIndividual, Object inInput, 142 | Object inOutput) { 143 | _effort++; 144 | 145 | _interpreter.ClearStacks(); 146 | 147 | _currentInput = (Float) inInput; 148 | 149 | floatStack fstack = _interpreter.floatStack(); 150 | 151 | fstack.push(_currentInput); 152 | 153 | // Must be included in order to use the input stack. 154 | _interpreter.inputStack().push(_currentInput); 155 | 156 | _interpreter.Execute(((PushGPIndividual) inIndividual)._program, 157 | _executionLimit); 158 | 159 | float result = fstack.top(); 160 | 161 | // System.out.println( _interpreter + " " + result ); 162 | 163 | //trh 164 | /* 165 | * System.out.println("\nevaluations according to interpreter " + 166 | * Interpreter.GetEvaluationExecutions()); 167 | * System.out.println("evaluations according to effort " + _effort); 168 | */ 169 | 170 | // Penalize individual if there is no result on the stack. 171 | if(fstack.size() == 0){ 172 | return _noResultPenalty; 173 | } 174 | 175 | return result - ((Float) inOutput); 176 | } 177 | 178 | protected boolean Success() { 179 | if(_success){ 180 | return true; 181 | } 182 | 183 | GAIndividual best = _populations[_currentPopulation][_bestIndividual]; 184 | float predictedFitness = best.GetFitness(); 185 | 186 | _predictorGA.EvaluateSolutionIndividual((PushGPIndividual) best); 187 | 188 | _bestMeanFitness = best.GetFitness(); 189 | 190 | if(_bestMeanFitness <= 0.1){ 191 | _success = true; 192 | return true; 193 | } 194 | 195 | best.SetFitness(predictedFitness); 196 | return false; 197 | } 198 | 199 | protected String Report() { 200 | Success(); // Finds the real fitness of the best individual 201 | 202 | return super.Report(); 203 | } 204 | 205 | private HashMap GetPredictorParameters( 206 | HashMap parameters) throws Exception { 207 | 208 | HashMap predictorParameters = new HashMap(); 209 | 210 | predictorParameters.put("max-generations", Integer 211 | .toString(Integer.MAX_VALUE)); 212 | 213 | predictorParameters.put("problem-class", 214 | GetParam("PREDICTOR-problem-class")); 215 | predictorParameters.put("individual-class", 216 | GetParam("PREDICTOR-individual-class")); 217 | predictorParameters.put("population-size", 218 | GetParam("PREDICTOR-population-size")); 219 | predictorParameters.put("mutation-percent", 220 | GetParam("PREDICTOR-mutation-percent")); 221 | predictorParameters.put("crossover-percent", 222 | GetParam("PREDICTOR-crossover-percent")); 223 | predictorParameters.put("tournament-size", 224 | GetParam("PREDICTOR-tournament-size")); 225 | predictorParameters.put("trivial-geography-radius", 226 | GetParam("PREDICTOR-trivial-geography-radius")); 227 | predictorParameters.put("generations-between-trainers", 228 | GetParam("PREDICTOR-generations-between-trainers")); 229 | predictorParameters.put("trainer-population-size", 230 | GetParam("PREDICTOR-trainer-population-size")); 231 | 232 | return predictorParameters; 233 | } 234 | 235 | /** 236 | * NOTE: This is entirely copied from PushGP, except EvaluateIndividual 237 | * was changed to PredictIndividual, as noted below. 238 | */ 239 | protected void Evaluate() { 240 | float totalFitness = 0; 241 | _bestMeanFitness = Float.MAX_VALUE; 242 | 243 | for (int n = 0; n < _populations[_currentPopulation].length; n++) { 244 | GAIndividual i = _populations[_currentPopulation][n]; 245 | 246 | PredictIndividual(i, false); 247 | 248 | totalFitness += i.GetFitness(); 249 | 250 | if (i.GetFitness() < _bestMeanFitness) { 251 | _bestMeanFitness = i.GetFitness(); 252 | _bestIndividual = n; 253 | _bestSize = ((PushGPIndividual) i)._program.programsize(); 254 | _bestErrors = i.GetErrors(); 255 | } 256 | } 257 | 258 | _populationMeanFitness = totalFitness / _populations[_currentPopulation].length; 259 | } 260 | 261 | /** 262 | * NOTE: This is entirely copied from PushGP, except EvaluateIndividual 263 | * was changed to PredictIndividual, as noted below (twice). 264 | */ 265 | protected PushGPIndividual Autosimplify(PushGPIndividual inIndividual, 266 | int steps) { 267 | 268 | PushGPIndividual simplest = (PushGPIndividual) inIndividual.clone(); 269 | PushGPIndividual trial = (PushGPIndividual) inIndividual.clone(); 270 | PredictIndividual(simplest, true); // Changed from EvaluateIndividual 271 | float bestError = simplest.GetFitness(); 272 | 273 | boolean madeSimpler = false; 274 | 275 | for (int i = 0; i < steps; i++) { 276 | madeSimpler = false; 277 | float method = _RNG.nextInt(100); 278 | 279 | if (trial._program.programsize() <= 0) 280 | break; 281 | if (method < _simplifyFlattenPercent) { 282 | // Flatten random thing 283 | int pointIndex = _RNG.nextInt(trial._program.programsize()); 284 | Object point = trial._program.Subtree(pointIndex); 285 | 286 | if (point instanceof Program) { 287 | trial._program.Flatten(pointIndex); 288 | madeSimpler = true; 289 | } 290 | } else { 291 | // Remove small number of random things 292 | int numberToRemove = _RNG.nextInt(3) + 1; 293 | 294 | for (int j = 0; j < numberToRemove; j++) { 295 | int trialSize = trial._program.programsize(); 296 | 297 | if (trialSize > 0) { 298 | int pointIndex = _RNG.nextInt(trialSize); 299 | trial._program.ReplaceSubtree(pointIndex, new Program( 300 | _interpreter)); 301 | trial._program.Flatten(pointIndex); 302 | madeSimpler = true; 303 | } 304 | } 305 | } 306 | 307 | if (madeSimpler) { 308 | PredictIndividual(trial, true); // Changed from EvaluateIndividual 309 | 310 | if (trial.GetFitness() <= bestError) { 311 | simplest = (PushGPIndividual) trial.clone(); 312 | bestError = trial.GetFitness(); 313 | } 314 | } 315 | 316 | trial = (PushGPIndividual) simplest.clone(); 317 | } 318 | 319 | return simplest; 320 | } 321 | 322 | } 323 | -------------------------------------------------------------------------------- /org/spiderland/Psh/Coevolution/FloatRegFitPrediction.java: -------------------------------------------------------------------------------- 1 | package org.spiderland.Psh.Coevolution; 2 | 3 | import java.util.ArrayList; 4 | 5 | import org.spiderland.Psh.GAIndividual; 6 | import org.spiderland.Psh.PushGPIndividual; 7 | 8 | public class FloatRegFitPrediction extends PredictionGA { 9 | private static final long serialVersionUID = 1L; 10 | 11 | @Override 12 | protected void InitIndividual(GAIndividual inIndividual) { 13 | FloatRegFitPredictionIndividual i = (FloatRegFitPredictionIndividual) inIndividual; 14 | 15 | int[] samples = new int[FloatRegFitPredictionIndividual._sampleSize]; 16 | for(int j = 0; j < samples.length; j++){ 17 | samples[j] = _RNG.nextInt(_solutionGA._testCases.size()); 18 | } 19 | i.SetSampleIndicesAndSolutionGA(_solutionGA, samples); 20 | } 21 | 22 | @Override 23 | protected void EvaluateIndividual(GAIndividual inIndividual) { 24 | 25 | FloatRegFitPredictionIndividual predictor = (FloatRegFitPredictionIndividual) inIndividual; 26 | ArrayList errors = new ArrayList(); 27 | 28 | for(int i = 0; i < _trainerPopulationSize; i++){ 29 | float predictedError = predictor.PredictSolutionFitness(_trainerPopulation.get(i)); 30 | 31 | // Error is difference between predictedError and the actual fitness 32 | // of the trainer. 33 | float error = Math.abs(predictedError) - Math.abs(_trainerPopulation.get(i).GetFitness()); 34 | errors.add(error); 35 | } 36 | 37 | predictor.SetFitness(AbsoluteAverageOfErrors(errors)); 38 | predictor.SetErrors(errors); 39 | } 40 | 41 | /** 42 | * Determines the predictor's fitness on a trainer, where the trainer is the 43 | * inInput, and the trainer's actual fitness is inOutput. The fitness of 44 | * the predictor is the absolute error between the prediction and the 45 | * trainer's actual fitness. 46 | * 47 | * @return Predictor's fitness (i.e. error) for the given trainer. 48 | * @throws Exception 49 | */ 50 | @Override 51 | public float EvaluateTestCase(GAIndividual inIndividual, Object inInput, 52 | Object inOutput) { 53 | 54 | PushGPIndividual trainer = (PushGPIndividual) inInput; 55 | float trainerFitness = (Float) inOutput; 56 | 57 | float predictedTrainerFitness = ((PredictionGAIndividual) inIndividual) 58 | .PredictSolutionFitness(trainer); 59 | 60 | return Math.abs(predictedTrainerFitness - trainerFitness); 61 | } 62 | 63 | @Override 64 | protected void EvaluateTrainerFitnesses() { 65 | for(PushGPIndividual trainer : _trainerPopulation){ 66 | if(!trainer.FitnessIsSet()){ 67 | EvaluateSolutionIndividual(trainer); 68 | } 69 | } 70 | } 71 | 72 | protected void Reproduce() { 73 | int nextPopulation = _currentPopulation == 0 ? 1 : 0; 74 | 75 | for (int n = 0; n < _populations[_currentPopulation].length; n++) { 76 | float method = _RNG.nextInt(100); 77 | GAIndividual next; 78 | 79 | if (method < _mutationPercent) { 80 | next = ReproduceByMutation(n); 81 | } else if (method < _crossoverPercent + _mutationPercent) { 82 | next = ReproduceByCrossover(n); 83 | } else { 84 | next = ReproduceByClone(n); 85 | } 86 | 87 | // Make sure next isn't already in the population, so that all 88 | // predictors are unique. 89 | for (int k = 0; k < n; k++) { 90 | if (((FloatRegFitPredictionIndividual) next) 91 | .equalPredictors(_populations[nextPopulation][k])) { 92 | int index = _RNG 93 | .nextInt(FloatRegFitPredictionIndividual._sampleSize); 94 | ((FloatRegFitPredictionIndividual) next).SetSampleIndex( 95 | index, _RNG.nextInt(_solutionGA._testCases.size())); 96 | } 97 | } 98 | 99 | _populations[nextPopulation][n] = next; 100 | 101 | } 102 | } 103 | 104 | /** 105 | * Mutates an individual by choosing an index at random and randomizing 106 | * its training point among possible individuals. 107 | */ 108 | @Override 109 | protected GAIndividual ReproduceByMutation(int inIndex) { 110 | FloatRegFitPredictionIndividual i = (FloatRegFitPredictionIndividual) ReproduceByClone(inIndex); 111 | 112 | int index = _RNG.nextInt(FloatRegFitPredictionIndividual._sampleSize); 113 | i.SetSampleIndex(index, _RNG.nextInt(_solutionGA._testCases.size())); 114 | 115 | return i; 116 | } 117 | 118 | @Override 119 | protected GAIndividual ReproduceByCrossover(int inIndex) { 120 | FloatRegFitPredictionIndividual a = (FloatRegFitPredictionIndividual) ReproduceByClone(inIndex); 121 | FloatRegFitPredictionIndividual b = (FloatRegFitPredictionIndividual) TournamentSelect( 122 | _tournamentSize, inIndex); 123 | 124 | // crossoverPoint is the first index of a that will be changed to the 125 | // gene from b. 126 | int crossoverPoint = _RNG 127 | .nextInt(FloatRegFitPredictionIndividual._sampleSize - 1) + 1; 128 | for (int i = crossoverPoint; i < FloatRegFitPredictionIndividual._sampleSize; i++) { 129 | a.SetSampleIndex(i, b.GetSampleIndex(i)); 130 | } 131 | 132 | return a; 133 | } 134 | 135 | 136 | } 137 | -------------------------------------------------------------------------------- /org/spiderland/Psh/Coevolution/FloatRegFitPredictionIndividual.java: -------------------------------------------------------------------------------- 1 | package org.spiderland.Psh.Coevolution; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | 6 | import org.spiderland.Psh.GAIndividual; 7 | import org.spiderland.Psh.GATestCase; 8 | import org.spiderland.Psh.PushGP; 9 | import org.spiderland.Psh.PushGPIndividual; 10 | 11 | public class FloatRegFitPredictionIndividual extends PredictionGAIndividual { 12 | private static final long serialVersionUID = 1L; 13 | 14 | // The sample test cases used for fitness prediction. 15 | private int _sampleIndices[]; 16 | protected static int _sampleSize = 8; 17 | 18 | protected PushGP _solutionGA; 19 | 20 | public FloatRegFitPredictionIndividual() { 21 | _sampleIndices = new int[_sampleSize]; 22 | _solutionGA = null; 23 | } 24 | 25 | public FloatRegFitPredictionIndividual(PushGP inSolutionGA) { 26 | _sampleIndices = new int[_sampleSize]; 27 | _solutionGA = inSolutionGA; 28 | } 29 | 30 | public FloatRegFitPredictionIndividual(PushGP inSolutionGA, int[] inSamples) { 31 | _sampleIndices = new int[_sampleSize]; 32 | for(int i = 0; i < _sampleSize; i++){ 33 | _sampleIndices[i] = inSamples[i]; 34 | } 35 | _solutionGA = inSolutionGA; 36 | } 37 | 38 | 39 | /** 40 | * Gets the given sample index 41 | * 42 | * @param inIndex 43 | * @return sample index 44 | */ 45 | public int GetSampleIndex(int inIndex){ 46 | return _sampleIndices[inIndex]; 47 | } 48 | 49 | /** 50 | * Sets one of the sample indices to a new sample index. 51 | * 52 | * @param index 53 | * @param sample 54 | */ 55 | public void SetSampleIndex(int inIndex, int inSample){ 56 | _sampleIndices[inIndex] = inSample; 57 | } 58 | 59 | public void SetSampleIndicesAndSolutionGA(PushGP inSolutionGA, int[] inSamples){ 60 | _sampleIndices = new int[_sampleSize]; 61 | for(int i = 0; i < _sampleSize; i++){ 62 | _sampleIndices[i] = inSamples[i]; 63 | } 64 | _solutionGA = inSolutionGA; 65 | } 66 | 67 | @Override 68 | public float PredictSolutionFitness(PushGPIndividual pgpIndividual) { 69 | ArrayList errors = new ArrayList(); 70 | 71 | for (int n = 0; n < _sampleSize; n++) { 72 | GATestCase test = _solutionGA._testCases.get(_sampleIndices[n]); 73 | float e = _solutionGA.EvaluateTestCase(pgpIndividual, test._input, 74 | test._output); 75 | errors.add(e); 76 | } 77 | 78 | return AbsoluteAverageOfErrors(errors); 79 | } 80 | 81 | @Override 82 | public GAIndividual clone() { 83 | return new FloatRegFitPredictionIndividual(_solutionGA, _sampleIndices); 84 | } 85 | 86 | public String toString() { 87 | String str = "Prediction Indices: [ "; 88 | for(int i : _sampleIndices){ 89 | str += i + " "; 90 | } 91 | str += "]"; 92 | return str; 93 | } 94 | 95 | public boolean equalPredictors(GAIndividual inB) { 96 | int[] a = copyArray(_sampleIndices); 97 | int[] b = copyArray(((FloatRegFitPredictionIndividual)inB)._sampleIndices); 98 | 99 | /* 100 | a = Arrays.copyOf(_sampleIndices, _sampleSize); 101 | b = Arrays.copyOf(((FloatRegFitPredictionIndividual)inB)._sampleIndices, _sampleSize); 102 | */ 103 | 104 | Arrays.sort(a); 105 | Arrays.sort(b); 106 | if(Arrays.equals(a, b)){ 107 | return true; 108 | } 109 | 110 | return false; 111 | } 112 | 113 | private int[] copyArray(int[] inArray){ 114 | int[] newArray = new int[inArray.length]; 115 | 116 | for(int i = 0; i < inArray.length; i++){ 117 | newArray[i] = inArray[i]; 118 | } 119 | 120 | return newArray; 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /org/spiderland/Psh/Coevolution/GenericPredictionIndividual.java: -------------------------------------------------------------------------------- 1 | package org.spiderland.Psh.Coevolution; 2 | 3 | import org.spiderland.Psh.GAIndividual; 4 | import org.spiderland.Psh.Program; 5 | import org.spiderland.Psh.PushGP; 6 | import org.spiderland.Psh.PushGPIndividual; 7 | 8 | public class GenericPredictionIndividual extends PredictionGAIndividual{ 9 | private static final long serialVersionUID = 1L; 10 | 11 | protected Program _program; 12 | 13 | protected PushGP _solutionGA; 14 | 15 | public GenericPredictionIndividual() { 16 | _solutionGA = null; 17 | } 18 | 19 | public GenericPredictionIndividual(Program inProgram, PushGP inSolutionGA) { 20 | _program = inProgram; 21 | _solutionGA = inSolutionGA; 22 | } 23 | 24 | @Override 25 | public float PredictSolutionFitness(PushGPIndividual pgpIndividual) { 26 | //TODO implement _program being run to predict fitness 27 | 28 | 29 | 30 | return -2999; 31 | } 32 | 33 | @Override 34 | public GAIndividual clone() { 35 | return new GenericPredictionIndividual(_program, _solutionGA); 36 | } 37 | 38 | void SetProgram(Program inProgram) { 39 | if (inProgram != null) 40 | _program = new Program(inProgram); 41 | } 42 | 43 | public String toString() { 44 | return _program.toString(); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /org/spiderland/Psh/Coevolution/PredictionGA.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh.Coevolution; 18 | 19 | import java.util.ArrayList; 20 | import java.util.HashMap; 21 | 22 | import org.spiderland.Psh.GA; 23 | import org.spiderland.Psh.GAIndividual; 24 | import org.spiderland.Psh.PushGP; 25 | import org.spiderland.Psh.PushGPIndividual; 26 | 27 | /** 28 | * An abstract class for a population of co-evolving predictors of fitness, 29 | * rank, or something similar. In this class, "fitness" or "predicted fitness" 30 | * of a solution individual may be referring to the actual fitness of the 31 | * individual, or it may be referring to something similar, such as the 32 | * individual's rank. 33 | */ 34 | public abstract class PredictionGA extends GA { 35 | private static final long serialVersionUID = 1L; 36 | 37 | // Note: Oldest trainer has the lowest index; newest trainer has the highest 38 | // index. 39 | protected ArrayList _trainerPopulation; 40 | protected int _generationsBetweenTrainers; 41 | protected int _trainerPopulationSize; 42 | 43 | // The solution population and genetic algorithm. 44 | protected PushGP _solutionGA; 45 | 46 | /** 47 | * Customizes GA.GAWithParameters to allow the inclusion of the solution GA, 48 | * which is required for the initialization of the prediction GA. 49 | * 50 | * @param ceFloatSymbolicRegression 51 | * @param getPredictorParameters 52 | * @return 53 | * @throws Exception 54 | */ 55 | public static PredictionGA PredictionGAWithParameters(PushGP inSolutionGA, 56 | HashMap inParams) throws Exception { 57 | 58 | Class cls = Class.forName(inParams.get("problem-class")); 59 | Object gaObject = cls.newInstance(); 60 | if (!(gaObject instanceof PredictionGA)) 61 | throw (new Exception("Predictor problem-class must inherit from" 62 | + " class PredictorGA")); 63 | 64 | PredictionGA ga = (PredictionGA) gaObject; 65 | 66 | // Must set the solution GA before InitFromParameters, since the latter 67 | // uses _solutionGA while creating the predictor population. 68 | ga.SetSolutionGA(inSolutionGA); 69 | ga.SetParams(inParams); 70 | ga.InitFromParameters(); 71 | 72 | return ga; 73 | } 74 | 75 | @Override 76 | protected void InitFromParameters() throws Exception { 77 | _generationsBetweenTrainers = (int) GetFloatParam("generations-between-trainers"); 78 | _trainerPopulationSize = (int) GetFloatParam("trainer-population-size"); 79 | 80 | InitTrainerPopulation(); 81 | 82 | super.InitFromParameters(); 83 | } 84 | 85 | /** 86 | * Runs a single generation. 87 | * 88 | * @throws Exception 89 | */ 90 | public void RunGeneration() throws Exception { 91 | Run(1); 92 | } 93 | 94 | @Override 95 | protected void BeginGeneration() { 96 | if (_generationCount % _generationsBetweenTrainers == _generationsBetweenTrainers - 1) { 97 | // Time to add a new trainer 98 | PushGPIndividual newTrainer = (PushGPIndividual) ChooseNewTrainer().clone(); 99 | EvaluateSolutionIndividual(newTrainer); 100 | 101 | _trainerPopulation.remove(0); 102 | _trainerPopulation.add(newTrainer); 103 | 104 | EvaluateTrainerFitnesses(); 105 | 106 | } 107 | } 108 | 109 | @Override 110 | public boolean Terminate() { 111 | return false; 112 | } 113 | 114 | @Override 115 | protected boolean Success() { 116 | return false; 117 | } 118 | 119 | /** 120 | * Chooses a new trainer from the solution population to add to the trainer 121 | * population. The solution individual is chosen with the highest variance 122 | * of the predictions from the current predictor population. 123 | */ 124 | protected PushGPIndividual ChooseNewTrainer() { 125 | ArrayList individualVariances = new ArrayList(); 126 | 127 | for (int i = 0; i < _solutionGA.GetPopulationSize(); i++) { 128 | PushGPIndividual individual = (PushGPIndividual) _solutionGA 129 | .GetIndividualFromPopulation(i); 130 | 131 | ArrayList predictions = new ArrayList(); 132 | for (int j = 0; j < _populations[_currentPopulation].length; j++) { 133 | PredictionGAIndividual predictor = (PredictionGAIndividual) _populations[_currentPopulation][j]; 134 | predictions.add(predictor.PredictSolutionFitness(individual)); 135 | } 136 | 137 | individualVariances.add(Variance(predictions)); 138 | } 139 | 140 | // Find individual with the highest variance 141 | int highestVarianceIndividual = 0; 142 | float highestVariance = individualVariances.get(0); 143 | 144 | for (int i = 0; i < _solutionGA.GetPopulationSize(); i++) { 145 | if (highestVariance < individualVariances.get(i)) { 146 | highestVarianceIndividual = i; 147 | highestVariance = individualVariances.get(i); 148 | } 149 | } 150 | 151 | return (PushGPIndividual) _solutionGA 152 | .GetIndividualFromPopulation(highestVarianceIndividual); 153 | } 154 | 155 | protected PredictionGAIndividual GetBestPredictor(){ 156 | float bestFitness = Float.MAX_VALUE; 157 | GAIndividual bestPredictor = _populations[_currentPopulation][0]; 158 | 159 | for(GAIndividual ind : _populations[_currentPopulation]){ 160 | if(ind.GetFitness() < bestFitness){ 161 | bestPredictor = ind; 162 | bestFitness = ind.GetFitness(); 163 | } 164 | } 165 | 166 | return (PredictionGAIndividual) bestPredictor; 167 | } 168 | 169 | /** 170 | * Calculates and sets the exact fitness from any individual of the 171 | * _solutionGA population. This includes trainers. 172 | * 173 | * @param inIndividual 174 | */ 175 | protected void EvaluateSolutionIndividual(PushGPIndividual inIndividual) { 176 | _solutionGA.EvaluateIndividual(inIndividual); 177 | } 178 | 179 | protected void SetSolutionGA(PushGP inGA) { 180 | _solutionGA = inGA; 181 | } 182 | 183 | /** 184 | * This must be private, since there must be a _solutionGA set before this 185 | * method is invoked. Use SetGAandTrainers() instead. 186 | */ 187 | private void InitTrainerPopulation() { 188 | _trainerPopulation = new ArrayList(); 189 | 190 | PushGPIndividual individual = new PushGPIndividual(); 191 | 192 | for (int i = 0; i < _trainerPopulationSize; i++) { 193 | _trainerPopulation.add((PushGPIndividual) individual.clone()); 194 | _solutionGA.InitIndividual(_trainerPopulation.get(i)); 195 | } 196 | 197 | EvaluateTrainerFitnesses(); 198 | } 199 | 200 | protected String Report() { 201 | String report = super.Report(); 202 | report = report.replace('-', '#'); 203 | report = report.replaceFirst("Report for", " Predictor"); 204 | 205 | report += ";; Best Predictor: " 206 | + _populations[_currentPopulation][_bestIndividual] + "\n"; 207 | report += ";; Best Predictor Fitness: " + _bestMeanFitness + "\n\n"; 208 | 209 | report += ";; Mean Predictor Fitness: " + _populationMeanFitness + "\n"; 210 | 211 | // The following code prints all of the predictors. 212 | /* 213 | report += "\n;; Mean Predictor Fitness: \n"; 214 | for(GAIndividual predictor : _populations[_currentPopulation]){ 215 | report += " " + predictor + "\n"; 216 | 217 | } 218 | */ 219 | 220 | report += ";;########################################################;;\n\n"; 221 | 222 | return report; 223 | } 224 | 225 | protected String FinalReport() { 226 | return ""; 227 | } 228 | 229 | private Float Variance(ArrayList list) { 230 | float sampleMean = SampleMean(list); 231 | float sum = 0; 232 | 233 | for(float element : list){ 234 | sum += (element - sampleMean) * (element - sampleMean); 235 | } 236 | 237 | return (sum / (list.size() - 1)); 238 | } 239 | 240 | private float SampleMean(ArrayList list) { 241 | float total = 0; 242 | for(float element : list){ 243 | total += element; 244 | } 245 | return (total / list.size()); 246 | } 247 | 248 | /** 249 | * Initiates inIndividual as a random predictor individual. 250 | */ 251 | @Override 252 | protected abstract void InitIndividual(GAIndividual inIndividual); 253 | 254 | /** 255 | * Evaluates a PredictionGAIndividual's fitness, based on the difference 256 | * between the predictions of the fitnesses of the trainers and the actual 257 | * fitnesses of the trainers. 258 | */ 259 | @Override 260 | protected abstract void EvaluateIndividual(GAIndividual inIndividual); 261 | 262 | /** 263 | * Determines the predictor's fitness on a trainer, where the trainer is the 264 | * inInput, and the trainer's actual fitness (or rank, whatever is to be 265 | * predicted) is inOutput. 266 | * 267 | * @return Predictor's fitness (or rank, etc.) for the given trainer. 268 | */ 269 | @Override 270 | public abstract float EvaluateTestCase(GAIndividual inIndividual, 271 | Object inInput, Object inOutput); 272 | 273 | /** 274 | * Actual fitnesses of trainers will always be stored as part of the 275 | * PushGPIndividual object. Some predictor types, such as rank predictors, 276 | * will also need a separate storage of data, such as a method of storing 277 | * the ranking of the predictors. Others, such as fitness predictors, may 278 | * just need the fitness information directly from the trainers. This 279 | * function may be used to make sure fitnesses or ranks are updated, i.e. to 280 | * recalculate rank order with the addition of a new trainer. 281 | */ 282 | protected abstract void EvaluateTrainerFitnesses(); 283 | 284 | @Override 285 | protected abstract GAIndividual ReproduceByMutation(int inIndex); 286 | 287 | @Override 288 | protected abstract GAIndividual ReproduceByCrossover(int inIndex); 289 | 290 | } 291 | -------------------------------------------------------------------------------- /org/spiderland/Psh/Coevolution/PredictionGAIndividual.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh.Coevolution; 18 | 19 | import java.util.ArrayList; 20 | 21 | import org.spiderland.Psh.GAIndividual; 22 | import org.spiderland.Psh.PushGPIndividual; 23 | 24 | /** 25 | * An abstract CEPredictorGA individual class for developing co-evolved 26 | * predictors. 27 | */ 28 | 29 | public abstract class PredictionGAIndividual extends GAIndividual { 30 | private static final long serialVersionUID = 1L; 31 | 32 | /** 33 | * Predicts the fitness of the input PushGPIndividual 34 | * 35 | * @param individual to predict the fitness of 36 | * @return predicted fitness 37 | */ 38 | public abstract float PredictSolutionFitness(PushGPIndividual pgpIndividual); 39 | 40 | /** 41 | * Computes the absolute-average-of-errors fitness from an error vector. 42 | * 43 | * @return the average error value for the vector. 44 | */ 45 | protected float AbsoluteAverageOfErrors(ArrayList inArray) { 46 | float total = 0.0f; 47 | 48 | for (int n = 0; n < inArray.size(); n++) 49 | total += Math.abs(inArray.get(n)); 50 | 51 | if(Float.isInfinite(total)) 52 | return Float.MAX_VALUE; 53 | 54 | return (total / inArray.size()); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /org/spiderland/Psh/GAIndividual.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh; 18 | 19 | import java.io.Serializable; 20 | import java.util.*; 21 | 22 | /** 23 | * An abstract GP individual class containing a fitness value. The fitness value 24 | * represents an individual's error values, such that lower 25 | * fitness values are better and such that a fitness value of 0 indicates a 26 | * perfect solution. 27 | */ 28 | 29 | public abstract class GAIndividual implements Serializable { 30 | private static final long serialVersionUID = 1L; 31 | 32 | float _fitness; 33 | ArrayList _errors; 34 | 35 | boolean _fitnessSet; 36 | 37 | public boolean FitnessIsSet(){ 38 | return _fitnessSet; 39 | } 40 | 41 | public float GetFitness() { 42 | return _fitness; 43 | } 44 | 45 | public void SetFitness(float inFitness) { 46 | _fitness = inFitness; 47 | _fitnessSet = true; 48 | } 49 | 50 | public ArrayList GetErrors() { 51 | return _errors; 52 | } 53 | 54 | public void SetErrors(ArrayList inErrors) { 55 | _errors = inErrors; 56 | } 57 | 58 | public abstract GAIndividual clone(); 59 | } 60 | -------------------------------------------------------------------------------- /org/spiderland/Psh/GATestCase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh; 18 | 19 | import java.io.Serializable; 20 | 21 | /** 22 | * An abstract container for a GATestCase containing an input and output object. 23 | */ 24 | 25 | public class GATestCase implements Serializable { 26 | private static final long serialVersionUID = 1L; 27 | 28 | public GATestCase(Object inInput, Object inOutput) { 29 | _input = inInput; 30 | _output = inOutput; 31 | } 32 | 33 | public Object _input; 34 | public Object _output; 35 | } 36 | -------------------------------------------------------------------------------- /org/spiderland/Psh/GenericStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh; 18 | 19 | import java.util.Arrays; 20 | 21 | /** 22 | * The Push stack type for generic data (Strings, Programs, etc.) 23 | */ 24 | 25 | public class GenericStack extends Stack { 26 | private static final long serialVersionUID = 1L; 27 | 28 | protected T _stack[]; 29 | final static int _blocksize = 16; 30 | 31 | public void PushAllReverse(GenericStack inOther) { 32 | for (int n = _size - 1; n >= 0; n--) 33 | inOther.push(_stack[n]); 34 | } 35 | 36 | @SuppressWarnings("unchecked") 37 | @Override 38 | public boolean equals(Object inOther) { 39 | if (this == inOther) 40 | return true; 41 | 42 | // Sadly, because generics are implemented using type erasure, 43 | // a GenericStack will be the same class as a GenericStack, 44 | // this being GenericStack. So the best we can do here is be assured 45 | // that inOther is at least a GenericStack. 46 | // 47 | // This just means that every empty stack is the same as every other 48 | // empty stack. 49 | 50 | if (inOther.getClass() != getClass()) 51 | return false; 52 | 53 | return ((GenericStack) inOther).comparestack(_stack, _size); 54 | } 55 | 56 | @Override 57 | public int hashCode() { 58 | int hash = getClass().hashCode(); 59 | hash = 37 * hash + Arrays.deepHashCode(this._stack); 60 | return hash; 61 | } 62 | 63 | boolean comparestack(T inOther[], int inOtherSize) { 64 | if (inOtherSize != _size) 65 | return false; 66 | 67 | for (int n = 0; n < _size; n++) { 68 | if (!_stack[n].equals(inOther[n])) 69 | return false; 70 | } 71 | 72 | return true; 73 | } 74 | 75 | @SuppressWarnings("unchecked") 76 | @Override 77 | void resize(int inSize) { 78 | T newstack[] = (T[]) new Object[inSize]; 79 | 80 | if (_stack != null) 81 | System.arraycopy(_stack, 0, newstack, 0, _size); 82 | 83 | _stack = newstack; 84 | _maxsize = inSize; 85 | } 86 | 87 | public T peek(int inIndex) { 88 | if (inIndex >= 0 && inIndex < _size) 89 | return _stack[inIndex]; 90 | 91 | return null; 92 | } 93 | 94 | public T top() { 95 | return peek(_size - 1); 96 | } 97 | 98 | public T pop() { 99 | T result = null; 100 | 101 | if (_size > 0) { 102 | result = _stack[_size - 1]; 103 | _size--; 104 | } 105 | 106 | return result; 107 | } 108 | 109 | @SuppressWarnings("unchecked") 110 | public void push(T inValue) { 111 | if (inValue instanceof Program) 112 | inValue = (T) new Program((Program) inValue); 113 | 114 | _stack[_size] = inValue; 115 | _size++; 116 | 117 | if (_size >= _maxsize) 118 | resize(_maxsize + _blocksize); 119 | } 120 | 121 | @Override 122 | public void dup() { 123 | if (_size > 0) 124 | push(_stack[_size - 1]); 125 | } 126 | 127 | public void shove(T obj, int n) { 128 | if (n > _size) 129 | n = _size; 130 | 131 | // n = 0 is the same as push, so 132 | // the position in the array we insert at is 133 | // _size-n. 134 | 135 | n = _size - n; 136 | 137 | for (int i = _size; i > n; i--) 138 | _stack[i] = _stack[i - 1]; 139 | _stack[n] = obj; 140 | _size++; 141 | if (_size >= _maxsize) 142 | resize(_maxsize + _blocksize); 143 | } 144 | 145 | @Override 146 | public void shove(int inIndex) { 147 | if (_size > 0) { 148 | if(inIndex < 0){ 149 | inIndex = 0; 150 | } 151 | if(inIndex > _size - 1){ 152 | inIndex = _size - 1; 153 | } 154 | 155 | T toShove = top(); 156 | int shovedIndex = _size - inIndex - 1; 157 | 158 | for (int i = _size - 1; i > shovedIndex; i--) { 159 | _stack[i] = _stack[i - 1]; 160 | } 161 | _stack[shovedIndex] = toShove; 162 | } 163 | } 164 | 165 | @Override 166 | public void swap() { 167 | if (_size > 1) { 168 | T tmp = _stack[_size - 2]; 169 | _stack[_size - 2] = _stack[_size - 1]; 170 | _stack[_size - 1] = tmp; 171 | } 172 | } 173 | 174 | @Override 175 | public void rot() { 176 | if (_size > 2) { 177 | T tmp = _stack[_size - 3]; 178 | _stack[_size - 3] = _stack[_size - 2]; 179 | _stack[_size - 2] = _stack[_size - 1]; 180 | _stack[_size - 1] = tmp; 181 | } 182 | } 183 | 184 | @Override 185 | public void yank(int inIndex) { 186 | if (_size > 0) { 187 | if(inIndex < 0){ 188 | inIndex = 0; 189 | } 190 | if(inIndex > _size - 1){ 191 | inIndex = _size - 1; 192 | } 193 | 194 | int yankedIndex = _size - inIndex - 1; 195 | T toYank = peek(yankedIndex); 196 | 197 | for (int i = yankedIndex; i < _size - 1; i++) { 198 | _stack[i] = _stack[i + 1]; 199 | } 200 | _stack[_size - 1] = toYank; 201 | } 202 | } 203 | 204 | public void yankdup(int inIndex) { 205 | if (_size > 0) { 206 | if(inIndex < 0){ 207 | inIndex = 0; 208 | } 209 | if(inIndex > _size - 1){ 210 | inIndex = _size - 1; 211 | } 212 | 213 | int yankedIndex = _size - inIndex - 1; 214 | push(peek(yankedIndex)); 215 | } 216 | } 217 | 218 | @Override 219 | public String toString() { 220 | String result = "["; 221 | 222 | for (int n = _size - 1; n >= 0; n--) { 223 | if (n == _size - 1) 224 | result += _stack[n]; 225 | else 226 | result += " " + _stack[n]; 227 | } 228 | result += "]"; 229 | 230 | return result; 231 | } 232 | } 233 | -------------------------------------------------------------------------------- /org/spiderland/Psh/IncludeException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh; 18 | 19 | public class IncludeException extends Exception { 20 | static final long serialVersionUID = 1L; 21 | 22 | IncludeException(String inStr) { 23 | super(inStr); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /org/spiderland/Psh/InputPusher.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh; 18 | 19 | import java.io.Serializable; 20 | 21 | public class InputPusher implements Serializable { 22 | private static final long serialVersionUID = 1L; 23 | 24 | public void pushInput(Interpreter inI, int n) { 25 | ObjectStack _stack = inI.inputStack(); 26 | 27 | if (_stack.size() > n) { 28 | Object inObject = _stack.peek(n); 29 | 30 | if (inObject instanceof Integer) { 31 | intStack istack = inI.intStack(); 32 | istack.push((Integer) inObject); 33 | } else if (inObject instanceof Number) { 34 | floatStack fstack = inI.floatStack(); 35 | fstack.push(((Number) inObject).floatValue()); 36 | } else if (inObject instanceof Boolean) { 37 | booleanStack bstack = inI.boolStack(); 38 | bstack.push((Boolean) inObject); 39 | 40 | } else { 41 | System.err.println("Error during input.index - object " 42 | + inObject.getClass() 43 | + " is not a legal object according to " 44 | + this.getClass() + "."); 45 | } 46 | } 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /org/spiderland/Psh/InspectorInput.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh; 18 | 19 | import java.io.*; 20 | 21 | /** 22 | * A utility class to help read PshInspector input files. 23 | */ 24 | 25 | public class InspectorInput { 26 | 27 | Program _program; 28 | int _executionLimit; 29 | Interpreter _interpreter; 30 | 31 | /** 32 | * Constructs an InspectorInput from a filename string 33 | * 34 | * @param inFilename 35 | * The file to input from. 36 | */ 37 | public InspectorInput(String inFilename) throws Exception { 38 | InitInspectorInput(new File(inFilename)); 39 | } 40 | 41 | /** 42 | * Constructs an InspectorInput from a filename string 43 | * 44 | * @param inFile 45 | * The file to input from. 46 | */ 47 | public InspectorInput(File inFile) throws Exception { 48 | InitInspectorInput(inFile); 49 | } 50 | 51 | /** 52 | * Initializes an InspectorInput. The file should be organized as follows: 53 | * 54 | * 1 Program to execute 55 | * 2 Execution limit 56 | * 3 Integer, float, or boolean inputs 57 | * 4 Available instructions. This is only used for creating random code 58 | * with code.rand or exec.rand 59 | * 60 | * @param inFile 61 | * The file to input from. 62 | */ 63 | private void InitInspectorInput(File inFile) throws Exception { 64 | _interpreter = new Interpreter(); 65 | 66 | // Read fileString 67 | String fileString = Params.ReadFileString(inFile); 68 | 69 | // Get programString 70 | int indexNewline = fileString.indexOf("\n"); 71 | String programString = fileString.substring(0, indexNewline).trim(); 72 | fileString = fileString.substring(indexNewline + 1); 73 | 74 | // Get _executionLimit 75 | indexNewline = fileString.indexOf("\n"); 76 | if (indexNewline != -1) { 77 | String limitString = fileString.substring(0,indexNewline).trim(); 78 | 79 | _executionLimit = Integer.parseInt(limitString); 80 | fileString = fileString.substring(indexNewline + 1); 81 | } else { 82 | // If here, no inputs to be pushed were included 83 | _executionLimit = Integer.parseInt(fileString); 84 | fileString = ""; 85 | } 86 | 87 | // Get inputs and push them onto correct stacks. If fileString = "" 88 | // at this point, then can still do the following with correct result. 89 | indexNewline = fileString.indexOf("\n"); 90 | if (indexNewline != -1) { 91 | String inputsString = fileString.substring(0, indexNewline).trim(); 92 | fileString = fileString.substring(indexNewline + 1); 93 | 94 | // Parse the inputs and load them into the interpreter 95 | parseAndLoadInputs(inputsString); 96 | } 97 | else { 98 | parseAndLoadInputs(fileString); 99 | fileString = ""; 100 | } 101 | 102 | // Get the available instructions for random code generation 103 | indexNewline = fileString.indexOf("\n"); 104 | if (!fileString.trim().equals("")) { 105 | _interpreter.SetInstructions(new Program(_interpreter, fileString.trim())); 106 | } 107 | 108 | // Check for input.inN instructions 109 | checkForInputIn(programString); 110 | 111 | // Add random integer and float parameters 112 | _interpreter._minRandomInt = -10; 113 | _interpreter._maxRandomInt = 10; 114 | _interpreter._randomIntResolution = 1; 115 | _interpreter._minRandomFloat = -10.0f; 116 | _interpreter._maxRandomFloat = 10.0f; 117 | _interpreter._randomFloatResolution = 0.01f; 118 | 119 | _interpreter._maxRandomCodeSize = 50; 120 | 121 | // Load the program 122 | _program = new Program(_interpreter, programString); 123 | _interpreter.LoadProgram(_program); // Initializes program 124 | } 125 | 126 | /** 127 | * Returns the initialized interpreter 128 | * 129 | * @return The initialized interpreter 130 | */ 131 | public Interpreter getInterpreter() { 132 | return _interpreter; 133 | } 134 | 135 | public Program getProgram() { 136 | return _program; 137 | } 138 | 139 | /** 140 | * Returns the execution limit 141 | * 142 | * @return The execution limit 143 | */ 144 | public int getExecutionLimit() { 145 | return _executionLimit; 146 | } 147 | 148 | private void parseAndLoadInputs(String inputs) throws Exception { 149 | String inputTokens[] = inputs.split("\\s+"); 150 | 151 | for (int i = 0; i < inputTokens.length; i++) { 152 | String token = inputTokens[i]; 153 | 154 | if (token.equals("")) { 155 | continue; 156 | } else if (token.equals("true")) { 157 | _interpreter.boolStack().push(true); 158 | _interpreter.inputStack().push(true); 159 | } else if (token.equals("false")) { 160 | _interpreter.boolStack().push(false); 161 | _interpreter.inputStack().push(false); 162 | } else if (token.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")) { 163 | if (token.indexOf('.') != -1) { 164 | _interpreter.floatStack().push(Float.parseFloat(token)); 165 | _interpreter.inputStack().push(Float.parseFloat(token)); 166 | } else { 167 | _interpreter.intStack().push(Integer.parseInt(token)); 168 | _interpreter.inputStack().push(Integer.parseInt(token)); 169 | } 170 | } else { 171 | throw new Exception( 172 | "Inputs must be of type int, float, or boolean. \"" 173 | + token + "\" is none of these."); 174 | } 175 | } 176 | } 177 | 178 | private void checkForInputIn(String programString) { 179 | String added = ""; 180 | String numstr = ""; 181 | int index = 0; 182 | int numindex = 0; 183 | int spaceindex = 0; 184 | int parenindex = 0; 185 | int endindex = 0; 186 | 187 | while (true) { 188 | 189 | index = programString.indexOf("input.in"); 190 | if (index == -1) 191 | break; 192 | 193 | // System.out.println(programString + " " + index); 194 | 195 | numindex = index + 8; 196 | if (!Character.isDigit(programString.charAt(numindex))) { 197 | programString = programString.substring(numindex); 198 | continue; 199 | } 200 | 201 | spaceindex = programString.indexOf(' ', numindex); 202 | parenindex = programString.indexOf(')', numindex); 203 | if (spaceindex == -1) 204 | endindex = parenindex; 205 | else if (parenindex == -1) 206 | endindex = spaceindex; 207 | else 208 | endindex = Math.min(spaceindex, parenindex); 209 | 210 | numstr = programString.substring(numindex, endindex); 211 | 212 | // Check for doubles in added 213 | if (added.indexOf(" " + numstr + " ") == -1) { 214 | added = added + " " + numstr + " "; 215 | _interpreter.AddInstruction("input.in" + numstr, new InputInN( 216 | Integer.parseInt(numstr))); 217 | } 218 | 219 | programString = programString.substring(numindex); 220 | } 221 | 222 | } 223 | 224 | } -------------------------------------------------------------------------------- /org/spiderland/Psh/Instruction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh; 18 | 19 | import java.io.Serializable; 20 | 21 | /** 22 | * Abstract instruction base for all instructions. 23 | */ 24 | 25 | public abstract class Instruction implements Serializable { 26 | private static final long serialVersionUID = 1L; 27 | 28 | public abstract void Execute(Interpreter inI); 29 | } 30 | -------------------------------------------------------------------------------- /org/spiderland/Psh/ObjectPair.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh; 18 | 19 | import java.io.Serializable; 20 | 21 | /** 22 | * An abstract container for a pair of objects. 23 | */ 24 | 25 | public class ObjectPair implements Serializable { 26 | private static final long serialVersionUID = 1L; 27 | 28 | public ObjectPair(Object inFirst, Object inSecond) { 29 | _first = inFirst; 30 | _second = inSecond; 31 | } 32 | 33 | public Object _first; 34 | public Object _second; 35 | 36 | public String toString(){ 37 | return "<" + _first.toString() + ", " + _second.toString() + ">"; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /org/spiderland/Psh/ObjectStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh; 18 | 19 | /** 20 | * The Push stack type for object-based data (Strings, Programs, etc.) 21 | */ 22 | 23 | public class ObjectStack extends Stack { 24 | private static final long serialVersionUID = 1L; 25 | 26 | protected Object _stack[]; 27 | final static int _blocksize = 16; 28 | 29 | public void PushAllReverse(ObjectStack inOther) { 30 | for (int n = _size - 1; n >= 0; n--) 31 | inOther.push(_stack[n]); 32 | } 33 | 34 | public boolean equals(Object inOther) { 35 | if (this == inOther) 36 | return true; 37 | 38 | if (!(inOther instanceof ObjectStack)) 39 | return false; 40 | 41 | return ((ObjectStack) inOther).comparestack(_stack, _size); 42 | } 43 | 44 | boolean comparestack(Object inOther[], int inOtherSize) { 45 | if (inOtherSize != _size) 46 | return false; 47 | 48 | for (int n = 0; n < _size; n++) { 49 | if (!_stack[n].equals(inOther[n])) 50 | return false; 51 | } 52 | 53 | return true; 54 | } 55 | 56 | void resize(int inSize) { 57 | Object newstack[] = new Object[inSize]; 58 | 59 | if (_stack != null) 60 | System.arraycopy(_stack, 0, newstack, 0, _size); 61 | 62 | _stack = newstack; 63 | _maxsize = inSize; 64 | } 65 | 66 | public Object peek(int inIndex) { 67 | if (inIndex >= 0 && inIndex < _size) 68 | return _stack[inIndex]; 69 | 70 | return null; 71 | } 72 | 73 | public Object top() { 74 | return peek(_size - 1); 75 | } 76 | 77 | public Object pop() { 78 | Object result = null; 79 | 80 | if (_size > 0) { 81 | result = _stack[_size - 1]; 82 | _size--; 83 | } 84 | 85 | return result; 86 | } 87 | 88 | public void push(Object inValue) { 89 | if (inValue instanceof Program) 90 | inValue = new Program((Program) inValue); 91 | 92 | _stack[_size] = inValue; 93 | _size++; 94 | 95 | if (_size >= _maxsize) 96 | resize(_maxsize + _blocksize); 97 | } 98 | 99 | public void dup() { 100 | if (_size > 0) 101 | push(_stack[_size - 1]); 102 | } 103 | 104 | public void shove(Object obj, int n) { 105 | if (n > _size) 106 | n = _size; 107 | 108 | // n = 0 is the same as push, so 109 | // the position in the array we insert at is 110 | // _size-n. 111 | 112 | n = _size - n; 113 | 114 | for (int i = _size; i > n; i--) 115 | _stack[i] = _stack[i - 1]; 116 | _stack[n] = obj; 117 | _size++; 118 | if (_size >= _maxsize) 119 | resize(_maxsize + _blocksize); 120 | } 121 | 122 | public void shove(int inIndex) { 123 | if (_size > 0) { 124 | if(inIndex < 0){ 125 | inIndex = 0; 126 | } 127 | if(inIndex > _size - 1){ 128 | inIndex = _size - 1; 129 | } 130 | 131 | Object toShove = top(); 132 | int shovedIndex = _size - inIndex - 1; 133 | 134 | for (int i = _size - 1; i > shovedIndex; i--) { 135 | _stack[i] = _stack[i - 1]; 136 | } 137 | _stack[shovedIndex] = toShove; 138 | } 139 | } 140 | 141 | public void swap() { 142 | if (_size > 1) { 143 | Object tmp = _stack[_size - 2]; 144 | _stack[_size - 2] = _stack[_size - 1]; 145 | _stack[_size - 1] = tmp; 146 | } 147 | } 148 | 149 | public void rot() { 150 | if (_size > 2) { 151 | Object tmp = _stack[_size - 3]; 152 | _stack[_size - 3] = _stack[_size - 2]; 153 | _stack[_size - 2] = _stack[_size - 1]; 154 | _stack[_size - 1] = tmp; 155 | } 156 | } 157 | 158 | public void yank(int inIndex) { 159 | if (_size > 0) { 160 | if(inIndex < 0){ 161 | inIndex = 0; 162 | } 163 | if(inIndex > _size - 1){ 164 | inIndex = _size - 1; 165 | } 166 | 167 | int yankedIndex = _size - inIndex - 1; 168 | Object toYank = peek(yankedIndex); 169 | 170 | for (int i = yankedIndex; i < _size - 1; i++) { 171 | _stack[i] = _stack[i + 1]; 172 | } 173 | _stack[_size - 1] = toYank; 174 | } 175 | } 176 | 177 | public void yankdup(int inIndex) { 178 | if (_size > 0) { 179 | if(inIndex < 0){ 180 | inIndex = 0; 181 | } 182 | if(inIndex > _size - 1){ 183 | inIndex = _size - 1; 184 | } 185 | 186 | int yankedIndex = _size - inIndex - 1; 187 | push(peek(yankedIndex)); 188 | } 189 | } 190 | 191 | public String toString() { 192 | String result = "["; 193 | 194 | for (int n = _size - 1; n >= 0; n--) { 195 | 196 | if (n == _size - 1) 197 | result += _stack[n]; 198 | else 199 | result += " " + _stack[n]; 200 | } 201 | result += "]"; 202 | 203 | return result; 204 | } 205 | } 206 | -------------------------------------------------------------------------------- /org/spiderland/Psh/Params.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh; 18 | 19 | import java.util.*; 20 | import java.io.*; 21 | 22 | /** 23 | * A utility class for reading PushGP params. 24 | */ 25 | 26 | public class Params { 27 | public static HashMap ReadFromFile(File inFile) 28 | throws Exception { 29 | HashMap map = new HashMap(); 30 | return Read(ReadFileString(inFile), map, inFile); 31 | } 32 | 33 | public static HashMap Read(String inParams) 34 | throws Exception { 35 | HashMap map = new HashMap(); 36 | return Read(inParams, map, null); 37 | } 38 | 39 | public static HashMap Read(String inParams, 40 | HashMap inMap, File inFile) throws Exception { 41 | int linenumber = 0; 42 | String filename = ""; 43 | 44 | try { 45 | BufferedReader reader = new BufferedReader(new StringReader( 46 | inParams)); 47 | String line; 48 | String parent; 49 | 50 | if (inFile == null) { 51 | parent = null; 52 | filename = ""; 53 | } else { 54 | parent = inFile.getParent(); 55 | filename = inFile.getName(); 56 | } 57 | 58 | while ((line = reader.readLine()) != null) { 59 | linenumber += 1; 60 | int comment = line.indexOf('#', 0); 61 | 62 | if (comment != -1) 63 | line = line.substring(0, comment); 64 | 65 | if (line.startsWith("include")) { 66 | int startIndex = "include".length(); 67 | String includefile = line.substring(startIndex, 68 | line.length()).trim(); 69 | 70 | try { 71 | File f = new File(parent, includefile); 72 | Read(ReadFileString(f), inMap, f); 73 | } catch (IncludeException e) { 74 | // A previous include exception should bubble up to the 75 | // top 76 | throw e; 77 | } catch (Exception e) { 78 | // Any other exception should generate an error message 79 | throw new IncludeException("Error including file \"" 80 | + includefile + "\" at line " + linenumber 81 | + " of file \"" + filename + "\""); 82 | } 83 | } else { 84 | int split = line.indexOf('=', 0); 85 | 86 | if (split != -1) { 87 | String name = line.substring(0, split).trim(); 88 | String value = line.substring(split + 1, line.length()) 89 | .trim(); 90 | 91 | while (value.endsWith("\\")) { 92 | value = value.substring(0, value.length() - 1); 93 | line = reader.readLine(); 94 | if (line == null) 95 | break; 96 | linenumber++; 97 | value += line.trim(); 98 | } 99 | 100 | inMap.put(name, value); 101 | } 102 | } 103 | } 104 | 105 | } catch (IncludeException e) { 106 | // A previous include exception should bubble up to the top 107 | throw e; 108 | } catch (Exception e) { 109 | // Any other exception should generate an error message 110 | throw new IncludeException("Error at line " + linenumber 111 | + " of parameter file \"" + filename + "\""); 112 | } 113 | 114 | return inMap; 115 | } 116 | 117 | /** 118 | * Utility function to read a file in its entirety to a string. 119 | * 120 | * @param inPath 121 | * The file path to be read. 122 | * @return The contents of a file represented as a string. 123 | */ 124 | 125 | static String ReadFileString(String inPath) throws Exception { 126 | return ReadFileString(new File(inPath)); 127 | } 128 | 129 | /** 130 | * Utility function to read a file in its entirety to a string. 131 | * 132 | * @param inFile 133 | * The file to be read. 134 | * @return The contents of a file represented as a string. 135 | */ 136 | 137 | public static String ReadFileString(File inFile) throws Exception { 138 | InputStream s = new FileInputStream(inFile); 139 | byte[] tmp = new byte[1024]; 140 | int read; 141 | String result = ""; 142 | 143 | while ((read = s.read(tmp)) > 0) { 144 | result += new String(tmp, 0, read); 145 | } 146 | 147 | return result; 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /org/spiderland/Psh/ProbClass/CartCentering.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh.ProbClass; 18 | 19 | import org.spiderland.Psh.GAIndividual; 20 | import org.spiderland.Psh.GATestCase; 21 | import org.spiderland.Psh.Interpreter; 22 | import org.spiderland.Psh.ObjectPair; 23 | import org.spiderland.Psh.ObjectStack; 24 | import org.spiderland.Psh.Program; 25 | import org.spiderland.Psh.PushGP; 26 | import org.spiderland.Psh.PushGPIndividual; 27 | import org.spiderland.Psh.booleanStack; 28 | import org.spiderland.Psh.floatStack; 29 | 30 | /** 31 | * A sample problem class for testing the cart centering problem. This solves 32 | * the cart centering problem as described in John Koza's Genetic Programming, 33 | * chapter 7.1. In this problem, a cart is placed on a 1-dimensional, 34 | * frictionless track. At every time, the cart has a position and velocity on 35 | * the track. The problem is to stop the cart at the origin (within reasonable 36 | * approximations) by applying a fixed-magnitude force to accelerate the cart 37 | * in the forward or backward direction. 38 | * 39 | * Note: Cart centering does not yet support test case generators. 40 | */ 41 | public class CartCentering extends PushGP { 42 | private static final long serialVersionUID = 1L; 43 | 44 | protected void InitFromParameters() throws Exception { 45 | super.InitFromParameters(); 46 | 47 | String cases = GetParam("test-cases"); 48 | 49 | Program caselist = new Program(_interpreter, cases); 50 | 51 | for (int i = 0; i < caselist.size(); i++) { 52 | Program singleCase = (Program) caselist.peek(i); 53 | 54 | if (singleCase.size() < 2) 55 | throw new Exception("Not enough elements for fitness case \"" 56 | + singleCase + "\""); 57 | 58 | Float x = new Float(singleCase.peek(0).toString()); 59 | Float v = new Float(singleCase.peek(1).toString()); 60 | 61 | Print(";; Fitness case #" + i + " position: " + x + " velocity: " + v 62 | + "\n"); 63 | 64 | ObjectPair xv = new ObjectPair(x,v); 65 | 66 | _testCases.add(new GATestCase(xv, null)); 67 | } 68 | } 69 | 70 | protected void InitInterpreter(Interpreter inInterpreter) { 71 | } 72 | 73 | public float EvaluateTestCase(GAIndividual inIndividual, Object inInput, 74 | Object inOutput) { 75 | 76 | int timeSteps = 1000; 77 | float timeDiscritized = 0.01f; 78 | float maxTime = timeSteps * timeDiscritized; 79 | 80 | float captureRadius = 0.01f; 81 | 82 | ObjectPair xv = (ObjectPair) inInput; 83 | float position = (Float) xv._first; 84 | float velocity = (Float) xv._second; 85 | 86 | for(int step = 1; step <= timeSteps; step++){ 87 | _interpreter.ClearStacks(); 88 | 89 | floatStack fStack = _interpreter.floatStack(); 90 | booleanStack bStack = _interpreter.boolStack(); 91 | ObjectStack iStack = _interpreter.inputStack(); 92 | 93 | // Position will be on the top of the stack, and velocity will be 94 | // second. 95 | fStack.push(position); 96 | fStack.push(velocity); 97 | 98 | // Must be included in order to use the input stack. Uses same order 99 | // as inputs on Float stack. 100 | iStack.push(position); 101 | iStack.push(velocity); 102 | 103 | _interpreter.Execute(((PushGPIndividual) inIndividual)._program, 104 | _executionLimit); 105 | 106 | // If there is no boolean on the stack, the program has failed to 107 | // return a reasonable output. So, return a penalty fitness of 108 | // twice the maximum time. 109 | if(bStack.size() == 0){ 110 | return 2 * maxTime; 111 | } 112 | 113 | // If there is a boolean, use it to compute the next position and 114 | // velocity. Then, check for termination conditions. 115 | // NOTE: If result == True, we will apply the force in the positive 116 | // direction, and if result == False, we will apply the force in 117 | // the negative direction. 118 | boolean positiveForce = bStack.top(); 119 | float acceleration; 120 | 121 | if(positiveForce){ 122 | acceleration = 0.5f; 123 | } 124 | else{ 125 | acceleration = -0.5f; 126 | } 127 | 128 | velocity = velocity + (timeDiscritized * acceleration); 129 | position = position + (timeDiscritized * velocity); 130 | 131 | // Check for termination conditions 132 | if(position <= captureRadius && position >= -captureRadius && 133 | velocity <= captureRadius && velocity >= -captureRadius){ 134 | //Cart is centered, so return time it took. 135 | return step * timeDiscritized; 136 | } 137 | 138 | } 139 | 140 | // If here, the cart failed to come to rest in the allotted time. So, 141 | // return the failed error of maxTime. 142 | 143 | return maxTime; 144 | } 145 | 146 | protected boolean Success() { 147 | return _generationCount >= _maxGenerations; 148 | } 149 | 150 | } 151 | -------------------------------------------------------------------------------- /org/spiderland/Psh/ProbClass/FloatClassification.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh.ProbClass; 18 | 19 | import org.spiderland.Psh.GAIndividual; 20 | import org.spiderland.Psh.GATestCase; 21 | import org.spiderland.Psh.Interpreter; 22 | import org.spiderland.Psh.Program; 23 | import org.spiderland.Psh.PushGP; 24 | import org.spiderland.Psh.PushGPIndividual; 25 | import org.spiderland.Psh.floatStack; 26 | 27 | public class FloatClassification extends PushGP { 28 | private static final long serialVersionUID = 1L; 29 | 30 | float _currentInput; 31 | int _inputCount; 32 | 33 | protected void InitFromParameters() throws Exception { 34 | super.InitFromParameters(); 35 | 36 | String cases = GetParam("test-cases"); 37 | 38 | Program caselist = new Program(_interpreter, cases); 39 | 40 | _inputCount = ((Program) caselist.peek(0)).size() - 1; 41 | 42 | for (int i = 0; i < caselist.size(); i++) { 43 | Program p = (Program) caselist.peek(i); 44 | 45 | if (p.size() < 2) 46 | throw new Exception("Not enough entries for fitness case \"" 47 | + p + "\""); 48 | 49 | if (p.size() != _inputCount + 1) 50 | throw new Exception( 51 | "Wrong number of inputs for fitness case \"" + p + "\""); 52 | 53 | Float in = new Float(p.peek(0).toString()); 54 | Float out = new Float(p.peek(1).toString()); 55 | 56 | Print(";; Fitness case #" + i + " input: " + in + " output: " + out 57 | + "\n"); 58 | 59 | _testCases.add(new GATestCase(in, out)); 60 | } 61 | } 62 | 63 | protected void InitInterpreter(Interpreter inInterpreter) { 64 | } 65 | 66 | public float EvaluateTestCase(GAIndividual inIndividual, Object inInput, 67 | Object inOutput) { 68 | _interpreter.ClearStacks(); 69 | 70 | _currentInput = (Float) inInput; 71 | 72 | floatStack stack = _interpreter.floatStack(); 73 | 74 | stack.push(_currentInput); 75 | 76 | _interpreter.Execute(((PushGPIndividual) inIndividual)._program, 77 | _executionLimit); 78 | 79 | float result = stack.top(); 80 | // System.out.println( _interpreter + " " + result ); 81 | 82 | return result - ((Float) inOutput); 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /org/spiderland/Psh/ProbClass/FloatSymbolicRegression.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh.ProbClass; 18 | 19 | import org.spiderland.Psh.GAIndividual; 20 | import org.spiderland.Psh.GATestCase; 21 | import org.spiderland.Psh.Interpreter; 22 | import org.spiderland.Psh.ObjectPair; 23 | import org.spiderland.Psh.Program; 24 | import org.spiderland.Psh.PushGP; 25 | import org.spiderland.Psh.PushGPIndividual; 26 | import org.spiderland.Psh.floatStack; 27 | import org.spiderland.Psh.TestCase.TestCaseGenerator; 28 | 29 | /** 30 | * This problem class implements symbolic regression for floating point numbers. 31 | * See also IntSymbolicRegression for integer symbolic regression. 32 | */ 33 | public class FloatSymbolicRegression extends PushGP { 34 | private static final long serialVersionUID = 1L; 35 | 36 | private float _noResultPenalty = 10000; 37 | 38 | protected void InitFromParameters() throws Exception { 39 | super.InitFromParameters(); 40 | 41 | String cases = GetParam("test-cases", true); 42 | String casesClass = GetParam("test-case-class", true); 43 | if (cases == null && casesClass == null) { 44 | throw new Exception("No acceptable test-case parameter."); 45 | } 46 | 47 | if (casesClass != null) { 48 | // Get test cases from the TestCasesClass. 49 | Class iclass = Class.forName(casesClass); 50 | Object iObject = iclass.newInstance(); 51 | if (!(iObject instanceof TestCaseGenerator)) { 52 | throw (new Exception( 53 | "test-case-class must inherit from class TestCaseGenerator")); 54 | } 55 | 56 | TestCaseGenerator testCaseGenerator = (TestCaseGenerator) iObject; 57 | int numTestCases = testCaseGenerator.TestCaseCount(); 58 | 59 | for (int i = 0; i < numTestCases; i++) { 60 | ObjectPair testCase = testCaseGenerator.TestCase(i); 61 | 62 | Float in = (Float) testCase._first; 63 | Float out = (Float) testCase._second; 64 | 65 | Print(";; Fitness case #" + i + " input: " + in + " output: " 66 | + out + "\n"); 67 | 68 | _testCases.add(new GATestCase(in, out)); 69 | } 70 | } else { 71 | // Get test cases from test-cases. 72 | Program caselist = new Program(_interpreter, cases); 73 | 74 | for (int i = 0; i < caselist.size(); i++) { 75 | Program p = (Program) caselist.peek(i); 76 | 77 | if (p.size() < 2) 78 | throw new Exception( 79 | "Not enough elements for fitness case \"" + p 80 | + "\""); 81 | 82 | Float in = new Float(p.peek(0).toString()); 83 | Float out = new Float(p.peek(1).toString()); 84 | 85 | Print(";; Fitness case #" + i + " input: " + in + " output: " 86 | + out + "\n"); 87 | 88 | _testCases.add(new GATestCase(in, out)); 89 | } 90 | } 91 | 92 | } 93 | 94 | protected void InitInterpreter(Interpreter inInterpreter) { 95 | } 96 | 97 | public float EvaluateTestCase(GAIndividual inIndividual, Object inInput, 98 | Object inOutput) { 99 | _interpreter.ClearStacks(); 100 | 101 | float currentInput = (Float) inInput; 102 | 103 | floatStack stack = _interpreter.floatStack(); 104 | 105 | stack.push(currentInput); 106 | 107 | // Must be included in order to use the input stack. 108 | _interpreter.inputStack().push(currentInput); 109 | 110 | _interpreter.Execute(((PushGPIndividual) inIndividual)._program, 111 | _executionLimit); 112 | 113 | float result = stack.top(); 114 | 115 | // Penalize individual if there is no result on the stack. 116 | if(stack.size() == 0){ 117 | return _noResultPenalty; 118 | } 119 | 120 | return result - ((Float) inOutput); 121 | } 122 | 123 | public float GetIndividualTestCaseResult(GAIndividual inIndividual, GATestCase inTestCase){ 124 | _interpreter.ClearStacks(); 125 | 126 | float currentInput = (Float) inTestCase._input; 127 | 128 | floatStack stack = _interpreter.floatStack(); 129 | 130 | stack.push(currentInput); 131 | 132 | // Must be included in order to use the input stack. 133 | _interpreter.inputStack().push(currentInput); 134 | 135 | _interpreter.Execute(((PushGPIndividual) inIndividual)._program, 136 | _executionLimit); 137 | 138 | float result = stack.top(); 139 | 140 | // If no result, return 0 141 | if(stack.size() == 0){ 142 | return 0; 143 | } 144 | 145 | return result; 146 | } 147 | 148 | protected boolean Success() { 149 | return _bestMeanFitness <= 0.1; 150 | } 151 | 152 | } 153 | -------------------------------------------------------------------------------- /org/spiderland/Psh/ProbClass/IntSymbolicRegression.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh.ProbClass; 18 | 19 | import org.spiderland.Psh.GAIndividual; 20 | import org.spiderland.Psh.GATestCase; 21 | import org.spiderland.Psh.Interpreter; 22 | import org.spiderland.Psh.ObjectPair; 23 | import org.spiderland.Psh.Program; 24 | import org.spiderland.Psh.PushGP; 25 | import org.spiderland.Psh.PushGPIndividual; 26 | import org.spiderland.Psh.intStack; 27 | import org.spiderland.Psh.TestCase.TestCaseGenerator; 28 | 29 | /** 30 | * This problem class implements symbolic regression for integers. See also 31 | * IntSymbolicRegression for integer symbolic regression. 32 | */ 33 | public class IntSymbolicRegression extends PushGP { 34 | private static final long serialVersionUID = 1L; 35 | 36 | protected float _noResultPenalty = 1000; 37 | 38 | protected void InitFromParameters() throws Exception { 39 | super.InitFromParameters(); 40 | 41 | String cases = GetParam("test-cases", true); 42 | String casesClass = GetParam("test-case-class", true); 43 | if (cases == null && casesClass == null) { 44 | throw new Exception("No acceptable test-case parameter."); 45 | } 46 | 47 | if (casesClass != null) { 48 | // Get test cases from the TestCasesClass. 49 | Class iclass = Class.forName(casesClass); 50 | Object iObject = iclass.newInstance(); 51 | if (!(iObject instanceof TestCaseGenerator)) { 52 | throw (new Exception( 53 | "test-case-class must inherit from class TestCaseGenerator")); 54 | } 55 | 56 | TestCaseGenerator testCaseGenerator = (TestCaseGenerator) iObject; 57 | int numTestCases = testCaseGenerator.TestCaseCount(); 58 | 59 | for (int i = 0; i < numTestCases; i++) { 60 | ObjectPair testCase = testCaseGenerator.TestCase(i); 61 | 62 | Integer in = (Integer) testCase._first; 63 | Integer out = (Integer) testCase._second; 64 | 65 | Print(";; Fitness case #" + i + " input: " + in + " output: " 66 | + out + "\n"); 67 | 68 | _testCases.add(new GATestCase(in, out)); 69 | } 70 | } else { 71 | // Get test cases from test-cases. 72 | Program caselist = new Program(_interpreter, cases); 73 | 74 | for (int i = 0; i < caselist.size(); i++) { 75 | Program p = (Program) caselist.peek(i); 76 | 77 | if (p.size() < 2) 78 | throw new Exception("Not enough elements for fitness case \"" 79 | + p + "\""); 80 | 81 | Integer in = new Integer(p.peek(0).toString()); 82 | Integer out = new Integer(p.peek(1).toString()); 83 | 84 | Print(";; Fitness case #" + i + " input: " + in + " output: " + out 85 | + "\n"); 86 | 87 | _testCases.add(new GATestCase(in, out)); 88 | } 89 | } 90 | 91 | } 92 | 93 | protected void InitInterpreter(Interpreter inInterpreter) { 94 | } 95 | 96 | public float EvaluateTestCase(GAIndividual inIndividual, Object inInput, 97 | Object inOutput) { 98 | _interpreter.ClearStacks(); 99 | 100 | int currentInput = (Integer) inInput; 101 | 102 | intStack stack = _interpreter.intStack(); 103 | 104 | stack.push(currentInput); 105 | 106 | // Must be included in order to use the input stack. 107 | _interpreter.inputStack().push(currentInput); 108 | 109 | _interpreter.Execute(((PushGPIndividual) inIndividual)._program, 110 | _executionLimit); 111 | 112 | int result = stack.top(); 113 | // System.out.println( _interpreter + " " + result ); 114 | 115 | // Penalize individual if there is no result on the stack. 116 | if(stack.size() == 0){ 117 | return _noResultPenalty; 118 | } 119 | 120 | return result - ((Integer) inOutput); 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /org/spiderland/Psh/Program.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh; 18 | 19 | import java.io.Serializable; 20 | 21 | /** 22 | * A Push program. 23 | */ 24 | 25 | public class Program extends ObjectStack implements Serializable { 26 | private static final long serialVersionUID = 1L; 27 | 28 | Interpreter _interpreter = null; 29 | 30 | public Interpreter getInterpreter() { 31 | return _interpreter; 32 | } 33 | 34 | public void setInterpreter(Interpreter _interpreter) { 35 | this._interpreter = _interpreter; 36 | } 37 | 38 | /** 39 | * Constructs an empty Program. 40 | * 41 | * @deprecated 42 | */ 43 | 44 | public Program() { 45 | } 46 | 47 | /** 48 | * Constructs an empty Program with an associated Interpreter. 49 | */ 50 | 51 | public Program(Interpreter inInterpreter) { 52 | _interpreter = inInterpreter; 53 | } 54 | 55 | /** 56 | * Constructs a copy of an existing Program. 57 | * 58 | * @param inOther 59 | * The Push program to copy. 60 | */ 61 | 62 | public Program(Program inOther) { 63 | inOther.CopyTo(this); 64 | _interpreter = inOther._interpreter; 65 | } 66 | 67 | /** 68 | * Constructs a Push program by parsing a String. 69 | * 70 | * @param inString 71 | * The Push program string to parse. 72 | * 73 | */ 74 | 75 | public Program(String inString) throws Exception { 76 | Parse(inString); 77 | } 78 | 79 | /** 80 | * Constructs a Push program by parsing a String. 81 | * 82 | * @param inString 83 | * The Push program string to parse. 84 | */ 85 | 86 | public Program(Interpreter _interpreter, String inString) throws Exception { 87 | this._interpreter = _interpreter; 88 | Parse(inString); 89 | } 90 | 91 | /** 92 | * Sets this program to the parsed program string. 93 | * 94 | * @param inString 95 | * The Push program string to parse. 96 | * @return The point size of the new program. 97 | */ 98 | 99 | public int Parse(String inString) throws Exception { 100 | clear(); 101 | 102 | inString = inString.replace("(", " ( "); 103 | inString = inString.replace(")", " ) "); 104 | 105 | String tokens[] = inString.split("\\s+"); 106 | 107 | Parse(tokens, 0); 108 | 109 | return programsize(); 110 | } 111 | 112 | private int Parse(String inTokens[], int inStart) throws Exception { 113 | boolean first = (inStart == 0); 114 | 115 | for (int n = inStart; n < inTokens.length; n++) { 116 | String token = inTokens[n]; 117 | 118 | if (!token.equals("")) { 119 | if (token.equals("(")) { 120 | 121 | // Found an open paren -- begin a recursive Parse, though 122 | // the very first 123 | // token in the list is a special case -- no need to create 124 | // a sub-program 125 | 126 | if (!first) { 127 | Program p = new Program(_interpreter); 128 | 129 | n = p.Parse(inTokens, n + 1); 130 | 131 | push(p); 132 | } 133 | } else if (token.equals(")")) { 134 | // End of the program -- return the advanced token index to 135 | // the caller 136 | 137 | return n; 138 | 139 | } else if (Character.isLetter(token.charAt(0))) { 140 | 141 | push(token); 142 | 143 | // This makes printing stacks very ugly. For now, will store 144 | // program instructions as strings, as was done before. 145 | /* 146 | Instruction i = _interpreter._instructions.get(token); 147 | if (i != null) 148 | push(i); 149 | else 150 | push(token); 151 | */ 152 | 153 | } else { 154 | Object number; 155 | 156 | if (token.indexOf('.') != -1) 157 | number = Float.parseFloat(token); 158 | else 159 | number = Integer.parseInt(token); 160 | 161 | push(number); 162 | } 163 | 164 | first = false; 165 | } 166 | } 167 | 168 | // If we're here, there was no closing brace for one of the programs 169 | 170 | throw new Exception("no closing brace found for program"); 171 | } 172 | 173 | /** 174 | * Returns the size of the program and all subprograms. 175 | * 176 | * @return The size of the program. 177 | */ 178 | public int programsize() { 179 | int size = _size; 180 | 181 | for (int n = 0; n < _size; n++) { 182 | Object o = _stack[n]; 183 | if (o instanceof Program) 184 | size += ((Program) o).programsize(); 185 | } 186 | 187 | return size; 188 | } 189 | 190 | /** 191 | * Returns the size of a subtree. 192 | * 193 | * @param inIndex 194 | * The index of the requested subtree. 195 | * @return The size of the subtree. 196 | */ 197 | 198 | public int SubtreeSize(int inIndex) { 199 | Object sub = Subtree(inIndex); 200 | 201 | if (sub == null) 202 | return 0; 203 | 204 | if (sub instanceof Program) 205 | return ((Program) sub).programsize(); 206 | 207 | return 1; 208 | } 209 | 210 | /** 211 | * Returns a subtree of the program. 212 | * 213 | * @param inIndex 214 | * The index of the requested subtree. 215 | * @return The program subtree. 216 | */ 217 | 218 | public Object Subtree(int inIndex) { 219 | if (inIndex < _size) { 220 | return _stack[inIndex]; 221 | } else { 222 | int startIndex = _size; 223 | 224 | for (int n = 0; n < _size; n++) { 225 | Object o = _stack[n]; 226 | 227 | if (o instanceof Program) { 228 | Program sub = (Program) o; 229 | int length = sub.programsize(); 230 | 231 | if (inIndex - startIndex < length) 232 | return sub.Subtree(inIndex - startIndex); 233 | 234 | startIndex += length; 235 | } 236 | } 237 | } 238 | 239 | return null; 240 | } 241 | 242 | /** 243 | * Replaces a subtree of this Program with a new object. 244 | * 245 | * @param inIndex 246 | * The index of the subtree to replace. 247 | * @param inReplacement 248 | * The replacement for the subtree 249 | * @return True if a replacement was made (the index was valid). 250 | */ 251 | 252 | public boolean ReplaceSubtree(int inIndex, Object inReplacement) { 253 | if (inIndex < _size) { 254 | _stack[inIndex] = cloneforprogram(inReplacement); 255 | return true; 256 | } else { 257 | int startIndex = _size; 258 | 259 | for (int n = 0; n < _size; n++) { 260 | Object o = _stack[n]; 261 | 262 | if (o instanceof Program) { 263 | Program sub = (Program) o; 264 | int length = sub.programsize(); 265 | 266 | if (inIndex - startIndex < length) 267 | return sub.ReplaceSubtree(inIndex - startIndex, 268 | inReplacement); 269 | 270 | startIndex += length; 271 | } 272 | } 273 | } 274 | 275 | return false; 276 | } 277 | 278 | public void Flatten(int inIndex) { 279 | if (inIndex < _size) { 280 | // If here, the index to be flattened is in this program. So, push 281 | // the rest of the program onto a new program, and replace this with 282 | // that new program. 283 | 284 | Program replacement = new Program(this); 285 | clear(); 286 | 287 | for (int i = 0; i < replacement._size; i++) { 288 | if (inIndex == i) { 289 | 290 | if (replacement._stack[i] instanceof Program) { 291 | Program p = (Program) replacement._stack[i]; 292 | for (int j = 0; j < p._size; j++) 293 | this.push(p._stack[j]); 294 | } else { 295 | this.push(replacement._stack[i]); 296 | } 297 | } else { 298 | this.push(replacement._stack[i]); 299 | } 300 | } 301 | } else { 302 | int startIndex = _size; 303 | 304 | for (int n = 0; n < _size; n++) { 305 | Object o = _stack[n]; 306 | 307 | if (o instanceof Program) { 308 | Program sub = (Program) o; 309 | int length = sub.programsize(); 310 | 311 | if (inIndex - startIndex < length) { 312 | sub.Flatten(inIndex - startIndex); 313 | break; 314 | } 315 | 316 | startIndex += length; 317 | } 318 | } 319 | } 320 | } 321 | 322 | /** 323 | * Copies this program to another. 324 | * 325 | * @param inOther 326 | * The program to receive the copy of this program 327 | */ 328 | 329 | public void CopyTo(Program inOther) { 330 | for (int n = 0; n < _size; n++) 331 | inOther.push(_stack[n]); 332 | } 333 | 334 | public String toString() { 335 | String result = "("; 336 | 337 | for (int n = 0; n < _size; n++) { 338 | if (result.charAt(result.length() - 1) == '(') 339 | result += _stack[n]; 340 | else 341 | result += " " + _stack[n]; 342 | } 343 | 344 | result += ")"; 345 | 346 | return result; 347 | } 348 | 349 | /** 350 | * Creates a copy of an object suitable for adding to a Push Program. Java's 351 | * clone() is unfortunately useless for this task. 352 | */ 353 | 354 | private Object cloneforprogram(Object inObject) { 355 | // Java clone() is useless :( 356 | 357 | if (inObject instanceof String) 358 | return new String((String) inObject); 359 | 360 | if (inObject instanceof Integer) 361 | return new Integer((Integer) inObject); 362 | 363 | if (inObject instanceof Float) 364 | return new Float((Float) inObject); 365 | 366 | if (inObject instanceof Program) 367 | return new Program((Program) inObject); 368 | 369 | if (inObject instanceof Instruction) 370 | return inObject; // no need to copy; instructions are singletons 371 | 372 | return null; 373 | } 374 | 375 | } 376 | -------------------------------------------------------------------------------- /org/spiderland/Psh/PushGPIndividual.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh; 18 | 19 | /** 20 | * A PushGA individual class which is a simple wrapper around a Push Program 21 | * object. 22 | */ 23 | 24 | public class PushGPIndividual extends GAIndividual { 25 | private static final long serialVersionUID = 1L; 26 | 27 | public Program _program; 28 | 29 | public PushGPIndividual() { 30 | } 31 | 32 | PushGPIndividual(Program inProgram) { 33 | SetProgram(inProgram); 34 | _fitnessSet = false; 35 | } 36 | 37 | void SetProgram(Program inProgram) { 38 | if (inProgram != null) 39 | _program = new Program(inProgram); 40 | } 41 | 42 | public String toString() { 43 | return _program.toString(); 44 | } 45 | 46 | public GAIndividual clone() { 47 | return new PushGPIndividual(_program); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /org/spiderland/Psh/Stack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh; 18 | 19 | import java.io.Serializable; 20 | 21 | /** 22 | * Abstract class for implementing stacks. 23 | */ 24 | abstract class Stack implements Serializable { 25 | private static final long serialVersionUID = 1L; 26 | 27 | protected int _size; 28 | protected int _maxsize; 29 | 30 | Stack() { 31 | _size = 0; 32 | resize(8); 33 | } 34 | 35 | abstract void resize(int inSize); 36 | 37 | abstract void dup(); 38 | 39 | abstract void rot(); 40 | 41 | abstract void shove(int inIndex); 42 | 43 | abstract void swap(); 44 | 45 | abstract void yank(int inIndex); 46 | 47 | abstract void yankdup(int inIndex); 48 | 49 | public void clear() { 50 | _size = 0; 51 | } 52 | 53 | public int size() { 54 | return _size; 55 | } 56 | 57 | public void popdiscard() { 58 | if (_size > 0) 59 | _size--; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /org/spiderland/Psh/TestCase/FloatRegTestCases1.java: -------------------------------------------------------------------------------- 1 | package org.spiderland.Psh.TestCase; 2 | 3 | import org.spiderland.Psh.ObjectPair; 4 | 5 | public class FloatRegTestCases1 extends TestCaseGenerator { 6 | 7 | private static int _testCaseCount = 200; 8 | private static float _firstSample = -10; 9 | private static float _lastSample = 10; 10 | 11 | private float[] _testCasesX = null; 12 | private float[] _testCasesY = null; 13 | 14 | @Override 15 | public int TestCaseCount() { 16 | return _testCaseCount; 17 | } 18 | 19 | @Override 20 | public ObjectPair TestCase(int inIndex) { 21 | if(_testCasesX == null){ 22 | _testCasesX = new float[_testCaseCount]; 23 | _testCasesY = new float[_testCaseCount]; 24 | 25 | for(int i = 0; i < _testCaseCount; i++){ 26 | _testCasesX[i] = XValue(i); 27 | _testCasesY[i] = TestCaseFunction(_testCasesX[i]); 28 | } 29 | } 30 | 31 | return new ObjectPair(_testCasesX[inIndex], _testCasesY[inIndex]); 32 | } 33 | 34 | private float XValue(float i) { 35 | return (float) _firstSample 36 | + (((_lastSample - _firstSample) / (_testCaseCount - 1)) * i); 37 | } 38 | 39 | private float TestCaseFunction(float x) { 40 | // y = 3x^2 + 4x 41 | return (3 * x * x) + (4 * x); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /org/spiderland/Psh/TestCase/FloatRegTestCases2.java: -------------------------------------------------------------------------------- 1 | package org.spiderland.Psh.TestCase; 2 | 3 | import org.spiderland.Psh.ObjectPair; 4 | 5 | public class FloatRegTestCases2 extends TestCaseGenerator { 6 | 7 | private static int _testCaseCount = 200; 8 | private float[] _testCasesX = null; 9 | private float[] _testCasesY = null; 10 | 11 | private static float _firstSample = -3; 12 | private static float _lastSample = 3; 13 | 14 | @Override 15 | public int TestCaseCount() { 16 | return _testCaseCount; 17 | } 18 | 19 | @Override 20 | public ObjectPair TestCase(int inIndex) { 21 | if(_testCasesX == null){ 22 | _testCasesX = new float[_testCaseCount]; 23 | _testCasesY = new float[_testCaseCount]; 24 | 25 | for(int i = 0; i < _testCaseCount; i++){ 26 | _testCasesX[i] = XValue(i); 27 | _testCasesY[i] = TestCaseFunction(_testCasesX[i]); 28 | } 29 | } 30 | 31 | return new ObjectPair(_testCasesX[inIndex], _testCasesY[inIndex]); 32 | } 33 | 34 | private float XValue(float i) { 35 | return (float) _firstSample 36 | + (((_lastSample - _firstSample) / (_testCaseCount - 1)) * i); 37 | } 38 | 39 | private float TestCaseFunction(float x) { 40 | return (float) (Math.exp(Math.abs(x)) * Math.sin(2.0 * Math.PI * x)); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /org/spiderland/Psh/TestCase/IntRegTestCases1.java: -------------------------------------------------------------------------------- 1 | package org.spiderland.Psh.TestCase; 2 | 3 | import org.spiderland.Psh.ObjectPair; 4 | 5 | public class IntRegTestCases1 extends TestCaseGenerator { 6 | 7 | private static int _testCaseCount = 200; 8 | private int[] _testCasesX = null; 9 | private int[] _testCasesY = null; 10 | 11 | private static int _firstSample = -99; 12 | private static int _stepSize = 1; 13 | 14 | @Override 15 | public int TestCaseCount() { 16 | return _testCaseCount; 17 | } 18 | 19 | @Override 20 | public ObjectPair TestCase(int inIndex) { 21 | if (_testCasesX == null) { 22 | _testCasesX = new int[_testCaseCount]; 23 | _testCasesY = new int[_testCaseCount]; 24 | 25 | for (int i = 0; i < _testCaseCount; i++) { 26 | _testCasesX[i] = XValue(i); 27 | _testCasesY[i] = TestCaseFunction(_testCasesX[i]); 28 | } 29 | } 30 | 31 | return new ObjectPair(_testCasesX[inIndex], _testCasesY[inIndex]); 32 | } 33 | 34 | private int XValue(int i) { 35 | return _firstSample + (_stepSize * i); 36 | } 37 | 38 | private int TestCaseFunction(int x) { 39 | // y = 9x^3 + 24x^2 - 3x + 10 40 | return (9 * x * x * x) + (24 * x * x) 41 | - (3 * x) + 10; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /org/spiderland/Psh/TestCase/TestCaseGenerator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh.TestCase; 18 | 19 | import org.spiderland.Psh.ObjectPair; 20 | 21 | /** 22 | * A class allowing for the runtime creation of custom test cases. 23 | * 24 | * Each test case is a dictionary of HashMap< String, Object >. Each entry in 25 | * the dictionary corresponds to a problem input, except for the special token 26 | * "output", which is reserved for the problem output. 27 | */ 28 | 29 | abstract public class TestCaseGenerator { 30 | 31 | /** 32 | * @returns The number of cases the generator will create. 33 | */ 34 | abstract public int TestCaseCount(); 35 | 36 | /** 37 | * @returns Test case at index n as an ObjectPair, where _first is the input 38 | * and _second is the output. The types of the objects may depend 39 | * on the problem type. 40 | */ 41 | abstract public ObjectPair TestCase(int inIndex); 42 | 43 | } 44 | -------------------------------------------------------------------------------- /org/spiderland/Psh/booleanStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh; 18 | 19 | /** 20 | * The Push stack type for booleans. 21 | */ 22 | 23 | public class booleanStack extends Stack { 24 | private static final long serialVersionUID = 1L; 25 | 26 | protected boolean _stack[]; 27 | 28 | @Override 29 | public boolean equals(Object obj) { 30 | if (obj == null) 31 | return false; 32 | if (getClass() != obj.getClass()) 33 | return false; 34 | final booleanStack other = (booleanStack) obj; 35 | if (_size != other._size) 36 | return false; 37 | for (int i = 0; i < _size; i++) 38 | if (_stack[i] != other._stack[i]) 39 | return false; 40 | return true; 41 | } 42 | 43 | @Override 44 | public int hashCode() { 45 | int hash = 7; 46 | for (int i = 0; i < _size; i++) 47 | hash = 41 * hash + Boolean.valueOf(_stack[i]).hashCode(); 48 | return hash; 49 | } 50 | 51 | void resize(int inSize) { 52 | boolean newstack[] = new boolean[inSize]; 53 | 54 | if (_stack != null) 55 | System.arraycopy(_stack, 0, newstack, 0, _size); 56 | 57 | _stack = newstack; 58 | _maxsize = inSize; 59 | } 60 | 61 | public boolean top() { 62 | if (_size > 0) 63 | return peek(_size - 1); 64 | 65 | return false; 66 | } 67 | 68 | public boolean peek(int inIndex) { 69 | if (inIndex >= 0 && inIndex < _size) 70 | return _stack[inIndex]; 71 | 72 | return false; 73 | } 74 | 75 | public boolean pop() { 76 | boolean result = false; 77 | 78 | if (_size > 0) { 79 | result = _stack[_size - 1]; 80 | _size--; 81 | } 82 | 83 | return result; 84 | } 85 | 86 | public void push(boolean inValue) { 87 | _stack[_size] = inValue; 88 | _size++; 89 | 90 | if (_size >= _maxsize) 91 | resize(_maxsize * 2); 92 | } 93 | 94 | public void dup() { 95 | if (_size > 0) 96 | push(_stack[_size - 1]); 97 | } 98 | 99 | public void shove(int inIndex) { 100 | if (_size > 0) { 101 | if(inIndex < 0){ 102 | inIndex = 0; 103 | } 104 | if(inIndex > _size - 1){ 105 | inIndex = _size - 1; 106 | } 107 | 108 | boolean toShove = top(); 109 | int shovedIndex = _size - inIndex - 1; 110 | 111 | for (int i = _size - 1; i > shovedIndex; i--) { 112 | _stack[i] = _stack[i - 1]; 113 | } 114 | _stack[shovedIndex] = toShove; 115 | } 116 | } 117 | 118 | public void swap() { 119 | if (_size > 1) { 120 | boolean tmp = _stack[_size - 1]; 121 | _stack[_size - 1] = _stack[_size - 2]; 122 | _stack[_size - 2] = tmp; 123 | } 124 | } 125 | 126 | public void rot() { 127 | if (_size > 2) { 128 | boolean tmp = _stack[_size - 3]; 129 | _stack[_size - 3] = _stack[_size - 2]; 130 | _stack[_size - 2] = _stack[_size - 1]; 131 | _stack[_size - 1] = tmp; 132 | } 133 | } 134 | 135 | public void yank(int inIndex) { 136 | if (_size > 0) { 137 | if(inIndex < 0){ 138 | inIndex = 0; 139 | } 140 | if(inIndex > _size - 1){ 141 | inIndex = _size - 1; 142 | } 143 | 144 | int yankedIndex = _size - inIndex - 1; 145 | boolean toYank = peek(yankedIndex); 146 | 147 | for (int i = yankedIndex; i < _size - 1; i++) { 148 | _stack[i] = _stack[i + 1]; 149 | } 150 | _stack[_size - 1] = toYank; 151 | } 152 | } 153 | 154 | public void yankdup(int inIndex) { 155 | if (_size > 0) { 156 | if(inIndex < 0){ 157 | inIndex = 0; 158 | } 159 | if(inIndex > _size - 1){ 160 | inIndex = _size - 1; 161 | } 162 | 163 | int yankedIndex = _size - inIndex - 1; 164 | push(peek(yankedIndex)); 165 | } 166 | } 167 | 168 | public String toString() { 169 | String result = "["; 170 | 171 | for (int n = _size - 1; n >= 0; n--) { 172 | if (n == _size - 1) 173 | result += _stack[n]; 174 | else 175 | result += " " + _stack[n]; 176 | } 177 | result += "]"; 178 | 179 | return result; 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /org/spiderland/Psh/floatStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh; 18 | 19 | /** 20 | * The Push stack type for object-based data (Strings, Programs, etc.) 21 | */ 22 | public class floatStack extends Stack { 23 | private static final long serialVersionUID = 1L; 24 | 25 | protected float _stack[]; 26 | 27 | @Override 28 | public boolean equals(Object obj) { 29 | if (obj == null) 30 | return false; 31 | if (getClass() != obj.getClass()) 32 | return false; 33 | final floatStack other = (floatStack) obj; 34 | if (_size != other._size) 35 | return false; 36 | for (int i = 0; i < _size; i++) 37 | if (_stack[i] != other._stack[i]) 38 | return false; 39 | return true; 40 | } 41 | 42 | @Override 43 | public int hashCode() { 44 | int hash = 7; 45 | for (int i = 0; i < _size; i++) 46 | hash = 41 * hash + Float.valueOf(_stack[i]).hashCode(); 47 | return hash; 48 | } 49 | 50 | void resize(int inSize) { 51 | float newstack[] = new float[inSize]; 52 | 53 | if (_stack != null) 54 | System.arraycopy(_stack, 0, newstack, 0, _size); 55 | 56 | _stack = newstack; 57 | _maxsize = inSize; 58 | } 59 | 60 | public float accumulate() { 61 | float f = 0; 62 | 63 | for (int n = 0; n < _size; n++) { 64 | f += _stack[n]; 65 | } 66 | 67 | return f; 68 | } 69 | 70 | public float top() { 71 | return peek(_size - 1); 72 | } 73 | 74 | public float peek(int inIndex) { 75 | if (inIndex >= 0 && inIndex < _size) 76 | return _stack[inIndex]; 77 | 78 | return 0.0f; 79 | } 80 | 81 | public float pop() { 82 | float result = 0.0f; 83 | 84 | if (_size > 0) { 85 | result = _stack[_size - 1]; 86 | _size--; 87 | } 88 | 89 | return result; 90 | } 91 | 92 | public void push(float inValue) { 93 | _stack[_size] = inValue; 94 | _size++; 95 | 96 | if (_size >= _maxsize) 97 | resize(_maxsize * 2); 98 | } 99 | 100 | public void dup() { 101 | if (_size > 0) 102 | push(_stack[_size - 1]); 103 | } 104 | 105 | public void shove(int inIndex) { 106 | if (_size > 0) { 107 | if(inIndex < 0){ 108 | inIndex = 0; 109 | } 110 | if(inIndex > _size - 1){ 111 | inIndex = _size - 1; 112 | } 113 | 114 | float toShove = top(); 115 | int shovedIndex = _size - inIndex - 1; 116 | 117 | for (int i = _size - 1; i > shovedIndex; i--) { 118 | _stack[i] = _stack[i - 1]; 119 | } 120 | _stack[shovedIndex] = toShove; 121 | } 122 | } 123 | 124 | public void swap() { 125 | if (_size > 1) { 126 | float tmp = _stack[_size - 1]; 127 | _stack[_size - 1] = _stack[_size - 2]; 128 | _stack[_size - 2] = tmp; 129 | } 130 | } 131 | 132 | public void rot() { 133 | if (_size > 2) { 134 | float tmp = _stack[_size - 3]; 135 | _stack[_size - 3] = _stack[_size - 2]; 136 | _stack[_size - 2] = _stack[_size - 1]; 137 | _stack[_size - 1] = tmp; 138 | } 139 | } 140 | 141 | public void yank(int inIndex) { 142 | if (_size > 0) { 143 | if(inIndex < 0){ 144 | inIndex = 0; 145 | } 146 | if(inIndex > _size - 1){ 147 | inIndex = _size - 1; 148 | } 149 | 150 | int yankedIndex = _size - inIndex - 1; 151 | float toYank = peek(yankedIndex); 152 | 153 | for (int i = yankedIndex; i < _size - 1; i++) { 154 | _stack[i] = _stack[i + 1]; 155 | } 156 | _stack[_size - 1] = toYank; 157 | } 158 | } 159 | 160 | public void yankdup(int inIndex) { 161 | if (_size > 0) { 162 | if(inIndex < 0){ 163 | inIndex = 0; 164 | } 165 | if(inIndex > _size - 1){ 166 | inIndex = _size - 1; 167 | } 168 | 169 | int yankedIndex = _size - inIndex - 1; 170 | push(peek(yankedIndex)); 171 | } 172 | } 173 | 174 | public void set(int inIndex, float inValue){ 175 | if (inIndex >= 0 && inIndex < _size) 176 | _stack[inIndex] = inValue; 177 | } 178 | 179 | public String toString() { 180 | String result = "["; 181 | 182 | for (int n = _size - 1; n >= 0; n--) { 183 | if (n == _size - 1) 184 | result += _stack[n]; 185 | else 186 | result += " " + _stack[n]; 187 | } 188 | result += "]"; 189 | 190 | return result; 191 | } 192 | } 193 | -------------------------------------------------------------------------------- /org/spiderland/Psh/intStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh; 18 | 19 | /** 20 | * The Push stack type for integers. 21 | */ 22 | 23 | public class intStack extends Stack { 24 | private static final long serialVersionUID = 1L; 25 | 26 | protected int _stack[]; 27 | 28 | @Override 29 | public boolean equals(Object obj) { 30 | if (obj == null) 31 | return false; 32 | if (getClass() != obj.getClass()) 33 | return false; 34 | final intStack other = (intStack) obj; 35 | if (_size != other._size) 36 | return false; 37 | for (int i = 0; i < _size; i++) 38 | if (_stack[i] != other._stack[i]) 39 | return false; 40 | return true; 41 | } 42 | 43 | @Override 44 | public int hashCode() { 45 | int hash = 7; 46 | for (int i = 0; i < _size; i++) 47 | hash = 41 * hash + _stack[i]; 48 | return hash; 49 | } 50 | 51 | void resize(int inSize) { 52 | int newstack[] = new int[inSize]; 53 | 54 | if (_stack != null) 55 | System.arraycopy(_stack, 0, newstack, 0, _size); 56 | 57 | _stack = newstack; 58 | _maxsize = inSize; 59 | } 60 | 61 | public int top() { 62 | return peek(_size - 1); 63 | } 64 | 65 | public int peek(int inIndex) { 66 | if (inIndex >= 0 && inIndex < _size) 67 | return _stack[inIndex]; 68 | 69 | return 0; 70 | } 71 | 72 | public int pop() { 73 | int result = 0; 74 | 75 | if (_size > 0) { 76 | result = _stack[_size - 1]; 77 | _size--; 78 | } 79 | 80 | return result; 81 | } 82 | 83 | public void push(int inValue) { 84 | _stack[_size] = inValue; 85 | _size++; 86 | 87 | if (_size >= _maxsize) 88 | resize(_maxsize * 2); 89 | } 90 | 91 | public void dup() { 92 | if (_size > 0) 93 | push(_stack[_size - 1]); 94 | } 95 | 96 | public void shove(int inIndex) { 97 | if (_size > 0) { 98 | if(inIndex < 0){ 99 | inIndex = 0; 100 | } 101 | if(inIndex > _size - 1){ 102 | inIndex = _size - 1; 103 | } 104 | 105 | int toShove = top(); 106 | int shovedIndex = _size - inIndex - 1; 107 | 108 | for (int i = _size - 1; i > shovedIndex; i--) { 109 | _stack[i] = _stack[i - 1]; 110 | } 111 | _stack[shovedIndex] = toShove; 112 | } 113 | } 114 | 115 | public void swap() { 116 | if (_size > 1) { 117 | int tmp = _stack[_size - 1]; 118 | _stack[_size - 1] = _stack[_size - 2]; 119 | _stack[_size - 2] = tmp; 120 | } 121 | } 122 | 123 | public void rot() { 124 | if (_size > 2) { 125 | int tmp = _stack[_size - 3]; 126 | _stack[_size - 3] = _stack[_size - 2]; 127 | _stack[_size - 2] = _stack[_size - 1]; 128 | _stack[_size - 1] = tmp; 129 | } 130 | } 131 | 132 | public void yank(int inIndex) { 133 | if (_size > 0) { 134 | if(inIndex < 0){ 135 | inIndex = 0; 136 | } 137 | if(inIndex > _size - 1){ 138 | inIndex = _size - 1; 139 | } 140 | 141 | int yankedIndex = _size - inIndex - 1; 142 | int toYank = peek(yankedIndex); 143 | 144 | for (int i = yankedIndex; i < _size - 1; i++) { 145 | _stack[i] = _stack[i + 1]; 146 | } 147 | _stack[_size - 1] = toYank; 148 | } 149 | } 150 | 151 | public void yankdup(int inIndex) { 152 | if (_size > 0) { 153 | if(inIndex < 0){ 154 | inIndex = 0; 155 | } 156 | if(inIndex > _size - 1){ 157 | inIndex = _size - 1; 158 | } 159 | 160 | int yankedIndex = _size - inIndex - 1; 161 | push(peek(yankedIndex)); 162 | } 163 | } 164 | 165 | public void set(int inIndex, int inValue){ 166 | if (inIndex >= 0 && inIndex < _size) 167 | _stack[inIndex] = inValue; 168 | } 169 | 170 | public String toString() { 171 | String result = "["; 172 | 173 | for (int n = _size - 1; n >= 0; n--) { 174 | if (n == _size - 1) 175 | result += _stack[n]; 176 | else 177 | result += " " + _stack[n]; 178 | } 179 | result += "]"; 180 | 181 | return result; 182 | } 183 | 184 | } 185 | -------------------------------------------------------------------------------- /org/spiderland/Psh/test/GenericStackTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein and Robert Baruch 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh.test; 18 | 19 | import java.util.Vector; 20 | import junit.framework.TestCase; 21 | import org.spiderland.Psh.GenericStack; 22 | 23 | public class GenericStackTest extends TestCase 24 | { 25 | public void testPushPop() throws Exception 26 | { 27 | GenericStack stringStack = new GenericStack(); 28 | GenericStack> stringVectorStack = new GenericStack>(); 29 | 30 | Vector vect = new Vector(); 31 | vect.add("a string in a vector 1"); 32 | vect.add("another string 2"); 33 | 34 | stringStack.push("value 1"); 35 | stringVectorStack.push(vect); 36 | 37 | stringStack.push("value 2"); 38 | stringVectorStack.push(null); 39 | 40 | assertEquals(2, stringStack.size()); 41 | assertEquals(2, stringVectorStack.size()); 42 | 43 | assertEquals("value 2", stringStack.pop()); 44 | assertEquals(1, stringStack.size()); 45 | assertEquals("value 1", stringStack.pop()); 46 | assertEquals(0, stringStack.size()); 47 | 48 | assertNull(stringVectorStack.pop()); 49 | assertEquals(vect, stringVectorStack.pop()); 50 | 51 | assertNull(stringStack.pop()); 52 | assertEquals(0, stringStack.size()); 53 | } 54 | 55 | public void testPushAllReverse() throws Exception 56 | { 57 | GenericStack stringStack = new GenericStack(); 58 | 59 | stringStack.push("value 1"); 60 | stringStack.push("value 2"); 61 | 62 | GenericStack stringStack2 = new GenericStack(); 63 | 64 | stringStack.PushAllReverse(stringStack2); 65 | 66 | assertEquals(2, stringStack.size()); 67 | assertEquals(2, stringStack2.size()); 68 | assertEquals("value 1", stringStack2.pop()); 69 | assertEquals("value 2", stringStack2.pop()); 70 | } 71 | 72 | public void testEquals() throws Exception 73 | { 74 | GenericStack stringStack = new GenericStack(); 75 | GenericStack stringStack2 = new GenericStack(); 76 | GenericStack> stringVectorStack = new GenericStack>(); 77 | 78 | System.out.println("StringStack type is " + stringStack.getClass()); 79 | assertTrue(stringStack.equals(stringVectorStack)); // see note in equals 80 | assertTrue(stringStack.equals(stringStack2)); 81 | 82 | assertEquals(stringStack.hashCode(), stringStack2.hashCode()); 83 | assertEquals(stringStack.hashCode(), stringVectorStack.hashCode()); // see note in equals 84 | 85 | stringStack.push("value 1"); 86 | assertFalse(stringStack.equals(stringStack2)); 87 | assertFalse(stringStack.equals(stringVectorStack)); 88 | assertFalse(stringStack.hashCode() == stringStack2.hashCode()); 89 | 90 | stringStack2.push("value 1"); 91 | assertTrue(stringStack.equals(stringStack2)); 92 | 93 | assertEquals(stringStack.hashCode(), stringStack2.hashCode()); 94 | } 95 | 96 | public void testPeek() throws Exception 97 | { 98 | GenericStack stringStack = new GenericStack(); 99 | 100 | stringStack.push("value 1"); 101 | stringStack.push("value 2"); 102 | 103 | assertEquals("value 1", stringStack.peek(0)); // deepest stack 104 | assertEquals(2, stringStack.size()); 105 | assertEquals("value 2", stringStack.top()); 106 | assertEquals(2, stringStack.size()); 107 | assertEquals("value 2", stringStack.peek(1)); 108 | } 109 | 110 | public void testDup() throws Exception 111 | { 112 | GenericStack stringStack = new GenericStack(); 113 | 114 | stringStack.dup(); 115 | assertEquals(0, stringStack.size()); 116 | 117 | stringStack.push("value 1"); 118 | stringStack.push("value 2"); 119 | stringStack.dup(); 120 | 121 | assertEquals(3, stringStack.size()); 122 | assertEquals("value 2", stringStack.peek(2)); 123 | assertEquals("value 2", stringStack.peek(1)); 124 | assertEquals("value 1", stringStack.peek(0)); 125 | } 126 | 127 | public void testSwap() throws Exception 128 | { 129 | GenericStack stringStack = new GenericStack(); 130 | 131 | stringStack.push("value 1"); 132 | stringStack.swap(); 133 | assertEquals(1, stringStack.size()); 134 | assertEquals("value 1", stringStack.peek(0)); 135 | 136 | stringStack.push("value 2"); 137 | stringStack.swap(); 138 | 139 | assertEquals(2, stringStack.size()); 140 | assertEquals("value 1", stringStack.peek(1)); 141 | assertEquals("value 2", stringStack.peek(0)); 142 | } 143 | 144 | public void testRot() throws Exception 145 | { 146 | GenericStack stringStack = new GenericStack(); 147 | 148 | stringStack.push("value 1"); 149 | stringStack.push("value 2"); 150 | stringStack.rot(); 151 | 152 | assertEquals(2, stringStack.size()); 153 | assertEquals("value 2", stringStack.peek(1)); 154 | assertEquals("value 1", stringStack.peek(0)); 155 | 156 | stringStack.push("value 3"); 157 | stringStack.push("value 4"); 158 | stringStack.rot(); 159 | assertEquals(4, stringStack.size()); 160 | assertEquals("value 2", stringStack.peek(3)); 161 | assertEquals("value 4", stringStack.peek(2)); 162 | assertEquals("value 3", stringStack.peek(1)); 163 | assertEquals("value 1", stringStack.peek(0)); 164 | } 165 | 166 | public void testShove() throws Exception 167 | { 168 | GenericStack stringStack = new GenericStack(); 169 | 170 | stringStack.shove("value 1", 0); 171 | assertEquals(1, stringStack.size()); 172 | assertEquals("value 1", stringStack.peek(0)); 173 | 174 | stringStack.shove("value 2", 1); 175 | assertEquals(2, stringStack.size()); 176 | assertEquals("value 2", stringStack.peek(0)); 177 | assertEquals("value 1", stringStack.peek(1)); 178 | 179 | stringStack.shove("value 3", 1); 180 | assertEquals(3, stringStack.size()); 181 | assertEquals("value 2", stringStack.peek(0)); 182 | assertEquals("value 3", stringStack.peek(1)); 183 | assertEquals("value 1", stringStack.peek(2)); 184 | 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /org/spiderland/Psh/test/ProgramTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2010 Jon Klein 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.spiderland.Psh.test; 18 | 19 | import junit.framework.*; 20 | import org.spiderland.Psh.*; 21 | 22 | public class ProgramTest extends TestCase { 23 | @SuppressWarnings("deprecation") 24 | public void testEquals() throws Exception { 25 | // Equality testing of nested programs 26 | 27 | Program p = new Program(), q = new Program(), r = new Program(); 28 | 29 | p.Parse( "( 1.0 ( TEST 2 ( 3 ) ) )" ); 30 | q.Parse( "( 1.0 ( TEST 2 ( 3 ) ) )" ); 31 | r.Parse( "( 2.0 ( TEST 2 ( 3 ) ) )" ); 32 | 33 | assertFalse( p.equals( r ) ); 34 | assertTrue( p.equals( q ) ); 35 | } 36 | 37 | @SuppressWarnings("deprecation") 38 | public void testParse() throws Exception { 39 | // Parse a program, and then re-parse its string representation. 40 | // They should be equal. 41 | 42 | Program p = new Program(), q = new Program(); 43 | String program = "(1(2) (3) TEST TEST (2 TEST))"; 44 | 45 | p.Parse( program ); 46 | q.Parse( p.toString() ); 47 | 48 | assertTrue( p.equals( q ) ); 49 | } 50 | 51 | @SuppressWarnings("deprecation") 52 | public void testSubtreeFetch() throws Exception { 53 | Program p = new Program(); 54 | p.Parse( "( 2.0 ( TEST 2 ( 3 ) ) )" ); 55 | 56 | assertTrue( true ); 57 | } 58 | 59 | @SuppressWarnings("deprecation") 60 | public void testSubtreeReplace() throws Exception { 61 | Program p = new Program(); 62 | Program q = new Program(); 63 | 64 | p.Parse( "( 2.0 ( TEST 2 ( 3 ) ) )" ); 65 | 66 | p.ReplaceSubtree( 0, 3 ); 67 | p.ReplaceSubtree( 2, "TEST2" ); 68 | p.ReplaceSubtree( 3, new Program( "( X )" ) ); 69 | 70 | System.out.println( p ); 71 | 72 | q.Parse( "( 3 ( TEST2 ( X ) ( 3 ) ) )" ); 73 | 74 | assertTrue( q.equals( p ) ); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /pushevolved/cartCenteringEvolved.push: -------------------------------------------------------------------------------- 1 | (float.abs input.in1 float.* float.neg float.<) 2 | 150 3 | 0.884483851852 0.463930712756 4 | -------------------------------------------------------------------------------- /pushevolved/cefloatreg2evolved.push: -------------------------------------------------------------------------------- 1 | (float.sin input.in0 float.sin input.in0 float.* float.* float.sin input.in0 float.* float.cos input.in0 float./ input.in0 float.+ input.in0 float.+ input.in0 float.* float.2pi float.2pi float.sin float.2pi float.2pi input.in0 float./ float.* float.* input.in0 input.in0 float.cos float./ float.* float.2pi float.2pi float.2pi float.* float.* float.* float.- float.2pi float.2pi float.sin input.in0 (input.in0 input.in0) float.* float.* input.in0 float.* float.* float.2pi (input.in0) float.- float.* float.* float.- input.in0 float.* float.sin float.*) 2 | 200 3 | 0.884483851852 4 | -------------------------------------------------------------------------------- /pushevolved/factorialEvolved.push: -------------------------------------------------------------------------------- 1 | ((((exec.do*count integer.swap exec.= (boolean.flush boolean.dup) exec.do*count) integer.+)) (integer.stackdepth ((integer.dup integer.* integer.swap integer.+ integer.*) integer.*) (integer.* integer.* exec.pop boolean.dup integer.+))) 2 | 200 3 | 8 -------------------------------------------------------------------------------- /pushsamples/exampleProgram0.push: -------------------------------------------------------------------------------- 1 | (1 2 integer.+) 2 | 116 3 | -------------------------------------------------------------------------------- /pushsamples/exampleProgram1.push: -------------------------------------------------------------------------------- 1 | (2994 5 integer.+) 2 | 100 3 | 44 22 true 17.76 4 | -------------------------------------------------------------------------------- /pushsamples/exampleProgram2.push: -------------------------------------------------------------------------------- 1 | (4 exec.do*count (7 integer.+)) 2 | 100 3 | -------------------------------------------------------------------------------- /pushsamples/exampleProgram3.push: -------------------------------------------------------------------------------- 1 | ((input.in3) input.in12 input.in3 3 input.index input.in4 input.inallrev) 2 | 100 3 | 0 1.83 2999 3.1415 false 5 6 7 8 9 10 11 12 13 4 | -------------------------------------------------------------------------------- /pushsamples/instructionTesting.push: -------------------------------------------------------------------------------- 1 | (6 2.3 true exec.noop) 2 | 100 3 | -------------------------------------------------------------------------------- /pushsamples/random.push: -------------------------------------------------------------------------------- 1 | ((code.swap (((exec.stackdepth code.= (((exec.do*range boolean.swap) integer.dup) (exec.do*range boolean.swap) ((exec.do*range boolean.swap) (integer.rot)))) boolean.swap) (integer.*)) exec.stackdepth) (((boolean.pop ((exec.do*range boolean.swap) ((true code.= (((integer.pop boolean.swap) integer.dup) ((exec.do*range (integer.* integer.swap (exec.if exec.=))) (code.swap)) (code.= ((exec.do*range boolean.swap))))) (exec.stackdepth code.= (((exec.do*range ((exec.do*range boolean.swap) (integer.pop))) integer.dup) ((exec.do*range boolean.swap) (code.swap)) ((exec.do*range boolean.swap) (integer.rot)))))) (code.stackdepth)) (code.do*times integer.+))) (code.do*count code.if) exec.stackdepth) 2 | 10000 3 | 19 4 | -------------------------------------------------------------------------------- /tools/InstructionListCleaner.java: -------------------------------------------------------------------------------- 1 | package tools; 2 | 3 | import java.io.File; 4 | 5 | import org.spiderland.Psh.Params; 6 | 7 | public class InstructionListCleaner { 8 | 9 | /** Cleans the file PushInstructionSet.text from a single line of 10 | * instructions to a list of instructions. 11 | * @param args 12 | */ 13 | public static void main(String[] args) { 14 | try { 15 | File f = new File("tools/PushInstructionSet.txt"); 16 | String line = Params.ReadFileString(f); 17 | 18 | String out = line.replace(' ', '\n'); 19 | System.out.println(out); 20 | 21 | 22 | } catch (Exception e) { 23 | e.printStackTrace(); 24 | } 25 | 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /tools/PushInstructionSet.txt: -------------------------------------------------------------------------------- 1 | boolean.= 2 | boolean.and 3 | boolean.dup 4 | boolean.flush 5 | boolean.fromfloat 6 | boolean.frominteger 7 | boolean.not 8 | boolean.or 9 | boolean.pop 10 | boolean.rand 11 | boolean.rot 12 | boolean.shove 13 | boolean.stackdepth 14 | boolean.swap 15 | boolean.xor 16 | boolean.yank 17 | boolean.yankdup 18 | true 19 | false 20 | 21 | integer.% 22 | integer.* 23 | integer.+ 24 | integer.- 25 | integer./ 26 | integer.< 27 | integer.= 28 | integer.> 29 | integer.abs 30 | integer.dup 31 | integer.flush 32 | integer.fromboolean 33 | integer.fromfloat 34 | integer.ln 35 | integer.log 36 | integer.max 37 | integer.min 38 | integer.neg 39 | integer.pop 40 | integer.pow 41 | integer.rand 42 | integer.rot 43 | integer.shove 44 | integer.stackdepth 45 | integer.swap 46 | integer.yank 47 | integer.yankdup 48 | 49 | float.% 50 | float.* 51 | float.+ 52 | float.- 53 | float./ 54 | float.< 55 | float.= 56 | float.> 57 | float.abs 58 | float.cos 59 | float.dup 60 | float.exp 61 | float.flush 62 | float.fromboolean 63 | float.frominteger 64 | float.ln 65 | float.log 66 | float.max 67 | float.min 68 | float.neg 69 | float.pop 70 | float.pow 71 | float.rand 72 | float.rot 73 | float.shove 74 | float.sin 75 | float.stackdepth 76 | float.swap 77 | float.tan 78 | float.yank 79 | float.yankdup 80 | 81 | exec.= 82 | exec.do*count 83 | exec.do*range 84 | exec.do*times 85 | exec.dup 86 | exec.flush 87 | exec.if 88 | exec.k 89 | exec.noop 90 | exec.pop 91 | exec.rand 92 | exec.rot 93 | exec.s 94 | exec.shove 95 | exec.stackdepth 96 | exec.swap 97 | exec.y 98 | exec.yank 99 | exec.yankdup 100 | 101 | code.= 102 | code.do*count 103 | code.do*range 104 | code.do*times 105 | code.dup 106 | code.flush 107 | code.fromboolean 108 | code.fromfloat 109 | code.frominteger 110 | code.if 111 | code.noop 112 | code.pop 113 | code.quote 114 | code.rand 115 | code.rot 116 | code.shove 117 | code.stackdepth 118 | code.swap 119 | code.yank 120 | code.yankdup 121 | 122 | input.inall 123 | input.inallrev 124 | input.index 125 | input.stackdepth 126 | 127 | name.dup 128 | name.flush 129 | name.pop 130 | name.rot 131 | name.shove 132 | name.stackdepth 133 | name.swap 134 | name.yank 135 | name.yankdup 136 | 137 | frame.pop 138 | frame.push 139 | -------------------------------------------------------------------------------- /tools/PushMissingInstructions.txt: -------------------------------------------------------------------------------- 1 | Instructions to Possibly Add. 2 | ============================================== 3 | These code and exec instructions could be useful for generic fitness prediction 4 | ------------------------------------------------------------------------------- 5 | code.append 6 | code.atom 7 | code.car 8 | code.cdr 9 | code.cons 10 | code.container 11 | code.contains 12 | code.discrepancy 13 | code.do 14 | code.do* 15 | code.extract 16 | code.fromname 17 | code.insert 18 | code.length 19 | code.list 20 | code.member 21 | code.nth 22 | code.nthcdr 23 | code.null 24 | code.position 25 | code.size 26 | code.subst 27 | 28 | 29 | Missing Instructions 30 | ==================== 31 | boolean.define 32 | 33 | code.define 34 | code.definition 35 | code.instructions 36 | 37 | exec.define 38 | 39 | float.define 40 | 41 | integer.define 42 | 43 | name.= 44 | name.quote 45 | name.rand 46 | name.randboundname 47 | 48 | --------------------------------------------------------------------------------