Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OKBJavaConnector/ECJClient/src/ec/display/Console.java @ 6152

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

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

File size: 39.8 KB
Line 
1/*
2  Copyright 2006 by Sean Paus
3  Licensed under the Academic Free License version 3.0
4  See the file "LICENSE" for more information
5*/
6
7
8/*
9 * Created on Feb 3, 2005
10 *
11 */
12package ec.display;
13
14import java.awt.*;
15import javax.swing.*;
16import ec.util.*;
17
18import java.awt.BorderLayout;
19import java.awt.FileDialog;
20import java.awt.GraphicsConfiguration;
21import java.awt.HeadlessException;
22import java.io.File;
23import java.io.FileNotFoundException;
24import java.io.IOException;
25import java.io.OptionalDataException;
26import java.util.Iterator;
27import java.util.Vector;
28
29import javax.swing.ImageIcon;
30import javax.swing.JButton;
31import javax.swing.JDialog;
32import javax.swing.JFileChooser;
33import javax.swing.JFrame;
34import javax.swing.JMenuItem;
35import javax.swing.JOptionPane;
36import javax.swing.JSeparator;
37import javax.swing.JTabbedPane;
38import javax.swing.JToolBar;
39import javax.swing.JTree;
40import javax.swing.filechooser.FileFilter;
41
42import ec.EvolutionState;
43import ec.Evolve;
44import ec.util.BadParameterException;
45import ec.util.Checkpoint;
46import ec.util.MersenneTwisterFast;
47import ec.util.Output;
48import ec.util.ParamClassLoadException;
49import ec.util.Parameter;
50import ec.util.ParameterDatabase;
51import ec.util.Version;
52import javax.swing.JPanel;
53import javax.swing.JTextField;
54import javax.swing.BoxLayout;
55/**
56 * @author spaus
57 *
58 */
59public class Console extends JFrame
60    {
61   
62    static final int DEFAULT_HEIGHT = 500;
63    static final int DEFAULT_WIDTH = 975;
64    ParameterDatabase parameters = null;
65    EvolutionState state = null;
66    Thread playThread = null;
67    boolean playing = false;
68    boolean paused = false;
69    Object buttonLock = new Object();
70    Object cleanupLock = new Object();
71    int currentJob;
72    final String[] clArgs;
73   
74    javax.swing.JPanel jContentPane = null;
75    javax.swing.JMenuBar jJMenuBar = null;
76    javax.swing.JMenu fileMenu = null;
77    javax.swing.JMenu helpMenu = null;
78    javax.swing.JMenuItem exitMenuItem = null;
79    javax.swing.JMenuItem aboutMenuItem = null;
80    JTabbedPane jTabbedPane = null;
81    JToolBar jToolBar = null;
82    JButton playButton = null;
83    JButton pauseButton = null;
84    JButton stopButton = null;
85   
86    JButton stepButton = null;
87    JMenuItem loadParametersMenuItem = null;
88    ParametersPanel paramPanel = null;
89    ControlPanel conPanel = null;
90    /**
91     * @throws java.awt.HeadlessException
92     */
93    public Console(String[] clArgs) throws HeadlessException
94        {
95        super();
96        initialize();
97        this.clArgs = clArgs;
98        }
99   
100    /**
101     * @param gc
102     */
103    public Console(GraphicsConfiguration gc, String[] clArgs)
104        {
105        super(gc);
106        initialize();
107        this.clArgs = clArgs;
108        }
109   
110    /**
111     * @param title
112     * @throws java.awt.HeadlessException
113     */
114    public Console(String title, String[] clArgs) throws HeadlessException
115        {
116        super(title);
117        initialize();
118        this.clArgs = clArgs;
119        }
120   
121    /**
122     * @param title
123     * @param gc
124     */
125    public Console(String title, GraphicsConfiguration gc, String[] clArgs)
126        {
127        super(title, gc);
128        initialize();
129        this.clArgs = clArgs;
130        }
131   
132    /**
133     * This method initializes jTabbedPane     
134     * 
135     * @return javax.swing.JTabbedPane 
136     */   
137    JTabbedPane getJTabbedPane()
138        {
139        if (jTabbedPane == null)
140            {
141            jTabbedPane = new JTabbedPane();
142            conPanel = new ControlPanel(this);
143            conPanel.disableControls();
144            jTabbedPane.add("Control",conPanel);
145            paramPanel = new ParametersPanel(this);
146            jTabbedPane.add("Parameters",paramPanel);
147            jTabbedPane.addTab("Statistics", null, getStatisticsPane(), null);
148            jTabbedPane.addTab("Inspection", null, getInspectionPane(), null);
149            }
150        return jTabbedPane;
151        }
152   
153    /**
154     * This method initializes jToolBar
155     * 
156     * @return javax.swing.JToolBar     
157     */   
158    JToolBar getJToolBar()
159        {
160        if (jToolBar == null)
161            {
162            jToolBar = new JToolBar();
163            jToolBar.add(getPlayButton());
164            jToolBar.add(getStepButton());
165            jToolBar.add(getPauseButton());
166            jToolBar.add(getStopButton());
167            }
168        return jToolBar;
169        }
170   
171    /**
172     * This method initializes jButton 
173     * 
174     * @return javax.swing.JButton     
175     */   
176    JButton getPlayButton()
177        {
178        if (playButton == null)
179            {
180            playButton = new JButton();
181            playButton.setIcon(new ImageIcon(getClass().getResource("/ec/display/Play.png")));
182            playButton.setEnabled(false);
183            playButton.setToolTipText("Play");
184            playButton.addActionListener(new java.awt.event.ActionListener()
185                {
186                public void actionPerformed(java.awt.event.ActionEvent e)
187                    {
188                    synchronized(buttonLock)
189                        {
190                        if (!playing || (playing && paused))
191                            {
192                            if (!paused)
193                                {
194                                currentJob = 0;
195                                spawnPlayThread(false);
196                                } else
197                                {
198                                resumePlayThread();
199                                }
200                            playButton.setEnabled(false);
201                            stepButton.setEnabled(false);
202                            pauseButton.setEnabled(true);
203                            stopButton.setEnabled(true);
204                            conPanel.disableControls();
205                            paused = false;
206                            playing = true;
207                            }
208                        }
209                    }
210                });
211            }
212        return playButton;
213        }
214    /**
215     * This method initializes jButton1
216     * 
217     * @return javax.swing.JButton     
218     */   
219    JButton getPauseButton()
220        {
221        if (pauseButton == null)
222            {
223            pauseButton = new JButton();
224            pauseButton.setIcon(new ImageIcon(getClass().getResource("/ec/display/Pause.png")));
225            pauseButton.setEnabled(false);
226            pauseButton.setToolTipText("Pause");
227            pauseButton.addActionListener(new java.awt.event.ActionListener()
228                {
229                public void actionPerformed(java.awt.event.ActionEvent e)
230                    {
231                    synchronized(buttonLock)
232                        {
233                        if (playing && !paused)
234                            {
235                            paused = true;
236                            pausePlayThread();
237                            stepButton.setEnabled(true);
238                            playButton.setEnabled(true);
239                            pauseButton.setEnabled(false);
240                            }
241                        }
242                    }
243                });
244            }
245        return pauseButton;
246        }
247    /**
248     * This method initializes jButton2
249     * 
250     * @return javax.swing.JButton     
251     */   
252    JButton getStopButton()
253        {
254        if (stopButton == null)
255            {
256            stopButton = new JButton();
257            stopButton.setIcon(
258                new ImageIcon(
259                    getClass().getResource("/ec/display/Stop.png")));
260            stopButton.setEnabled(false);
261            stopButton.setToolTipText("Stop");
262            stopButton.addActionListener(new java.awt.event.ActionListener()
263                {
264                public void actionPerformed(java.awt.event.ActionEvent e)
265                    {
266                    synchronized(buttonLock)
267                        {
268                        if (playing)
269                            {
270                            killPlayThread();
271                            stopButton.setEnabled(false);
272                            pauseButton.setEnabled(false);
273                            stepButton.setEnabled(true);
274                            playButton.setEnabled(true);
275                            conPanel.enableControls();
276                            paused = false;
277                            playing = false;
278                            }
279                        }
280                    }
281                });
282            }
283        return stopButton;
284        }
285    /**
286     * This method initializes jButton 
287     * 
288     * @return javax.swing.JButton     
289     */   
290    JButton getStepButton()
291        {
292        if (stepButton == null)
293            {
294            stepButton = new JButton();
295            stepButton.setEnabled(false);
296            stepButton.setIcon(new ImageIcon(getClass().getResource("/ec/display/Step.png")));
297            stepButton.setPressedIcon(new ImageIcon(getClass().getResource("/ec/display/Stepping.png")));
298            stepButton.setToolTipText("Step");
299            stepButton.addActionListener(new java.awt.event.ActionListener()
300                {
301                public void actionPerformed(java.awt.event.ActionEvent e)
302                    {
303                    synchronized(buttonLock)
304                        {
305                        paused = true;
306                        setStep(true);
307                        if (!playing)
308                            {
309                            spawnPlayThread(false);
310                            stopButton.setEnabled(true);
311                            conPanel.disableControls();
312                            playing = true;
313                            }
314                       
315                        synchronized(playThread)
316                            {
317                            playThread.notify();
318                            }
319                        }
320                    }
321                });
322            }
323        return stepButton;
324        }
325    /**
326     * This method initializes jMenuItem       
327     * 
328     * @return javax.swing.JMenuItem   
329     */   
330    JMenuItem getLoadParametersMenuItem()
331        {
332        if (loadParametersMenuItem == null)
333            {
334            final String PARAMFILE_EXT = "params";
335            this.getAboutMenuItem();
336            loadParametersMenuItem = new JMenuItem();
337            loadParametersMenuItem.setText("Load Parameters...");
338            loadParametersMenuItem.addActionListener(new java.awt.event.ActionListener()
339                {
340                public void actionPerformed(java.awt.event.ActionEvent e)
341                    {   
342                    FileDialog fileDialog = new FileDialog(Console.this,"Open...",FileDialog.LOAD);
343                    fileDialog.setDirectory(System.getProperty("user.dir"));
344                    fileDialog.setFile("*."+PARAMFILE_EXT);
345                    fileDialog.setVisible(true);
346                    String fileName = fileDialog.getFile();
347                    while (fileName != null && !fileName.endsWith("."+PARAMFILE_EXT))
348                        {
349                        JOptionPane optPane = new JOptionPane(fileDialog.getFile()+" is not a legal parameters file",JOptionPane.ERROR_MESSAGE);
350                        JDialog optDialog = optPane.createDialog(Console.this,"Error!");
351                        optDialog.setVisible(true);
352                        fileDialog.setFile("*."+PARAMFILE_EXT);
353                        fileDialog.setVisible(true);
354                        fileName = fileDialog.getFile();
355                        }
356                   
357                    if (fileName != null)
358                        {   
359                        File f = new File(fileDialog.getDirectory(), fileName);
360                        Console.this.loadParameters(f);
361                        playButton.setEnabled(true);
362                        stepButton.setEnabled(true);
363                        conPanel.enableControls();
364                        }
365                    }
366                });
367            }
368        return loadParametersMenuItem;
369        }
370   
371    /**
372     * This method initializes jMenuItem       
373     * 
374     * @return javax.swing.JMenuItem   
375     */   
376    JMenuItem getLoadCheckpointMenuItem()
377        {
378        if (loadCheckpointMenuItem == null)
379            {
380            loadCheckpointMenuItem = new JMenuItem();
381            loadCheckpointMenuItem.setText("Load Checkpoint...");
382            loadCheckpointMenuItem.addActionListener(new java.awt.event.ActionListener()
383                {
384                public void actionPerformed(java.awt.event.ActionEvent e)
385                    {   
386                    JFileChooser chooser = new JFileChooser(
387                        System.getProperty("user.dir"));
388                    chooser.setFileFilter(new FileFilter()
389                        {
390                        public boolean accept( File f )
391                           
392                            {
393                            if ( f.isDirectory() )
394                                return true;
395                           
396                            String extension = null;
397                            String filename = f.getName();
398                            int idx = filename.lastIndexOf( '.' );
399                            if ( idx > 0 && idx < filename.length() - 1 )
400                               
401                                {
402                                extension = filename.substring( idx + 1 ).toLowerCase();
403                                }
404                           
405                            if ( extension != null )
406                               
407                                {
408                                if ( extension.equals( "gz" ) )
409                                    return true;
410                                }
411                           
412                            return false;
413                            }
414                       
415                        public String getDescription()
416                           
417                            {
418                            return "Checkpoint Files";
419                            }
420                        });
421                    int option = chooser.showOpenDialog( Console.this );
422                    if ( option == JFileChooser.APPROVE_OPTION )
423                       
424                        {
425                        File f = chooser.getSelectedFile();
426                        Console.this.restoreFromCheckpoint(f);
427                        playButton.setEnabled(true);
428                        stepButton.setEnabled(true);
429                        }
430                    }
431                });
432            }
433        return loadCheckpointMenuItem;
434        }
435   
436    /**
437     * This method initializes jTabbedPane1     
438     * 
439     * @return javax.swing.JTabbedPane 
440     */   
441    JTabbedPane getStatisticsPane()
442        {
443        if (statisticsPane == null)
444            {
445            statisticsPane = new JTabbedPane();
446            }
447        return statisticsPane;
448        }
449    /**
450     * This method initializes jTabbedPane2     
451     * 
452     * @return javax.swing.JTabbedPane 
453     */   
454    JTabbedPane getInspectionPane()
455        {
456        if (inspectionPane == null)
457            {
458            inspectionPane = new JTabbedPane();
459            }
460        return inspectionPane;
461        }
462   
463    /**
464     * This method initializes jPanel       
465     *     
466     * @return javax.swing.JPanel   
467     */   
468    JPanel getStatusPane()
469        {
470        if (statusPane == null)
471            {
472            statusPane = new JPanel();
473            statusPane.setLayout(new BoxLayout(statusPane, BoxLayout.X_AXIS));
474            statusPane.add(getStatusField(), null);
475            }
476        return statusPane;
477        }
478    /**
479     * This method initializes jTextField   
480     *     
481     * @return javax.swing.JTextField       
482     */   
483    JTextField getStatusField()
484        {
485        if (statusField == null)
486            {
487            statusField = new JTextField();
488            statusField.setEditable(false);
489            }
490        return statusField;
491        }
492    public static void main(String[] args)
493        {
494        Console application = new Console(args);
495        application.setVisible(true);
496        }
497   
498    /**
499     * This method initializes this
500     *
501     * @return void
502     */
503    void initialize()
504        {
505        this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
506        this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
507        this.setJMenuBar(getJJMenuBar());
508        this.setContentPane(getJContentPane());
509        this.setJMenuBar(getJJMenuBar());
510        this.setContentPane(getJContentPane());
511        this.setTitle("ECJ Console");
512        }
513    /**
514     * This method initializes jContentPane
515     *
516     * @return javax.swing.JPanel
517     */
518    javax.swing.JPanel getJContentPane()
519        {
520        if(jContentPane == null)
521            {
522            jContentPane = new javax.swing.JPanel();
523            jContentPane.setLayout(new BorderLayout());
524            jContentPane.add(getJTabbedPane(), java.awt.BorderLayout.CENTER);
525            jContentPane.add(getJToolBar(), java.awt.BorderLayout.NORTH);
526            jContentPane.add(getStatusPane(), java.awt.BorderLayout.SOUTH);
527            }
528        return jContentPane;
529        }
530    /**
531     * This method initializes jJMenuBar       
532     * 
533     * @return javax.swing.JMenuBar     
534     */   
535    javax.swing.JMenuBar getJJMenuBar()
536        {
537        if (jJMenuBar == null)
538            {
539            jJMenuBar = new javax.swing.JMenuBar();
540            jJMenuBar.add(getFileMenu());
541            jJMenuBar.add(getHelpMenu());
542            }
543        return jJMenuBar;
544        }
545    /**
546     * This method initializes jMenu   
547     * 
548     * @return javax.swing.JMenu       
549     */   
550    javax.swing.JMenu getFileMenu()
551        {
552        if (fileMenu == null)
553            {
554            fileMenu = new javax.swing.JMenu();
555            fileMenu.setText("File");
556            fileMenu.add(getLoadParametersMenuItem());
557            fileMenu.add(getLoadCheckpointMenuItem());
558            fileMenu.add(new JSeparator());
559            fileMenu.add(getExitMenuItem());
560            }
561        return fileMenu;
562        }
563    /**
564     * This method initializes jMenu   
565     * 
566     * @return javax.swing.JMenu       
567     */   
568    javax.swing.JMenu getHelpMenu()
569        {
570        if (helpMenu == null)
571            {
572            helpMenu = new javax.swing.JMenu();
573            helpMenu.setText("Help");
574            helpMenu.add(getAboutMenuItem());
575            }
576        return helpMenu;
577        }
578    /**
579     * This method initializes jMenuItem       
580     * 
581     * @return javax.swing.JMenuItem   
582     */   
583    javax.swing.JMenuItem getExitMenuItem()
584        {
585        if (exitMenuItem == null)
586            {
587            exitMenuItem = new javax.swing.JMenuItem();
588            exitMenuItem.setText("Exit");
589            exitMenuItem.addActionListener(new java.awt.event.ActionListener()
590                {
591                public void actionPerformed(java.awt.event.ActionEvent e)
592                    {   
593                    System.exit(0);
594                    }
595                });
596            }
597        return exitMenuItem;
598        }
599   
600    JFrame aboutFrame;
601   
602    /**
603     * This method initializes jMenuItem       
604     * 
605     * @return javax.swing.JMenuItem   
606     */   
607    javax.swing.JMenuItem getAboutMenuItem()
608        {
609        if (aboutMenuItem == null)
610            {
611            aboutMenuItem = new javax.swing.JMenuItem();
612            aboutMenuItem.setText("About ECJ");
613            aboutMenuItem.addActionListener(new java.awt.event.ActionListener()
614                {
615                public void actionPerformed(java.awt.event.ActionEvent e)
616                   
617                    {   
618                    if (aboutFrame == null)
619                       
620                        {
621                        // construct the frame
622                        aboutFrame = new JFrame("About ECJ");
623                        JPanel p = new JPanel();  // 1.3.1 only has borders for JComponents, not Boxes
624                        p.setBorder(BorderFactory.createEmptyBorder(25,30,30,30));
625                        Box b = new Box(BoxLayout.Y_AXIS);
626                        p.add(b,BorderLayout.CENTER);
627                        aboutFrame.getContentPane().add(p,BorderLayout.CENTER);
628                        aboutFrame.setResizable(false);
629                        Font small = new Font("Dialog",0,10);
630
631                        // start dumping in text
632                        JLabel j = new JLabel("ECJ");
633                        j.setFont(new Font("Serif",0,36));
634                        b.add(j);
635                               
636                        j = new JLabel("An Evolutionary Computation System");
637                        b.add(j);
638                        j = new JLabel("Version " +Version.version);
639                        b.add(j);
640                        JLabel spacer = new JLabel(" ");
641                        spacer.setFont(new Font("Dialog",0,6));
642                        b.add(spacer);
643
644                        j = new JLabel("By " + Version.author);
645                        b.add(j);
646                       
647                        spacer = new JLabel(" ");
648                        spacer.setFont(new Font("Dialog",0,6));
649                        b.add(spacer);
650                       
651                        j = new JLabel("Contributors:");
652                        b.add(j);
653                        j = new JLabel("     " + Version.contributors);
654                        b.add(j);
655                        j = new JLabel("     " + Version.contributors2);
656                        b.add(j);
657                           
658                        spacer = new JLabel(" ");
659                        spacer.setFont(new Font("Dialog",0,6));
660                        b.add(spacer);
661                       
662                        // can't figure out why I need a second one...
663                        spacer = new JLabel(" ");
664                        spacer.setFont(new Font("Dialog",0,6));
665                        b.add(spacer);
666
667                        j = new JLabel("ECJ's homepage is " + Version.authorURL);
668                        j.setFont(small);
669                        b.add(j);
670
671                        j = new JLabel("For help, send mail to " + Version.authorEmail0 + "@" +
672                            Version.authorEmail1);
673                        j.setFont(small);
674                        b.add(j);
675
676                        j = new JLabel("     " + Version.authorEmail2);
677                        j.setFont(small);
678                        b.add(j);
679
680                        spacer.setFont(new Font("Dialog",0,6));
681                        b.add(spacer);
682
683                        j = new JLabel("Version " + Version.version + " released on " + Version.date + ".");
684                        j.setFont(small);
685                        b.add(j);
686
687                        String javaVersion = System.getProperties().getProperty("java.version");
688                        j = new JLabel("Current Java: " + javaVersion);
689                        j.setFont(small);
690                        b.add(j);
691                       
692                        j = new JLabel("Minimum Java: " + Version.minimumJavaVersion);
693                        j.setFont(small);
694                        b.add(j);
695                                           
696                        aboutFrame.pack();
697                        }
698                       
699                    // if not on screen right now, move to center of screen
700                    if (!aboutFrame.isVisible())
701                       
702                        {
703                        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
704                        d.width -= aboutFrame.getWidth();
705                        d.height -= aboutFrame.getHeight();
706                        d.width /= 2;
707                        d.height /= 2;
708                        if (d.width < 0) d.width = 0;
709                        if (d.height < 0) d.height = 0;
710                        aboutFrame.setLocation(d.width,d.height);
711                        }
712                   
713                    // show it!
714                    aboutFrame.setVisible(true);
715                    }
716                });
717            }
718        return aboutMenuItem;
719        }
720    /**
721     * @param f
722     */
723    void loadParameters(File f)
724        {
725        try
726            {
727            parameters = new ParameterDatabase(f,clArgs);
728            }
729        catch (FileNotFoundException ex)
730            {
731            Output.initialError(
732                "A File Not Found Exception was generated upon " +
733                "reading the parameter file \"" + f.getPath() +
734                "\".\nHere it is:\n" + ex);
735            }
736        catch (IOException ex)
737            {
738            Output.initialError(
739                "An IO Exception was generated upon reading the " +
740                "parameter file \"" + f.getPath() +
741                "\".\nHere it is:\n" + ex);
742            }
743       
744        if (parameters == null)
745            {
746            Output.initialError("No parameter file was loaded");
747            } else
748            {
749            paramPanel.loadParameters();
750            conPanel.loadParameters();
751            }
752        }
753   
754    void restoreFromCheckpoint(File checkpoint)
755        {
756        try
757            {
758            state=Checkpoint.restoreFromCheckpoint(checkpoint.getCanonicalPath());
759            parameters = state.parameters;
760            paramPanel.loadParameters();
761            conPanel.loadParameters();
762            paused = true;
763            setStep(false);
764            spawnPlayThread(true);
765            stopButton.setEnabled(true);
766            }
767        catch(OptionalDataException e)
768            {
769            Output.initialError(
770                "A ClassNotFoundException was generated upon" +
771                "starting up from a checkpoint." +
772                "\nHere it is:\n" + e);
773            }
774        catch(ClassNotFoundException e)
775            {
776            Output.initialError(
777                "A ClassNotFoundException was generated upon" +
778                "starting up from a checkpoint." +
779                "\nHere it is:\n" + e);
780            }
781        catch (IOException e)
782            {
783            Output.initialError(
784                "An IO Exception was generated upon" +
785                "starting up, probably in setting up a log" +
786                "\nHere it is:\n" + e);
787            }
788        }
789   
790    boolean threadIsToStop;
791   
792    void tellThreadToStop()
793        {
794        threadIsToStop = true;
795        }
796   
797    void setStep(boolean step)
798        {
799        _step = step;
800        }
801   
802    boolean isThreadToStop()
803        {
804        return threadIsToStop;
805        }
806   
807    boolean _step = false;
808   
809    boolean getStep()
810        {
811        return _step;
812        }
813   
814    void setPaused(boolean paused)
815        {
816        this.paused = paused;
817        }
818   
819    boolean isPaused()
820        {
821        return paused;
822        }
823   
824    void spawnPlayThread(final boolean rfc)
825        {
826        threadIsToStop = false;
827       
828        Runnable run = new Runnable()
829            {
830            Vector listeners = new Vector();
831            boolean restoreFromCheckpoint = rfc;
832           
833            void addListener(EvolutionStateListener l)
834                {
835                listeners.add(l);
836                }
837           
838
839           
840            void firePostEvolutionStep()
841                {
842                EvolutionStateEvent evt = new EvolutionStateEvent(this);
843                Iterator it = listeners.iterator();
844                while (it.hasNext())
845                    {
846                    EvolutionStateListener l = (EvolutionStateListener)it.next();
847                    l.postEvolution(evt);
848                    }
849                }
850           
851            void restoreFromCheckpoint()
852                {
853                state.startFromCheckpoint();
854                statisticsPane.removeAll();
855                setupChartPanes();
856                setupInspectionPanes();
857                }
858           
859            /**
860             * @throws BadParameterException
861             * @throws ParamClassLoadException
862             */
863            void initializeEvolutionState()
864                throws BadParameterException, ParamClassLoadException
865                {
866                listeners.removeAllElements();
867                Output output = initializeOutput();
868               
869                // 2. set up thread values
870                /*
871                  int breedthreads = parameters.getInt(
872                  new Parameter(Evolve.P_BREEDTHREADS),null,1);
873                  if (breedthreads < 1)
874                  Output.initialError("Number of breeding threads should be an integer >0.",
875                  new Parameter(Evolve.P_BREEDTHREADS));
876               
877                  int evalthreads = parameters.getInt(
878                  new Parameter(Evolve.P_EVALTHREADS),null,1);
879                  if (evalthreads < 1)
880                  Output.initialError("Number of eval threads should be an integer >0.",
881                  new Parameter(Evolve.P_EVALTHREADS));
882                */
883               
884                int breedthreads = Evolve.determineThreads(output, parameters, new Parameter(Evolve.P_BREEDTHREADS));
885                int evalthreads = Evolve.determineThreads(output, parameters, new Parameter(Evolve.P_EVALTHREADS));
886                boolean auto = (Evolve.V_THREADS_AUTO.equalsIgnoreCase(parameters.getString(new Parameter(Evolve.P_BREEDTHREADS),null)) ||
887                    Evolve.V_THREADS_AUTO.equalsIgnoreCase(parameters.getString(new Parameter(Evolve.P_EVALTHREADS),null)));  // at least one thread is automatic.  Seeds may need to be dynamic.
888
889                // 3. create the Mersenne Twister random number generators,
890                // one per thread
891                MersenneTwisterFast[] random = new MersenneTwisterFast[breedthreads > evalthreads ?
892                    breedthreads : evalthreads];
893                int[] seeds = new int[breedthreads > evalthreads ?
894                    breedthreads : evalthreads];
895               
896                String seed_message = "Seed: ";
897                for (int x=0;x<random.length;x++)
898                   
899                    {
900                    seeds[x] = conPanel.getSeed(currentJob,x);
901                    seed_message = seed_message + seeds[x] + " ";
902                    }
903               
904                for (int x=0;x<random.length;x++)
905                   
906                    {
907                    for (int y=x+1;y<random.length;y++)
908                        if (seeds[x]==seeds[y])
909                           
910                            {
911                            Output.initialError(Evolve.P_SEED+"."+x+" ("+seeds[x]+") and "+Evolve.P_SEED+"."+y+" ("+seeds[y]+") ought not be the same seed.");
912                            }
913                    random[x] = Evolve.primeGenerator(new MersenneTwisterFast(seeds[x]));   // we prime the generator to be more sure of randomness.
914                    }
915               
916                state = (EvolutionState)parameters.getInstanceForParameter(
917                    new Parameter(Evolve.P_STATE),null,EvolutionState.class);
918               
919                state.parameters = parameters;
920                state.random = random;
921                state.output = output;
922                String jobFilePrefix = Console.this.conPanel.getJobFilePrefix();
923                if (Console.this.conPanel.getNumJobs() > 1)
924                    {
925                    if (jobFilePrefix == null || jobFilePrefix.length()<1)
926                        {
927                        jobFilePrefix = "job";
928                        }
929                    jobFilePrefix = jobFilePrefix+"."+Console.this.currentJob+".";
930                    state.output.setFilePrefix(jobFilePrefix);
931                    }
932               
933                state.evalthreads = evalthreads;
934                state.breedthreads = breedthreads;
935               
936                output.systemMessage("Threads:  breed/" + breedthreads + " eval/" + evalthreads);
937                output.systemMessage(seed_message);
938               
939                state.startFresh();
940
941                if (Console.this.conPanel.getNumJobs() > 0)
942                    {
943                    state.checkpointPrefix = jobFilePrefix+state.checkpointPrefix;
944                    }
945
946                if (currentJob == 0)
947                    {
948                    statisticsPane.removeAll();
949                    }
950               
951                setupChartPanes();
952                setupInspectionPanes();
953                }
954           
955            /**
956             * @throws NumberFormatException
957             * @throws BadParameterException
958             */
959            void setupInspectionPanes()
960                throws NumberFormatException, BadParameterException
961                {
962                inspectionPane.removeAll();
963                // Setup the Evolution State inspection pane
964                JScrollPane stateInspectionPane = new JScrollPane();
965                JTree stateInspectionTree = new JTree(
966                    new ReflectedObject(Console.this.state));
967                stateInspectionPane.setViewportView(stateInspectionTree);
968                inspectionPane.add("Evolution State", stateInspectionPane);
969               
970                // Setup the subpopulation inspection panes
971                Parameter p_subPops = new Parameter("pop.subpops");
972                int numSubPops = parameters.getInt(p_subPops,null);
973                for (int subPop = 0; subPop < numSubPops; ++subPop)
974                    {
975                    SubpopulationPanel subPopPane = new SubpopulationPanel(Console.this, subPop);
976                    subPopPane.setup(Console.this.state,p_subPops.push(""+subPop));
977                    inspectionPane.add("SubPop "+subPop, subPopPane);
978                    addListener(subPopPane);
979                    }
980                }
981
982            /**
983             * @throws BadParameterException
984             */
985            void setupChartPanes()
986                throws BadParameterException
987                {
988                // Set up statistics charts (if any)
989                StatisticsChartPane statPane = new StatisticsChartPane();
990                statPane.setup(state, new Parameter("stat"));
991                if (statPane.numCharts > 0)
992                    statisticsPane.addTab("Job "+currentJob, statPane);
993                }
994
995            public void run()
996                {
997               
998                try
999                    {
1000                    while (currentJob < conPanel.getNumJobs())
1001                        {
1002                        if (!restoreFromCheckpoint)
1003                            initializeEvolutionState();
1004                        else
1005                            restoreFromCheckpoint();
1006                        state.output.message("\nJob "+currentJob);
1007                       
1008                        result = EvolutionState.R_NOTDONE;
1009                        while (result == EvolutionState.R_NOTDONE &&
1010                            !Thread.currentThread().isInterrupted() &&
1011                            !isThreadToStop())
1012                            {
1013                           
1014                            try
1015                                {
1016                                synchronized (playThread)
1017                                    {
1018                                    while (isPaused() && ! getStep())
1019                                        {
1020                                        playThread.wait();
1021                                        }
1022                                    }
1023                                }
1024                            catch (InterruptedException e)
1025                                {
1026                                // This can happen if the play thread is stopped
1027                                // while paused
1028                                }
1029                           
1030                            if (!Thread.currentThread().isInterrupted() &&
1031                                !isThreadToStop())
1032                                {
1033                                result = state.evolve();
1034                                firePostEvolutionStep();
1035                                Console.this.getStatusField().setText("Job: "+currentJob+" Generation: "+state.generation);
1036                                setStep(false);
1037                                }
1038                            }
1039                       
1040                        /*
1041                         * If the play thread has been interrupted before the experiment
1042                         * has completed, consider the experiment a failure.
1043                         */
1044                        if (result == EvolutionState.R_NOTDONE)
1045                            result = EvolutionState.R_FAILURE;
1046                       
1047                        if (state != null && result != EvolutionState.R_NOTDONE)
1048                            {
1049                            state.finish(result);
1050                            }
1051                       
1052                        currentJob++;
1053                        }
1054                    }
1055                catch (Exception e)
1056                    {
1057                    System.err.println("Exception when running job:\n\t");
1058                    e.printStackTrace();
1059                    }
1060               
1061                conPanel.enableControls();
1062                finishAndCleanup();
1063                }
1064            };
1065       
1066        playThread = new Thread(run);
1067        playThread.start();
1068        }
1069   
1070    /**
1071     * @return
1072     * @throws BadParameterException
1073     */
1074    Output initializeOutput()
1075        throws BadParameterException
1076        {
1077        // 1. create the output
1078        //boolean store = parameters.getBoolean(new Parameter(Evolve.P_STORE),null,false);
1079       
1080        Output output = new Output(true);
1081        //output.setFlush(
1082        //    parameters.getBoolean(new Parameter(Evolve.P_FLUSH),null,false));
1083       
1084       
1085        // stdout is always log #0.  stderr is always log #1.
1086        // stderr accepts announcements, and both are fully verbose
1087        // by default.
1088        output.addLog(ec.util.Log.D_STDOUT,false);
1089        output.addLog(ec.util.Log.D_STDERR,true);
1090        output.systemMessage(Version.message());
1091        return output;
1092        }
1093   
1094    /**
1095     * Pauses the background play thread.
1096     *
1097     */
1098    void pausePlayThread()
1099        {
1100        setPaused(true);
1101        }
1102   
1103    void resumePlayThread()
1104        {
1105        synchronized (playThread)
1106            {
1107            setPaused(false);
1108            playThread.notify();
1109            }
1110        }
1111   
1112    /**
1113     *
1114     */
1115    void killPlayThread()
1116        {
1117        tellThreadToStop();
1118       
1119        try
1120            {
1121            if (playThread != null)
1122                {
1123                while (playThread.isAlive())
1124                    {
1125                    try
1126                        {
1127                        playThread.interrupt();
1128                        }
1129                    // Ignore security exceptions resulting from
1130                    // attempting to interrupt a thread.
1131                    // TODO Explain this better.
1132                    catch (SecurityException ex) { }
1133                    playThread.join(50);
1134                    }
1135               
1136                playThread = null;
1137                }
1138            }
1139        catch (InterruptedException ex)
1140            {
1141            System.out.println("Interrupted while killing the play thread.  Shouldn't happen.");
1142            }
1143        }
1144   
1145    /**
1146     *
1147     */
1148    void finishAndCleanup()
1149        {
1150        synchronized(cleanupLock)
1151            {
1152            stopButton.setEnabled(false);
1153            pauseButton.setEnabled(false);
1154            stepButton.setEnabled(true);
1155            playButton.setEnabled(true);
1156            paused = false;
1157            playing = false;
1158            _step = false;
1159            currentJob = 0;
1160            }
1161        }
1162   
1163    int result;
1164    JMenuItem loadCheckpointMenuItem = null;
1165    JTabbedPane statisticsPane = null;
1166    JTabbedPane inspectionPane = null;
1167    JPanel statusPane = null;
1168    JTextField statusField = null;
1169    }  //  @jve:decl-index=0:visual-constraint="21,10"
Note: See TracBrowser for help on using the repository browser.