Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization/Evaluation/MainWindow.xaml.cs @ 12840

Last change on this file since 12840 was 12840, checked in by aballeit, 9 years ago

#2283 Final

File size: 17.6 KB
RevLine 
[12762]1using System.Collections.ObjectModel;
[12815]2using System.Security.AccessControl;
[12824]3using System.Text;
[12762]4using System.Threading;
[12832]5using System.Threading.Tasks;
[12824]6using System.Windows.Documents;
[12840]7using System.Windows.Media;
[12762]8using System.Xml.Serialization;
[12503]9using Evaluation.ViewModel;
10using HeuristicLab.Algorithms.Bandits;
11using HeuristicLab.Algorithms.Bandits.BanditPolicies;
12using HeuristicLab.Algorithms.GeneticProgramming;
13using HeuristicLab.Algorithms.GrammaticalOptimization;
14using HeuristicLab.Algorithms.MonteCarloTreeSearch;
15using HeuristicLab.Algorithms.MonteCarloTreeSearch.Simulation;
16using HeuristicLab.Problems.GrammaticalOptimization;
17using Microsoft.Research.DynamicDataDisplay;
18using Microsoft.Research.DynamicDataDisplay.DataSources;
[12762]19using System;
20using System.Collections.Generic;
21using System.ComponentModel;
22using System.Diagnostics;
23using System.IO;
24using System.Windows;
25using System.Windows.Controls;
26using System.Windows.Threading;
27using Microsoft.Win32;
28using WpfTestSvgSample;
[12503]29
30namespace Evaluation
31{
32    /// <summary>
33    /// Interaction logic for MainWindow.xaml
34    /// </summary>
35    public partial class MainWindow : Window
36    {
37        private EvaluationViewModel vm;
38
[12762]39        private DrawingPage treeDrawingPage;
40
[12503]41        public MainWindow()
42        {
43            InitializeComponent();
[12762]44            CenterWindowOnScreen();
[12503]45            this.DataContext = vm = new EvaluationViewModel();
[12840]46            vm.MaxLen = 17;
47            vm.MaxIterations = 300000;
[12829]48            vm.NrRuns = 20;
[12840]49            vm.MaxThreads = 10;
[12762]50        }
[12503]51
[12762]52        private void CenterWindowOnScreen()
53        {
54            double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
55            double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
56            double windowWidth = this.Width;
57            double windowHeight = this.Height;
58            this.Left = (screenWidth / 2) - (windowWidth / 2);
59            this.Top = (screenHeight / 2) - (windowHeight / 2);
[12503]60        }
61
[12815]62        private void DrawQualityChart(Run run)
[12503]63        {
[12781]64            List<FoundSolution> solutions = new List<FoundSolution>(run.FoundSolutions);
[12762]65
[12781]66            if (run.BestSolutionFoundAt < run.Evaluations)
67            {
68                solutions.Add(new FoundSolution(run.EndTime, run.Evaluations, run.BestQuality, run.BestSolution));
69            }
[12762]70
[12781]71            var ds = new EnumerableDataSource<FoundSolution>(solutions);
72
73
[12503]74            ds.SetXMapping(x => x.Iteration);
[12840]75            ds.SetYMapping(y => y.Quality / run.BestKnownQuality);
[12503]76
77            LineGraph graph = new LineGraph(ds);
78
79            graph.StrokeThickness = 2;
[12815]80            graph.AddToPlotter(QualityChartPlotter);
[12503]81        }
[12762]82
[12815]83        private void DrawSelectionChart(Run run)
84        {
[12840]85            // quality line
86            List<FoundSolution> solutions = new List<FoundSolution>(run.FoundSolutions);
[12815]87
[12840]88            if (run.BestSolutionFoundAt < run.Evaluations)
89            {
90                solutions.Add(new FoundSolution(run.EndTime, run.Evaluations, run.BestQuality, run.BestSolution));
91            }
[12815]92
[12840]93            var ds = new EnumerableDataSource<FoundSolution>(solutions);
[12815]94
[12840]95
96            ds.SetXMapping(x => x.Iteration);
97            ds.SetYMapping(y => y.Quality / run.BestKnownQuality);
98
[12815]99            LineGraph graph = new LineGraph(ds);
[12840]100            graph.StrokeThickness = 2;
101            graph.AddToPlotter(SelectionChartPlotter);
[12815]102
[12840]103            // selection indicator line
104            List<SelectionIndicator> selectionIndicators = new List<SelectionIndicator>(run.SelectionIndicators);
105
106            var dssi = new EnumerableDataSource<SelectionIndicator>(selectionIndicators);
107
108            dssi.SetXMapping(x => x.Evaluation);
109            dssi.SetYMapping(y => y.Indicator);
110
111            graph = new LineGraph(dssi);
[12815]112            graph.StrokeThickness = 2;
[12840]113            graph.Stroke = Brushes.Red;
[12815]114            graph.AddToPlotter(SelectionChartPlotter);
115        }
116
[12762]117        private void DrawTreeChart(Run run)
118        {
119            if (!string.IsNullOrEmpty(run.SvgFile))
120            {
121                treeDrawingPage.LoadDocument(run.SvgFile);
122            }
123        }
124
[12781]125        private void DoRun(Object threadContext)
126        {
127            Run run = (Run)threadContext;
128            run.RunState = RunState.Running;
129            run.StartTime = DateTime.Now;
[12762]130
[12815]131            run.Solver.Run(run.MaxIterations);
[12781]132
133            run.EndTime = DateTime.Now;
134            run.RunState = RunState.Analyzing;
135
136            if (run.FoundSolutions.Count > 0)
137            {
138                if (run.Solver is MonteCarloTreeSearch)
139                {
140                    MonteCarloTreeSearch mctsSolver = (MonteCarloTreeSearch)run.Solver;
141
142                    run.TreeInfos = mctsSolver.GetTreeInfos();
143
144                    //byte[] output = mctsSolver.GenerateSvg();
145                    //if (output != null && output.Length > 0)
146                    //{
147                    //    run.SvgFile = string.Format("MCTS_SVG_#{0}_{1}.svg", run.RunNumber, DateTime.Now.Ticks);
148                    //    File.WriteAllBytes(run.SvgFile, mctsSolver.GenerateSvg());
149                    //}
[12832]150                    mctsSolver.FreeAll();
[12781]151                }
152            }
153            run.RunState = RunState.Finished;
154            lock (vm.CompletedRuns)
155            {
156                int completed = 0;
157                foreach (Run r in vm.Runs)
158                {
159                    if (r.RunState == RunState.Finished)
160                    {
161                        completed++;
162                    }
163                }
164                vm.CompletedRuns = string.Format("{0}/{1}", completed, vm.Runs.Count);
165                if (completed == vm.NrRuns)
166                {
167                    Dispatcher.Invoke(AllRunsFinished);
168                }
169            }
170        }
171
172        private void AllRunsFinished()
[12503]173        {
[12781]174            ButtonRun.IsEnabled = true;
[12815]175            TextBoxMaxIterations.IsEnabled = true;
[12781]176            TextBoxMaxLen.IsEnabled = true;
177            TextBoxRuns.IsEnabled = true;
[12833]178            TextBoxMaxThreads.IsEnabled = true;
[12503]179        }
180
[12781]181        private void StartRuns()
[12503]182        {
[12781]183            vm.CompletedRuns = string.Format("0/{0}", vm.NrRuns);
[12762]184
[12503]185            Type algorithmType = vm.SelectedAlgorithm;
186
187            ISymbolicExpressionTreeProblem problem = vm.SelectedProblem;
188
189            Type policy = vm.SelectedPolicy;
190            IBanditPolicy policyInstance = null;
191
192            if (policy == typeof(UCTPolicy))
193            {
194                policyInstance = new UCTPolicy();
195            }
[12762]196            else if (policy == typeof(ThresholdAscentPolicy))
[12503]197            {
198                policyInstance = new ThresholdAscentPolicy();
199            }
[12815]200            else if (policy == typeof(BoltzmannExplorationPolicy))
201            {
202                policyInstance = new BoltzmannExplorationPolicy(2);
203            }
[12840]204            else if (policy == typeof(EpsGreedyPolicy))
[12833]205            {
206                policyInstance = new EpsGreedyPolicy(vm.Epsylon);
207            }
[12503]208            else
209            {
210                policyInstance = (IBanditPolicy)Activator.CreateInstance(policy);
211            }
212
[12762]213            for (int i = 0; i < vm.NrRuns; i++)
214            {
215                ISolver solver = null;
[12830]216
[12828]217                Random random = new Random(Guid.NewGuid().GetHashCode());
[12503]218
[12781]219                if (algorithmType == typeof(MonteCarloTreeSearch_PruneLeaves))
[12762]220                {
[12781]221                    solver = new MonteCarloTreeSearch_PruneLeaves(problem, vm.MaxLen, random, policyInstance, new RandomSimulation(problem, random, vm.MaxLen));
222                }
223                else if (algorithmType == typeof(MonteCarloTreeSearch))
224                {
[12762]225                    solver = new MonteCarloTreeSearch(problem, vm.MaxLen, random, policyInstance, new RandomSimulation(problem, random, vm.MaxLen));
226                }
227                else if (algorithmType == typeof(SequentialSearch))
228                {
229                    solver = new SequentialSearch(problem, vm.MaxLen, random, 0,
230                        new HeuristicLab.Algorithms.Bandits.GrammarPolicies.GenericGrammarPolicy(problem, policyInstance));
231                }
232                else if (algorithmType == typeof(RandomSearch))
233                {
234                    solver = new RandomSearch(problem, random, vm.MaxLen);
235                }
236                else if (algorithmType == typeof(StandardGP))
237                {
238                    solver = new StandardGP(problem, random);
239                }
240                else if (algorithmType == typeof(OffspringSelectionGP))
241                {
242                    solver = new OffspringSelectionGP(problem, random);
243                }
[12503]244
[12815]245                Run run = new Run(problem, policyInstance, solver, i + 1, vm.MaxIterations, vm.MaxLen);
[12762]246
[12781]247                vm.Runs.Add(run);
[12762]248            }
[12832]249            Task.Run(() =>
[12840]250                Parallel.For(0, vm.NrRuns, new ParallelOptions { MaxDegreeOfParallelism = vm.MaxThreads },
[12832]251                    i => DoRun(vm.Runs[i])));
[12762]252        }
[12503]253
[12815]254        private void ClearQualityChart()
[12762]255        {
[12815]256            QualityChartPlotter.Children.RemoveAll<LineGraph>();
[12503]257        }
258
[12781]259        private void ClearComparisonChart()
260        {
261            ComparisonChartPlotter.Children.RemoveAll<LineGraph>();
262        }
263
[12815]264        private void ClearSelectionChart()
265        {
266            SelectionChartPlotter.Children.RemoveAll<LineGraph>();
267        }
268
[12503]269        private void ButtonRun_OnClick(object sender, RoutedEventArgs e)
270        {
[12815]271            ClearQualityChart();
[12781]272            ClearComparisonChart();
[12815]273            ClearSelectionChart();
[12781]274
[12762]275            vm.Runs.Clear();
[12781]276            vm.SelectedRun = null;
[12503]277            ButtonRun.IsEnabled = false;
[12815]278            TextBoxMaxIterations.IsEnabled = false;
[12762]279            TextBoxMaxLen.IsEnabled = false;
280            TextBoxRuns.IsEnabled = false;
[12781]281            StartRuns();
[12503]282        }
283
284        private void ButtonPause_OnClick(object sender, RoutedEventArgs e)
285        {
[12762]286            //if (vm.SelectedAlgorithm == typeof(MonteCarloTreeSearch))
287            //{
288            //    MonteCarloTreeSearch mcts = (MonteCarloTreeSearch)solver;
289            //    mcts.PauseContinue();
290            //    if (mcts.IsPaused)
291            //    {
292            //        ButtonPause.Content = "Continue";
293            //    }
294            //    else
295            //    {
296            //        ButtonPause.Content = "Pause";
297            //    }
298            //}
[12503]299        }
300
301        private void ButtonStop_OnClick(object sender, RoutedEventArgs e)
302        {
[12781]303            //worker.CancelAsync();
[12503]304        }
305
306        private void ComboBoxAlgorithms_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
307        {
[12781]308            if (vm.SelectedAlgorithm == typeof(MonteCarloTreeSearch) || vm.SelectedAlgorithm == typeof(MonteCarloTreeSearch_PruneLeaves))
[12503]309            {
310                ComboBoxPolicies.IsEnabled = true;
[12762]311                TabItemTree.IsEnabled = true;
[12503]312            }
[12762]313            else if (vm.SelectedAlgorithm == typeof(SequentialSearch))
314            {
315                ComboBoxPolicies.IsEnabled = true;
316                TabItemTree.IsEnabled = false;
317            }
[12503]318            else
319            {
320                ComboBoxPolicies.IsEnabled = false;
[12762]321                TabItemTree.IsEnabled = false;
[12503]322            }
323        }
[12762]324
325        private void Window_Loaded(object sender, RoutedEventArgs e)
326        {
327            treeDrawingPage = treeDrawing.Content as DrawingPage;
328        }
329
330        private void ListBoxRuns_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
331        {
[12781]332            if (vm.SelectedRun != null)
333            {
334                vm.SelectedRun.Solver.FoundNewBestSolution -= SelectedRun_FoundNewBestSolution;
335            }
[12762]336            if (ListBoxRuns.SelectedItem != null)
337            {
[12781]338                vm.SelectedRun = (Run)ListBoxRuns.SelectedItem;
339
340                vm.SelectedRun.Solver.FoundNewBestSolution += SelectedRun_FoundNewBestSolution;
341
[12815]342                ClearQualityChart();
343                DrawQualityChart(vm.SelectedRun);
344
345                if (vm.SelectedRun.RunState == RunState.Finished)
346                {
347                    ClearSelectionChart();
348                    DrawSelectionChart(vm.SelectedRun);
349                }
[12781]350                //DrawTreeChart(vm.SelectedRun);
[12762]351            }
[12781]352            else
353            {
354                vm.SelectedRun = null;
355            }
[12762]356        }
357
[12781]358        void SelectedRun_FoundNewBestSolution(string arg1, double arg2)
359        {
360            Dispatcher.BeginInvoke(new Action(() =>
361            {
[12815]362                ClearQualityChart();
363                DrawQualityChart(vm.SelectedRun);
[12781]364            }));
365        }
366
[12762]367        public void SaveToFile()
368        {
369            SaveFileDialog dlg = new SaveFileDialog();
370            dlg.FileName = "runs"; // Default file name
371            dlg.DefaultExt = ".xml"; // Default file extension
372
373            // Show save file dialog box
374            Nullable<bool> result = dlg.ShowDialog();
375
376            // Process save file dialog box results
377            if (result == true)
378            {
379                // Save document
380                string filename = dlg.FileName;
381
382                XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<Run>));
383                using (TextWriter writer = new StreamWriter(filename))
384                {
385                    serializer.Serialize(writer, vm.Runs);
386                }
387            }
388
389        }
390
391        public void LoadFromFile()
392        {
393            OpenFileDialog dlg = new OpenFileDialog();
394
395            // Show save file dialog box
396            Nullable<bool> result = dlg.ShowDialog();
397
398            // Process save file dialog box results
399            if (result == true)
400            {
401                // Load document
402                string filename = dlg.FileName;
403
404                XmlSerializer deserializer = new XmlSerializer(typeof(ObservableCollection<Run>));
405                using (TextReader reader = new StreamReader(filename))
406                {
407                    object obj = deserializer.Deserialize(reader);
408                    vm.Runs = (ObservableCollection<Run>)obj;
409
410                }
411            }
412        }
413
414        private void LoadButton_OnClick(object sender, RoutedEventArgs e)
415        {
[12781]416            LoadFromFile();
[12762]417        }
418
419        private void SaveButton_OnClick(object sender, RoutedEventArgs e)
420        {
421            SaveToFile();
422        }
[12824]423
424        private void MenuItemCopyToClipboard_OnClick(object sender, RoutedEventArgs e)
425        {
426            StringBuilder tableExport = new StringBuilder();
[12827]427            tableExport.Append(
[12824]428                "Run\tMaxIterations\tEvaluations\tBestKnownQuality\tQuality\tQuality %\tFoundAt\tTotalTime\tSolutionTime\tEvaluationsPerSecond\tSolution");
[12830]429            if (ListViewRuns.Items.Count > 0 && ((Run)ListViewRuns.Items[0]).TreeInfos != null)
[12827]430            {
431                tableExport.Append("\tTotalNodes\tUnexpandedNodes\tExpandedNodes\tLeaveNodes\tDeepestLevel");
432            }
433            tableExport.AppendLine();
[12824]434            for (int i = 0; i < ListViewRuns.Items.Count; i++)
435            {
436                Run run = (Run)ListViewRuns.Items[i];
[12827]437                tableExport.Append(string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}", run.RunNumber,
[12824]438                    run.MaxIterations, run.Evaluations, run.BestKnownQuality, run.BestQuality,
439                    run.BestQuality / run.BestKnownQuality, run.BestSolutionFoundAt, run.TotalTime, run.BestSolutionTime,
440                    run.EvaluationsPerSecond, run.BestSolution));
[12827]441
442                if (run.TreeInfos != null)
443                {
444                    tableExport.Append(string.Format("\t{0}\t{1}\t{2}\t{3}\t{4}", run.TreeInfos.TotalNodes,
445                        run.TreeInfos.UnexpandedNodes, run.TreeInfos.ExpandedNodes, run.TreeInfos.LeaveNodes,
446                        run.TreeInfos.DeepestLevel));
447                }
448
449                tableExport.AppendLine();
[12824]450            }
451            Clipboard.SetData(DataFormats.Text, tableExport.ToString());
452        }
[12833]453
454        private void ComboBoxPolicies_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
455        {
[12840]456            if (vm.SelectedPolicy == typeof(EpsGreedyPolicy))
[12833]457            {
458                TextBoxEpsylon.Visibility = Visibility.Visible;
459                TextBlockEpsylon.Visibility = Visibility.Visible;
460            }
461            else
462            {
463                TextBoxEpsylon.Visibility = Visibility.Hidden;
464                TextBlockEpsylon.Visibility = Visibility.Hidden;
465            }
466        }
[12840]467
468        private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
469        {
470            if (ChartSelector.SelectedItem == TabSelectionIndicator)
471            {
472                if (vm.SelectedRun != null)
473                {
474                    if (vm.SelectedRun.RunState == RunState.Finished)
475                    {
476                        ClearSelectionChart();
477                        DrawSelectionChart(vm.SelectedRun);
478                    }
479                }
480            }
481            else if (ChartSelector.SelectedItem == TabQualityChart)
482            {
483                if (vm.SelectedRun != null)
484                {
485                    if (vm.SelectedRun.RunState == RunState.Finished)
486                    {
487                        ClearQualityChart();
488                        DrawQualityChart(vm.SelectedRun);
489                    }
490                }
491            }
492        }
[12503]493    }
494}
Note: See TracBrowser for help on using the repository browser.