示例#1
0
        public Geometry BoundaryPolygonSMeshTest(string meshPath, bool alwaysMultiPolygon = true, string extra = "")
        {
            string fileName = Path.GetFileName(meshPath);

            Stopwatch timer;
            SMeshData mesh;

            if (Path.GetExtension(meshPath) == ".dfsu")
            {
                DfsuFile file = DfsFileFactory.DfsuFileOpen(meshPath);
                timer = MeshExtensions.StartTimer();
                mesh  = new SMeshData(file.Projection.WKTString, file.NodeIds, file.X, file.Y, file.Z.ToDoubleArray(), file.Code, file.ElementIds, file.ElementType, file.ElementTable.ToZeroBased());
                file.Close();
            }
            else
            {
                MeshFile meshFile = MeshFile.ReadMesh(meshPath);
                timer = MeshExtensions.StartTimer();
                mesh  = meshFile.ToSMeshData();
            }

            Console.Out.WriteLine("(#nodes,#elmts)=({0},{1}) ({2})", mesh.NumberOfNodes, mesh.NumberOfElements, mesh.NumberOfNodes + mesh.NumberOfElements);
            timer.ReportAndRestart("Create ");

            Geometry boundaryGeom = mesh.BuildBoundaryGeometry(alwaysMultiPolygon);

            timer.ReportAndRestart("Build  ");

            BoundaryPolygonWriter(fileName, "-sbnd" + extra, boundaryGeom, timer);
            return(boundaryGeom);
        }
示例#2
0
        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();
            }
        }
示例#3
0
        public List <SMeshBoundary> BoundaryListSMeshTest(string meshPath)
        {
            string fileName = Path.GetFileName(meshPath);

            Stopwatch timer;
            SMeshData mesh;

            if (Path.GetExtension(meshPath) == ".dfsu")
            {
                DfsuFile file = DfsFileFactory.DfsuFileOpen(meshPath);
                timer = MeshExtensions.StartTimer();
                mesh  = new SMeshData(file.Projection.WKTString, file.NodeIds, file.X, file.Y, file.Z.ToDoubleArray(), file.Code, file.ElementIds, file.ElementType, file.ElementTable.ToZeroBased());
                file.Close();
            }
            else
            {
                MeshFile meshFile = MeshFile.ReadMesh(meshPath);
                timer = MeshExtensions.StartTimer();
                mesh  = meshFile.ToSMeshData();
            }
            Console.Out.WriteLine("(#nodes,#elmts)=({0},{1}) ({2})", mesh.NumberOfNodes, mesh.NumberOfElements, mesh.NumberOfNodes + mesh.NumberOfElements);

            timer.ReportAndRestart("Create");

            List <SMeshBoundary> boundaries = mesh.BuildBoundaryList();

            timer.ReportAndRestart("Time  ");

            string gpFileName = UnitTestHelper.TestDataDir + "test_" + fileName + "-bndscode.txt";

            GnuPlotWriteBoundaryList(mesh, gpFileName, boundaries);

            return(boundaries);
        }
示例#4
0
        private IMeshDataInfo GetMesh(string dfsufilepath, bool smesh)
        {
            IMeshDataInfo mesh;

            DfsuFile file = DfsFileFactory.DfsuFileOpen(dfsufilepath);

            if (smesh)
            {
                mesh = new SMeshData(file.Projection.WKTString, file.NodeIds, file.X, file.Y, file.Z.ToDoubleArray(),
                                     file.Code, file.ElementIds, file.ElementType, file.ElementTable.ToZeroBased());
                return(mesh);
            }
            else
            {
                mesh = new MeshData(file.Projection.WKTString, file.NodeIds, file.X, file.Y, file.Z.ToDoubleArray(),
                                    file.Code, file.ElementIds, file.ElementType, file.ElementTable.ToZeroBased());
                return(mesh);
            }
        }
示例#5
0
        /// <summary>
        /// Introductory example of how to load a dfsu file.
        /// <para>
        /// The method assumes that the OresundHD.dfsu test file
        /// is the input file.
        /// </para>
        /// </summary>
        /// <param name="filename">path and name of OresundHD.dfsu test file</param>
        public static void ReadingDfsuFile(string filename)
        {
            IDfsuFile file = DfsuFile.Open(filename);

            // Read geometry
            int    numberOfElements     = file.NumberOfElements; // 3636
            int    numberOfNodes        = file.NumberOfNodes;    // 2057
            double firstNodeXCoordinate = file.X[0];             // 359978.8

            int[] firstElementNodes = file.ElementTable[0];      // [1, 2, 3]

            // Read dynamic item info
            string      firstItemName = file.ItemInfo[0].Name;     // "Surface elevation"
            eumQuantity quantity      = file.ItemInfo[0].Quantity; // eumISurfaceElevation in eumUmeter

            // load data for the first item, 6th timestep
            float[] itemTimeStepData = (float[])file.ReadItemTimeStep(1, 5).Data;
            // Read the value of the third element
            float thirdElementValue = itemTimeStepData[2]; // 0.0014070312

            file.Close();
        }
示例#6
0
        /// <summary>
        /// Example of how to modify the geometry of a dfsu file.
        /// The method will rotate the geometry by 125 degrees.
        /// <para>
        /// The method will work on any dfsu file. The OresundHD.dfsu test file
        /// (preferably a copy of it) can be used as input file.
        /// </para>
        /// </summary>
        /// <param name="filename">Path and name of a dfsu file</param>
        public static void ModifyDfsuFileGeometry(string filename)
        {
            // Open file for editing
            IDfsuFile dfsuFile = DfsuFile.OpenEdit(filename);

            dfsuFile.TimeStepInSeconds /= 2;
            dfsuFile.StartDateTime      = new DateTime(2019, 6, 27, 13, 50, 30);

            // Make a rotation matrix
            double rotation = 125.0 / 180.0 * System.Math.PI;
            double x1       = System.Math.Cos(rotation);
            double y1       = -System.Math.Sin(rotation);
            double x2       = System.Math.Sin(rotation);
            double y2       = System.Math.Cos(rotation);

            // Get the x- and y-coordinates from the file
            double[] x = dfsuFile.X;
            double[] y = dfsuFile.Y;

            // Point to rotate around
            double x0 = x[0];
            double y0 = y[0];

            // Rotate coordinates
            for (int i = 0; i < dfsuFile.NumberOfNodes; i++)
            {
                double xx = x[i] - x0;
                double yy = y[i] - y0;
                x[i] = x1 * xx + y1 * yy + x0;
                y[i] = x2 * xx + y2 * yy + y0;
            }

            // Set the x- and y-coordinates back to the file
            dfsuFile.X = x;
            dfsuFile.Y = y;

            // Close the file
            dfsuFile.Close();
        }
示例#7
0
        /// <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();
        }
