Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2283 better random initialization

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