Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
07/14/15 20:42:55 (9 years ago)
Author:
aballeit
Message:

#2283 GUI updates, Tree-chart, MCTS Version 2 (prune leaves)

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/HeuristicLab.Problems.GrammaticalOptimization/Evaluation/MainWindow.xaml.cs

    r12503 r12762  
    1 using System;
    2 using System.Collections.Generic;
    3 using System.ComponentModel;
    4 using System.Diagnostics;
    5 using System.Linq;
    6 using System.Text;
    7 using System.Threading.Tasks;
    8 using System.Windows;
    9 using System.Windows.Controls;
    10 using System.Windows.Data;
    11 using System.Windows.Documents;
    12 using System.Windows.Input;
    13 using System.Windows.Media;
    14 using System.Windows.Media.Imaging;
    15 using System.Windows.Navigation;
    16 using System.Windows.Shapes;
    17 using System.Windows.Threading;
     1using System.Collections.ObjectModel;
     2using System.Threading;
     3using System.Xml.Serialization;
    184using Evaluation.ViewModel;
    195using HeuristicLab.Algorithms.Bandits;
     
    2612using Microsoft.Research.DynamicDataDisplay;
    2713using Microsoft.Research.DynamicDataDisplay.DataSources;
     14using System;
     15using System.Collections.Generic;
     16using System.ComponentModel;
     17using System.Diagnostics;
     18using System.IO;
     19using System.Windows;
     20using System.Windows.Controls;
     21using System.Windows.Threading;
     22using Microsoft.Win32;
     23using WpfTestSvgSample;
    2824
    2925namespace Evaluation
     
    3632        private BackgroundWorker worker = new BackgroundWorker();
    3733        private EvaluationViewModel vm;
    38         private List<EvaluationStat> stats = new List<EvaluationStat>();
    39 
    40         private Stack<EvaluationStat> newStats = new Stack<EvaluationStat>();
     34
    4135        private DispatcherTimer updateCollectionTimer;
    4236
     37        private DrawingPage treeDrawingPage;
     38
    4339        public MainWindow()
    4440        {
    4541            InitializeComponent();
     42            CenterWindowOnScreen();
    4643            this.DataContext = vm = new EvaluationViewModel();
     44            vm.MaxLen = 50;
     45            vm.MaxEvaluations = 250000;
     46            vm.NrRuns = 1;
     47            vm.CurrentRunString = "0/1";
     48            vm.Threads = 6;
     49            vm.VerticalAxisString = "SolutionQuality";
     50            vm.HorizontalAxisString = "Iteration";
    4751            this.worker.WorkerSupportsCancellation = true;
    4852            this.worker.DoWork += worker_DoWork;
     
    5458            ////updateCollectionTimer.Tick += updateCollectionTimer_Tick;
    5559            ////updateCollectionTimer.Start();
    56 
    57             vm.HorizontalAxisString = "Evaluations";
    58             vm.VerticalAxisString = "BestKnownQuality";
    59 
     60        }
     61
     62        private void CenterWindowOnScreen()
     63        {
     64            double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
     65            double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
     66            double windowWidth = this.Width;
     67            double windowHeight = this.Height;
     68            this.Left = (screenWidth / 2) - (windowWidth / 2);
     69            this.Top = (screenHeight / 2) - (windowHeight / 2);
    6070        }
    6171
     
    7181        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    7282        {
    73             if (stats.Count > 0)
    74             {
    75                 TimeSpan timeNeeded = stats[stats.Count - 1].Time - stats[0].Time;
    76                 vm.EvaluationsPerSec = Math.Round(vm.Evaluations / timeNeeded.TotalSeconds, 2);
    77             }
    78             var ds = new EnumerableDataSource<EvaluationStat>(stats);
     83            ButtonRun.IsEnabled = true;
     84            TextBoxMaxEvaluations.IsEnabled = true;
     85            TextBoxMaxLen.IsEnabled = true;
     86            TextBoxRuns.IsEnabled = true;
     87            TextBoxThreads.IsEnabled = true;
     88        }
     89
     90        private void DrawCharts(Run run)
     91        {
     92            ClearChart();
     93
     94            var ds = new EnumerableDataSource<EvaluationStat>(run.EvaluationStats);
    7995            ds.SetXMapping(x => x.Iteration);
    8096            ds.SetYMapping(y => y.CurrentBestQuality);
     
    85101            graph.AddToPlotter(ChartPlotter);
    86102
    87             Debug.WriteLine("DONE");
    88             ButtonRun.IsEnabled = true;
    89         }
     103            DrawTreeChart(run);
     104        }
     105
     106        private void DrawTreeChart(Run run)
     107        {
     108            if (!string.IsNullOrEmpty(run.SvgFile))
     109            {
     110                treeDrawingPage.LoadDocument(run.SvgFile);
     111            }
     112        }
     113
     114
    90115        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    91116        {
     
    95120        void worker_DoWork(object sender, DoWorkEventArgs e)
    96121        {
     122
    97123            Type algorithmType = vm.SelectedAlgorithm;
    98124
     
    108134                policyInstance = new UCTPolicy();
    109135            }
    110             else if (policy == typeof (ThresholdAscentPolicy))
     136            else if (policy == typeof(ThresholdAscentPolicy))
    111137            {
    112138                policyInstance = new ThresholdAscentPolicy();
     
    117143            }
    118144
    119             vm.MaxLen = 1000;
    120             vm.MaxEvaluations = 250000;
    121 
    122145            vm.BestKnownQuality = problem.BestKnownQuality(vm.MaxLen);
    123146
    124             vm.Evaluations = 0;
    125             vm.CurrentBestQuality = 0;
    126 
    127             stats.Clear();
    128 
    129             SolverBase solver = null;
    130 
    131             if (algorithmType == typeof(MonteCarloTreeSearch))
    132             {
    133                 solver = new MonteCarloTreeSearch(problem, vm.MaxLen, random, policyInstance, new RandomSimulation(problem, random, vm.MaxLen));
    134             }
    135             else if (algorithmType == typeof(SequentialSearch))
    136             {
    137                 solver = new SequentialSearch(problem, vm.MaxLen, random, 0,
    138                     new HeuristicLab.Algorithms.Bandits.GrammarPolicies.GenericGrammarPolicy(problem, policyInstance));
    139             }
    140             else if (algorithmType == typeof(RandomSearch))
    141             {
    142                 solver = new RandomSearch(problem, random, vm.MaxLen);
    143             }
    144             else if (algorithmType == typeof(StandardGP))
    145             {
    146                 solver = new StandardGP(problem, random);
    147             }
    148             else if (algorithmType == typeof(OffspringSelectionGP))
    149             {
    150                 solver = new OffspringSelectionGP(problem, random);
    151             }
    152 
    153             solver.FoundNewBestSolution += (sentence, quality) => vm.BestSolutionFoundAt = vm.Evaluations;
    154             solver.SolutionEvaluated += (sentence, quality) =>
    155             {
    156                 vm.Evaluations++;
    157                 if (vm.CurrentBestQuality < quality)
    158                 {
    159                     vm.CurrentBestQuality = quality;
    160                 }
    161                 stats.Add(new EvaluationStat(DateTime.Now, vm.Evaluations, quality, vm.CurrentBestQuality));
    162             };
    163 
    164             solver.Run(vm.MaxEvaluations);
     147            for (int i = 0; i < vm.NrRuns; i++)
     148            {
     149                vm.CurrentRunString = string.Format("{0}/{1}", i + 1, vm.NrRuns);
     150                vm.Evaluations = 0;
     151                vm.CurrentBestQuality = 0;
     152
     153                List<EvaluationStat> stats = new List<EvaluationStat>();
     154
     155                ISolver solver = null;
     156
     157                if (algorithmType == typeof(MonteCarloTreeSearch))
     158                {
     159                    solver = new MonteCarloTreeSearch(problem, vm.MaxLen, random, policyInstance, new RandomSimulation(problem, random, vm.MaxLen));
     160                }
     161                else if (algorithmType == typeof(SequentialSearch))
     162                {
     163                    solver = new SequentialSearch(problem, vm.MaxLen, random, 0,
     164                        new HeuristicLab.Algorithms.Bandits.GrammarPolicies.GenericGrammarPolicy(problem, policyInstance));
     165                }
     166                else if (algorithmType == typeof(RandomSearch))
     167                {
     168                    solver = new RandomSearch(problem, random, vm.MaxLen);
     169                }
     170                else if (algorithmType == typeof(StandardGP))
     171                {
     172                    solver = new StandardGP(problem, random);
     173                }
     174                else if (algorithmType == typeof(OffspringSelectionGP))
     175                {
     176                    solver = new OffspringSelectionGP(problem, random);
     177                }
     178
     179                solver.FoundNewBestSolution += (sentence, quality) =>
     180                {
     181                    vm.BestSolutionFoundAt = vm.Evaluations;
     182                    vm.BestSolution = sentence;
     183                };
     184                solver.SolutionEvaluated += (sentence, quality) =>
     185                {
     186                    vm.Evaluations++;
     187                    if (vm.CurrentBestQuality < quality)
     188                    {
     189                        vm.CurrentBestQuality = quality;
     190                    }
     191                    stats.Add(new EvaluationStat(DateTime.Now, vm.Evaluations, quality, vm.CurrentBestQuality));
     192                };
     193
     194                solver.Run(vm.MaxEvaluations);
     195
     196
     197                if (stats.Count > 0)
     198                {
     199                    TimeSpan totalTimeNeeded = stats[stats.Count - 1].Time - stats[0].Time;
     200                    vm.EvaluationsPerSec = Math.Round(vm.Evaluations / totalTimeNeeded.TotalSeconds, 2);
     201
     202                    TimeSpan timeForBestSolution = stats[vm.BestSolutionFoundAt - 1].Time - stats[0].Time;
     203
     204                    Run run = new Run(i, vm.Evaluations, vm.CurrentBestQuality, vm.BestKnownQuality,
     205                        vm.BestSolutionFoundAt, vm.BestSolution, vm.EvaluationsPerSec,
     206                        totalTimeNeeded, timeForBestSolution, stats);
     207
     208
     209                    MonteCarloTreeSearch mctsSolver = null;
     210                    if (algorithmType == typeof(MonteCarloTreeSearch))
     211                    {
     212                        mctsSolver = (MonteCarloTreeSearch)solver;
     213
     214                        run.TreeInfos = mctsSolver.GetTreeInfos();
     215
     216                        byte[] output = mctsSolver.GenerateSvg();
     217                        if (output.Length > 0)
     218                        {
     219                            run.SvgFile = string.Format("MCTS_SVG_#{0}_{1}.svg", i, DateTime.Now.Ticks);
     220                            File.WriteAllBytes(run.SvgFile, mctsSolver.GenerateSvg());
     221                        }
     222                    }
     223
     224                    Dispatcher.BeginInvoke(new Action(() => vm.Runs.Add(run)));
     225                }
     226            }
     227        }
     228
     229        private void ClearChart()
     230        {
     231            ChartPlotter.Children.RemoveAll<LineGraph>();
    165232        }
    166233
    167234        private void ButtonRun_OnClick(object sender, RoutedEventArgs e)
    168235        {
    169             ChartPlotter.Children.RemoveAll<LineGraph>();
     236            ClearChart();
     237            vm.Runs.Clear();
     238            vm.CurrentRun = null;
    170239            ButtonRun.IsEnabled = false;
     240            TextBoxMaxEvaluations.IsEnabled = false;
     241            TextBoxMaxLen.IsEnabled = false;
     242            TextBoxRuns.IsEnabled = false;
     243            TextBoxThreads.IsEnabled = false;
    171244            worker.RunWorkerAsync();
    172245        }
     
    174247        private void ButtonPause_OnClick(object sender, RoutedEventArgs e)
    175248        {
     249            //if (vm.SelectedAlgorithm == typeof(MonteCarloTreeSearch))
     250            //{
     251            //    MonteCarloTreeSearch mcts = (MonteCarloTreeSearch)solver;
     252            //    mcts.PauseContinue();
     253            //    if (mcts.IsPaused)
     254            //    {
     255            //        ButtonPause.Content = "Continue";
     256            //    }
     257            //    else
     258            //    {
     259            //        ButtonPause.Content = "Pause";
     260            //    }
     261            //}
    176262        }
    177263
     
    183269        private void ComboBoxAlgorithms_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    184270        {
    185             if (vm.SelectedAlgorithm == typeof(MonteCarloTreeSearch)
    186                 || vm.SelectedAlgorithm == typeof(SequentialSearch))
     271            if (vm.SelectedAlgorithm == typeof(MonteCarloTreeSearch))
    187272            {
    188273                ComboBoxPolicies.IsEnabled = true;
     274                TabItemTree.IsEnabled = true;
     275            }
     276            else if (vm.SelectedAlgorithm == typeof(SequentialSearch))
     277            {
     278                ComboBoxPolicies.IsEnabled = true;
     279                TabItemTree.IsEnabled = false;
    189280            }
    190281            else
    191282            {
    192283                ComboBoxPolicies.IsEnabled = false;
    193             }
     284                TabItemTree.IsEnabled = false;
     285            }
     286        }
     287
     288        private void Window_Loaded(object sender, RoutedEventArgs e)
     289        {
     290            treeDrawingPage = treeDrawing.Content as DrawingPage;
     291        }
     292
     293        private void ListBoxRuns_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
     294        {
     295            if (ListBoxRuns.SelectedItem != null)
     296            {
     297                vm.CurrentRun = (Run)ListBoxRuns.SelectedItem;
     298                DrawCharts(vm.CurrentRun);
     299            }
     300        }
     301
     302        public void SaveToFile()
     303        {
     304            SaveFileDialog dlg = new SaveFileDialog();
     305            dlg.FileName = "runs"; // Default file name
     306            dlg.DefaultExt = ".xml"; // Default file extension
     307
     308            // Show save file dialog box
     309            Nullable<bool> result = dlg.ShowDialog();
     310
     311            // Process save file dialog box results
     312            if (result == true)
     313            {
     314                // Save document
     315                string filename = dlg.FileName;
     316
     317                XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<Run>));
     318                using (TextWriter writer = new StreamWriter(filename))
     319                {
     320                    serializer.Serialize(writer, vm.Runs);
     321                }
     322            }
     323
     324        }
     325
     326        public void LoadFromFile()
     327        {
     328            OpenFileDialog dlg = new OpenFileDialog();
     329
     330            // Show save file dialog box
     331            Nullable<bool> result = dlg.ShowDialog();
     332
     333            // Process save file dialog box results
     334            if (result == true)
     335            {
     336                // Load document
     337                string filename = dlg.FileName;
     338
     339                XmlSerializer deserializer = new XmlSerializer(typeof(ObservableCollection<Run>));
     340                using (TextReader reader = new StreamReader(filename))
     341                {
     342                    object obj = deserializer.Deserialize(reader);
     343                    vm.Runs = (ObservableCollection<Run>)obj;
     344
     345                }
     346            }
     347        }
     348
     349        private void LoadButton_OnClick(object sender, RoutedEventArgs e)
     350        {
     351           LoadFromFile();
     352        }
     353
     354        private void SaveButton_OnClick(object sender, RoutedEventArgs e)
     355        {
     356            SaveToFile();
     357        }
     358
     359        private void TabControlRunComparison_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
     360        {
     361            ////if (TabControlRunComparison.SelectedItem == TabItemChartRunComparison)
     362            ////{
     363            ////    ComparisonChartPlotter.Children.RemoveAll<LineGraph>();
     364
     365            ////    var ds = new EnumerableDataSource<EvaluationStat>(run.EvaluationStats);
     366            ////    ds.SetXMapping(x => x.Iteration);
     367            ////    ds.SetYMapping(y => y.CurrentBestQuality);
     368
     369            ////    LineGraph graph = new LineGraph(ds);
     370
     371            ////    graph.StrokeThickness = 2;
     372            ////    graph.AddToPlotter(ChartPlotter);
     373
     374            ////}
    194375        }
    195376    }
Note: See TracChangeset for help on using the changeset viewer.