Free cookie consent management tool by TermsFeed Policy Generator

source: addons/HeuristicLab.Problems.BioBoost/HeuristicLab.Problems.BioBoost.Views/3.3/BioBoostProblemDataView.cs @ 16101

Last change on this file since 16101 was 13074, checked in by gkronber, 9 years ago

#2499: added license header and removed unused usings

File size: 11.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using GeoAPI.Geometries;
23using HeuristicLab.BioBoost.Persistence;
24using HeuristicLab.BioBoost.ProblemDescription;
25using HeuristicLab.Core.Views;
26using HeuristicLab.MainForm;
27using HeuristicLab.Persistence.Default.Xml;
28using SharpMap.Data;
29using SharpMap.Data.Providers;
30using SharpMap.Forms;
31using SharpMap.Layers;
32using SharpMap.Rendering.Thematics;
33using SharpMap.Styles;
34using System;
35using System.Collections.Generic;
36using System.Collections.ObjectModel;
37using System.ComponentModel;
38using System.Drawing;
39using System.Drawing.Drawing2D;
40using System.IO;
41using System.Windows.Forms;
42using ColorBlend = SharpMap.Rendering.Thematics.ColorBlend;
43
44namespace HeuristicLab.BioBoost.Views {
45
46  [Content(typeof(BioBoostProblemData), IsDefaultView = true)]
47  public partial class BioBoostProblemDataView : NamedItemView {
48
49    public new BioBoostProblemData Content {
50      get { return (BioBoostProblemData)base.Content; }
51      set { base.Content = value; }
52    }
53
54    private VectorLayer regions;
55    private FilterDialog filterDialog;
56
57    public BioBoostProblemDataView() {
58      InitializeComponent();
59      filterDialog = new FilterDialog();
60    }
61
62    private GeometryFeatureProvider gfp2;
63    private void PrepareMap(object sender, DoWorkEventArgs e) {
64      var gfp = ShapeFileLoader.LoadShapeFile("C:\\Users\\P40031\\SkyDrive\\NUTS3\\NUTS3_regions_2010_WGS84.shp"); // TODO!
65      var ms = new MemoryStream();
66      XmlGenerator.Serialize(gfp, ms);
67      gfp2 = XmlParser.Deserialize<GeometryFeatureProvider>(new MemoryStream(ms.ToArray()));
68    }
69
70    private void ShowMap(object sender, RunWorkerCompletedEventArgs e) {
71      var outline = new Pen(Color.FromArgb(128, Color.White), 0.5f);
72      var small = new VectorStyle { Fill = Brushes.Blue, EnableOutline = true, Outline = outline };
73      var large = new VectorStyle { Fill = Brushes.Red, EnableOutline = true, Outline = outline };
74      regions = new VectorLayer("NUTS3 Regions") {
75        DataSource = gfp2,
76        Theme =
77          new GradientTheme("Shape_Area", 0, 5, small, large) { FillColorBlend = ColorBlend.Rainbow5 },
78      };
79
80      // add labels
81      var l = new LabelLayer("NUTS3 Labels") {
82        DataSource = gfp2,
83        LabelColumn = "NUTS_ID",
84        PriorityColumn = "Shape_Area",
85      };
86
87      // add geometries
88      var geometries = new Collection<IGeometry>();
89      GeoAPI.GeometryServiceProvider.Instance = new NetTopologySuite.NtsGeometryServices();
90      var f = GeoAPI.GeometryServiceProvider.Instance.CreateGeometryFactory(4326);
91      regions.DataSource.Open();
92      var rows = regions.DataSource.GetObjectIDsInView(regions.Envelope);
93      foreach (var row in rows) {
94        var source = regions.DataSource.GetFeature(row).Geometry.Centroid;
95        var ds = new FeatureDataSet();
96        regions.DataSource.ExecuteIntersectionQuery(source.Buffer(0.1), ds);
97        var neighbors = ds.Tables[0].Rows;
98        if (neighbors.Count > 0) {
99          var ls = f.CreateLineString(new[] {
100            source.Coordinate,
101            ((FeatureDataRow) neighbors[rng.Next(neighbors.Count)]).
102                                        Geometry.Centroid.
103                                        Coordinate,
104          });
105          geometries.Add(ls);
106        }
107      }
108      regions.DataSource.Close();
109      var v = new VectorLayer("Vectors") {
110        DataSource = new GeometryProvider(geometries),
111      };
112      v.Style.Line.SetLineCap(LineCap.NoAnchor, LineCap.ArrowAnchor, DashCap.Flat);
113
114      // add layers
115      mapBox.Map.Layers.Add(regions);
116      mapBox.Map.Layers.Add(l);
117      mapBox.Map.Layers.Add(v);
118
119      // configure map
120      mapBox.Map.ZoomToExtents();
121      mapBox.Refresh();
122      mapBox.ActiveTool = MapBox.Tools.Pan;
123      tabControl.SelectedTab = mapPage;
124    }
125
126    private readonly Dictionary<string, VectorStyle> styles = new Dictionary<string, VectorStyle>();
127    private readonly Random rng = new Random();
128    private VectorStyle GetRandomStyle(FeatureDataRow row) {
129      var name = row["NUTS_ID"].ToString();
130      VectorStyle style;
131      if (!styles.TryGetValue(name, out style)) {
132        style = new VectorStyle {
133          Fill = new SolidBrush(Color.FromArgb(rng.Next(256), rng.Next(256), rng.Next(256)))
134        };
135        styles[name] = style;
136      }
137      return style;
138    }
139
140    protected override void DeregisterContentEvents() {
141      base.DeregisterContentEvents();
142      Content.GeometryChanged -= GeometryChanged;
143    }
144
145    protected override void RegisterContentEvents() {
146      base.RegisterContentEvents();
147      Content.GeometryChanged += GeometryChanged;
148    }
149
150
151    #region Event Handlers (Content)
152    private void GeometryChanged(object sender, EventArgs eventArgs) {
153      if (InvokeRequired) {
154        Invoke(new EventHandler<EventArgs>(GeometryChanged), new object[] { sender, eventArgs });
155      } else {
156        UpdateMap();
157      }
158    }
159    #endregion
160
161    protected override void OnContentChanged() {
162      base.OnContentChanged();
163      if (Content == null) {
164        parameterCollectionView.Content = null;
165      } else {
166        parameterCollectionView.Content = Content.Parameters;
167      }
168      UpdateMap();
169    }
170
171    protected override void SetEnabledStateOfControls() {
172      base.SetEnabledStateOfControls();
173      parameterCollectionView.Enabled = Content != null;
174      loadShapeFileButton.Enabled = Content != null;
175      importFeedstockButton.Enabled = Content != null;
176      importDistancesButton.Enabled = Content != null;
177    }
178
179    private void UpdateMap() {
180      mapBox.Map.Layers.Clear();
181      mapBox.ShowProgressUpdate = false;
182      if (Content == null || Content.Geometry == null) return;
183      mapBox.ShowProgressUpdate = true;
184      var outline = new Pen(Color.FromArgb(128, Color.White), 0.5f);
185      var small = new VectorStyle { Fill = Brushes.Blue, EnableOutline = true, Outline = outline };
186      var large = new VectorStyle { Fill = Brushes.Red, EnableOutline = true, Outline = outline };
187      mapBox.Map.Layers.Add(new VectorLayer("Regions", Content.Geometry) {
188        //Theme = new GradientTheme("Shape_Area", 0, 5, small, large) {
189        //FillColorBlend = ColorBlend.Rainbow5,
190        //},
191      });
192      mapBox.Map.ZoomToExtents();
193      mapBox.Refresh();
194      mapBox.ActiveTool = MapBox.Tools.Pan;
195    }
196
197    #region Event Handlers (child controls)
198    private void mapBox_MouseClick(object sender, MouseEventArgs e) {
199      if (e.Button == MouseButtons.Right) {
200        var c = mapBox.Map.ImageToWorld(e.Location);
201        var f = GeoAPI.GeometryServiceProvider.Instance.CreateGeometryFactory(4326);
202        var ds = new FeatureDataSet();
203        regions.ExecuteIntersectionQuery(f.CreatePoint(c), ds);
204        if (ds.Tables[0].Rows.Count > 0) {
205          var text = ds.Tables[0].Rows[0]["NUTS_ID"].ToString();
206          toolTip.SetToolTip(mapBox, text);
207        }
208      }
209    }
210
211    private void importFeedstockButton_Click(object sender, EventArgs e) {
212      openFileDialog.Filter = "Comma Separted Value|*.csv|All Files|*.*";
213      if (openFileDialog.ShowDialog() == DialogResult.OK) {
214        try {
215          Enabled = false;
216          Content.LoadFeedstockPotentials(openFileDialog.FileName);
217        } catch (Exception x) {
218          PluginInfrastructure.ErrorHandling.ShowErrorDialog(this, x);
219        } finally {
220          Enabled = true;
221        }
222      }
223    }
224
225    private void loadShapeFileButton_Click(object sender, EventArgs e) {
226      openFileDialog.Filter = "ESRI Shape Files|*.shp|All Files|*.*";
227      if (openFileDialog.ShowDialog() == DialogResult.OK) {
228        try {
229          Enabled = false;
230          Content.LoadShapeFile(openFileDialog.FileName);
231          tabControl.SelectedTab = mapPage;
232        } catch (Exception x) {
233          PluginInfrastructure.ErrorHandling.ShowErrorDialog(this, x);
234        } finally {
235          Enabled = true;
236        }
237      }
238    }
239
240    private void importDistancesButton_Click(object sender, EventArgs e) {
241      openFileDialog.Filter = "Comma Serparted Value|*.csv|All Files|*.*";
242      if (openFileDialog.ShowDialog() == DialogResult.OK) {
243        try {
244          Enabled = false;
245          Content.LoadDistanceMatrix(openFileDialog.FileName);
246        } catch (Exception x) {
247          PluginInfrastructure.ErrorHandling.ShowErrorDialog(this, x);
248        } finally {
249          Enabled = true;
250        }
251      }
252    }
253
254    private void importNeighborsButton_Click(object sender, EventArgs e) {
255      openFileDialog.Filter = "Comma Separated Value|*.csv|All Files|*.*";
256      if (openFileDialog.ShowDialog() == DialogResult.OK) {
257        try {
258          Enabled = false;
259          Content.LoadNeighbors(openFileDialog.FileName);
260        } catch (Exception x) {
261          PluginInfrastructure.ErrorHandling.ShowErrorDialog(this, x);
262        } finally {
263          Enabled = true;
264        }
265      }
266    }
267
268    private void checkButton_Click(object sender, EventArgs e) {
269      var warnings = Content.CheckGeoData();
270      if (!string.IsNullOrEmpty(warnings))
271        MessageBox.Show(warnings, "Warnings", MessageBoxButtons.OK);
272    }
273
274    private void importConversionsButton_Click(object sender, EventArgs e) {
275      openFileDialog.Filter = "YAML Files|*.yaml|All Files|*.*";
276      if (openFileDialog.ShowDialog() == DialogResult.OK) {
277        try {
278          Enabled = false;
279          Content.LoadDescriptors(openFileDialog.FileName);
280        } catch (Exception x) {
281          PluginInfrastructure.ErrorHandling.ShowErrorDialog(this, x);
282        } finally {
283          Enabled = true;
284        }
285      }
286
287    }
288
289    private void splitRegionFactorsImportButton_Click(object sender, EventArgs e) {
290      openFileDialog.Filter = "CSV Files|*.csv|All Files|*.*";
291      if (openFileDialog.ShowDialog() == DialogResult.OK) {
292        try {
293          Enabled = false;
294          Content.LoadSplitRegionDistanceFactors(openFileDialog.FileName);
295        } catch (Exception x) {
296          PluginInfrastructure.ErrorHandling.ShowErrorDialog(this, x);
297        } finally {
298          Enabled = true;
299        }
300      }
301    }
302
303    private void filterButton_Click(object sender, EventArgs e) {
304      if (filterDialog.ShowDialog() == DialogResult.OK) {
305        if (filterDialog.Keep) {
306          Content.KeepRegions(filterDialog.Regex);
307        } else {
308          Content.RemoveRegions(filterDialog.Regex);
309        }
310      }
311    }
312
313    #endregion
314
315  }
316}
Note: See TracBrowser for help on using the repository browser.