source: java/ecj/framsticks/FramsticksUtils.java @ 61

Last change on this file since 61 was 61, checked in by mszubert, 14 years ago

Parsing 2-genotype-evaluation results.
Parameters file updated.

File size: 8.1 KB
Line 
1package framsticks;
2
3import java.io.BufferedReader;
4import java.io.BufferedWriter;
5import java.io.File;
6import java.io.FileNotFoundException;
7import java.io.FileReader;
8import java.io.FileWriter;
9import java.io.IOException;
10import java.io.InputStreamReader;
11
12import cecj.interaction.InteractionResult;
13import cecj.interaction.RealValuedResult;
14import cecj.utils.Pair;
15import ec.EvolutionState;
16import ec.util.Parameter;
17
18public class FramsticksUtils {
19
20        private static final String NEW_CMD = "%s \"getsimplest 1 %s\" -q";
21        private static final String EVAL_CMD = "%s \"ex %s\" \"eval %s %s\" -q";
22        private static final String MUTATE_CMD = "%s rnd mut -q < %s";
23        private static final String XOVER_CMD = "%s rnd \"crossover %s %s\" -q";
24
25        private static final String GENOTYPE_DESC = "org:\ngenotype:~\n%s~\n";
26        private static final String TEMPORARY_FILE_NAME = "temp.gen";
27
28        private static final String P_DIRECTORY_PATH = "directory-path";
29        private static final String P_SCRIPTS_OUTPUT = "scripts-output";
30        private static final String P_SETTINGS = "settings-file";
31        private static final String P_WORKING_DIRECTORY = "working-directory";
32        private static final String P_EXPERIMENT_DEFINITION = "expdef";
33        private static final String P_EXECUTABLE_COMMAND = "executable-cmd";
34        private static final String P_DEBUG = "debug";
35
36        private String directoryPath;
37        private String scriptsOutputPath;
38        private String settingsFile;
39        private String workingDirectory;
40        private String experimentDefinition;
41        private String executableCommand;
42        private boolean debug;
43
44        private static FramsticksUtils instance;
45
46        public synchronized static FramsticksUtils getInstance(final EvolutionState state) {
47                if (instance == null) {
48                        instance = new FramsticksUtils();
49                        instance.setup(state);
50                }
51                return instance;
52        }
53
54        private void setup(final EvolutionState state) {
55                Parameter def = FramsticksDefaults.base();
56                directoryPath = state.parameters.getString(null, def.push(P_DIRECTORY_PATH));
57                if (directoryPath == null) {
58                        state.output.fatal("No Framsticks directory specified", def.push(P_DIRECTORY_PATH));
59                }
60                scriptsOutputPath = state.parameters.getString(null, def.push(P_SCRIPTS_OUTPUT));
61                if (scriptsOutputPath == null) {
62                        state.output.fatal("No scripts output file specified", def.push(P_SCRIPTS_OUTPUT));
63                }
64                settingsFile = state.parameters.getString(null, def.push(P_SETTINGS));
65                if (settingsFile == null) {
66                        state.output.fatal("No settings file specified", def.push(P_SETTINGS));
67                }
68                workingDirectory = state.parameters.getString(null, def.push(P_WORKING_DIRECTORY));
69                if (workingDirectory == null) {
70                        state.output.fatal("No working directory specified", def.push(P_WORKING_DIRECTORY));
71                }
72                experimentDefinition = state.parameters.getString(null, def.push(P_EXPERIMENT_DEFINITION));
73                if (experimentDefinition == null) {
74                        state.output.fatal("No experiment definition specified", def
75                                        .push(P_EXPERIMENT_DEFINITION));
76                }
77                executableCommand = state.parameters.getString(null, def.push(P_EXECUTABLE_COMMAND));
78                if (executableCommand == null) {
79                        state.output.fatal("No executable command specified", def.push(P_EXECUTABLE_COMMAND));
80                }
81
82                debug = state.parameters.getBoolean(null, def.push(P_DEBUG), false);
83        }
84
85        private String executeCommand(String command) {
86                if (debug) {
87                        System.err.println("Executing command : " + command);
88                }
89
90                String result = new String();
91                try {
92                        File f = new File(directoryPath);
93                        Process p = Runtime.getRuntime().exec(
94                                        new String[] { "cmd.exe", "/C", directoryPath + command }, null, f);
95                        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
96                        result = readInput(input);
97                } catch (Exception ex) {
98                        ex.printStackTrace();
99                }
100
101                if (debug) {
102                        System.err.println("Result : " + result);
103                }
104
105                return result;
106        }
107
108        private void saveToFile(String filePath, String contents) {
109                try {
110                        BufferedWriter output = new BufferedWriter(new FileWriter(filePath));
111                        output.write(contents);
112                        output.close();
113                } catch (Exception ex) {
114                        ex.printStackTrace();
115                }
116        }
117
118        private String readFromFile(String filePath) {
119                String result = new String();
120                try {
121                        BufferedReader input = new BufferedReader(new FileReader(filePath));
122                        result = readInput(input);
123                } catch (FileNotFoundException e) {
124                        e.printStackTrace();
125                }
126                return result;
127        }
128
129        private String readInput(BufferedReader input) {
130                StringBuilder result = new StringBuilder();
131
132                try {
133                        String line;
134                        while ((line = input.readLine()) != null) {
135                                result.append(line + '\n');
136                        }
137                        input.close();
138                } catch (IOException ex) {
139                        ex.printStackTrace();
140                }
141
142                // Delete last newline character
143                if (result.length() > 0) {
144                        return result.substring(0, result.length() - 1);
145                } else {
146                        return result.toString();
147                }
148        }
149
150        public float evaluateGenotype(String genotype, String fileName) {
151                String fileContents = String.format(GENOTYPE_DESC, genotype);
152                String filePath = workingDirectory + fileName;
153
154                saveToFile(filePath, fileContents);
155                executeCommand(String.format(EVAL_CMD, executableCommand, experimentDefinition,
156                                settingsFile, filePath));
157                String evaluation = readFromFile(scriptsOutputPath);
158
159                return Float.parseFloat(evaluation.split("\t")[1]);
160        }
161
162        @Deprecated
163        public Pair<? extends InteractionResult> pseudoCoevolutionaryEvaluate(String candidate,
164                        String test, String fileName) {
165                float candidateResult = evaluateGenotype(candidate, fileName);
166                float testResult = evaluateGenotype(test, fileName);
167
168                return new Pair<RealValuedResult>(new RealValuedResult(candidateResult),
169                                new RealValuedResult(testResult));
170        }
171       
172        private static float chasingBest = 2.0f;
173        private static float chasedBest = 2.0f;
174
175        public Pair<? extends InteractionResult> coevolutionaryEvaluate(String candidate, String test,
176                        String fileName) {
177                String fileContents = String.format(GENOTYPE_DESC, candidate) + "\n"
178                                + String.format(GENOTYPE_DESC, test);
179                String filePath = workingDirectory + fileName;
180                saveToFile(filePath, fileContents);
181
182                executeCommand(String.format(EVAL_CMD, executableCommand, experimentDefinition,
183                                settingsFile, filePath));
184                String evaluation = readFromFile(scriptsOutputPath);
185
186                float candidateResult = 0;
187                float testResult      = 0;
188               
189                try {
190                       
191                        String[] str = evaluation.split("\n");
192                        candidateResult = Float.parseFloat(str[0].split("\t")[1]); //chasing
193                        testResult      = Float.parseFloat(str[1].split("\t")[1]); //chased
194                       
195                        chasingBest = ((candidateResult < chasingBest)?(candidateResult):(chasingBest));
196                        chasedBest  = ((chasedBest      < testResult )?(chasedBest     ):(testResult));
197                       
198                        System.out.printf("%7.4f %7.4f --> %7.4f %7.4f\n", candidateResult, chasingBest, testResult, chasedBest);
199                }
200                catch(Exception ex) {
201                       
202                        System.out.println(scriptsOutputPath + " in bad format. There must be 2 lines with results.");
203                }
204
205                return new Pair<RealValuedResult>(new RealValuedResult(candidateResult),
206                                new RealValuedResult(testResult));
207        }
208
209        public String mutateGenotype(String genotype) {
210                String filePath = workingDirectory + TEMPORARY_FILE_NAME;
211                saveToFile(filePath, genotype);
212                return executeCommand(String.format(MUTATE_CMD, executableCommand, filePath));
213        }
214
215        public String crossoverGenotypes(String genotype1, String genotype2) {
216                String filePath1 = workingDirectory + TEMPORARY_FILE_NAME;
217                String filePath2 = workingDirectory + "_" + TEMPORARY_FILE_NAME;
218                saveToFile(filePath1, genotype1);
219                saveToFile(filePath2, genotype2);
220                return executeCommand(String.format(XOVER_CMD, executableCommand, filePath1, filePath2));
221        }
222
223        public String getNewGenotype(int initializationType) {
224                return executeCommand(String.format(NEW_CMD, executableCommand, initializationType));
225        }
226
227        /*
228         * Sample usage :
229         */
230        /*
231         * public static void main(String[] args) { FramsticksUtils utils =
232         * FramsticksUtils.getInstance(); System.out.println(utils.evaluateGenotype("X", "halo1.gen"));
233         * System.out.println(utils.mutateGenotype("X"));
234         * System.out.println(utils.crossoverGenotypes("AX", "MX"));
235         * System.out.println(utils.getNewGenotype()); }
236         */
237}
Note: See TracBrowser for help on using the repository browser.