示例#8
0
        public bool GetStudyAreaContourPolygonList(List <ContourPolygon> contourPolygonList)
        {
            //contourPolygonList = new List<ContourPolygon>();

            using (DFSU dfsu = new DFSU(fi))
            {
                List <List <Node> > StudyAreaList = new List <List <Node> >();

                DfsuFile   dfsuFile;
                List <int> PolygonIndexes = new List <int>();

                try
                {
                    dfsuFile = DfsuFile.Open(fi.FullName);
                }
                catch (Exception ex)
                {
                    ErrorMessage = string.Format(CSSPDHIRes.CouldNotOpen_Error_, fi.FullName, ex.Message + (ex.InnerException != null ? "Inner: " + ex.InnerException.Message : ""));
                    OnCSSPDHIChanged(new CSSPDHIEventArgs(new CSSPDHIMessage("Error", -1, false, ErrorMessage)));
                    contourPolygonList.Add(new ContourPolygon()
                    {
                        Error = ErrorMessage
                    });
                    return(false);
                }

                int TotalNumberWithCodeBigger0 = dfsuFile.Code.Where(c => c > 0).Count();

                List <Element> ElementList = new List <Element>();
                List <Node>    NodeList    = new List <Node>();

                // ----------------------------------------
                // filling the ElementList and The NodeList
                // ----------------------------------------

                FillElementListAndNodeList(ElementList, NodeList);

                List <Node> AllNodeList = new List <Node>();
                //List<ContourPolygon> ContourPolygonList = new List<ContourPolygon>();

                List <Node> AboveNodeList = (from n in NodeList
                                             where n.Code != 0
                                             select n).ToList <Node>();

                foreach (Node sn in AboveNodeList)
                {
                    List <Node> EndNodeList = (from n in sn.ConnectNodeList
                                               where n.Code != 0
                                               select n).ToList <Node>();

                    foreach (Node en in EndNodeList)
                    {
                        AllNodeList.Add(en);
                    }

                    if (sn.Code != 0)
                    {
                        AllNodeList.Add(sn);
                    }
                }

                List <Element> UniqueElementList = new List <Element>();

                List <Element> TempUniqueElementList = new List <Element>();

                // filling UniqueElementList
                TempUniqueElementList = (from el in ElementList
                                         where (el.Type == 21 || el.Type == 32)
                                         select el).Distinct().ToList <Element>();

                foreach (Element el in TempUniqueElementList)
                {
                    if ((el.NodeList[0].Code != 0 && el.NodeList[1].Code != 0) ||
                        (el.NodeList[0].Code != 0 && el.NodeList[2].Code != 0) ||
                        (el.NodeList[1].Code != 0 && el.NodeList[2].Code != 0))
                    {
                        UniqueElementList.Add(el);
                    }
                }

                TempUniqueElementList = (from el in ElementList
                                         where (el.Type == 25 || el.Type == 33)
                                         select el).Distinct().ToList <Element>();

                foreach (Element el in TempUniqueElementList)
                {
                    if ((el.NodeList[0].Code != 0 && el.NodeList[1].Code != 0) ||
                        (el.NodeList[1].Code != 0 && el.NodeList[2].Code != 0) ||
                        (el.NodeList[2].Code != 0 && el.NodeList[3].Code != 0) ||
                        (el.NodeList[3].Code != 0 && el.NodeList[0].Code != 0))
                    {
                        UniqueElementList.Add(el);
                    }
                }

                List <Node> UniqueNodeList = (from n in AllNodeList orderby n.ID select n).Distinct().ToList <Node>();


                Dictionary <String, Vector> ForwardVector  = new Dictionary <String, Vector>();
                Dictionary <String, Vector> BackwardVector = new Dictionary <String, Vector>();

                //_TaskRunnerBaseService.SendPercentToDB(_TaskRunnerBaseService._BWObj.appTaskModel.AppTaskID, 30);

                foreach (Element el in UniqueElementList)
                {
                    Node Node0 = new Node();
                    Node Node1 = new Node();
                    Node Node2 = new Node();
                    Node Node3 = new Node();


                    if (el.Type == 21 || el.Type == 32)
                    {
                        Node0 = el.NodeList[0];
                        Node1 = el.NodeList[1];
                        Node2 = el.NodeList[2];

                        int ElemCount01 = (from el1 in UniqueElementList
                                           from el2 in Node0.ElementList
                                           from el3 in Node1.ElementList
                                           where el1 == el2 && el1 == el3
                                           select el1).Count();

                        int ElemCount02 = (from el1 in UniqueElementList
                                           from el2 in Node0.ElementList
                                           from el3 in Node2.ElementList
                                           where el1 == el2 && el1 == el3
                                           select el1).Count();

                        int ElemCount12 = (from el1 in UniqueElementList
                                           from el2 in Node1.ElementList
                                           from el3 in Node2.ElementList
                                           where el1 == el2 && el1 == el3
                                           select el1).Count();


                        if (Node0.Code != 0 && Node1.Code != 0)
                        {
                            if (ElemCount01 == 1)
                            {
                                ForwardVector.Add(Node0.ID.ToString() + "," + Node1.ID.ToString(), new Vector()
                                {
                                    StartNode = Node0, EndNode = Node1
                                });
                                BackwardVector.Add(Node1.ID.ToString() + "," + Node0.ID.ToString(), new Vector()
                                {
                                    StartNode = Node1, EndNode = Node0
                                });
                            }
                        }
                        if (Node0.Code != 0 && Node2.Code != 0)
                        {
                            if (ElemCount02 == 1)
                            {
                                ForwardVector.Add(Node0.ID.ToString() + "," + Node2.ID.ToString(), new Vector()
                                {
                                    StartNode = Node0, EndNode = Node2
                                });
                                BackwardVector.Add(Node2.ID.ToString() + "," + Node0.ID.ToString(), new Vector()
                                {
                                    StartNode = Node2, EndNode = Node0
                                });
                            }
                        }
                        if (Node1.Code != 0 && Node2.Code != 0)
                        {
                            if (ElemCount12 == 1)
                            {
                                ForwardVector.Add(Node1.ID.ToString() + "," + Node2.ID.ToString(), new Vector()
                                {
                                    StartNode = Node1, EndNode = Node2
                                });
                                BackwardVector.Add(Node2.ID.ToString() + "," + Node1.ID.ToString(), new Vector()
                                {
                                    StartNode = Node2, EndNode = Node1
                                });
                            }
                        }
                    }
                    else if (el.Type == 25 || el.Type == 33)
                    {
                        Node0 = el.NodeList[0];
                        Node1 = el.NodeList[1];
                        Node2 = el.NodeList[2];
                        Node3 = el.NodeList[3];

                        int ElemCount01 = (from el1 in UniqueElementList
                                           from el2 in Node0.ElementList
                                           from el3 in Node1.ElementList
                                           where el1 == el2 && el1 == el3
                                           select el1).Count();

                        int ElemCount03 = (from el1 in UniqueElementList
                                           from el2 in Node0.ElementList
                                           from el3 in Node3.ElementList
                                           where el1 == el2 && el1 == el3
                                           select el1).Count();

                        int ElemCount12 = (from el1 in UniqueElementList
                                           from el2 in Node1.ElementList
                                           from el3 in Node2.ElementList
                                           where el1 == el2 && el1 == el3
                                           select el1).Count();

                        int ElemCount23 = (from el1 in UniqueElementList
                                           from el2 in Node2.ElementList
                                           from el3 in Node3.ElementList
                                           where el1 == el2 && el1 == el3
                                           select el1).Count();


                        if (Node0.Code != 0 && Node1.Code != 0)
                        {
                            if (ElemCount01 == 1)
                            {
                                ForwardVector.Add(Node0.ID.ToString() + "," + Node1.ID.ToString(), new Vector()
                                {
                                    StartNode = Node0, EndNode = Node1
                                });
                                BackwardVector.Add(Node1.ID.ToString() + "," + Node0.ID.ToString(), new Vector()
                                {
                                    StartNode = Node1, EndNode = Node0
                                });
                            }
                        }
                        if (Node0.Code != 0 && Node3.Code != 0)
                        {
                            if (ElemCount03 == 1)
                            {
                                ForwardVector.Add(Node0.ID.ToString() + "," + Node3.ID.ToString(), new Vector()
                                {
                                    StartNode = Node0, EndNode = Node3
                                });
                                BackwardVector.Add(Node3.ID.ToString() + "," + Node0.ID.ToString(), new Vector()
                                {
                                    StartNode = Node3, EndNode = Node0
                                });
                            }
                        }
                        if (Node1.Code != 0 && Node2.Code != 0)
                        {
                            if (ElemCount12 == 1)
                            {
                                ForwardVector.Add(Node1.ID.ToString() + "," + Node2.ID.ToString(), new Vector()
                                {
                                    StartNode = Node1, EndNode = Node2
                                });
                                BackwardVector.Add(Node2.ID.ToString() + "," + Node1.ID.ToString(), new Vector()
                                {
                                    StartNode = Node2, EndNode = Node1
                                });
                            }
                        }
                        if (Node2.Code != 0 && Node3.Code != 0)
                        {
                            if (ElemCount23 == 1)
                            {
                                ForwardVector.Add(Node2.ID.ToString() + "," + Node3.ID.ToString(), new Vector()
                                {
                                    StartNode = Node2, EndNode = Node3
                                });
                                BackwardVector.Add(Node3.ID.ToString() + "," + Node2.ID.ToString(), new Vector()
                                {
                                    StartNode = Node3, EndNode = Node2
                                });
                            }
                        }
                    }
                    else
                    {
                        ErrorMessage = string.Format(CSSPDHIRes.ElementTypeIsOtherThan_Its_, "21, 25, 32, 33", el.Type.ToString());
                        OnCSSPDHIChanged(new CSSPDHIEventArgs(new CSSPDHIMessage("Error", -1, false, ErrorMessage)));
                        contourPolygonList.Add(new ContourPolygon()
                        {
                            Error = ErrorMessage
                        });
                        return(false);
                    }
                }

                //_TaskRunnerBaseService.SendPercentToDB(_TaskRunnerBaseService._BWObj.appTaskModel.AppTaskID, 40);

                bool MoreStudyAreaLine = true;
                int  PolygonCount      = 0;
                //MapInfoService mapInfoService = new MapInfoService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
                while (MoreStudyAreaLine)
                {
                    PolygonCount += 1;

                    List <Node> FinalContourNodeList = new List <Node>();
                    Vector      LastVector           = new Vector();
                    LastVector = ForwardVector.First().Value;
                    FinalContourNodeList.Add(LastVector.StartNode);
                    FinalContourNodeList.Add(LastVector.EndNode);
                    ForwardVector.Remove(LastVector.StartNode.ID.ToString() + "," + LastVector.EndNode.ID.ToString());
                    BackwardVector.Remove(LastVector.EndNode.ID.ToString() + "," + LastVector.StartNode.ID.ToString());
                    bool PolygonCompleted = false;
                    while (!PolygonCompleted)
                    {
                        List <string> KeyStrList = (from k in ForwardVector.Keys
                                                    where k.StartsWith(LastVector.EndNode.ID.ToString() + ",") &&
                                                    !k.EndsWith("," + LastVector.StartNode.ID.ToString())
                                                    select k).ToList <string>();

                        if (KeyStrList.Count != 1)
                        {
                            KeyStrList = (from k in BackwardVector.Keys
                                          where k.StartsWith(LastVector.EndNode.ID.ToString() + ",") &&
                                          !k.EndsWith("," + LastVector.StartNode.ID.ToString())
                                          select k).ToList <string>();

                            if (KeyStrList.Count != 1)
                            {
                                PolygonCompleted = true;
                                break;
                            }
                            else
                            {
                                LastVector = BackwardVector[KeyStrList[0]];
                                BackwardVector.Remove(LastVector.StartNode.ID.ToString() + "," + LastVector.EndNode.ID.ToString());
                                ForwardVector.Remove(LastVector.EndNode.ID.ToString() + "," + LastVector.StartNode.ID.ToString());
                            }
                        }
                        else
                        {
                            LastVector = ForwardVector[KeyStrList[0]];
                            ForwardVector.Remove(LastVector.StartNode.ID.ToString() + "," + LastVector.EndNode.ID.ToString());
                            BackwardVector.Remove(LastVector.EndNode.ID.ToString() + "," + LastVector.StartNode.ID.ToString());
                        }
                        FinalContourNodeList.Add(LastVector.EndNode);
                        if (FinalContourNodeList[FinalContourNodeList.Count - 1] == FinalContourNodeList[0])
                        {
                            PolygonCompleted = true;
                        }
                    }

                    double Area = CalculateAreaOfPolygon(FinalContourNodeList);
                    if (Area < 0)
                    {
                        FinalContourNodeList.Reverse();
                        Area = CalculateAreaOfPolygon(FinalContourNodeList);
                    }

                    FinalContourNodeList.Add(FinalContourNodeList[0]);

                    ContourPolygon contourLine = new ContourPolygon()
                    {
                    };
                    contourLine.ContourNodeList = FinalContourNodeList;
                    contourLine.ContourValue    = 0;
                    contourPolygonList.Add(contourLine);

                    if (ForwardVector.Count == 0)
                    {
                        MoreStudyAreaLine = false;
                    }
                }
            }

            return(true);
        }
