Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.BioBoost/HeuristicLab.Problems.BioBoost.Views/3.3/BioBoostProblemDataView.cs @ 13072

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

#2499: added code from HeuristicLab.BioBoost.Views (from private repository) nothing much has been changed

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