private static void DfsuBuildGeometry(string targetMeshFilename, DfsuBuilder builder) { DfsFactory factory = new DfsFactory(); if (targetMeshFilename.EndsWith(".mesh", StringComparison.OrdinalIgnoreCase)) { MeshFile target = MeshFile.ReadMesh(targetMeshFilename); // Setup header and geometry, copy from source file builder.SetNodes(target.X, target.Y, target.Z.ToFloatArray(), target.Code); builder.SetElements(target.ElementTable); builder.SetProjection(factory.CreateProjection(target.Projection)); builder.SetZUnit(eumUnit.eumUmeter); } else { DfsuFile target = DfsFileFactory.DfsuFileOpen(targetMeshFilename); // Setup header and geometry, copy from source file builder.SetNodes(target.X, target.Y, target.Z, target.Code); builder.SetElements(target.ElementTable); builder.SetProjection(target.Projection); builder.SetZUnit(eumUnit.eumUmeter); target.Close(); } }
/// <summary> /// Example of how to create a Dfsu file from scratch. This method /// creates a copy of the OresundHD.dfsu test file. /// <para> /// Data for static and dynamic item is taken from a source dfs file, /// which here is the OresundHD.dfsu test file. The data could come /// from any other source. /// </para> /// </summary> /// <param name="sourceFilename">Path and name of the OresundHD.dfsu test file</param> /// <param name="filename">Path and name of the new file to create</param> /// <param name="zInMeters">Flag specifying whether the z values are in meters or feet </param> public static void CreateDfsuFile(string sourceFilename, string filename, bool zInMeters) { IDfsuFile source = DfsuFile.Open(sourceFilename); DfsuBuilder builder = DfsuBuilder.Create(DfsuFileType.Dfsu2D); // Setup header and geometry, copy from source file builder.SetNodes(source.X, source.Y, source.Z, source.Code); builder.SetElements(source.ElementTable); builder.SetProjection(source.Projection); builder.SetTimeInfo(source.StartDateTime, source.TimeStepInSeconds); if (zInMeters) { builder.SetZUnit(eumUnit.eumUmeter); } else { builder.SetZUnit(eumUnit.eumUfeet); } // Add dynamic items, copying from source foreach (DfsuDynamicItemInfo itemInfo in source.ItemInfo) { builder.AddDynamicItem(itemInfo.Name, itemInfo.Quantity); } DfsuFile file = builder.CreateFile(filename); // Add data for all item-timesteps, copying from source IDfsItemData sourceData; while (null != (sourceData = source.ReadItemTimeStepNext())) { file.WriteItemTimeStepNext(sourceData.Time, sourceData.Data); } source.Close(); file.Close(); }
/// <summary> /// Create a difference file between <paramref name="referenceFilename"/> /// and <paramref name="compareFilename"/>, and store it in /// <paramref name="diffFilename"/>. /// The compare-file data is interpolated to the reference-file mesh, if /// meshes does not match. /// </summary> /// <param name="referenceFilename">Reference data for comparison</param> /// <param name="compareFilename">Comparison data</param> /// <param name="diffFilename">File to store difference data to</param> /// <param name="deleteValueDiff">If set to true, comparing delete value to non-delete value will return the non-delete value</param> public static void DfsuDiff(string referenceFilename, string compareFilename, string diffFilename, bool deleteValueDiff = true) { System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); // Open reference file and comparison file DfsuFile refdfsu = DfsFileFactory.DfsuFileOpen(referenceFilename); DfsuFile comdfsu = DfsFileFactory.DfsuFileOpen(compareFilename); float refDeleteValueFloat = refdfsu.DeleteValueFloat; float comDeleteValueFloat = comdfsu.DeleteValueFloat; // Create diff file, matching reference file. DfsuBuilder builder = DfsuBuilder.Create(DfsuFileType.Dfsu2D); // Setup header and geometry, copy from source file builder.SetNodes(refdfsu.X, refdfsu.Y, refdfsu.Z, refdfsu.Code); builder.SetElements(refdfsu.ElementTable); builder.SetProjection(refdfsu.Projection); builder.SetZUnit(refdfsu.ZUnit); builder.SetTimeInfo(refdfsu.StartDateTime, refdfsu.TimeStepInSeconds); // Add dynamic items, copying from source foreach (IDfsSimpleDynamicItemInfo itemInfo in refdfsu.ItemInfo) { builder.AddDynamicItem(itemInfo.Name, itemInfo.Quantity); } DfsuFile diffDfsu = builder.CreateFile(diffFilename); watch.Stop(); Console.Out.WriteLine("Create File : " + watch.Elapsed.TotalSeconds); watch.Reset(); watch.Start(); // Build up mesh structures for interpolation SMeshData refMesh = SCreate(refdfsu); SMeshData comMesh = SCreate(comdfsu); watch.Stop(); Console.Out.WriteLine("Create mesh : " + watch.Elapsed.TotalSeconds); watch.Reset(); watch.Start(); bool meshEquals = refMesh.EqualsGeometry(comMesh); if (!meshEquals) { comMesh.BuildDerivedData(); } watch.Stop(); Console.Out.WriteLine("Build Deriv : " + watch.Elapsed.TotalSeconds); watch.Reset(); MeshInterpolator2D interpolator = null; float[] targetData = null; // Do not interpolate if meshes equals if (!meshEquals) { watch.Start(); // Build up interpolatin structures interpolator = new MeshInterpolator2D(comMesh, MeshValueType.Elements) { DeleteValue = comdfsu.DeleteValueFloat, DeleteValueFloat = comdfsu.DeleteValueFloat, //AllowExtrapolation = true, }; interpolator.SetTarget(refMesh, MeshValueType.Elements); // Temporary, interpolated compare-data targetData = new float[diffDfsu.NumberOfElements]; watch.Stop(); Console.Out.WriteLine("Interpolator: " + watch.Elapsed.TotalSeconds); watch.Reset(); } watch.Start(); // Loop over all time steps IDfsItemData <float> refData; IDfsItemData <float> comData; while (null != (refData = refdfsu.ReadItemTimeStepNext() as IDfsItemData <float>) && null != (comData = comdfsu.ReadItemTimeStepNext() as IDfsItemData <float>)) { if (interpolator != null) { interpolator.InterpolateElmtToTarget(comData.Data, targetData); } else { targetData = comData.Data; } for (int i = 0; i < targetData.Length; i++) { // ReSharper disable CompareOfFloatsByEqualityOperator if (refData.Data[i] != refDeleteValueFloat && targetData[i] != comDeleteValueFloat) { targetData[i] = refData.Data[i] - targetData[i]; } else if (refData.Data[i] == refDeleteValueFloat && targetData[i] == comDeleteValueFloat) { targetData[i] = refDeleteValueFloat; } else if (deleteValueDiff) { if (refData.Data[i] != refDeleteValueFloat) { targetData[i] = refData.Data[i]; } else // (targetData[i] != comDeleteValueFloat) { targetData[i] = -targetData[i]; } } else { targetData[i] = refDeleteValueFloat; } // ReSharper restore CompareOfFloatsByEqualityOperator } diffDfsu.WriteItemTimeStepNext(refData.Time, targetData); } watch.Stop(); Console.Out.WriteLine("Interpolate : " + watch.Elapsed.TotalSeconds); watch.Reset(); refdfsu.Close(); comdfsu.Close(); diffDfsu.Close(); }
/// <summary> /// Create a difference file between <paramref name="referenceFilename"/> /// and <paramref name="compareFilename"/>, and store it in /// <paramref name="diffFilename"/>. /// The compare-file data is interpolated to the reference-file mesh, if /// meshes does not match. /// </summary> /// <param name="referenceFilename">Reference data for comparison</param> /// <param name="compareFilename">Comparison data</param> /// <param name="diffFilename">File to store difference data to</param> public static void DfsuDiff(string referenceFilename, string compareFilename, string diffFilename) { System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); // Open reference file and comparison file DfsuFile refdfsu = DfsFileFactory.DfsuFileOpen(referenceFilename); DfsuFile comdfsu = DfsFileFactory.DfsuFileOpen(compareFilename); float deleteValueFloat = refdfsu.DeleteValueFloat; // Create diff file, matching reference file. DfsuBuilder builder = DfsuBuilder.Create(DfsuFileType.Dfsu2D); // Setup header and geometry, copy from source file builder.SetNodes(refdfsu.X, refdfsu.Y, refdfsu.Z, refdfsu.Code); builder.SetElements(refdfsu.ElementTable); builder.SetProjection(refdfsu.Projection); builder.SetZUnit(refdfsu.ZUnit); builder.SetTimeInfo(refdfsu.StartDateTime, refdfsu.TimeStepInSeconds); // Add dynamic items, copying from source foreach (DfsuDynamicItemInfo itemInfo in refdfsu.ItemInfo) { builder.AddDynamicItem(itemInfo.Name, itemInfo.Quantity); } DfsuFile diffDfsu = builder.CreateFile(diffFilename); watch.Stop(); Console.Out.WriteLine("Create File : " + watch.Elapsed.TotalSeconds); watch.Reset(); watch.Start(); // Build up mesh structures for interpolation MeshData sourceMesh = Create(refdfsu); MeshData targetMesh = Create(diffDfsu); sourceMesh.BuildDerivedData(); watch.Stop(); Console.Out.WriteLine("Build mesh : " + watch.Elapsed.TotalSeconds); watch.Reset(); watch.Start(); // Build up interpolatin structures MeshInterpolator2D interpolator = new MeshInterpolator2D(sourceMesh) { DeleteValue = refdfsu.DeleteValueFloat, DeleteValueFloat = refdfsu.DeleteValueFloat, }; interpolator.SetTarget(targetMesh); watch.Stop(); Console.Out.WriteLine("Interpolator: " + watch.Elapsed.TotalSeconds); watch.Reset(); watch.Start(); // Temporary, interpolated compare-data float[] targetData = new float[diffDfsu.NumberOfElements]; // Loop over all time steps IDfsItemData <float> refData; IDfsItemData <float> comData; while (null != (refData = refdfsu.ReadItemTimeStepNext() as IDfsItemData <float>) && null != (comData = comdfsu.ReadItemTimeStepNext() as IDfsItemData <float>)) { interpolator.InterpolateToTarget(comData.Data, targetData); for (int i = 0; i < targetData.Length; i++) { if (refData.Data[i] != deleteValueFloat && targetData[i] != deleteValueFloat) { targetData[i] = refData.Data[i] - targetData[i]; } else { targetData[i] = deleteValueFloat; } } diffDfsu.WriteItemTimeStepNext(refData.Time, targetData); } watch.Stop(); Console.Out.WriteLine("Interpolate : " + watch.Elapsed.TotalSeconds); watch.Reset(); refdfsu.Close(); comdfsu.Close(); diffDfsu.Close(); }
private void ComputeHmax(string filename) { btStart.Enabled = false; //Disable the Start button, to prevent user from running the tool twice at the same time btClose.Enabled = false; //Disable the Close button, to prevent user from closing the tool while running //Read input file and find relevant items IDfsuFile InputFile = DfsuFile.Open(filename); //Open the file int ItemNb = InputFile.ItemInfo.Count; //Number of items in the file int ItemNbH = -1; //Stores the item number for water depth. Initialised with a temporary value. int ItemNbU = -1; //Stores the item number for U velocity. Initialised with a temporary value. int ItemNbV = -1; //Stores the item number for V velocity. Initialised with a temporary value. for (int i = 0; i < ItemNb; i++) //Loop finding appropriate items H, U and V { if (InputFile.ItemInfo[i].Name == "Total water depth") { ItemNbH = i; //Save the actual item number when Total water depth is found } if (InputFile.ItemInfo[i].Name == "U velocity") { ItemNbU = i; //Save the actual item number when U velocity is found } if (InputFile.ItemInfo[i].Name == "V velocity") { ItemNbV = i; //Save the actual item number when V velocity is found } } if (ItemNbH == -1 || ItemNbU == -1 || ItemNbV == -1) //If one of the required item cannot be found { btClose.Enabled = true; //Enable the Close button again throw new Exception("The result file doesn't contain the necessary items H, U and V"); //Throw error message } else { //Create output file, with same nodes, elements, projection and time info as the input file, but with different output items DfsuBuilder OutputBuilder = DfsuBuilder.Create(DfsuFileType.Dfsu2D); OutputBuilder.SetNodes(InputFile.X, InputFile.Y, InputFile.Z, InputFile.Code); OutputBuilder.SetElements(InputFile.ElementTable); OutputBuilder.SetProjection(InputFile.Projection); OutputBuilder.SetTimeInfo(InputFile.StartDateTime, InputFile.TimeStepInSeconds); OutputBuilder.SetZUnit(InputFile.ZUnit); OutputBuilder.AddDynamicItem("Maximum water depth", InputFile.ItemInfo[ItemNbH].Quantity); //Create item H OutputBuilder.AddDynamicItem("U velocity @ max. depth", InputFile.ItemInfo[ItemNbU].Quantity); //Create item U OutputBuilder.AddDynamicItem("V velocity @ max. depth", InputFile.ItemInfo[ItemNbV].Quantity); //Create item V OutputBuilder.AddDynamicItem("Current speed @ max. depth", InputFile.ItemInfo[ItemNbU].Quantity); //Create item Speed OutputBuilder.AddDynamicItem("Current direction @ max. depth", eumQuantity.Create(eumItem.eumICurrentDirection, eumUnit.eumUradian)); //Create item Direction. Note: eumQuantity requires "using DHI.Generic.MikeZero" //Initialization of all output variables. Both source data and output data are intialized with data from first time step of the input file. float[] SourceDataH = (float[])InputFile.ReadItemTimeStep(ItemNbH + 1, 0).Data; //ReadItemTimeStep is 1-based! That is, the first time step must be numbered 1, whereas the first time step in the file is numbered 0, hence the +1. float[] SourceDataU = (float[])InputFile.ReadItemTimeStep(ItemNbU + 1, 0).Data; float[] SourceDataV = (float[])InputFile.ReadItemTimeStep(ItemNbV + 1, 0).Data; float[] OutputDataH = (float[])InputFile.ReadItemTimeStep(ItemNbH + 1, 0).Data; float[] OutputDataU = (float[])InputFile.ReadItemTimeStep(ItemNbU + 1, 0).Data; float[] OutputDataV = (float[])InputFile.ReadItemTimeStep(ItemNbV + 1, 0).Data; float[] OutputDataSpeed = (float[])InputFile.ReadItemTimeStep(ItemNbU + 1, 0).Data; //Initialise speed with values of U at time step 0 float[] OutputDataDir = (float[])InputFile.ReadItemTimeStep(ItemNbU + 1, 0).Data; //Initialise direction with values of U at time step 0 for (int m = 0; m < InputFile.NumberOfElements; m++) //Change speed and direction at first time step based on U and V values, with a loop over each element { OutputDataSpeed[m] = (float)Math.Sqrt(Math.Pow(SourceDataU[m], 2) + Math.Pow(SourceDataV[m], 2)); OutputDataDir[m] = (float)Math.Atan2(SourceDataU[m], SourceDataV[m]); } //Define the properties of the progress bar progressBar1.Maximum = InputFile.NumberOfTimeSteps - 1; progressBar1.Step = 1; //Loop over all time steps to get results for maxH (starting from 2nd time step) for (int j = 1; j < InputFile.NumberOfTimeSteps; j++) { SourceDataH = (float[])InputFile.ReadItemTimeStep(ItemNbH + 1, j).Data; //Load the new time step H data into the SourceDataH array. ReadItemTimeStep is 1-based! SourceDataU = (float[])InputFile.ReadItemTimeStep(ItemNbU + 1, j).Data; //Load the new time step U data into the SourceDataU array. ReadItemTimeStep is 1-based! SourceDataV = (float[])InputFile.ReadItemTimeStep(ItemNbV + 1, j).Data; //Load the new time step V data into the SourceDataV array. ReadItemTimeStep is 1-based! for (int k = 0; k < InputFile.NumberOfElements; k++) //Loop over all elements { if (SourceDataH[k] > OutputDataH[k]) //If the water depth for the new time step is higher than the previous maximum depth, then store the corresponding U, V, speed and direction values { OutputDataH[k] = SourceDataH[k]; OutputDataU[k] = SourceDataU[k]; OutputDataV[k] = SourceDataV[k]; OutputDataSpeed[k] = (float)Math.Sqrt(Math.Pow(SourceDataU[k], 2) + Math.Pow(SourceDataV[k], 2)); OutputDataDir[k] = (float)Math.Atan2(SourceDataU[k], SourceDataV[k]); } } progressBar1.PerformStep(); //Increment progress bar } // Write results string folder = Path.GetDirectoryName(txtPath.Text); string FileRoot = Path.GetFileNameWithoutExtension(txtPath.Text); string FileNameOut = folder + "\\" + FileRoot + "_Statistics_Hmax.dfsu"; //Add suffix to input file name, to be used for output file DfsuFile OutputFile = OutputBuilder.CreateFile(FileNameOut); //Create output file OutputFile.WriteItemTimeStepNext(0, OutputDataH); //Write H data. Time set to 0 : ignored since equidistant interval OutputFile.WriteItemTimeStepNext(0, OutputDataU); //Write U data OutputFile.WriteItemTimeStepNext(0, OutputDataV); //Write V data OutputFile.WriteItemTimeStepNext(0, OutputDataSpeed); //Write speed data OutputFile.WriteItemTimeStepNext(0, OutputDataDir); //Write direction data InputFile.Close(); //Release the input file OutputFile.Close(); //Release the output file MessageBox.Show("File created"); //Confirm that the file has been created progressBar1.Value = 0; //Reset the progress bar btStart.Enabled = true; //Enable the Start button again btClose.Enabled = true; //Enable the Close button again } }
/// <summary> /// Extract sub-area of dfsu (2D) file to a new dfsu file /// </summary> /// <param name="sourceFilename">Name of source file, i.e. OresundHD.dfsu test file</param> /// <param name="outputFilename">Name of output file</param> /// <param name="x1">Lower left x coordinate of sub area</param> /// <param name="y1">Lower left y coordinate of sub area</param> /// <param name="x2">upper right x coordinate of sub area</param> /// <param name="y2">upper right y coordinate of sub area</param> public static void ExtractSubareaDfsu2D(string sourceFilename, string outputFilename, double x1, double y1, double x2, double y2) { DfsuFile dfsu = DfsFileFactory.DfsuFileOpen(sourceFilename); // Node coordinates double[] X = dfsu.X; double[] Y = dfsu.Y; float[] Z = dfsu.Z; int[] Code = dfsu.Code; // Loop over all elements, and all its nodes: If one node is inside // region, element (and nodes) are to be included in new mesh List <int> elmtsIncluded = new List <int>(); bool[] nodesIncluded = new bool[dfsu.NumberOfNodes]; for (int i = 0; i < dfsu.NumberOfElements; i++) { // Nodes of element int[] nodes = dfsu.ElementTable[i]; // Check if one of the nodes of the element is inside region bool elmtIncluded = false; for (int j = 0; j < nodes.Length; j++) { int node = nodes[j] - 1; if (x1 <= X[node] && X[node] <= x2 && y1 <= Y[node] && Y[node] <= y2) { elmtIncluded = true; } } if (elmtIncluded) { // Add element to list of included elements elmtsIncluded.Add(i); // Mark all nodes of element as included for (int j = 0; j < nodes.Length; j++) { int node = nodes[j] - 1; nodesIncluded[node] = true; } } } // array containing numbers of existing nodes in new mesh (indices) int[] renumber = new int[dfsu.NumberOfNodes]; // new mesh nodes List <double> X2 = new List <double>(); List <double> Y2 = new List <double>(); List <float> Z2 = new List <float>(); List <int> Code2 = new List <int>(); List <int> nodeIds = new List <int>(); int i2 = 0; for (int i = 0; i < dfsu.NumberOfNodes; i++) { if (nodesIncluded[i]) { X2.Add(X[i]); Y2.Add(Y[i]); Z2.Add(Z[i]); Code2.Add(Code[i]); nodeIds.Add(dfsu.NodeIds[i]); // Node with index i will get index i2 in new mesh renumber[i] = i2; i2++; } } // New mesh elements List <int[]> elmttable2 = new List <int[]>(); List <int> elmtIds = new List <int>(); for (int i = 0; i < elmtsIncluded.Count; i++) { // Add new element int elmt = elmtsIncluded[i]; int[] nodes = dfsu.ElementTable[elmt]; // newNodes must be renumbered int[] newNodes = new int[nodes.Length]; for (int j = 0; j < nodes.Length; j++) { // Do the renumbering of nodes from existing mesh to new mesh newNodes[j] = renumber[nodes[j] - 1] + 1; } elmttable2.Add(newNodes); elmtIds.Add(dfsu.ElementIds[i]); } // Create 2D dfsu file DfsuBuilder builder = DfsuBuilder.Create(DfsuFileType.Dfsu2D); // Setup header and geometry builder.SetNodes(X2.ToArray(), Y2.ToArray(), Z2.ToArray(), Code2.ToArray()); //builder.SetNodeIds(nodeIds.ToArray()); builder.SetElements(elmttable2.ToArray()); builder.SetElementIds(elmtIds.ToArray()); // retain original element id's builder.SetProjection(dfsu.Projection); builder.SetTimeInfo(dfsu.StartDateTime, dfsu.TimeStepInSeconds); if (dfsu.ZUnit == eumUnit.eumUUnitUndefined) { builder.SetZUnit(eumUnit.eumUmeter); } else { builder.SetZUnit(dfsu.ZUnit); } // Add dynamic items, copying from source for (int i = 0; i < dfsu.ItemInfo.Count; i++) { IDfsSimpleDynamicItemInfo itemInfo = dfsu.ItemInfo[i]; builder.AddDynamicItem(itemInfo.Name, itemInfo.Quantity); } // Create new file DfsuFile dfsuOut = builder.CreateFile(outputFilename); // Add new data float[] data2 = new float[elmtsIncluded.Count]; for (int i = 0; i < dfsu.NumberOfTimeSteps; i++) { for (int j = 0; j < dfsu.ItemInfo.Count; j++) { // Read data from existing dfsu IDfsItemData <float> itemData = (IDfsItemData <float>)dfsu.ReadItemTimeStep(j + 1, i); // Extract value for elements in new mesh for (int k = 0; k < elmtsIncluded.Count; k++) { data2[k] = itemData.Data[elmtsIncluded[k]]; } // write data dfsuOut.WriteItemTimeStepNext(itemData.Time, data2); } } dfsuOut.Close(); dfsu.Close(); }
/// <summary> /// Create dfsu and mesh file from dfs2 file. /// <para> /// Note 1: Boundary code is set to land value at /// all boundaries of mesh and dfsu file. /// These must be updated to something "better" /// if to use as input in another simulation. /// </para> /// <para> /// Note 2: P and Q values are not rotated with the /// grid, but should be so, if used in the /// projected coordinate system. It must take /// the 327 degrees rotation into account. /// </para> /// </summary> /// <param name="dfs2Filename">Name of input dfs2 file, e.g. the OresundHD.dfs2</param> /// <param name="meshFilename">Name of output mesh file</param> /// <param name="dfsuFilename">Name of output dfsu file</param> public static void CreateDfsuFromDfs2(string dfs2Filename, string meshFilename, string dfsuFilename) { // Open file Dfs2File dfs2 = DfsFileFactory.Dfs2FileOpen(dfs2Filename); // Read bathymetry from first static item IDfsStaticItem bathymetryItem = dfs2.ReadStaticItemNext(); float[] bathymetry = (float[])bathymetryItem.Data; // Extract spatial axis IDfsAxisEqD2 spatialAxis = (IDfsAxisEqD2)dfs2.SpatialAxis; // Some convenience variables double dx = spatialAxis.Dx; double dy = spatialAxis.Dy; double x0 = spatialAxis.X0; double y0 = spatialAxis.Y0; int xCount = spatialAxis.XCount; int yCount = spatialAxis.YCount; // First custom block (index 0) contains the M21_MISC values, // where the 4th (index 3) is the land value float landValue = (float)dfs2.FileInfo.CustomBlocks[0][3]; //----------------------------------------- // Find out which elements in the dfs2 grid that is not a land value // and include all those elements and their surrounding nodes in mesh // Arrays indicating if element and node in grid is used or not in mesh bool[,] elmts = new bool[xCount, yCount]; int[,] nodes = new int[xCount + 1, yCount + 1]; // Loop over all elements in 2D grid for (int l = 0; l < yCount; l++) { for (int k = 0; k < xCount; k++) { // If bathymetry is not land value, use element. if (bathymetry[k + l * xCount] != landValue) { // element [l,k] is used, and also the 4 nodes around it elmts[k, l] = true; nodes[k, l] = 1; nodes[k + 1, l] = 1; nodes[k, l + 1] = 1; nodes[k + 1, l + 1] = 1; } } } //----------------------------------------- // Create new mest nodes // Cartography object can convert grid (x,y) to projection (east,north) IDfsProjection proj = dfs2.FileInfo.Projection; DHI.Projections.Cartography cart = new DHI.Projections.Cartography(proj.WKTString, proj.Longitude, proj.Latitude, proj.Orientation); // New mesh nodes List <double> X = new List <double>(); List <double> Y = new List <double>(); List <float> Zf = new List <float>(); // float values for dfsu file List <double> Zd = new List <double>(); // double values for mesh file List <int> Code = new List <int>(); // Loop over all nodes int nodesCount = 0; for (int l = 0; l < yCount + 1; l++) { for (int k = 0; k < xCount + 1; k++) { // Check if node is included in mesh if (nodes[k, l] > 0) { // Convert from mesh (x,y) to projection (east,north) double east, north; cart.Xy2Proj((k - 0.5) * dx + x0, (l - 0.5) * dy + y0, out east, out north); // Average Z on node from neighbouring grid cell values, cell value is used // unless they are outside grid or has land values double z = 0; int zCount = 0; if (k > 0 && l > 0 && bathymetry[k - 1 + (l - 1) * xCount] != landValue) { zCount++; z += bathymetry[k - 1 + (l - 1) * xCount]; } if (k < xCount && l > 0 && bathymetry[k + (l - 1) * xCount] != landValue) { zCount++; z += bathymetry[k + (l - 1) * xCount]; } if (k > 0 && l < yCount && bathymetry[k - 1 + (l) * xCount] != landValue) { zCount++; z += bathymetry[k - 1 + (l) * xCount]; } if (k < xCount && l < yCount && bathymetry[k + (l) * xCount] != landValue) { zCount++; z += bathymetry[k + (l) * xCount]; } if (zCount > 0) { z /= zCount; } else { z = landValue; } // Store new node number and add node nodesCount++; nodes[k, l] = nodesCount; // this is the node number to use in the element table X.Add(east); Y.Add(north); Zf.Add((float)z); Zd.Add(z); Code.Add(zCount == 4 ? 0 : 1); // Land boundary if zCount < 4 } } } // New mesh elements List <int[]> elmttable2 = new List <int[]>(); for (int l = 0; l < yCount; l++) { for (int k = 0; k < xCount; k++) { // Check if element is included in mesh if (elmts[k, l]) { // For this element, add the four surrounding nodes, // counter-clockwise order int[] newNodes = new int[4]; newNodes[0] = nodes[k, l]; newNodes[1] = nodes[k + 1, l]; newNodes[2] = nodes[k + 1, l + 1]; newNodes[3] = nodes[k, l + 1]; elmttable2.Add(newNodes); } } } //----------------------------------------- // Create mesh { // Create 2D dfsu file MeshBuilder builder = new MeshBuilder(); // Setup header and geometry builder.SetNodes(X.ToArray(), Y.ToArray(), Zd.ToArray(), Code.ToArray()); builder.SetElements(elmttable2.ToArray()); builder.SetProjection(dfs2.FileInfo.Projection); // Create new file MeshFile mesh = builder.CreateMesh(); mesh.Write(meshFilename); } //----------------------------------------- // Create dfsu file { // dfs2 time axis IDfsEqCalendarAxis timeAxis = (IDfsEqCalendarAxis)dfs2.FileInfo.TimeAxis; // Create 2D dfsu file DfsuBuilder builder = DfsuBuilder.Create(DfsuFileType.Dfsu2D); // Setup header and geometry builder.SetNodes(X.ToArray(), Y.ToArray(), Zf.ToArray(), Code.ToArray()); builder.SetElements(elmttable2.ToArray()); builder.SetProjection(dfs2.FileInfo.Projection); builder.SetTimeInfo(timeAxis.StartDateTime, timeAxis.TimeStepInSeconds()); builder.SetZUnit(eumUnit.eumUmeter); // Add dynamic items, copying from dfs2 file for (int i = 0; i < dfs2.ItemInfo.Count; i++) { IDfsSimpleDynamicItemInfo itemInfo = dfs2.ItemInfo[i]; builder.AddDynamicItem(itemInfo.Name, itemInfo.Quantity); } // Create new file DfsuFile dfsu = builder.CreateFile(dfsuFilename); // Add dfs2 data to dfsu file float[] dfsuData = new float[dfsu.NumberOfElements]; for (int i = 0; i < dfs2.FileInfo.TimeAxis.NumberOfTimeSteps; i++) { for (int j = 0; j < dfs2.ItemInfo.Count; j++) { // Read dfs2 grid data IDfsItemData2D <float> itemData = (IDfsItemData2D <float>)dfs2.ReadItemTimeStep(j + 1, i); // Extract 2D grid data to dfsu data array int lk = 0; for (int l = 0; l < yCount; l++) { for (int k = 0; k < xCount; k++) { if (elmts[k, l]) { dfsuData[lk++] = itemData[k, l]; } } } // write data dfsu.WriteItemTimeStepNext(itemData.Time, dfsuData); } } dfsu.Close(); } dfs2.Close(); }
/// <summary> /// Extract a single layer from a 3D dfsu file, and write it to a 2D dfsu file. /// <para> /// If a layer value does not exist for a certain 2D element, delete value is written /// to the 2D resut file. This is relevant for Sigma-Z type of files. /// </para> /// </summary> /// <param name="filenameDfsu3">Name of 3D dfsu source file</param> /// <param name="filenameDfsu2">Name of 2D dfsu result file</param> /// <param name="layerNumber">Layer to extract. /// <para> /// Positive values count from bottom up i.e. 1 is bottom layer, 2 is second layer from bottom etc. /// </para> /// <para> /// Negative values count from top down, i.e. -1 is toplayer, -2 is second layer from top etc. /// </para> /// </param> public static void ExtractDfsu2DLayerFrom3D(string filenameDfsu3, string filenameDfsu2, int layerNumber) { IDfsuFile dfsu3File = DfsFileFactory.DfsuFileOpen(filenameDfsu3); // Check that dfsu3 file is a 3D dfsu file. switch (dfsu3File.DfsuFileType) { case DfsuFileType.Dfsu2D: case DfsuFileType.DfsuVerticalColumn: case DfsuFileType.DfsuVerticalProfileSigma: case DfsuFileType.DfsuVerticalProfileSigmaZ: throw new InvalidOperationException("Input file is not a 3D dfsu file"); } // Calculate offset from toplayer element. Offset is between 0 (top layer) and // dfsu3File.NumberOfLayers-1 (bottom layer) int topLayerOffset; if (layerNumber > 0 && layerNumber <= dfsu3File.NumberOfLayers) { topLayerOffset = dfsu3File.NumberOfLayers - layerNumber; } else if (layerNumber < 0 && -layerNumber <= dfsu3File.NumberOfLayers) { topLayerOffset = -layerNumber - 1; } else { throw new ArgumentException("Layer number is out of range"); } double[] xv = dfsu3File.X; double[] yv = dfsu3File.Y; float[] zv = dfsu3File.Z; int[] cv = dfsu3File.Code; // -------------------------------------------------- // Create 2D mesh from 3D mesh // List of new 2D nodes int node2DCount = 0; List <double> xv2 = new List <double>(); List <double> yv2 = new List <double>(); List <float> zv2 = new List <float>(); List <int> cv2 = new List <int>(); // Renumbering array, from 3D node numbers to 2D node numbers // i.e. if a 3D element refers to node number k, the 2D element node number is renumber[k] int[] renumber = new int[dfsu3File.NumberOfNodes]; // Coordinates of last created node double xr2 = -1e-10; double yr2 = -1e-10; // Create 2D nodes, by skipping nodes with equal x,y coordinates for (int i = 0; i < dfsu3File.NumberOfNodes; i++) { // If 3D x,y coordinates are equal to the last created 2D node, // map this node to the last created 2D node, otherwise // create new 2D node and map to that one if (xv[i] != xr2 || yv[i] != yr2) { // Create new node node2DCount++; xr2 = xv[i]; yr2 = yv[i]; float zr2 = zv[i]; int cr2 = cv[i]; xv2.Add(xr2); yv2.Add(yr2); zv2.Add(zr2); cv2.Add(cr2); } // Map this 3D node to the last created 2D node. renumber[i] = node2DCount; } // Find indices of top layer elements IList <int> topLayer = dfsu3File.FindTopLayerElements(); // Create element table for 2D dfsu file int[][] elmttable2 = new int[topLayer.Count][]; for (int i = 0; i < topLayer.Count; i++) { // 3D element nodes int[] elmt3 = dfsu3File.ElementTable[topLayer[i]]; // 2D element nodes, only half as big, so copy over the first half int[] elmt2 = new int[elmt3.Length / 2]; for (int j = 0; j < elmt2.Length; j++) { elmt2[j] = renumber[elmt3[j]]; } elmttable2[i] = elmt2; } // -------------------------------------------------- // Create 2D dfsu file DfsuBuilder builder = DfsuBuilder.Create(DfsuFileType.Dfsu2D); // Setup header and geometry builder.SetNodes(xv2.ToArray(), yv2.ToArray(), zv2.ToArray(), cv2.ToArray()); builder.SetElements(elmttable2); builder.SetProjection(dfsu3File.Projection); builder.SetTimeInfo(dfsu3File.StartDateTime, dfsu3File.TimeStepInSeconds); if (dfsu3File.ZUnit == eumUnit.eumUUnitUndefined) { builder.SetZUnit(eumUnit.eumUmeter); } else { builder.SetZUnit(dfsu3File.ZUnit); } // Add dynamic items, copying from source, though not the first one, if it // contains the z-variation on the nodes for (int i = 0; i < dfsu3File.ItemInfo.Count; i++) { IDfsSimpleDynamicItemInfo itemInfo = dfsu3File.ItemInfo[i]; if (itemInfo.ElementCount == dfsu3File.NumberOfElements) { builder.AddDynamicItem(itemInfo.Name, itemInfo.Quantity); } } // Create file DfsuFile dfsu2File = builder.CreateFile(filenameDfsu2); // -------------------------------------------------- // Process data // Check if the layer number exists for 2D element, i.e. if that element // in 2D has that number of columnes in the 3D (relevant for sigma-z files) // If elementExists[i] is false, write delete value to file bool[] elementExists = new bool[topLayer.Count]; int numLayersInColumn = topLayer[0] + 1; elementExists[0] = (numLayersInColumn - topLayerOffset) > 0; for (int i = 1; i < topLayer.Count; i++) { numLayersInColumn = (topLayer[i] - topLayer[i - 1]); elementExists[i] = (numLayersInColumn - topLayerOffset) > 0; } // For performance, use predefined itemdata objects when reading data from dfsu 3D file IDfsItemData <float>[] dfsu3ItemDatas = new IDfsItemData <float> [dfsu3File.ItemInfo.Count]; for (int j = 0; j < dfsu3File.ItemInfo.Count; j++) { dfsu3ItemDatas[j] = (IDfsItemData <float>)dfsu3File.ItemInfo[j].CreateEmptyItemData(); } // Float data to write to dfsu 2D file float[] data2 = new float[dfsu2File.NumberOfElements]; float deleteValueFloat = dfsu2File.DeleteValueFloat; for (int i = 0; i < dfsu3File.NumberOfTimeSteps; i++) { for (int j = 0; j < dfsu3File.ItemInfo.Count; j++) { // Read data from 3D dfsu IDfsItemData <float> data3Item = dfsu3ItemDatas[j]; bool ok = dfsu3File.ReadItemTimeStep(data3Item, i); // 3D data float[] data3 = data3Item.Data; // Skip any items not having size = NumberOfElments (the z-variation on the nodes) if (data3.Length != dfsu3File.NumberOfElements) { continue; } // Loop over all 2D elements for (int k = 0; k < topLayer.Count; k++) { // Extract layer data from 3D column into 2D element value if (elementExists[k]) { data2[k] = data3[topLayer[k] - topLayerOffset]; } else { data2[k] = deleteValueFloat; } } dfsu2File.WriteItemTimeStepNext(data3Item.Time, data2); } } dfsu3File.Close(); dfsu2File.Close(); }