示例#9
0
 public static SMeshData SCreate(DfsuFile dfsu)
 {
     return(new SMeshData(dfsu.Projection.WKTString, dfsu.NodeIds, dfsu.X, dfsu.Y, dfsu.Z.ToDoubleArray(), dfsu.Code, dfsu.ElementIds, dfsu.ElementType, dfsu.ElementTable.ToZeroBased()));
 }
示例#10
0
        /// <summary>
        /// Interpolate values from <paramref name="sourceFilename"/> to mesh
        /// defined by <paramref name="targetMeshFilename"/>, and store it in
        /// <paramref name="targetFilename"/>
        /// </summary>
        /// <param name="sourceFilename">Source data for interpolation</param>
        /// <param name="targetMeshFilename">Target mesh to interpolate to. Can be a mesh or dfsu file</param>
        /// <param name="targetFilename">File to store interpolated data to</param>
        public static void Interpolate(string sourceFilename, string targetMeshFilename, string targetFilename)
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();

            DfsuFile sourceDfsu = DfsFileFactory.DfsuFileOpen(sourceFilename);

            DfsuBuilder builder = DfsuBuilder.Create(DfsuFileType.Dfsu2D);

            DfsuBuildGeometry(targetMeshFilename, builder);
            builder.SetTimeInfo(sourceDfsu.StartDateTime, sourceDfsu.TimeStepInSeconds);

            // Add dynamic items, copying from source
            foreach (IDfsSimpleDynamicItemInfo itemInfo in sourceDfsu.ItemInfo)
            {
                builder.AddDynamicItem(itemInfo.Name, itemInfo.Quantity);
            }

            DfsuFile targetDfsu = builder.CreateFile(targetFilename);

            watch.Stop();
            Console.Out.WriteLine("Create File : " + watch.Elapsed.TotalSeconds);
            watch.Reset();
            watch.Start();


            SMeshData sourceMesh = Create(sourceDfsu);
            SMeshData targetMesh = Create(targetDfsu);

            sourceMesh.BuildDerivedData();


            watch.Stop();
            Console.Out.WriteLine("Build mesh  : " + watch.Elapsed.TotalSeconds);
            watch.Reset();
            watch.Start();

            MeshInterpolator2D interpolator = new MeshInterpolator2D(sourceMesh, MeshValueType.Elements)
            {
                DeleteValue      = sourceDfsu.DeleteValueFloat,
                DeleteValueFloat = sourceDfsu.DeleteValueFloat,
                //AllowExtrapolation = true,
            };

            interpolator.SetTarget(targetMesh, MeshValueType.Elements);

            watch.Stop();
            Console.Out.WriteLine("Interpolator: " + watch.Elapsed.TotalSeconds);
            watch.Reset();
            watch.Start();

            // Temporary, interpolated target-data
            float[] targetData = new float[targetDfsu.NumberOfElements];

            // Add data for all item-timesteps, copying from source, interpolating
            IDfsItemData <float> sourceData;

            while (null != (sourceData = sourceDfsu.ReadItemTimeStepNext() as IDfsItemData <float>))
            {
                interpolator.InterpolateElmtToTarget(sourceData.Data, targetData);
                targetDfsu.WriteItemTimeStepNext(sourceData.Time, targetData);
            }
            watch.Stop();
            Console.Out.WriteLine("Interpolate : " + watch.Elapsed.TotalSeconds);
            watch.Reset();

            sourceDfsu.Close();
            targetDfsu.Close();
        }
