Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OKBJavaConnector/ECJClient/src/ec/gp/koza/KozaStatistics.java @ 9598

Last change on this file since 9598 was 6152, checked in by bfarka, 14 years ago

added ecj and custom statistics to communicate with the okb services #1441

File size: 16.4 KB
Line 
1/*
2  Copyright 2006 by Sean Luke
3  Licensed under the Academic Free License version 3.0
4  See the file "LICENSE" for more information
5*/
6
7
8package ec.gp.koza;
9import ec.steadystate.*;
10import ec.*;
11import ec.simple.*;
12import ec.gp.*;
13import ec.util.*;
14import java.io.*;
15
16/*
17 * KozaStatistics.java
18 *
19 * Created: Fri Nov  5 16:03:44 1999
20 * By: Sean Luke
21 */
22
23/**
24 * A simple Koza-style statistics generator.  Prints the mean fitness
25 * (raw,adjusted,hits) and best individual of each generation.
26 * At the end, prints the best individual of the run and the number of
27 * individuals processed.
28 *
29 * <p>If gather-full is true, then final timing information, number of nodes
30 * and depths of trees, approximate final memory utilization, etc. are also given.
31 *
32 * <p>Compressed files will be overridden on restart from checkpoint; uncompressed files will be
33 * appended on restart.
34 *
35 * <p>KozaStatistics implements a simple version of steady-state statistics in the
36 * same fashion that SimpleStatistics does: if it quits before a generation boundary,
37 * it will include the best individual discovered, even if the individual was discovered
38 * after the last boundary.  This is done by using individualsEvaluatedStatistics(...)
39 * to update best-individual-of-generation in addition to doing it in
40 * postEvaluationStatistics(...).
41 
42 <p><b>Parameters</b><br>
43 <table>
44 <tr><td valign=top><i>base.</i><tt>gzip</tt><br>
45 <font size=-1>boolean</font></td>
46 <td valign=top>(whether or not to compress the file (.gz suffix added)</td></tr>
47 <tr><td valign=top><i>base.</i><tt>file</tt><br>
48 <font size=-1>String (a filename), or nonexistant (signifies stdout)</font></td>
49 <td valign=top>(the log for statistics)</td></tr>
50 <tr><td valign=top><i>base</i>.<tt>gather-full</tt><br>
51 <font size=-1>bool = <tt>true</tt> or <tt>false</tt> (default)</font></td>
52 <td valign=top>(should we full statistics on individuals (will run slower, though the slowness is due to off-line processing that won't mess up timings)</td></tr>
53 </table>
54 * @author Sean Luke
55 * @deprecated use SimpleStatistics instead
56 */
57
58public class KozaStatistics extends Statistics implements SteadyStateStatisticsForm
59    {
60    public Individual[] getBestSoFar() { return best_of_run; }
61
62    /** log file parameter */
63    public static final String P_STATISTICS_FILE = "file";
64
65    /** The Statistics' log */
66    public int statisticslog;
67
68    /** The best individual we've found so far */
69    public Individual[] best_of_run;
70
71    /** compress? */
72    public static final String P_COMPRESS = "gzip";
73
74    public static final String P_FULL = "gather-full";
75
76    boolean doFull;
77
78    // total number of individuals
79    long numInds;
80
81    // timings
82    long lastTime;
83    long initializationTime;
84    long breedingTime;
85    long evaluationTime;
86    long nodesInitialized;
87    long nodesEvaluated;
88    long nodesBred;
89
90    // memory usage info
91    long lastUsage = 0;
92    long initializationUsage = 0;
93    long breedingUsage = 0;
94    long evaluationUsage = 0;
95
96    public KozaStatistics() { best_of_run = null; statisticslog = 0; /* stdout */ }
97
98    public void setup(final EvolutionState state, final Parameter base)
99        {
100        super.setup(state,base);
101               
102        state.output.warnOnce("KozaStatistics is deprecated and will soon be deleted.  Use SimpleStatistics instead.");
103       
104        File statisticsFile = state.parameters.getFile(
105            base.push(P_STATISTICS_FILE),null);
106
107        if (statisticsFile!=null) try
108                                      {
109                                      statisticslog = state.output.addLog(statisticsFile,
110                                          !state.parameters.getBoolean(base.push(P_COMPRESS),null,false),
111                                          state.parameters.getBoolean(base.push(P_COMPRESS),null,false));
112                                      }
113            catch (IOException i)
114                {
115                state.output.fatal("An IOException occurred while trying to create the log " + statisticsFile + ":\n" + i);
116                }
117           
118        doFull = state.parameters.getBoolean(base.push(P_FULL),null,false);
119        nodesInitialized = nodesEvaluated = nodesBred = 0;
120        breedingTime=evaluationTime=0;
121        }
122
123
124    public void preInitializationStatistics(final EvolutionState state)
125        {
126        super.preInitializationStatistics(state);
127        if (doFull)
128            {
129            Runtime r = Runtime.getRuntime();
130            lastTime = System.currentTimeMillis();
131            lastUsage = r.totalMemory() - r.freeMemory();
132            }
133        }
134
135    public void postInitializationStatistics(final EvolutionState state)
136        {
137        super.postInitializationStatistics(state);
138
139        // set up our best_of_run array -- can't do this in setup, because
140        // we don't know if the number of subpopulations has been determined yet
141        best_of_run = new Individual[state.population.subpops.length];
142
143        // gather timings       
144        if (doFull)
145            {
146            Runtime r = Runtime.getRuntime();
147            long curU =  r.totalMemory() - r.freeMemory();
148            if (curU > lastUsage) initializationUsage = curU - lastUsage;
149            initializationTime = System.currentTimeMillis()-lastTime;
150           
151            // Determine how many nodes we have
152            for(int x=0;x<state.population.subpops.length;x++)
153                {
154                // check to make sure they're the right class
155                if ( !(state.population.subpops[x].species instanceof GPSpecies ))
156                    state.output.fatal("Subpopulation " + x +
157                        " is not of the species form GPSpecies." +
158                        "  Cannot do timing statistics with KozaStatistics.");
159               
160                for(int y=0;y<state.population.subpops[x].individuals.length;y++)
161                    {
162                    GPIndividual i =
163                        (GPIndividual)(state.population.subpops[x].individuals[y]);
164                    for(int z=0;z<i.trees.length;z++)
165                        nodesInitialized += i.trees[z].child.numNodes(GPNode.NODESEARCH_ALL);
166                    }
167                }
168            }
169        }
170
171    public void preBreedingStatistics(final EvolutionState state)
172        {
173        super.preBreedingStatistics(state);
174        if (doFull)
175            {
176            Runtime r = Runtime.getRuntime();
177            lastTime = System.currentTimeMillis();
178            lastUsage = r.totalMemory() - r.freeMemory();
179            }
180        }
181
182    public void postBreedingStatistics(final EvolutionState state)
183        {
184        super.postBreedingStatistics(state);
185        // gather timings
186        if (doFull)
187            {
188            Runtime r = Runtime.getRuntime();
189            long curU =  r.totalMemory() - r.freeMemory();
190            if (curU > lastUsage) breedingUsage += curU - lastUsage;
191            breedingTime += System.currentTimeMillis()-lastTime;
192           
193            // Determine how many nodes we have
194            for(int x=0;x<state.population.subpops.length;x++)
195                {
196                // check to make sure they're the right class
197                if ( !(state.population.subpops[x].species instanceof GPSpecies ))
198                    state.output.fatal("Subpopulation " + x +
199                        " is not of the species form GPSpecies." +
200                        "  Cannot do timing statistics with KozaStatistics.");
201                               
202                for(int y=0;y<state.population.subpops[x].individuals.length;y++)
203                    {
204                    GPIndividual i =
205                        (GPIndividual)(state.population.subpops[x].individuals[y]);
206                    for(int z=0;z<i.trees.length;z++)
207                        nodesBred += i.trees[z].child.numNodes(GPNode.NODESEARCH_ALL);
208                    }
209                }
210            }
211        }
212
213    public void preEvaluationStatistics(final EvolutionState state)
214        {
215        super.preEvaluationStatistics(state);
216        if (doFull)
217            {
218            Runtime r = Runtime.getRuntime();
219            lastTime = System.currentTimeMillis();
220            lastUsage = r.totalMemory() - r.freeMemory();
221            }
222        }
223
224    public void postEvaluationStatistics(final EvolutionState state)
225        {
226        super.postEvaluationStatistics(state);
227       
228        // Gather statistics
229        Runtime r = Runtime.getRuntime();
230        long curU =  r.totalMemory() - r.freeMemory();
231        if (curU > lastUsage) evaluationUsage += curU - lastUsage;
232        if (doFull) evaluationTime += System.currentTimeMillis()-lastTime;
233
234
235        state.output.println("\n\n\nGeneration " + state.generation + "\n================",statisticslog);
236
237        Individual[] best_i = new Individual[state.population.subpops.length];
238        for(int x=0;x<state.population.subpops.length;x++)
239            {
240            state.output.println("\nSubpopulation " + x + "\n----------------",statisticslog);
241
242            // gather timings
243            if (doFull)
244                {
245                long totNodesPerGen = 0;
246                long totDepthPerGen = 0;
247               
248                // check to make sure they're the right class
249                if ( !(state.population.subpops[x].species instanceof GPSpecies ))
250                    state.output.fatal("Subpopulation " + x +
251                        " is not of the species form GPSpecies." +
252                        "  Cannot do timing statistics with KozaStatistics.");
253               
254                long[] numNodes = new long[((GPIndividual)(state.population.subpops[x].species.i_prototype)).trees.length];
255                long[] numDepth = new long[((GPIndividual)(state.population.subpops[x].species.i_prototype)).trees.length];
256
257                for(int y=0;y<state.population.subpops[x].individuals.length;y++)
258                    {
259                    GPIndividual i =
260                        (GPIndividual)(state.population.subpops[x].individuals[y]);
261                    for(int z=0;z<i.trees.length;z++)
262                        {
263                        nodesEvaluated += i.trees[z].child.numNodes(GPNode.NODESEARCH_ALL);
264                        numNodes[z] += i.trees[z].child.numNodes(GPNode.NODESEARCH_ALL);
265                        numDepth[z] += i.trees[z].child.depth();
266                        }
267                    }
268               
269                for(int tr=0;tr<numNodes.length;tr++) totNodesPerGen += numNodes[tr];
270                state.output.println("Avg Nodes: " + ((double)totNodesPerGen)/state.population.subpops[x].individuals.length, statisticslog);
271                state.output.print("Nodes/tree: [", statisticslog);
272                for(int tr=0;tr<numNodes.length;tr++)
273                    {
274                    if (tr>0) state.output.print("|", statisticslog);
275                    state.output.print(""+((double)numNodes[tr])/state.population.subpops[x].individuals.length, statisticslog);
276                    }
277                state.output.println("]", statisticslog);
278
279
280                for(int tr=0;tr<numDepth.length;tr++) totDepthPerGen += numDepth[tr];
281                state.output.println("Avg Depth: " + ((double)totDepthPerGen)/
282                    (state.population.subpops[x].individuals.length * numDepth.length), statisticslog);
283                state.output.print("Depth/tree: [", statisticslog);
284                for(int tr=0;tr<numDepth.length;tr++)
285                    {
286                    if (tr>0) state.output.print("|", statisticslog);
287                    state.output.print(""+((double)numDepth[tr])/state.population.subpops[x].individuals.length, statisticslog);
288                    }
289                state.output.println("]", statisticslog);
290
291                }           
292           
293           
294            float meanStandardized = 0.0f;
295            float meanAdjusted = 0.0f;
296            long hits = 0;
297
298            if (!(state.population.subpops[x].species.f_prototype instanceof KozaFitness))
299                state.output.fatal("Subpopulation " + x +
300                    " is not of the fitness KozaFitness.  Cannot do timing statistics with KozaStatistics.");
301               
302
303            best_i[x] = state.population.subpops[x].individuals[0];
304            for(int y=0;y<state.population.subpops[x].individuals.length;y++)
305                {
306                // best individual
307                if (state.population.subpops[x].individuals[y].fitness.betterThan(best_i[x].fitness))
308                    best_i[x] = state.population.subpops[x].individuals[y];
309                // mean for population
310                meanStandardized += ((KozaFitness)(state.population.subpops[x].individuals[y].fitness)).standardizedFitness();
311                meanAdjusted += ((KozaFitness)(state.population.subpops[x].individuals[y].fitness)).adjustedFitness();
312                hits += ((KozaFitness)(state.population.subpops[x].individuals[y].fitness)).hits;
313                }
314
315            // compute fitness stats
316            meanStandardized /= state.population.subpops[x].individuals.length;
317            meanAdjusted /= state.population.subpops[x].individuals.length;
318            state.output.print("Mean fitness raw: " + meanStandardized + " adjusted: " + meanAdjusted + " hits: " + ((double)hits)/state.population.subpops[x].individuals.length, statisticslog);
319                   
320            state.output.println("", statisticslog);
321
322            // compute inds stats
323            numInds += state.population.subpops[x].individuals.length;
324            }
325
326        // now test to see if it's the new best_of_run
327        for(int x=0;x<state.population.subpops.length;x++)
328            {
329            if (best_of_run[x]==null || best_i[x].fitness.betterThan(best_of_run[x].fitness))
330                best_of_run[x] = (Individual)(best_i[x].clone());
331
332            // print the best-of-generation individual
333            state.output.println("\nBest Individual of Generation:",statisticslog);
334            best_i[x].printIndividualForHumans(state,statisticslog);
335            state.output.message("Subpop " + x + " best fitness of generation: " + best_i[x].fitness.fitnessToStringForHumans());
336            }
337        }
338
339
340    /** Logs the best individual of the run. */
341    public void finalStatistics(final EvolutionState state, final int result)
342        {
343        super.finalStatistics(state,result);
344       
345        state.output.println("\n\n\nFinal Statistics\n================",statisticslog);
346
347        state.output.println("Total Individuals Evaluated: " + numInds,statisticslog);
348        // for now we just print the best fitness
349       
350        state.output.println("\nBest Individual of Run:",statisticslog);
351        for(int x=0;x<state.population.subpops.length;x++)
352            {
353            best_of_run[x].printIndividualForHumans(state,statisticslog);
354            state.output.message("Subpop " + x + " best fitness of run: " + best_of_run[x].fitness.fitnessToStringForHumans());
355
356            // finally describe the winner if there is a description
357            ((SimpleProblemForm)(state.evaluator.p_problem.clone())).describe(state, best_of_run[x], x, 0, statisticslog); 
358            }
359
360        // Output timings
361        if (doFull)
362            {
363            state.output.println("\n\n\nTimings\n=======",statisticslog);
364
365            state.output.println("Initialization: " + ((float)initializationTime)/1000 + " secs total, " + nodesInitialized + " nodes, " + nodesInitialized/(((float)initializationTime)/1000) + " nodes/sec",statisticslog);
366            state.output.println("Evaluating: " + ((float)evaluationTime)/1000 + " secs total, " + nodesEvaluated + " nodes, " + nodesEvaluated/(((float)evaluationTime)/1000) + " nodes/sec",statisticslog);
367            state.output.println("Breeding: " + ((float)breedingTime)/1000 + " secs total, " + nodesBred + " nodes, " + nodesBred/(((float)breedingTime)/1000) + " nodes/sec",statisticslog);
368
369            state.output.println("\n\n\nMemory Usage\n==============",statisticslog);
370            state.output.println("Initialization: " + ((float)initializationUsage)/1024 + " KB total, " + nodesInitialized + " nodes, " + nodesInitialized/(((float)initializationUsage)/1024) + " nodes/KB",statisticslog);
371            state.output.println("Evaluating: " + ((float)evaluationUsage)/1024 + " KB total, " + nodesEvaluated + " nodes, " + nodesEvaluated/(((float)evaluationUsage)/1024) + " nodes/KB",statisticslog);
372            state.output.println("Breeding: " + ((float)breedingUsage)/1024 + " KB total, " + nodesBred + " nodes, " + nodesBred/(((float)breedingUsage)/1024) + " nodes/KB",statisticslog);           
373            }
374       
375        }
376
377    }
Note: See TracBrowser for help on using the repository browser.