#region License Information /* HeuristicLab * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL) * * This file is part of HeuristicLab. * * HeuristicLab is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HeuristicLab is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HeuristicLab. If not, see . */ #endregion using HeuristicLab.Analysis; using HeuristicLab.Analysis.QualityAnalysis; using HeuristicLab.Analysis.SelfOrganizingMaps; using HeuristicLab.Common; using HeuristicLab.Core; using HeuristicLab.Data; using HeuristicLab.MainForm; using HeuristicLab.Optimization; using HeuristicLab.OptimizationExpertSystem.Common; using HeuristicLab.Random; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows.Forms; using System.Windows.Forms.DataVisualization.Charting; namespace HeuristicLab.OptimizationExpertSystem { [View("Understanding Solutions")] [Content(typeof(KnowledgeCenter), IsDefaultView = false)] public partial class UnderstandingSolutionsView : KnowledgeCenterViewBase { protected virtual bool SuppressEvents { get; set; } public UnderstandingSolutionsView() { InitializeComponent(); solutionNetworkProjectionComboBox.SelectedIndex = 0; } protected override void OnContentChanged() { base.OnContentChanged(); UpdateSimilarityCalculators(); UpdateNamesComboboxes(); UpdateSolutionVisualization(); } #region Update Controls private void UpdateSimilarityCalculators() { var selected = (ISolutionSimilarityCalculator)(similarityComboBox.SelectedIndex >= 0 ? similarityComboBox.SelectedItem : null); similarityComboBox.Items.Clear(); if (Content == null || Content.Problem == null) return; foreach (var calc in Content.Problem.Operators.OfType()) { similarityComboBox.Items.Add(calc); if (selected != null && calc.ItemName == selected.ItemName) similarityComboBox.SelectedItem = calc; } if (selected == null && similarityComboBox.Items.Count > 0) similarityComboBox.SelectedIndex = 0; } private void UpdateNamesComboboxes() { var selectedSolutionName = solutionNameComboBox.SelectedIndex >= 0 ? (string)solutionNameComboBox.SelectedItem : string.Empty; solutionNameComboBox.Items.Clear(); if (Content == null) return; var solutionNames = Content.Problem.Solutions.Select(x => x.Solution).OfType().SelectMany(x => x.Variables); foreach (var sn in solutionNames.GroupBy(x => x.Name).OrderBy(x => x.Key)) { solutionNameComboBox.Items.Add(sn.Key); // either it was previously selected, or the variable value is defined in the HeuristicLab.Encodings sub-namespace if (sn.Key == selectedSolutionName || (string.IsNullOrEmpty(selectedSolutionName) && sn.All(x => x.Value != null && x.Value.GetType().FullName.StartsWith("HeuristicLab.Encodings.")))) solutionNameComboBox.SelectedItem = sn.Key; } } public void UpdateSolutionVisualization() { if (InvokeRequired) { Invoke((Action)UpdateSolutionVisualization); return; } var qualityName = Content.Problem.Problem.Evaluator.QualityParameter.ActualName; UpdateSolutionQualityAnalysis(qualityName); if (similarityComboBox.SelectedIndex >= 0) { var calculator = (ISolutionSimilarityCalculator)similarityComboBox.SelectedItem; UpdateSolutionDiversityAnalysis(calculator); UpdateSolutionFdcAnalysis(calculator, fdcBetweenBestCheckBox.Checked); UpdateSolutionLengthScaleAnalysis(calculator); UpdateSolutionNetworkAnalysis(calculator, (string)solutionNetworkProjectionComboBox.SelectedItem, linesCheckBox.Checked, contrastTrackBar.Value, minimumTrackBar.Value); } else { solutionsDiversityViewHost.Content = null; solutionsFdcViewHost.Content = null; solutionsLengthScaleViewHost.Content = null; solutionsNetworkChart.Series.First().Points.Clear(); } } private void UpdateSolutionQualityAnalysis(string qualityName) { var dt = solutionsQualityViewHost.Content as DataTable; if (dt == null) { dt = QualityDistributionAnalyzer.PrepareTable(qualityName); dt.VisualProperties.Title = "Quality Distribution"; solutionsQualityViewHost.Content = dt; } QualityDistributionAnalyzer.UpdateTable(dt, GetSolutionScopes().Select(x => GetQuality(x, qualityName) ?? double.NaN).Where(x => !double.IsNaN(x))); } private void UpdateSolutionDiversityAnalysis(ISolutionSimilarityCalculator calculator) { try { solutionsDiversityViewHost.Content = null; var solutionScopes = GetSolutionScopes(); var similarities = new double[solutionScopes.Count, solutionScopes.Count]; for (var i = 0; i < solutionScopes.Count; i++) { for (var j = 0; j < solutionScopes.Count; j++) similarities[i, j] = calculator.CalculateSolutionSimilarity(solutionScopes[i], solutionScopes[j]); } var hm = new HeatMap(similarities, "Solution Similarities", 0.0, 1.0); solutionsDiversityViewHost.Content = hm; } catch { } } private void UpdateSolutionFdcAnalysis(ISolutionSimilarityCalculator calculator, bool distanceToBest) { try { solutionsFdcViewHost.Content = null; fdcSpearmanLabel.Text = "-"; fdcPearsonLabel.Text = "-"; var solutionScopes = GetSolutionScopes(); var points = new List>(); if (distanceToBest) { var maximization = ((IValueParameter)Content.Problem.MaximizationParameter).Value.Value; var bestSolutions = (maximization ? solutionScopes.MaxItems(x => GetQuality(x, calculator.QualityVariableName) ?? double.NegativeInfinity) : solutionScopes.MinItems(x => GetQuality(x, calculator.QualityVariableName) ?? double.PositiveInfinity)).ToList(); foreach (var solScope in solutionScopes.Except(bestSolutions)) { var maxSimilarity = bestSolutions.Max(x => calculator.CalculateSolutionSimilarity(solScope, x)); var qDiff = (GetQuality(solScope, calculator.QualityVariableName) ?? double.NaN) - (GetQuality(bestSolutions[0], calculator.QualityVariableName) ?? double.NaN); points.Add(new Point2D(Math.Abs(qDiff), 1.0 - maxSimilarity)); } } else { for (int i = 0; i < solutionScopes.Count; i++) { for (int j = 0; j < solutionScopes.Count; j++) { if (i == j) continue; var qDiff = (GetQuality(solutionScopes[i], calculator.QualityVariableName) ?? double.NaN) - (GetQuality(solutionScopes[j], calculator.QualityVariableName) ?? double.NaN); if (double.IsNaN(qDiff)) continue; points.Add(new Point2D(Math.Abs(qDiff), 1.0 - calculator.CalculateSolutionSimilarity(solutionScopes[i], solutionScopes[j]))); } } } var xs = points.Select(p => p.X).ToArray(); var ys = points.Select(p => p.Y).ToArray(); var scorr = alglib.spearmancorr2(xs, ys); var pcorr = alglib.pearsoncorr2(xs, ys); pcorr = pcorr * pcorr; fdcSpearmanLabel.Text = scorr.ToString("F2"); fdcPearsonLabel.Text = pcorr.ToString("F2"); var splot = new ScatterPlot("Fitness-Distance", ""); splot.VisualProperties.XAxisTitle = "Absolute Fitness Difference"; splot.VisualProperties.XAxisMinimumAuto = false; splot.VisualProperties.XAxisMinimumFixedValue = 0.0; splot.VisualProperties.YAxisTitle = "Solution Distance"; splot.VisualProperties.YAxisMinimumAuto = false; splot.VisualProperties.YAxisMinimumFixedValue = 0.0; splot.VisualProperties.YAxisMaximumAuto = false; splot.VisualProperties.YAxisMaximumFixedValue = 1.0; var row = new ScatterPlotDataRow("Fdc", "", points); row.VisualProperties.PointSize = 10; row.VisualProperties.RegressionType = ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Linear; splot.Rows.Add(row); solutionsFdcViewHost.Content = splot; } catch { } } private void UpdateSolutionLengthScaleAnalysis(ISolutionSimilarityCalculator calculator) { try { solutionsLengthScaleViewHost.Content = null; var dt = solutionsLengthScaleViewHost.Content as DataTable; if (dt == null) { dt = QualityDistributionAnalyzer.PrepareTable("Length Scale"); solutionsLengthScaleViewHost.Content = dt; } QualityDistributionAnalyzer.UpdateTable(dt, CalculateLengthScale(calculator)); } catch { solutionsLengthScaleViewHost.Content = null; } } private IEnumerable CalculateLengthScale(ISolutionSimilarityCalculator calculator) { var solutionScopes = GetSolutionScopes(); for (var i = 0; i < solutionScopes.Count; i++) { for (var j = 0; j < solutionScopes.Count; j++) { if (i == j) continue; var sim = calculator.CalculateSolutionSimilarity(solutionScopes[i], solutionScopes[j]); if (sim.IsAlmost(0)) continue; var qDiff = (GetQuality(solutionScopes[i], calculator.QualityVariableName) ?? double.NaN) - (GetQuality(solutionScopes[j], calculator.QualityVariableName) ?? double.NaN); if (!double.IsNaN(qDiff)) yield return Math.Abs(qDiff) / sim; } } } private void UpdateSolutionNetworkAnalysis(ISolutionSimilarityCalculator calculator, string projection, bool lines, double contrast, double minimum) { var series = solutionsNetworkChart.Series["SolutionSeries"]; var seedingSeries = solutionsNetworkChart.Series["SeedingSolutionSeries"]; try { solutionsNetworkChart.Annotations.Clear(); series.Points.Clear(); seedingSeries.Points.Clear(); var solutionScopes = GetSolutionScopes(); var dissimilarities = new DoubleMatrix(solutionScopes.Count, solutionScopes.Count); for (var i = 0; i < solutionScopes.Count; i++) { for (var j = 0; j < solutionScopes.Count; j++) { if (i == j) continue; dissimilarities[i, j] = 1.0 - calculator.CalculateSolutionSimilarity(solutionScopes[i], solutionScopes[j]); } } DoubleMatrix coords = null; if (projection == "SOM") coords = RelationalSOM.Map(dissimilarities, new MersenneTwister(42), jittering: true); else coords = MultidimensionalScaling.KruskalShepard(dissimilarities); var dataPoints = new List(); for (var i = 0; i < coords.Rows; i++) { var quality = GetQuality(solutionScopes[i], calculator.QualityVariableName) ?? double.NaN; var dataPoint = new DataPoint() { Name = (i + 1).ToString(), XValue = coords[i, 0], YValues = new[] {coords[i, 1], quality}, Label = (i + 1) + ": " + quality, Tag = solutionScopes[i] }; dataPoints.Add(dataPoint); if (Content.SolutionSeedingPool.Contains(solutionScopes[i]) && Content.SolutionSeedingPool.ItemChecked(solutionScopes[i])) seedingSeries.Points.Add(dataPoint); else series.Points.Add(dataPoint); } if (lines) { for (var i = 0; i < dataPoints.Count - 1; i++) { for (var j = i + 1; j < dataPoints.Count; j++) { if (dissimilarities[i, j].IsAlmost(1.0)) continue; // s-shaped curve for mapping dissimilarities to alpha values var alpha = (int)Math.Round(255.0 / (1.0 + Math.Exp(-contrast * ((1.0 - dissimilarities[i, j]) - (minimum / 100.0))))); var lw = (int)Math.Round((1 - dissimilarities[i, j]) * 3.0 + 1.0); // linewidth of 1 to 4 var an = new LineAnnotation(); an.SetAnchor(dataPoints[i], dataPoints[j]); an.LineColor = Color.FromArgb(alpha, Color.DarkGray); an.LineWidth = lw; solutionsNetworkChart.Annotations.Add(an); } } } } catch { // problems in calculating the similarity series.Points.Clear(); seedingSeries.Points.Clear(); } } #endregion #region Content Event Handlers protected override void OnProblemChanged() { base.OnProblemInstancesChanged(); UpdateSimilarityCalculators(); UpdateNamesComboboxes(); UpdateSolutionVisualization(); } protected override void OnProblemSolutionsChanged() { base.OnProblemSolutionsChanged(); UpdateNamesComboboxes(); UpdateSolutionVisualization(); } protected override void OnSolutionSeedingPoolChanged() { base.OnSolutionSeedingPoolChanged(); UpdateSolutionNetworkAnalysis(similarityComboBox.SelectedItem as ISolutionSimilarityCalculator, (string)solutionNetworkProjectionComboBox.SelectedItem, linesCheckBox.Checked, contrastTrackBar.Value, minimumTrackBar.Value); } #endregion #region Control Event Handlers private void SimilarityComboBoxOnSelectedIndexChanged(object sender, EventArgs e) { if (InvokeRequired) { Invoke((Action)SimilarityComboBoxOnSelectedIndexChanged, sender, e); return; } var calculator = (ISolutionSimilarityCalculator)similarityComboBox.SelectedItem; if (calculator != null) { calculator.SolutionVariableName = (string)solutionNameComboBox.SelectedItem; calculator.QualityVariableName = Content.Problem.Problem.Evaluator.QualityParameter.ActualName; } UpdateSolutionDiversityAnalysis(calculator); UpdateSolutionFdcAnalysis(calculator, fdcBetweenBestCheckBox.Checked); UpdateSolutionLengthScaleAnalysis(calculator); UpdateSolutionNetworkAnalysis(calculator, (string)solutionNetworkProjectionComboBox.SelectedItem, linesCheckBox.Checked, contrastTrackBar.Value, minimumTrackBar.Value); } private void SolutionNameComboBoxOnSelectedIndexChanged(object sender, EventArgs e) { if (InvokeRequired) { Invoke((Action)SolutionNameComboBoxOnSelectedIndexChanged, sender, e); return; } var calculator = (ISolutionSimilarityCalculator)similarityComboBox.SelectedItem; if (calculator != null) { calculator.SolutionVariableName = (string)solutionNameComboBox.SelectedItem; calculator.QualityVariableName = Content.Problem.Problem.Evaluator.QualityParameter.ActualName; } UpdateSolutionDiversityAnalysis(calculator); UpdateSolutionFdcAnalysis(calculator, fdcBetweenBestCheckBox.Checked); UpdateSolutionLengthScaleAnalysis(calculator); UpdateSolutionNetworkAnalysis(calculator, (string)solutionNetworkProjectionComboBox.SelectedItem, linesCheckBox.Checked, contrastTrackBar.Value, minimumTrackBar.Value); } private void FdcBetweenBestCheckBoxOnCheckedChanged(object sender, EventArgs e) { if (InvokeRequired) { Invoke((Action)FdcBetweenBestCheckBoxOnCheckedChanged, sender, e); return; } UpdateSolutionFdcAnalysis((ISolutionSimilarityCalculator)similarityComboBox.SelectedItem, fdcBetweenBestCheckBox.Checked); } private void SolutionNetworkProjectionComboBoxOnSelectedIndexChanged(object sender, EventArgs e) { if (InvokeRequired) { Invoke((Action)SolutionNetworkProjectionComboBoxOnSelectedIndexChanged, sender, e); return; } var calculator = (ISolutionSimilarityCalculator)similarityComboBox.SelectedItem; if (calculator != null) { calculator.SolutionVariableName = (string)solutionNameComboBox.SelectedItem; calculator.QualityVariableName = Content.Problem.Problem.Evaluator.QualityParameter.ActualName; } UpdateSolutionNetworkAnalysis(calculator, (string)solutionNetworkProjectionComboBox.SelectedItem, linesCheckBox.Checked, contrastTrackBar.Value, minimumTrackBar.Value); } private void LinesCheckBoxOnCheckedChanged(object sender, EventArgs e) { if (InvokeRequired) { Invoke((Action)LinesCheckBoxOnCheckedChanged, sender, e); return; } var calculator = (ISolutionSimilarityCalculator)similarityComboBox.SelectedItem; if (calculator != null) { calculator.SolutionVariableName = (string)solutionNameComboBox.SelectedItem; calculator.QualityVariableName = Content.Problem.Problem.Evaluator.QualityParameter.ActualName; } UpdateSolutionNetworkAnalysis(calculator, (string)solutionNetworkProjectionComboBox.SelectedItem, linesCheckBox.Checked, contrastTrackBar.Value, minimumTrackBar.Value); } private void ContrastTrackBarOnScroll(object sender, EventArgs e) { if (InvokeRequired) { Invoke((Action)ContrastTrackBarOnScroll, sender, e); return; } var calculator = (ISolutionSimilarityCalculator)similarityComboBox.SelectedItem; if (calculator != null) { calculator.SolutionVariableName = (string)solutionNameComboBox.SelectedItem; calculator.QualityVariableName = Content.Problem.Problem.Evaluator.QualityParameter.ActualName; } UpdateSolutionNetworkAnalysis(calculator, (string)solutionNetworkProjectionComboBox.SelectedItem, linesCheckBox.Checked, contrastTrackBar.Value, minimumTrackBar.Value); } private void MinimumTrackBarOnScroll(object sender, EventArgs e) { if (InvokeRequired) { Invoke((Action)MinimumTrackBarOnScroll, sender, e); return; } var calculator = (ISolutionSimilarityCalculator)similarityComboBox.SelectedItem; if (calculator != null) { calculator.SolutionVariableName = (string)solutionNameComboBox.SelectedItem; calculator.QualityVariableName = Content.Problem.Problem.Evaluator.QualityParameter.ActualName; } UpdateSolutionNetworkAnalysis(calculator, (string)solutionNetworkProjectionComboBox.SelectedItem, linesCheckBox.Checked, contrastTrackBar.Value, minimumTrackBar.Value); } private void SolutionsNetworkChartOnMouseClick(object sender, MouseEventArgs e) { var result = solutionsNetworkChart.HitTest(e.X, e.Y); if (result.ChartElementType == ChartElementType.DataPoint) { var point = (DataPoint)result.Object; var solutionScope = (IScope)point.Tag; if (!Content.SolutionSeedingPool.Contains(solutionScope)) return; Content.SolutionSeedingPool.SetItemCheckedState(solutionScope, !Content.SolutionSeedingPool.ItemChecked(solutionScope)); } } private void SolutionsNetworkChartOnMouseDoubleClick(object sender, MouseEventArgs e) { var result = solutionsNetworkChart.HitTest(e.X, e.Y); if (result.ChartElementType == ChartElementType.DataPoint) { var point = (DataPoint)result.Object; var solutionScope = (IScope)point.Tag; MainForm.ShowContent(solutionScope, true); } } #endregion #region Helper Classes and Methods private List GetSolutionScopes() { return Content.Problem.Solutions.Select(x => x.Solution).OfType().ToList(); } private double? GetQuality(IScope scope, string qualityName) { IVariable v; if (!scope.Variables.TryGetValue(qualityName, out v)) return null; var dval = v.Value as DoubleValue; if (dval == null) return null; return dval.Value; } #endregion } }