示例#11
0
        /// <summary>
        /// Example on how to extract dfs0 data from a 2D dfsu file for certain elements. All items
        /// from dfsu file are extracted.
        /// </summary>
        /// <param name="dfsuFileNamePath">Name, including path, of 2D dfsu file</param>
        /// <param name="elmtsIndices">Indices of elements to extract data from</param>
        /// <param name="useStream">Use stream when writing dfs0 files - then more than 400 files can be created simultaneously</param>
        public static void ExtractDfs0FromDfsu(string dfsuFileNamePath, IList <int> elmtsIndices, bool useStream)
        {
            // If not using stream approach, at most 400 elements at a time can be processed.
            // There is a limit on how many files you can have open at the same time using
            // the standard approach. It will fail in a nasty way, if the maximum number of
            // file handles are exceeded. This is not an issue when using .NET streams.
            if (!useStream && elmtsIndices.Count > 400)
            {
                throw new ArgumentException("At most 400 elements at a time");
            }

            // Open source dfsu file
            IDfsuFile source;
            Stream    stream = null;

            if (useStream)
            {
                stream = new FileStream(dfsuFileNamePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                source = DfsuFile.Open(stream);
            }
            else
            {
                source = DfsuFile.Open(dfsuFileNamePath);
            }

            // Figure out "basic" dfs0 file name
            string dfsuFilename     = Path.GetFileNameWithoutExtension(dfsuFileNamePath);
            string path             = Path.GetDirectoryName(dfsuFileNamePath);
            string dfs0BaseFilename = Path.Combine(path, "test_" + dfsuFilename + "-");

            // Factory for creating dfs objects
            DfsFactory factory = new DfsFactory();

            // Create a dfs0 file for each element in elmtsIndices
            DfsFile[] dfs0Files   = new DfsFile[elmtsIndices.Count];
            Stream[]  dfs0Streams = new Stream [elmtsIndices.Count];
            double    timeSpan    = source.TimeStepInSeconds * source.NumberOfTimeSteps;

            for (int k = 0; k < elmtsIndices.Count; k++)
            {
                // Index of element to create dfs0 for
                int elmtsIndex = elmtsIndices[k];

                // Calculate element center coordinates, to be stored in dfs0 items.
                // Stored as float in dfs0, hence possible loss of precision...
                float x = 0, y = 0, z = 0;
                int[] nodeNumbers = source.ElementTable[elmtsIndex];
                for (int i = 0; i < nodeNumbers.Length; i++)
                {
                    int nodeIndex = nodeNumbers[i] - 1; // from number to index
                    x += (float)source.X[nodeIndex];
                    y += (float)source.Y[nodeIndex];
                    z += source.Z[nodeIndex];
                }
                x /= nodeNumbers.Length;
                y /= nodeNumbers.Length;
                z /= nodeNumbers.Length;

                // Start building dfs0 file header
                DfsBuilder builder = DfsBuilder.Create("fileTitle", "appTitle", 1);
                builder.SetDataType(1); // standard dfs0 value
                builder.SetGeographicalProjection(source.Projection);
                builder.SetTemporalAxis(factory.CreateTemporalEqCalendarAxis(eumUnit.eumUsec, source.StartDateTime, 0, source.TimeStepInSeconds));

                // Add all dynamic items from dfsu file to dfs0 file
                for (int j = 0; j < source.ItemInfo.Count; j++)
                {
                    IDfsSimpleDynamicItemInfo sourceItem  = source.ItemInfo[j];
                    DfsDynamicItemBuilder     itemBuilder = builder.CreateDynamicItemBuilder();
                    itemBuilder.Set(sourceItem.Name, sourceItem.Quantity, sourceItem.DataType);
                    itemBuilder.SetAxis(factory.CreateAxisEqD0());
                    itemBuilder.SetValueType(sourceItem.ValueType);
                    itemBuilder.SetReferenceCoordinates(x, y, z); // optional
                    builder.AddDynamicItem(itemBuilder.GetDynamicItemInfo());
                }


                // Create and get file, store them in dfs0s array
                string dfs0Filename = dfs0BaseFilename + (elmtsIndex).ToString("000000") + ".dfs0";
                if (useStream)
                {
                    // Create file using C# streams - necessary to provie number of time steps and timespan of data
                    builder.SetNumberOfTimeSteps(source.NumberOfTimeSteps);
                    builder.SetTimeInfo(0, timeSpan);
                    Stream dfs0FileStream = new FileStream(dfs0Filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                    builder.CreateStream(dfs0FileStream);
                    dfs0Streams[k] = dfs0FileStream;
                }
                else
                {
                    // Create file in the ordinary way. Will include statistics (of delete values etc).
                    builder.CreateFile(dfs0Filename);
                }
                dfs0Files[k] = builder.GetFile();
            }

            // For performance, use predefined itemdata objects when reading data from dfsu
            IDfsItemData <float>[] dfsuItemDatas = new IDfsItemData <float> [source.ItemInfo.Count];
            for (int j = 0; j < source.ItemInfo.Count; j++)
            {
                dfsuItemDatas[j] = (IDfsItemData <float>)source.ItemInfo[j].CreateEmptyItemData();
            }

            // Read data from dfsu and store in dfs0
            float[] dfs0Data = new float[1];
            for (int i = 0; i < source.NumberOfTimeSteps; i++)
            {
                for (int j = 0; j < source.ItemInfo.Count; j++)
                {
                    // Read data from dfsu
                    IDfsItemData <float> dfsuItemData = dfsuItemDatas[j];
                    bool    ok     = source.ReadItemTimeStep(dfsuItemData, i);
                    float[] floats = dfsuItemData.Data;

                    // write data to dfs0's
                    for (int k = 0; k < elmtsIndices.Count; k++)
                    {
                        int elmtsIndex = elmtsIndices[k];
                        dfs0Data[0] = floats[elmtsIndex];
                        dfs0Files[k].WriteItemTimeStepNext(0, dfs0Data);
                    }
                }
            }

            // Close dfsu files
            source.Close();
            if (stream != null)
            {
                stream.Close();
            }
            // Close all dfs0 files
            for (int k = 0; k < elmtsIndices.Count; k++)
            {
                dfs0Files[k].Close();
                if (dfs0Streams[k] != null)
                {
                    dfs0Streams[k].Close();
                }
            }
        }
示例#12
0
        /// <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();
        }
示例#13
0
 public static MeshData Create(DfsuFile dfsu)
 {
     return(MeshData.CreateMesh(dfsu.Projection.WKTString, dfsu.NodeIds, dfsu.X, dfsu.Y, dfsu.Z.ToDoubleArray(), dfsu.Code, dfsu.ElementIds, dfsu.ElementType, dfsu.ElementTable));
 }
示例#14
0
        /// <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 bool GenerateHTMLMikeScenario_MikeScenarioParametersAtOnePointXLSX()
        {
            string NotUsed    = "";
            bool   ErrorInDoc = false;

            string Lat = "";
            string Lng = "";

            List <string> ParamValueList = Parameters.Split("|||".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();

            Lat = GetParameters("Lat", ParamValueList);
            Lng = GetParameters("Lng", ParamValueList);

            DfsuFile            dfsuFileHydrodynamic = null;
            DfsuFile            dfsuFileTransport    = null;
            List <ElementLayer> elementLayerList     = new List <ElementLayer>();
            List <Element>      elementList          = new List <Element>();
            List <Node>         nodeList             = new List <Node>();
            List <NodeLayer>    topNodeLayerList     = new List <NodeLayer>();
            List <NodeLayer>    bottomNodeLayerList  = new List <NodeLayer>();

            dfsuFileHydrodynamic = GetHydrodynamicDfsuFile();
            if (dfsuFileHydrodynamic == null)
            {
                if (_TaskRunnerBaseService._BWObj.TextLanguageList.Count == 0)
                {
                    NotUsed = string.Format(TaskRunnerServiceRes.Error_WhileCreating_Document_, "GetHydrodynamicDfsuFile", "XLSX", fi.FullName);
                    _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat3List("Error_WhileCreating_Document_", "GetHydrodynamicDfsuFile", "XLSX", fi.FullName);
                }
                return(false);
            }

            dfsuFileTransport = GetTransportDfsuFile();
            if (dfsuFileTransport == null)
            {
                if (_TaskRunnerBaseService._BWObj.TextLanguageList.Count == 0)
                {
                    NotUsed = string.Format(TaskRunnerServiceRes.Error_WhileCreating_Document_, "GetTransportDfsuFile", "XLSX", fi.FullName);
                    _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat3List("Error_WhileCreating_Document_", "GetTransportDfsuFile", "XLSX", fi.FullName);
                }
                return(false);
            }

            if (!FillRequiredList(dfsuFileTransport, elementList, elementLayerList, nodeList, topNodeLayerList, bottomNodeLayerList))
            {
                if (_TaskRunnerBaseService._BWObj.TextLanguageList.Count == 0)
                {
                    NotUsed = string.Format(TaskRunnerServiceRes.Error_WhileCreating_Document_, "FillRequiredList", "XLSX", fi.FullName);
                    _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat3List("Error_WhileCreating_Document_", "FillRequiredList", "XLSX", fi.FullName);
                }
                return(false);
            }

            Node node = new Node();

            if (Thread.CurrentThread.CurrentCulture.Name == "fr-CA")
            {
                node.X = float.Parse(Lng.Replace(".", ","));
                node.Y = float.Parse(Lat.Replace(".", ","));
            }
            else
            {
                node.X = float.Parse(Lng);
                node.Y = float.Parse(Lat);
            }

            List <Node> NodeList = new List <Node>()
            {
                node
            };
            List <ElementLayer> SelectedElementLayerList = GetElementSurrondingEachPoint(elementLayerList, NodeList);

            if (_TaskRunnerBaseService._BWObj.TextLanguageList.Count > 0)
            {
                return(false);
            }

            if (SelectedElementLayerList.Count == 0)
            {
                NotUsed = string.Format(TaskRunnerServiceRes.Error_WhileCreating_Document_, "FillRequiredList", "XLSX", fi.FullName);
                _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat3List("Error_WhileCreating_Document_", "FillRequiredList", "XLSX", fi.FullName);
                return(false);
            }

            if (_TaskRunnerBaseService._BWObj.TextLanguageList.Count > 0)
            {
                return(false);
            }

            if (!GetTopHTML())
            {
                return(false);
            }

            if (!WriteHTMLParameterContent(sb, dfsuFileHydrodynamic, dfsuFileTransport, elementLayerList, topNodeLayerList, bottomNodeLayerList, SelectedElementLayerList, node))
            {
                ErrorInDoc = true;
            }

            if (!GetBottomHTML())
            {
                return(false);
            }

            dfsuFileHydrodynamic.Close();
            dfsuFileTransport.Close();

            if (ErrorInDoc)
            {
                NotUsed = string.Format(TaskRunnerServiceRes.ErrorOccuredWhileCreating_Document_, "XLSX", fi.FullName);
                _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat2List("ErrorOccuredWhileCreating_Document_", "XLSX", fi.FullName);
                return(false);
            }
            return(true);
        }
        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
            }
        }
