Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2283 UCT parameter c -> refactoring

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