Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 14071 was 13533, checked in by aballeit, 8 years ago

#2283 quality diagram fix

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