示例#17
0
        /// <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();
        }
示例#18
0
        /// <summary>
        /// Find element (index) for a specified coordinate
        /// <para>
        /// The method assumes that the OresundHD.dfsu test file
        /// is the input file.
        /// </para>
        /// </summary>
        /// <param name="filename">path and name of OresundHD.dfsu test file</param>
        public static void FindElementForCoordinate(string filename)
        {
            IDfsuFile file = DfsuFile.Open(filename);

            double[] X = file.X;
            double[] Y = file.Y;

            // Coordinate to search for
            double xc = 346381;
            double yc = 6153637;

            // Loop over all elements - linear search, which may be slow!
            // If to find element for a large number of coordinates and if especially the
            // file has many elements, then a search tree procedure should be used to
            // optimize the searching performance.
            int elmt = -1; // result of search

            for (int i = 0; i < file.NumberOfElements; i++)
            {
                // Take out nodes for element
                int[] nodes = file.ElementTable[i];

                // Loop over all faces in element. The coordinate (x,y) is
                // inside an element if the coordinate is "left of" all faces,
                // when travelling faces counter-clockwise

                bool isInside = true;
                for (int j = 0; j < nodes.Length; j++)
                {
                    // face start/end node indices
                    int a = nodes[j] - 1;
                    int b = nodes[(j + 1) % nodes.Length] - 1;

                    // Assuming face is A->B and coordinate is C, then "left of" test:
                    // (B-A) X (C-A) > 0
                    // where X is the cross product
                    double cross = (X[b] - X[a]) * (yc - Y[a]) - (Y[b] - Y[a]) * (xc - X[a]);
                    if (cross < 0)
                    {
                        // (xc, yc) is "right of", hence not inside, skip to next element
                        isInside = false;
                        break;
                    }
                }
                if (isInside)
                {
                    // All "left of" tests succeded, element found!
                    elmt = i;
                    break;
                }
            }

            if (elmt >= 0)
            {
                Console.Out.WriteLine("Found     element index: = {0}", elmt);
                Console.Out.WriteLine("(xc,yc) = ({0},{1})", xc, yc);
                int[] resNodes = file.ElementTable[elmt];
                for (int j = 0; j < resNodes.Length; j++)
                {
                    int node = resNodes[j] - 1;
                    Console.Out.WriteLine("(x,y)   = ({0},{1})", X[node], Y[node]);
                }
            }

            file.Close();
        }
