напиши код на c# wpf для построения contour maps на вход файл .dat в котором только…
- User
напиши код на c# wpf для построения contour maps на вход файл .dat в котором только значения z
- Assistant
напиши код на c# wpf для построения contour maps на вход файл .dat в котором только значения z
Creating a contour map in a WPF application involves several steps:
.dat file containing Z values.Below is a comprehensive example demonstrating how to achieve this in C# using WPF. This example includes:
Canvas to display the contour map and a Button to load the .dat file.Create a new WPF Application and replace the MainWindow.xaml content with the following:
<Window x:Class="ContourMapApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ContourMapApp"
Title="Contour Map" Height="800" Width="1000">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button Content="Load .dat File" Margin="10" Padding="5" Click="LoadDatFile_Click"/>
<ScrollViewer Grid.Row="1">
<Canvas Name="ContourCanvas" Background="White"/>
</ScrollViewer>
</Grid>
</Window>
Explanation:
Grid with two rows: one for the button and the other for the Canvas.Button to trigger loading of the .dat file.ScrollViewer containing a Canvas named ContourCanvas where contour lines will be drawn.Replace the MainWindow.xaml.cs content with the following code:
Explanation:
Loading the .dat File:
LoadDatFile method reads the .dat file, assuming it's a text file with rows of Z values separated by spaces, commas, or tabs.zValues while ensuring consistency in the number of columns.Generating Contours:
GenerateAndDrawContours determines contour levels based on the min and max Z values and defines a number of contour levels (e.g., 10).MarchingSquares method to generate contour lines.Marching Squares Algorithm:
MarchingSquares method iterates through each cell in the grid and determines the edges intersected by the contour level.Rendering Contours:
Polyline is created and added to the ContourCanvas.ConvertToCanvasPoint method scales the grid coordinates to fit the Canvas (you can adjust cellSize as needed).User Interaction:
LoadDatFile_Click event handler is triggered when the user clicks the "Load .dat File" button. It opens a file dialog to select the .dat file and initiates the loading and rendering process..dat FileEnsure your .dat file is formatted correctly. It should consist of rows of Z values separated by spaces, commas, or tabs. For example:
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
Contour Smoothing and Connectivity: The simple Marching Squares implementation here connects points with straight lines within each cell but does not ensure that contour lines are continuous across cells. For more accurate and visually appealing contours, you might want to implement a version that connects segments across cells properly.
Performance: For large datasets, generating contours can be computationally intensive. Consider optimizing the algorithm or using parallel processing if necessary.
Visualization Enhancements:
Using Libraries: For more advanced and feature-rich contour mapping, consider using existing libraries such as ILNumerics or Helix Toolkit, which provide advanced visualization capabilities.
With the provided XAML and C# code, you have a basic WPF application that can load a .dat file containing Z values and render simple contour lines on a Canvas. This should serve as a solid foundation, which you can further enhance based on your specific requirements.
Not yet included in a published release.
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
namespace ContourMapApp
{
public partial class MainWindow : Window
{
private double[,] zValues;
private int rows;
private int cols;
public MainWindow()
{
InitializeComponent();
}
private void LoadDatFile_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog
{
Filter = "DAT files (*.dat)|*.dat|All files (*.*)|*.*"
};
if (openFileDialog.ShowDialog() == true)
{
try
{
LoadDatFile(openFileDialog.FileName);
GenerateAndDrawContours();
}
catch (Exception ex)
{
MessageBox.Show($"Error loading file: {ex.Message}");
}
}
}
private void LoadDatFile(string filePath)
{
var lines = File.ReadAllLines(filePath).Where(l => !string.IsNullOrWhiteSpace(l)).ToArray();
rows = lines.Length;
cols = lines[0].Split(new[] { ' ', ',', '\t' }, StringSplitOptions.RemoveEmptyEntries).Length;
zValues = new double[rows, cols];
for (int i = 0; i < rows; i++)
{
var tokens = lines[i].Split(new[] { ' ', ',', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (tokens.Length != cols)
throw new Exception($"Inconsistent number of columns at line {i + 1}.");
for (int j = 0; j < cols; j++)
{
if (!double.TryParse(tokens[j], NumberStyles.Any, CultureInfo.InvariantCulture, out double val))
throw new Exception($"Invalid number at line {i + 1}, column {j + 1}.");
zValues[i, j] = val;
}
}
}
private void GenerateAndDrawContours()
{
ContourCanvas.Children.Clear();
// Determine contour levels
double min = zValues.Cast<double>().Min();
double max = zValues.Cast<double>().Max();
int numContours = 10;
double step = (max - min) / numContours;
List<double> levels = new List<double>();
for (int i = 1; i < numContours; i++)
{
levels.Add(min + i * step);
}
// Generate contours for each level
foreach (var level in levels)
{
var contours = MarchingSquares(zValues, rows, cols, level);
foreach (var contour in contours)
{
var polyline = new Polyline
{
Stroke = Brushes.Black,
StrokeThickness = 1
};
foreach (var point in contour)
{
polyline.Points.Add(ConvertToCanvasPoint(point));
}
ContourCanvas.Children.Add(polyline);
}
}
// Optionally, adjust the Canvas size
double cellSize = 5; // Adjust as needed
ContourCanvas.Width = cols * cellSize;
ContourCanvas.Height = rows * cellSize;
}
private Point ConvertToCanvasPoint((double x, double y) point)
{
double cellSize = 5; // Same as in GenerateAndDrawContours
return new Point(point.x * cellSize, (rows - point.y) * cellSize); // Flip Y for display
}
/// <summary>
/// Implements the Marching Squares algorithm to generate contour lines.
/// Returns a list of contours, each contour is a list of points.
/// </summary>
private List<List<(double x, double y)>> MarchingSquares(double[,] data, int rows, int cols, double level)
{
List<List<(double x, double y)>> contours = new List<List<(double x, double y)>>();
bool[,] visited = new bool[rows, cols];
for (int i = 0; i < rows - 1; i++)
{
for (int j = 0; j < cols - 1; j++)
{
// Check if this cell could have a contour
double z0 = data[i, j];
double z1 = data[i, j + 1];
double z2 = data[i + 1, j + 1];
double z3 = data[i + 1, j];
// Determine the square index
int squareIndex = 0;
if (z0 >= level) squareIndex |= 1;
if (z1 >= level) squareIndex |= 2;
if (z2 >= level) squareIndex |= 4;
if (z3 >= level) squareIndex |= 8;
if (squareIndex == 0 || squareIndex == 15)
continue; // No contour for this cell
// Determine the edges intersected by the contour
List<(double x, double y)> edgePoints = new List<(double x, double y)>();
// Linear interpolation function
double Interpolate(double val1, double val2, int p1, int p2)
{
if (Math.Abs(val2 - val1) < 1e-6)
return (p1 + p2) / 2.0;
return p1 + (level - val1) * (p2 - p1) / (val2 - val1);
}
// Define positions of corners
// (i, j) is bottom-left
// Assuming grid is like:
// z3 --- z2
// | |
// z0 --- z1
// Compute interpolation points
// Left edge (z0-z3)
if ((squareIndex & 1) != (squareIndex & 8) != false)
{
double y = Interpolate(z0, z3, i, i + 1);
edgePoints.Add((j, y));
}
// Top edge (z3-z2)
if ((squareIndex & 8) != (squareIndex & 4) != false)
{
double x = Interpolate(z3, z2, j, j + 1);
edgePoints.Add((x, i + 1));
}
// Right edge (z1-z2)
if ((squareIndex & 2) != (squareIndex & 4) != false)
{
double y = Interpolate(z1, z2, i, i + 1);
edgePoints.Add((j + 1, y));
}
// Bottom edge (z0-z1)
if ((squareIndex & 1) != (squareIndex & 2) != false)
{
double x = Interpolate(z0, z1, j, j + 1);
edgePoints.Add((x, i));
}
// Depending on the configuration, connect edge points
if (edgePoints.Count >= 2)
{
// For simplicity, add straight lines between pairs of points
for (int k = 0; k + 1 < edgePoints.Count; k += 2)
{
contours.Add(new List<(double x, double y)>
{
edgePoints[k],
edgePoints[k + 1]
});
}
}
}
}
return contours;
}
}
}