001    /*
002     * SimuCS - Simulator to use with Classifier Systems 
003     * MSc project - Oxford University 
004     * by Benoit Isaac - Summer 2005
005     */
006    
007    package simuLCS;
008    import java.io.BufferedWriter;
009    import java.io.File;
010    import java.io.FileWriter;
011    import java.io.PrintWriter;
012    import java.util.Iterator;
013    import javax.swing.ImageIcon;
014    
015    import simuLCS.graphics.G_ListPanel;
016    
017    /**
018     * Utility class. Save the coordinates of the mouse, contains functions
019     * for writing the performance files (gnuplot, rules, ...) and several small 
020     * functions
021     * @author Benoit
022     * 
023     */
024    public class Utils {
025    
026            /** Coordinates of the Cursor */
027    
028            private int coord_x;
029            private int coord_y;
030    
031            public Utils() {
032            }
033    
034            public void mouseSetX(int x) {
035                    coord_x = x;
036            }
037    
038            public void mouseSetY(int y) {
039                    coord_y = y;
040            }
041    
042            public int mouseGetX() {
043                    return coord_x;
044            }
045    
046            public int mouseGetY() {
047                    return coord_y;
048            }
049    
050            /**
051             * Get the int value represented in binary by a String of Bits
052             * Example : getValueFromBits("1101") =  13
053             * @author Benoit
054             * @return -1 if there is a # symbol, otherwise the int value
055             */
056            public static int getValueFromBits(String s) {
057                    int l = s.length();
058                    int r = 0;
059                    String current;
060                    for (int i = 0; i < l; i++) {
061                            current = s.substring(s.length() - i - 1, s.length() - i);
062                            if (current.equals(String.valueOf(ZCSConfig.dontCare))) {
063                                    return -1;
064                            } else {
065                                    if (current.equals("1"))
066                                            r = r + (int) Math.pow(2, (double) i);
067    
068                            }
069                    }
070                    return r;
071            }
072    
073            /**
074             * Get the string of bits representing an int value
075             * @param val
076             * @param nbBits
077             * @return
078             */
079            public static String getBitsFromValue(int val, int nbBits) {
080                    StringBuffer r = new StringBuffer("");
081                    int currentPow;
082                    int currentVal = val;
083                    for (int i = nbBits - 1; i >= 0; i--) {
084                            currentPow = (int) Math.pow(2, (double) i);
085                            if (currentPow > currentVal) {
086                                    r.append("0");
087                            } else {
088                                    currentVal = currentVal - currentPow;
089                                    r.append("1");
090                            }
091                    }
092                    return r.toString();
093            }
094    
095            /**
096             * Writes the <b>gnuplot</b> command file
097             * @param fileBase
098             * @param en
099             * @param type
100             */
101            public static void writeFileGnuplot(
102                    String fileBase,
103                    Entity[] en,
104                    String type) {
105                    File outFile = new File(Config.FOLDER_DATA + fileBase + ".gp");
106                    PrintWriter pW;
107                    FileWriter fW;
108                    BufferedWriter bW;
109                    try {
110                            fW = new FileWriter(outFile);
111                            bW = new BufferedWriter(fW);
112                            pW = new PrintWriter(bW);
113    
114                            if (type == "ps") {
115                                    pW.println("set terminal postscript");
116                                    pW.println("set output \"" + fileBase + ".ps\"");
117                            }
118                            //                      TODO tex
119    
120                            StringBuffer plot = new StringBuffer("plot ");
121                            int nbAgentsLearning = 0;
122                            for (int i = 0; i < en.length; i++) {
123                                    if (en[i] instanceof AgentClassifierLearning) {
124                                            nbAgentsLearning++;
125                                            if (nbAgentsLearning != 1)
126                                                    plot.append(" , ");
127                                            plot.append(
128                                                    "\""
129                                                            + fileBase
130                                                            + ".dat\" using 1:"
131                                                            + (1 + nbAgentsLearning)
132                                                            + " title 'Agent "
133                                                            + en[i].getName()
134                                                            + "' w lines ");
135                                    }
136    
137                            }
138                            if (nbAgentsLearning > 1) {
139                                    pW.println("set title \"" + nbAgentsLearning + " Agents\"");
140                            } else {
141                                    pW.println("set title \"" + nbAgentsLearning + " Agent\"");
142                            }
143                            pW.println("set xlabel \"Time Steps\"");
144                            pW.println("set yrange [800:2000]");
145                            pW.println("show xlabel");
146                            pW.println("set ylabel \"Average Reward\"");
147                            pW.println("show ylabel");
148    
149                            pW.println(plot);
150                            pW.flush();
151                            bW.flush();
152                            fW.flush();
153                            fW.close();
154                            //                      if (Config.PRINT_MODE > -1)
155                            System.out.println(
156                                    "GNUPLOT file created here:"
157                                            + Config.FOLDER_DATA
158                                            + fileBase
159                                            + ".gp"
160                                            + "\n"
161                                            + "Run 'gnuplot "
162                                            + Config.FOLDER_DATA
163                                            + fileBase
164                                            + ".gp"
165                                            + "' to obtain a Postscript graph");
166                    } catch (Exception e) {
167                            System.out.println("Mistake while creating the Gnuplot file:" + e);
168                    }
169    
170            }
171    
172            /**
173             * Write the set of rules at the end using the LaTeX syntax
174             * to include it in a LaTeX file.
175             * @param a
176             * @return
177             */
178            private static String getLateXTable(AgentClassifierLearning a) {
179                    StringBuffer r = new StringBuffer("");
180                    r.append("\n\n\\begin{table}[ht] \n");
181                    r.append("\\centering \n \\begin{tabular}{|r|ll||r|ll|} \n");
182                    r.append(
183                            "\\hline \n \\multicolumn{6}{|c|}{\\textbf{\\textit{Real} behaviour}} \\\\ \n");
184                    r.append("\\hline \n ");
185                    Iterator i =
186                            a
187                                    .getBehaviour(AgentClassifierLearning.REAL_BEHAVIOUR)
188                                    .getIterator();
189                    Classifier current ;
190                    while (i.hasNext()) {
191                            current = (Classifier) i.next();
192                            r.append("\\multicolumn{6}{|c|}{\\texttt{");
193                            String cond = current.getCondition().replaceAll("#", "\\\\#");
194                            r.append(cond);
195                            r.append("} $\\rightarrow$ ");
196                            r.append("\\texttt{");
197                            r.append(current.getAction());
198                            r.append("}  ");
199                            r.append("["+(current.getName().replaceAll("[0-9]",""))+"]");
200                            r.append("} \\\\ \n");
201                    }
202                    r.append("\\hline \\hline \n");
203                    r.append(
204                            "\\multicolumn{6}{|c|}{\\textbf{\\textit{Expected} behaviour }(rules inside the LCS)} \\\\ \n   ");
205                    r.append("\\hline \n");
206    
207                    Classifier[] cl =
208                            a
209                                    .getBehaviour(
210                                            AgentClassifierLearning.EXPECTED_BEHAVIOUR_TO_SHOW)
211                                    .getClassifiers();
212                    int nbClassifiers = cl.length;
213                    int switchTo = (int) (nbClassifiers / 2);
214    
215                    for (int j = 0; j < switchTo; j++) {
216    
217                            if (j < cl.length) {
218                                    r.append((j + 1) + ":&\\texttt{");
219                                    String cond = cl[j].getCondition().replaceAll("#", "\\\\#");
220                                    r.append(cond);
221                                    r.append("} $\\rightarrow$ ");
222                                    r.append("\\texttt{");
223                                    r.append(cl[j].getAction());
224                                    r.append("} & ");
225                                    if (cl[j] instanceof ZClassifier) {
226                                            r.append(" Str.:");
227                                            r.append((float) ((ZClassifier) cl[j]).getStrength());
228                                    }
229                                    r.append(" & ");
230                            }
231    
232                            if (j + switchTo < cl.length) {
233                                    r.append((j + switchTo + 1) + ":&\\texttt{");
234                                    String cond =
235                                            cl[j + switchTo].getCondition().replaceAll("#", "\\\\#");
236                                    r.append(cond);
237                                    r.append("} $\\rightarrow$ ");
238                                    r.append("\\texttt{");
239                                    r.append(cl[j + switchTo].getAction());
240                                    r.append("} & ");
241                                    if (cl[j + switchTo] instanceof ZClassifier) {
242                                            r.append(" Str.:");
243                                            r.append(
244                                                    (float) ((ZClassifier) cl[j + switchTo]).getStrength());
245                                    }
246                                    r.append(" \\\\ \n");
247                            }
248                    }
249    
250                    r.append("\\hline \n \\end{tabular} ");
251                    r.append(
252                            " \\caption{\\textit{Expected} behaviour learnt for Agent 2 after 30,000 time steps, compared with the \\textit{real} behaviour.} \n");
253                    r.append("\\label{tab:ExpectedBehaviour}\n");
254                    r.append("\\end{table}\n\n");
255    
256                    return r.toString();
257    
258            }
259    
260            /**
261             * Writes a file with the rules remaining in the population for each agent
262             * at the end of the simulation, together with a LaTeX table to include it
263             * in a LaTeX file
264             * @param fileBase
265             * @param en
266             */
267            public static void writeFileWithRules(String fileBase, Entity[] en) {
268                    File outFile = new File(Config.FOLDER_DATA + fileBase + ".rules");
269                    PrintWriter pW;
270                    FileWriter fW;
271                    BufferedWriter bW;
272                    try {
273                            fW = new FileWriter(outFile);
274                            bW = new BufferedWriter(fW);
275                            pW = new PrintWriter(bW);
276    
277                            StringBuffer rules = new StringBuffer("");
278                            int nbAgentsLearning = 0;
279                            for (int i = 0; i < en.length; i++) {
280                                    if (en[i] instanceof AgentClassifierLearning) {
281                                            nbAgentsLearning++;
282                                            rules.append(
283                                                    "----------Agent " + en[i].getName() + "---------- \n");
284                                            rules.append("-Real behaviour:\n");
285                                            rules.append(
286                                                    ((AgentClassifierLearning) en[i]).getBehaviour(
287                                                            AgentClassifierLearning.REAL_BEHAVIOUR));
288                                            rules.append("-Expected behaviour:\n");
289                                            ((AgentClassifierLearning) en[i]).updateBehaviourToShow();
290                                            rules.append(
291                                                    ((AgentClassifierLearning) en[i]).getBehaviour(
292                                                            AgentClassifierLearning
293                                                                    .EXPECTED_BEHAVIOUR_TO_SHOW));
294    
295                                            rules.append(
296                                                    getLateXTable(((AgentClassifierLearning) en[i])));
297                                    }
298    
299                            }
300    
301                            pW.println(rules);
302    
303                            pW.flush();
304                            bW.flush();
305                            fW.flush();
306                            fW.close();
307                            //                      if (Config.PRINT_MODE > -1)
308                            System.out.println(
309                                    "Saved the expected behaviours (rules) here:"
310                                            + Config.FOLDER_DATA
311                                            + fileBase
312                                            + ".rules");
313                    } catch (Exception e) {
314                            System.out.println(
315                                    "Mistake while creating the file for rules:" + e);
316                    }
317    
318            }
319    
320            /** 
321             * Returns an ImageIcon, or null if the path was invalid.
322             */
323            public static ImageIcon createImageIcon(String imageName) {
324                    String imgLocation = "../../images/" + imageName + ".gif";
325                    java.net.URL imageURL = G_ListPanel.class.getResource(imgLocation);
326    
327                    if (imageURL == null) {
328                            System.err.println("Resource not found: " + imgLocation);
329                            return null;
330                    } else {
331                            return new ImageIcon(imageURL);
332                    }
333            }
334    }