示例#19
0
        /// <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();
        }
示例#20
0
        /// <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();
        }
        private bool WriteHTMLParameterContent(StringBuilder sbHTML, DfsuFile dfsuFileHydrodynamic, DfsuFile dfsuFileTransport, List <ElementLayer> elementLayerList, List <NodeLayer> topNodeLayerList, List <NodeLayer> bottomNodeLayerList, List <ElementLayer> SelectedElementLayerList, Node node)
        {
            MapInfoService mapInfoService = new MapInfoService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);

            string NotUsed = "";

            int ItemUVelocity   = 0;
            int ItemVVelocity   = 0;
            int ItemSalinity    = 0;
            int ItemTemperature = 0;
            int ItemWaterDepth  = 0;

            if (SelectedElementLayerList.Count == 0)
            {
                NotUsed = string.Format(TaskRunnerServiceRes.Error_WhileCreating_Document_, "FillRequiredList", "XLSX", fi.FullName);
                _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat3List("Error_WhileCreating_Document_", "FillRequiredList", "XLSX", fi.FullName);
                return(false);
            }

            sb.AppendLine($@"<h2>Parameters output at Latitude: {node.Y} Longitude: {node.X}</h2>");

            // getting the ItemNumber
            foreach (IDfsSimpleDynamicItemInfo dfsDyInfo in dfsuFileTransport.ItemInfo)
            {
                if (dfsDyInfo.Quantity.Item == eumItem.eumIuVelocity)
                {
                    ItemUVelocity = dfsDyInfo.ItemNumber;
                }
                if (dfsDyInfo.Quantity.Item == eumItem.eumIvVelocity)
                {
                    ItemVVelocity = dfsDyInfo.ItemNumber;
                }
            }

            if (ItemUVelocity == 0 || ItemVVelocity == 0)
            {
                NotUsed = string.Format(TaskRunnerServiceRes.CouldNotFind_, TaskRunnerServiceRes.Parameters);
                _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("CouldNotFind_", TaskRunnerServiceRes.Parameters);
                return(false);
            }

            foreach (IDfsSimpleDynamicItemInfo dfsDyInfo in dfsuFileHydrodynamic.ItemInfo)
            {
                if (dfsDyInfo.Quantity.Item == eumItem.eumISalinity)
                {
                    ItemSalinity = dfsDyInfo.ItemNumber;
                }
                if (dfsDyInfo.Quantity.Item == eumItem.eumITemperature)
                {
                    ItemTemperature = dfsDyInfo.ItemNumber;
                }
                if (dfsDyInfo.Quantity.Item == eumItem.eumIWaterDepth)
                {
                    ItemWaterDepth = dfsDyInfo.ItemNumber;
                }
            }

            if (ItemUVelocity == 0 || ItemVVelocity == 0)
            {
                NotUsed = string.Format(TaskRunnerServiceRes.CouldNotFind_, TaskRunnerServiceRes.Parameters);
                _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("CouldNotFind_", TaskRunnerServiceRes.Parameters);
                return(false);
            }

            int CountLayer = (dfsuFileTransport.NumberOfSigmaLayers == 0 ? 1 : dfsuFileTransport.NumberOfSigmaLayers);

            for (int Layer = 1; Layer <= CountLayer; Layer++)
            {
                sb.AppendLine($@"<h2>Layer: {Layer}</h2>");

                sbHTML.AppendLine(@"<table>");
                sbHTML.AppendLine(@"<thead>");
                sbHTML.AppendLine(@"<tr>");
                sbHTML.AppendLine(@"<th>StartTime</th>");
                sbHTML.AppendLine(@"<th>EndTime</th>");
                sbHTML.AppendLine(@"<th>UVelocity</th>");
                sbHTML.AppendLine(@"<th>VVelocity</th>");
                sbHTML.AppendLine(@"<th>CurrentVelocity</th>");
                sbHTML.AppendLine(@"<th>CurrentDirection</th>");
                //sbHTML.AppendLine(@"<th>Salinity</th>");
                //sbHTML.AppendLine(@"<th>Temperature</th>");
                sbHTML.AppendLine(@"<th>WaterDepth</th>");
                sbHTML.AppendLine(@"</tr>");
                sbHTML.AppendLine(@"</thead>");
                sbHTML.AppendLine(@"<tbody>");

                int vCount = 0;
                for (int timeStep = 0; timeStep < dfsuFileTransport.NumberOfTimeSteps; timeStep++)
                {
                    if (vCount % 10 == 0)
                    {
                        _TaskRunnerBaseService.SendPercentToDB(_TaskRunnerBaseService._BWObj.appTaskModel.AppTaskID, (int)((float)(vCount / dfsuFileTransport.NumberOfTimeSteps) * 100.0f));
                    }

                    sbHTML.AppendLine(@"<tr>");
                    sbHTML.AppendLine($@"<td>{dfsuFileTransport.StartDateTime.AddSeconds(vCount * dfsuFileTransport.TimeStepInSeconds).ToString("yyyy-MM-dd HH:mm:ss")}</td>");
                    sbHTML.AppendLine($@"<td>{dfsuFileTransport.StartDateTime.AddSeconds((vCount + 1) * dfsuFileTransport.TimeStepInSeconds).ToString("yyyy-MM-dd HH:mm:ss")}</td>");

                    float[] UvelocityList = (float[])dfsuFileTransport.ReadItemTimeStep(ItemUVelocity, timeStep).Data;
                    float[] VvelocityList = (float[])dfsuFileTransport.ReadItemTimeStep(ItemVVelocity, timeStep).Data;

                    ElementLayer el = SelectedElementLayerList.Where(c => c.Layer == Layer).Take(1).FirstOrDefault();

                    float UV = UvelocityList[el.Element.ID - 1];
                    float VV = VvelocityList[el.Element.ID - 1];

                    double VectorVal          = Math.Sqrt((UV * UV) + (VV * VV));
                    double VectorDir          = 0.0D;
                    double VectorDirCartesian = Math.Acos(Math.Abs(UV / VectorVal)) * mapInfoService.r2d;

                    if (VectorDirCartesian <= 360 && VectorDirCartesian >= 0)
                    {
                        // everything is ok
                    }
                    else
                    {
                        VectorDirCartesian = 0.0D;
                    }

                    if (UV >= 0 && VV >= 0)
                    {
                        VectorDir = 90 - VectorDirCartesian;
                    }
                    else if (UV < 0 && VV >= 0)
                    {
                        VectorDir          = 270 + VectorDirCartesian;
                        VectorDirCartesian = 180 - VectorDirCartesian;
                    }
                    else if (UV >= 0 && VV < 0)
                    {
                        VectorDir          = 90 + VectorDirCartesian;
                        VectorDirCartesian = 360 - VectorDirCartesian;
                    }
                    else if (UV < 0 && VV < 0)
                    {
                        VectorDir          = 270 - VectorDirCartesian;
                        VectorDirCartesian = 180 + VectorDirCartesian;
                    }

                    //string SalinityText = "Salinity";
                    //if (ItemSalinity != 0)
                    //{
                    //    float[] SalinityList = (float[])dfsuFileHydrodynamic.ReadItemTimeStep(ItemSalinity, timeStep).Data;

                    //    SalinityText = SalinityList[el.Element.ID - 1].ToString();
                    //}

                    //string TemperatureText = "Temperature";
                    //if (ItemTemperature != 0)
                    //{
                    //    float[] TemperatureList = (float[])dfsuFileHydrodynamic.ReadItemTimeStep(ItemTemperature, timeStep).Data;

                    //    TemperatureText = TemperatureList[el.Element.ID - 1].ToString();
                    //}

                    string WaterDepthText = "WaterDepth";
                    if (ItemWaterDepth != 0)
                    {
                        float[] TotalWaterDepthList = (float[])dfsuFileHydrodynamic.ReadItemTimeStep(ItemWaterDepth, timeStep).Data;

                        WaterDepthText = TotalWaterDepthList[el.Element.ID - 1].ToString();
                    }


                    sbHTML.AppendLine($@"<td>{UV}</td>");
                    sbHTML.AppendLine($@"<td>{VV}</td>");
                    sbHTML.AppendLine($@"<td>{VectorVal}</td>");
                    sbHTML.AppendLine($@"<td>{VectorDirCartesian}</td>");
                    //sbHTML.AppendLine($@"<td>{SalinityText}</td>");
                    //sbHTML.AppendLine($@"<td>{TemperatureText}</td>");
                    sbHTML.AppendLine($@"<td>{WaterDepthText}</td>");
                    sbHTML.AppendLine(@"</tr>");

                    vCount += 1;
                }

                sbHTML.AppendLine(@"</tbody>");
                sbHTML.AppendLine(@"</table>");
            }

            return(true);
        }
示例#22
0
        public void FillElementListAndNodeList(List <Element> ElementList, List <Node> NodeList)
        {
            DfsuFile dfsuFile = DfsuFile.Open(fi.FullName);

            try
            {
                for (int i = 0; i < dfsuFile.NumberOfNodes; i++)
                {
                    Node n = new Node()
                    {
                        Code            = dfsuFile.Code[i],
                        ID              = dfsuFile.NodeIds[i],
                        X               = (float)dfsuFile.X[i],
                        Y               = (float)dfsuFile.Y[i],
                        Z               = dfsuFile.Z[i],
                        Value           = 0,
                        ConnectNodeList = new List <Node>(),
                        ElementList     = new List <Element>()
                    };
                    NodeList.Add(n);
                }

                for (int i = 0; i < dfsuFile.NumberOfElements; i++)
                {
                    Element el = new Element()
                    {
                        ID          = dfsuFile.ElementIds[i],
                        Type        = dfsuFile.ElementType[i],
                        Value       = 0,
                        NodeList    = new List <Node>(),
                        NumbOfNodes = 0
                    };
                    ElementList.Add(el);
                }

                for (int i = 0; i < dfsuFile.NumberOfElements; i++)
                {
                    int CountNode = 0;
                    for (int j = 0; j < dfsuFile.ElementTable[i].Count(); j++)
                    {
                        CountNode += 1;
                        ElementList[i].NodeList.Add(NodeList[dfsuFile.ElementTable[i][j] - 1]);
                        if (!NodeList[dfsuFile.ElementTable[i][j] - 1].ElementList.Contains(ElementList[i]))
                        {
                            NodeList[dfsuFile.ElementTable[i][j] - 1].ElementList.Add(ElementList[i]);
                        }
                        for (int k = 0; k < dfsuFile.ElementTable[i].Count(); k++)
                        {
                            if (k != j)
                            {
                                if (!NodeList[dfsuFile.ElementTable[i][j] - 1].ConnectNodeList.Contains(NodeList[dfsuFile.ElementTable[i][k] - 1]))
                                {
                                    NodeList[dfsuFile.ElementTable[i][j] - 1].ConnectNodeList.Add(NodeList[dfsuFile.ElementTable[i][k] - 1]);
                                }
                            }
                        }
                    }
                    ElementList[i].NumbOfNodes = CountNode;
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                dfsuFile.Close();
            }
        }
示例#23
0
        public void FillElementLayerList_Test()
        {
            //AppTaskID TVItemID    TVItemID2 AppTaskCommand  AppTaskStatus PercentCompleted    Parameters Language    StartDateTime_UTC EndDateTime_UTC EstimatedLength_second RemainingTime_second    LastUpdateDate_UTC LastUpdateContactTVItemID
            //10371	336990	336990	19	2	1	|||TVItemID,336925|||ReportTypeID,30|||ContourValues,14 88|||	1	2018-02-12 14:25:06.863	NULL NULL    NULL	2018-02-12 14:25:07.663	2
            foreach (LanguageEnum LanguageRequest in new List <LanguageEnum>()
            {
                LanguageEnum.en, LanguageEnum.fr
            })
            {
                SetupTest(LanguageRequest);

                int    MikeScenarioTVItemID = 336990;
                int    ReportTypeID         = 30;
                string ContourValues        = "14 88";
                int    Year = 2017;

                FileInfo        fi              = new FileInfo(@"C:\Users\leblancc\Desktop\TestHTML\FillElementLayerList_" + LanguageRequest.ToString() + ".KML");
                StringBuilder   sbKML           = new StringBuilder();
                string          Parameters      = $"|||TVItemID,{ MikeScenarioTVItemID }|||ReportTypeID,{ ReportTypeID }|||CoutourValues,{ ContourValues }|||";
                ReportTypeModel reportTypeModel = _ReportTypeService.GetReportTypeModelWithReportTypeIDDB(ReportTypeID);

                AppTaskModel appTaskModel = new AppTaskModel()
                {
                    AppTaskID                 = 100000,
                    TVItemID                  = MikeScenarioTVItemID,
                    TVItemID2                 = MikeScenarioTVItemID,
                    AppTaskCommand            = AppTaskCommandEnum.CreateDocumentFromParameters,
                    AppTaskStatus             = AppTaskStatusEnum.Created,
                    PercentCompleted          = 1,
                    Parameters                = Parameters,
                    Language                  = LanguageRequest,
                    StartDateTime_UTC         = DateTime.Now,
                    EndDateTime_UTC           = null,
                    EstimatedLength_second    = null,
                    RemainingTime_second      = null,
                    LastUpdateDate_UTC        = DateTime.Now,
                    LastUpdateContactTVItemID = 2, // Charles LeBlanc
                };

                appTaskModel.AppTaskStatus = AppTaskStatusEnum.Running;

                BWObj bwObj = new BWObj()
                {
                    Index            = 1,
                    appTaskModel     = appTaskModel,
                    appTaskCommand   = appTaskModel.AppTaskCommand,
                    TextLanguageList = new List <TextLanguage>(),
                    bw = new BackgroundWorker(),
                };

                TaskRunnerBaseService taskRunnerBaseService = new TaskRunnerBaseService(new List <BWObj>()
                {
                    bwObj
                });

                taskRunnerBaseService._BWObj = bwObj;
                ParametersService parameterService = new ParametersService(taskRunnerBaseService);
                parameterService.fi              = fi;
                parameterService.sb              = sbKML;
                parameterService.Parameters      = Parameters;
                parameterService.reportTypeModel = reportTypeModel;
                parameterService.TVItemID        = MikeScenarioTVItemID;
                parameterService.Year            = Year;

                DfsuFile            dfsuFile            = null;
                List <Element>      elementList         = new List <Element>();
                List <ElementLayer> elementLayerList    = new List <ElementLayer>();
                List <NodeLayer>    topNodeLayerList    = new List <NodeLayer>();
                List <NodeLayer>    bottomNodeLayerList = new List <NodeLayer>();
                List <Node>         nodeList            = new List <Node>();

                dfsuFile = parameterService.GetTransportDfsuFile();
                Assert.IsNotNull(dfsuFile);
                Assert.AreEqual(0, taskRunnerBaseService._BWObj.TextLanguageList.Count);

                StringBuilder sbTemp  = new StringBuilder();
                bool          retBool = parameterService.FillRequiredList(dfsuFile, elementList, elementLayerList, nodeList, topNodeLayerList, bottomNodeLayerList);
                Assert.AreEqual(true, retBool);
                Assert.AreEqual(15829, nodeList.Count);
                Assert.AreEqual(22340, elementLayerList.Count);
                Assert.AreEqual(22340, elementList.Count);

                try
                {
                    dfsuFile.Close();
                }
                catch (Exception)
                {
                    // nothing
                }

                break;
            }
        }
示例#24
0
        /// <summary>
        /// Example of plotting dfsu file data, water levels with a velocity vector overlay.
        /// </summary>
        public static void DfsuTest(bool makeBmp)
        {
            DHI.Chart.Map.Chart.Init();

            // File to load
            string   pathName = Path.Combine(UnitTestHelper.TestDataRoot, @"OresundHD.dfsu");
            DfsuFile dfsu     = DfsFileFactory.DfsuFileOpen(pathName);

            // FemVolGridData is data for the water levels, a value in the center of each element, used for coloring
            FemVolGridData data = new FemVolGridData();

            data.CreateNodesAndElements(dfsu.NumberOfNodes, dfsu.NumberOfElements, dfsu.X, dfsu.Y, dfsu.Z, dfsu.ElementTable);

            // FemVolVectorData is data for the vector overlay
            FemVolVectorData uvData = new FemVolVectorData();

            uvData.CreateNodesAndElements(dfsu.NumberOfNodes, dfsu.NumberOfElements, dfsu.X, dfsu.Y, dfsu.Z, dfsu.ElementTable);
            uvData.CreateUV();
            uvData.CreateStructuredElements(50, 100);

            // Create chart
            DHI.Chart.Map.Chart chart = new DHI.Chart.Map.Chart(1024, 1024);

            // Add overlay that plots the water levels
            FemVolGridOverlay overlay = new FemVolGridOverlay();

            overlay.SetGridData(data);
            overlay.EnableNiceValue = true;
            overlay.CreateAutoScaledRainbowPalette();
            overlay.EnableIsoline = true;
            overlay.ColoringType  = MapOverlay.EColoringType.ContinuousColoring;
            overlay.SetFeathering(true, 0.5f);
            overlay.EnableIsolineLabel = true;
            overlay.SetLineColor(MapOverlay.ELineType.Isoline, Color.LawnGreen);
            //overlay.DrawElementNumbers = true;
            chart.AddOverlay(overlay);

            // Add overlay that plots the vectors
            FemVolVectorOverlay uvOverlay = new FemVolVectorOverlay();

            uvOverlay.SetVectorData(uvData);
            uvOverlay.SetScale(VectorOverlay.EScaleType.UserDefinedScale, 2000.0);
            uvOverlay.EnableAutomaticScaling = false;
            uvOverlay.VectorStyle            = FemVolVectorOverlay.EVectorStyle.StructuredVectors;
            uvOverlay.LineColor = Color.BlueViolet;
            uvOverlay.SetLineThickness(VectorOverlay.EVectorType.NormalVector, 0.4f);
            chart.AddOverlay(uvOverlay);

            // Select rectangle to plot, by default the full data area
            MzRectangle wrect = new MzRectangle();

            data.GetDataArea(wrect);

            // Here you may limit the area to be plotted
            //wrect.X0 = wrect.X0 + 20000;
            //wrect.Y0 = wrect.Y0 + 20000;
            //wrect.X1 = wrect.X0 + 30000;
            //wrect.Y1 = wrect.Y0 + 30000;

            chart.SetDataArea(wrect);
            chart.SetView(wrect);

            string pngFilepath = null;

            // Loop over the first 4 time steps
            for (int i = 0; i < 4; i++)
            {
                // Set water level data
                data.SetElementValues(dfsu.ReadItemTimeStep(1, i).Data as float[]);
                // Set u-v vector data
                uvData.SetUV(dfsu.ReadItemTimeStep(2, i).Data as float[], dfsu.ReadItemTimeStep(3, i).Data as float[]);
                // When running with autoscaled palette, an update is required.
                overlay.UpdatePalette();
                // Draw to bitmap
                Bitmap bmp = chart.DrawBitmap();

                // Save bitmap to disc
                if (makeBmp)
                {
                    pngFilepath = Path.Combine(UnitTestHelper.TestDataRoot, string.Format(@"test_oresundHD.1.{0}.png", i));
                    bmp.Save(pngFilepath);
                }
            }

            chart.Dispose();

            if (makeBmp && pngFilepath != null) // Show last bitmap saved
            {
                System.Diagnostics.Process.Start(pngFilepath);
            }
        }