static void Main(string[] args)
        {
            string filename = @"..\..\TestData\OresundHD.dfs2";

            // Load the file
            Dfs2File dfs2File = DfsFileFactory.Dfs2FileOpen(filename);

            // Print out some info on the spatial axis
            IDfsAxisEqD2 axis = (IDfsAxisEqD2)dfs2File.SpatialAxis;

            Console.Out.WriteLine("Size of grid    : {0} x {1}", axis.XCount, axis.YCount);
            Console.Out.WriteLine("Projection      : " + dfs2File.FileInfo.Projection.WKTString);

            // Print out some info of the first item
            IDfsSimpleDynamicItemInfo dynamicItemInfo = dfs2File.ItemInfo[0];

            Console.Out.WriteLine("Item 1 name     : " + dynamicItemInfo.Name);
            Console.Out.WriteLine("Item 1 datatype : " + dynamicItemInfo.DataType);

            // This iterates through the first 5 time steps and print out the value in the grid
            // at index (3,4) for the first item
            for (int i = 0; i < 5; i++)
            {
                IDfsItemData2D <float> data2D = (IDfsItemData2D <float>)dfs2File.ReadItemTimeStep(1, i);
                float value = data2D[3, 4];
                Console.Out.WriteLine("Value in time step {0} = {1}", i, value);
            }
        }
Beispiel #2
0
        /// <summary>
        /// Update DFS2 bathymetry, lowering bathymetry with 5.61 meters everywhere,
        /// taking land value into account.
        /// <para>
        /// The method assumes that the OresundBathy900.dfs2 test file
        /// (or preferably a copy of it) is the input file.
        /// </para>
        /// </summary>
        /// <param name="bathyFilename">Path and name of OresundBathy900.dfs2 test file</param>
        public static void ModifyDfs2Bathymetry(string bathyFilename)
        {
            // Open file
            Dfs2File dfs2 = DfsFileFactory.Dfs2FileOpenEdit(bathyFilename);

            // Second custom block (index 1) contains the M21_MISC values,
            // where the 4th (index 3) is the land value
            float landValue = (float)dfs2.FileInfo.CustomBlocks[1][3];

            // Read bathymetry data
            IDfsItemData2D <float> bathyData = (IDfsItemData2D <float>)dfs2.ReadItemTimeStepNext();

            // Modify bathymetry data
            for (int i = 0; i < bathyData.Data.Length; i++)
            {
                if (bathyData.Data[i] != landValue)
                {
                    bathyData.Data[i] -= 5.61f;
                }
            }

            // Write back bathymetry data
            dfs2.WriteItemTimeStep(1, 0, 0, bathyData.Data);
            dfs2.Close();
        }
Beispiel #3
0
        public void Run(string inputfile1, string inputfile2, double fac1, double fac2, string outputfile)
        {
            if (!File.Exists(inputfile1))
            {
                throw new Exception(String.Format("First input file {0} does not exist!", inputfile1));
            }
            if (!File.Exists(inputfile2))
            {
                throw new Exception(String.Format("Second input file {0} does not exist!", inputfile1));
            }

            try
            {
                _dfsInput1 = DfsFileFactory.DfsGenericOpen(inputfile1);
                _dfsInput2 = DfsFileFactory.DfsGenericOpen(inputfile2);
                _VerifyInputSimilarity(_dfsInput1, _dfsInput2);
                _dfsOutput = DfsOutput.CreateFromTemplate(_dfsInput1, outputfile);

                ProcessAllTimeSteps(_dfsOutput, (float)fac1, (float)fac2);
            }
            finally
            {
                _dfsInput1.Close();
                _dfsInput2.Close();
                _dfsOutput.Close();
            }
        }
Beispiel #4
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);
        }
Beispiel #5
0
        public void PercentileTest()
        {
            DFSBase target = DfsFileFactory.OpenFile(@"..\..\..\TestData\novomr4_indv_dfs0_ud1.dfs0");

            double[] Percentiles = new double[] { 0.1, 0.5, 0.9 };
            DFSBase  outf        = DfsFileFactory.CreateFile(@"..\..\..\TestData\novomr4_indv_dfs0_ud1_percentiles.dfs0", Percentiles.Count());

            outf.CopyFromTemplate(target);
            int Item = 1; // TODO: Initialize to an appropriate value

            int k = 0;

            //Create the items
            foreach (double j in Percentiles)
            {
                outf.Items[k].EumItem = target.Items[Item - 1].EumItem;
                outf.Items[k].EumUnit = target.Items[Item - 1].EumUnit;
                outf.Items[k].Name    = j.ToString() + " Percentile";
                k++;
            }

            int[] TSteps = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            target.Percentile(Item, TSteps, outf, Percentiles);
            outf.Dispose();
            target.Dispose();

            DFS0 df = new DFS0(@"..\..\..\TestData\novomr4_indv_dfs0_ud1_percentiles.dfs0");

            Assert.AreEqual(25952, df.GetData(0, 1), 0.5);
            Assert.AreEqual(27294, df.GetData(0, 2), 0.5);
            Assert.AreEqual(33422, df.GetData(0, 3), 0.5);

            df.Dispose();
        }
Beispiel #6
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);
        }
Beispiel #7
0
        /// <summary>
        /// Example of how to resample a dfs2 file in x/y space
        /// </summary>
        /// <param name="inputFilename">Path and name of the file to resample</param>
        /// <param name="outputFilename">Path and name of the new file to create</param>
        /// <param name="xCount">Number of cells in x-direction</param>
        /// <param name="yCount">Number of cells in y-direction</param>
        public static void Resample(string inputFilename, string outputFilename, int xCount, int yCount)
        {
            // Load dfs2 file
            Dfs2File     dfs2File = DfsFileFactory.Dfs2FileOpen(inputFilename);
            IDfsAxisEqD2 axis     = (IDfsAxisEqD2)dfs2File.SpatialAxis;

            // Create reprojector
            Dfs2Reprojector reproj = new Dfs2Reprojector(dfs2File, outputFilename);

            // scale change
            double dxScale = (double)axis.XCount / xCount;
            double dyScale = (double)axis.YCount / yCount;

            // Calculate new lon/lat origin - center of lower left cell
            Cartography cart = new Cartography(dfs2File.FileInfo.Projection.WKTString, dfs2File.FileInfo.Projection.Longitude, dfs2File.FileInfo.Projection.Latitude, dfs2File.FileInfo.Projection.Orientation);
            // Change in center of lower left cell
            double dxOrigin = 0.5 * axis.Dx * (dxScale - 1);
            double dyOrigin = 0.5 * axis.Dy * (dyScale - 1);

            cart.Xy2Geo(dxOrigin, dyOrigin, out double lonOrigin, out double latOrigin);

            // Set new target
            reproj.SetTarget(dfs2File.FileInfo.Projection.WKTString, lonOrigin, latOrigin, dfs2File.FileInfo.Projection.Orientation, xCount, 0, axis.Dx * dxScale, yCount, 0, axis.Dy * dyScale);
            reproj.Interpolate = true;
            // Create new file
            reproj.Process();
        }
Beispiel #8
0
        /// <summary>
        /// Example of how to append data from one file to another. It is assumed that:
        /// <list type="bullet">
        /// <item>The files has identical dynamic and static items</item>
        /// <item>The last time step of the target file is equal to the first
        ///       timestep of the sourceFile, and therefor the first time step
        ///       from the source file is not added to the target file</item>
        /// </list>
        /// <para>
        /// This example uses the generic DFS functionality, and will work for any type
        /// of DFS file.
        /// </para>
        /// </summary>
        public static void AppendToFile(string targetFile, string sourceFile)
        {
            // Open target for appending and source for reading
            IDfsFile target = DfsFileFactory.DfsGenericOpenAppend(targetFile);
            IDfsFile source = DfsFileFactory.DfsGenericOpen(sourceFile);

            // Time of last time step of file, in the time unit of the time axis.
            // This is sufficient as long as TimeAxis.StartTimeOffset equals in
            // source and target file (it is zero for most files)
            double targetEndTime = target.FileInfo.TimeAxis.TimeSpan();

            // Do not add initial time step 0 of source to target file,
            // so go directly to time step 1 in source
            source.FindTimeStep(1);

            // Copy over data
            IDfsItemData sourceData2;

            while (null != (sourceData2 = source.ReadItemTimeStepNext()))
            {
                target.WriteItemTimeStepNext(targetEndTime + sourceData2.Time, sourceData2.Data);
            }

            // Close the files
            target.Close();
            source.Close();
        }
Beispiel #9
0
    /// <summary>
    /// Example of reading 1D axis from dfs1 file
    /// </summary>
    public void Read1DAxis(string filename)
    {
      // Open the file as a dfs1 file
      Dfs1File dfs1File = DfsFileFactory.Dfs1FileOpen(filename);

      switch (dfs1File.SpatialAxis.AxisType)
      {
        case SpaceAxisType.EqD1:
          // Spatial axis for this file is a 1D equidistant axis
          IDfsAxisEqD1 axisEqD1 = ((IDfsAxisEqD1)dfs1File.SpatialAxis);
          Console.Out.WriteLine("x0    = " + axisEqD1.X0);
          Console.Out.WriteLine("dx    = " + axisEqD1.Dx);
          Console.Out.WriteLine("count = " + axisEqD1.XCount);
          break;
        case SpaceAxisType.NeqD1:
          // Spatial axis for this file is a 1D non-equidistant axis, 
          // which is similar to a curve-linear 1D axis.
          IDfsAxisNeqD1 axisNeqD1 = ((IDfsAxisNeqD1)dfs1File.SpatialAxis);
          for (int i = 0; i < axisNeqD1.Coordinates.Length; i++)
          {
            Coords coord = axisNeqD1.Coordinates[i];
            Console.Out.WriteLine("{0,10} {1,10} {2,10}", coord.X, coord.Y, coord.Z);
          }
          break;
      }

      dfs1File.Close();
    }
Beispiel #10
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();
            }
        }
Beispiel #11
0
        /// <summary>
        /// Update time series with a constant change factor, adding 10% to all values
        /// </summary>
        /// <param name="dfs0File">Path and name of file, e.g. Rain_instantaneous.dfs0 test file</param>
        /// <param name="dfs0FileNew">Name of new updated file</param>
        public static void UpdateDfs0Data(string dfs0File, string dfs0FileNew)
        {
            // Open source file
            IDfsFile source = DfsFileFactory.DfsGenericOpen(dfs0File);

            // Create a new file with updated rain values
            DfsBuilder builder = DfsBuilder.Create(source.FileInfo.FileTitle + "Updated", "MIKE SDK", 13);

            // Copy header info from source file to new file
            builder.SetDataType(source.FileInfo.DataType);
            builder.SetGeographicalProjection(source.FileInfo.Projection);
            builder.SetTemporalAxis(source.FileInfo.TimeAxis);

            // Copy over first item from source file to new file
            builder.AddDynamicItem(source.ItemInfo[0]);

            // Create the new file
            builder.CreateFile(dfs0FileNew);
            IDfsFile target = builder.GetFile();

            // Loop over all timesteps
            for (int i = 0; i < source.FileInfo.TimeAxis.NumberOfTimeSteps; i++)
            {
                // Read time step for item, and extract value
                IDfsItemData <double> itemData = (IDfsItemData <double>)source.ReadItemTimeStep(1, i);
                double value = itemData.Data[0];
                // Write new value to target, adding 10% to its value
                target.WriteItemTimeStepNext(itemData.Time, new double[] { value * 1.1 });
            }

            source.Close();
            target.Close();
        }
Beispiel #12
0
        public void Run(string inputfile, double fac, double constant, string outputfile)
        {
            if (!File.Exists(inputfile))
            {
                throw new Exception(String.Format("Input file {0} does not exist!", inputfile));
            }

            var ext1 = Path.GetExtension(inputfile).ToLower();
            var ext2 = Path.GetExtension(outputfile).ToLower();

            if (ext1 != ext2)
            {
                throw new Exception("Input and output files must have same extension!");
            }

            try
            {
                _dfsInput  = DfsFileFactory.DfsGenericOpen(inputfile);
                _dfsOutput = DfsOutput.CreateFromTemplate(_dfsInput, outputfile);

                ProcessAllTimeSteps(_dfsOutput, (float)fac, (float)constant);
            }
            finally
            {
                _dfsInput.Close();
                _dfsOutput.Close();
            }
        }
Beispiel #13
0
        public static DfsFile CreateFromTemplate(string dfsTemplate, string outputfile)
        {
            var iDfsTemplate = DfsFileFactory.DfsGenericOpen(dfsTemplate);
            var outputDfs    = CreateFromTemplate(iDfsTemplate, outputfile);

            iDfsTemplate.Close();
            return(outputDfs);
        }
Beispiel #14
0
        public void SetStartDateTest()
        {
            System.IO.File.Copy(@"..\..\..\TestData\dmi_kgrid_55hr_temp_fcast.dfs2", @"..\..\..\TestData\dmi_kgrid_55hr_temp_fcast_copy.dfs2", true);

            HydroNumerics.MikeSheTools.DFS.DFSBase target = DfsFileFactory.OpenFile(@"..\..\..\TestData\dmi_kgrid_55hr_temp_fcast_copy.dfs2");
            target.TimeOfFirstTimestep = new DateTime(2010, 1, 1);
            target.Dispose();
        }
Beispiel #15
0
        private void _OpenFiles()
        {
            if (!File.Exists(InputFile))
            {
                throw new Exception(String.Format("Input file {0} does not exist!", InputFile));
            }

            _inputDfs = DfsFileFactory.DfsGenericOpen(InputFile);
        }
Beispiel #16
0
        /// <summary>
        /// Does simple factor math on all or selected time steps and items in a dfs-file.
        /// </summary>
        /// <param name="OperationData"></param>
        public static void FactorMath(XElement OperationData)
        {
            DFS3.MaxEntriesInBuffer = 1;
            DFS2.MaxEntriesInBuffer = 1;

            string File1 = OperationData.Element("DFSFileName").Value;

            //DFSOutputFileName is optional. If it exists the input file is copied to this filename
            var outfile = OperationData.Element("DFSOutputFileName");

            if (outfile != null && outfile.Value != "")
            {
                if (File1.ToLower() != outfile.Value.ToLower())
                {
                    File.Copy(File1, outfile.Value, true);
                }
                File1 = OperationData.Element("DFSOutputFileName").Value;
            }

            DFSBase dfs = DfsFileFactory.OpenFile(File1);

            int[] Items     = ParseString(OperationData.Element("Items").Value, 1, dfs.Items.Count());
            int[] TimeSteps = ParseString(OperationData.Element("TimeSteps").Value, 0, dfs.NumberOfTimeSteps - 1);

            string Operator = OperationData.Element("MathOperation").Value;
            double Factor   = double.Parse(OperationData.Element("Factor").Value);

            foreach (int j in TimeSteps)
            {
                foreach (int i in Items)
                {
                    switch (Operator)
                    {
                    case "+":
                        dfs.AddToItemTimeStep(j, i, Factor);
                        break;

                    case "-":
                        dfs.AddToItemTimeStep(j, i, -Factor);
                        break;

                    case "*":
                        dfs.MultiplyItemTimeStep(j, i, Factor);
                        break;

                    case "/":
                        dfs.MultiplyItemTimeStep(j, i, 1.0 / Factor);
                        break;

                    default:
                        break;
                    }
                }
            }
            dfs.Dispose();
        }
Beispiel #17
0
        public double GetWebTideStepsInMinutes()
        {
            IDfsFile dfs0File = DfsFileFactory.DfsGenericOpen(fi.FullName);

            DfsBuilder dfsNewFile = DfsBuilder.Create(dfs0File.FileInfo.FileTitle, dfs0File.FileInfo.ApplicationTitle, dfs0File.FileInfo.ApplicationVersion);

            double WebTideStepsInMinutes = ((double)((IDfsEqCalendarAxis)((dfs0File.FileInfo).TimeAxis)).TimeStep / 60);

            return(WebTideStepsInMinutes);
        }
Beispiel #18
0
        /// <summary>
        /// Example on how to modify a custom block.
        /// <para>
        /// The method assumes that a dfs2 file with the "M21_Misc" custom block, alike
        /// the OresundHD.dfs2 test file, is the input file.
        /// </para>
        /// </summary>
        /// <param name="filename">path and name of dfs2 test file</param>
        public static void CustomBlockModify(string filename)
        {
            IDfsFile dfsFile = DfsFileFactory.DfsGenericOpenEdit(filename);

            IDfsFileInfo    fileInfo    = dfsFile.FileInfo;
            IDfsCustomBlock customBlock = fileInfo.CustomBlocks[0];

            customBlock[3] = 25;

            dfsFile.Close();
        }
Beispiel #19
0
        /// <summary>
        /// Example of how to get from a geographical coordinate to an (j,k) index
        /// in the 2D grid. It also shows how to get the closest cell value and how
        /// to perform bilinear interpolation.
        /// <para>
        /// The method assumes that the OresundHD.dfs2 test file is the input file.
        /// </para>
        /// </summary>
        /// <param name="filename">Path and name of OresundHD.dfs2 test file</param>
        public static void GetjkIndexForGeoCoordinate(string filename)
        {
            Dfs2File file = DfsFileFactory.Dfs2FileOpen(filename);

            // The spatial axis is a EqD2 axis
            IDfsAxisEqD2 axis = (IDfsAxisEqD2)file.SpatialAxis;

            // Data for first time step
            IDfsItemData2D <float> data = (IDfsItemData2D <float>)file.ReadItemTimeStep(1, 0);

            // Get the projection and create a cartography object
            IDfsProjection projection = file.FileInfo.Projection;

            DHI.Projections.Cartography cart = new DHI.Projections.Cartography(projection.WKTString, projection.Longitude, projection.Latitude, projection.Orientation);

            // Coordinates just south of Amager
            double lon = 12.59;
            double lat = 55.54;

            // Get the (x,y) grid coordinates
            double x;
            double y;

            cart.Geo2Xy(lon, lat, out x, out y);

            Console.Out.WriteLine("Grid coordinates          (x,y) = ({0:0.000},{1:0.000})", x, y);
            Console.Out.WriteLine("Relative grid coordinates (x,y) = ({0:0.000},{1:0.000})", x / axis.Dx, y / axis.Dy);

            // Calculate the cell indices of the lon-lat coordinate.
            // The cell extents from its center and +/- 1/2 dx and dy
            // in each direction
            int j = (int)(x / axis.Dx + 0.5); // 30
            int k = (int)(y / axis.Dy + 0.5); // 27

            Console.Out.WriteLine("Value in cell ({0},{1})           = {2}", j, k, data[j, k]);

            // If you want to interpolate between the values, calculate
            // the (j,k) indices of lower left corner and do bilinear interpolation.
            // This procedure does not take delete values into account!!!
            j = (int)(x / axis.Dx);                 // 30
            k = (int)(y / axis.Dy);                 // 26

            double xFrac = (x % axis.Dx) / axis.Dx; // fraction of j+1 value
            double yFrac = (y % axis.Dy) / axis.Dy; // fraction of k+1 value

            double vk   = (1 - xFrac) * data[j, k] + xFrac * data[j + 1, k];
            double vkp1 = (1 - xFrac) * data[j, k + 1] + xFrac * data[j + 1, k + 1];
            double v    = (1 - yFrac) * vk + yFrac * vkp1;

            Console.Out.WriteLine("Interpolated value              = {0}", v);

            file.Close();
        }
        static void Main(string[] args)
        {
            int[] nodeNumber = new int[] { 899, 2686, 2856, 2866, 2331, 3806, 2231, 3831 };

            IDfsFile     resFile     = DfsFileFactory.DfsGenericOpenEdit(@"E:\FFWS\Model\MIKEHYDRO\GBM_MIKEHYDRO.mhydro - Result Files\RiverBasin_GBM.dfs0");
            IDfsFileInfo resfileInfo = resFile.FileInfo;
            int          noTimeSteps = resfileInfo.TimeAxis.NumberOfTimeSteps;

            DateTime[] date      = resFile.FileInfo.TimeAxis.GetDateTimes();
            DateTime   startDate = date[0];

            double[] timeSpan = new double[noTimeSteps];
            for (int j = 0; j < noTimeSteps; j++)
            {
                timeSpan[j] = resFile.ReadItemTimeStep(899, j).Time;
            }
            foreach (int element in nodeNumber)
            {
                IDfsItemData <float> data;
                float[] QSimvalues = new float[noTimeSteps];

                for (int j = 0; j < noTimeSteps; j++)
                {
                    data          = (IDfsItemData <float>)resFile.ReadItemTimeStep(element, j);
                    QSimvalues[j] = Convert.ToSingle(data.Data[0]);
                }

                DfsFactory factory     = new DfsFactory();
                string     filename    = @"E:\FFWS\Model\BrahmaputraHD\Boundary\" + element + ".dfs0";
                DfsBuilder filecreator = DfsBuilder.Create(element.ToString(), element.ToString(), 2014);
                filecreator.SetDataType(1);
                filecreator.SetGeographicalProjection(factory.CreateProjectionUndefined());
                filecreator.SetTemporalAxis(factory.CreateTemporalNonEqCalendarAxis(eumUnit.eumUsec, new DateTime(startDate.Year, startDate.Month, startDate.Day, startDate.Hour, startDate.Minute, startDate.Second)));
                filecreator.SetItemStatisticsType(StatType.RegularStat);
                DfsDynamicItemBuilder item = filecreator.CreateDynamicItemBuilder();
                item.Set(element.ToString(), eumQuantity.Create(eumItem.eumIDischarge, eumUnit.eumUm3PerSec), DfsSimpleType.Float);
                item.SetValueType(DataValueType.Instantaneous);
                item.SetAxis(factory.CreateAxisEqD0());
                item.SetReferenceCoordinates(1f, 2f, 3f);
                filecreator.AddDynamicItem(item.GetDynamicItemInfo());

                filecreator.CreateFile(filename);
                IDfsFile     file     = filecreator.GetFile();
                IDfsFileInfo fileinfo = file.FileInfo;

                for (int j = 0; j < noTimeSteps; j++)
                {
                    file.WriteItemTimeStepNext(timeSpan[j], new float[] { QSimvalues[j] });
                }
                file.Close();
            }
        }
Beispiel #21
0
        /// <summary>
        /// Example of how to update item axis in a dfs2 file.
        /// <para>
        /// The method assumes that the OresundHD.dfs2 test file
        /// (or preferably a copy of it) is the input file.
        /// </para>
        /// </summary>
        /// <param name="filename">Path and name of OresundHD.dfs2 test file</param>
        public static void ModifyDfs2ItemAxis(string filename)
        {
            Dfs2File file = DfsFileFactory.Dfs2FileOpenEdit(filename);

            IDfsAxisEqD2 axisEqD2 = ((IDfsAxisEqD2)file.SpatialAxis);

            axisEqD2.X0 = 55;
            axisEqD2.Dx = 905;
            axisEqD2.Y0 = -55;
            axisEqD2.Dy = 915;

            file.Close();
        }
Beispiel #22
0
        /// <summary>
        /// Example of how to update item information in a dfs2 file.
        /// <para>
        /// The method assumes that the Landuse.dfs2 test file
        /// (or preferably a copy of it) is the input file.
        /// </para>
        /// </summary>
        /// <param name="filename">Path and name of Landuse.dfs2 test file</param>
        public static void ModifyDfs2ItemInfo(string filename)
        {
            // Open the file for editing
            IDfs2File file = DfsFileFactory.Dfs2FileOpenEdit(filename);

            // Original name is "Landuse" (7 characters), "GroundUse" is truncated to "GroundU"
            file.ItemInfo[0].Name = "GroundUse";
            // Provide a new quantity (updating the item and unit of the quantity directly does not work!)
            file.ItemInfo[0].Quantity = new eumQuantity(eumItem.eumIAreaFraction, eumUnit.eumUPerCent);

            // done
            file.Close();
        }
Beispiel #23
0
        /// <summary>
        /// Updates the temporal axis of a file with an <see cref="IDfsEqCalendarAxis"/>
        /// type time axis.
        /// <para>
        /// The method will work on a file like the OresundHD.dfs2 test file, which has
        /// an <see cref="IDfsEqCalendarAxis"/> type time axis.
        /// </para>
        /// </summary>
        /// <param name="filename">path and name of test file</param>
        public static void TemporalAxisModify(string filename)
        {
            IDfsFile           dfsFile  = DfsFileFactory.DfsGenericOpenEdit(filename);
            IDfsEqCalendarAxis timeAxis = (IDfsEqCalendarAxis)dfsFile.FileInfo.TimeAxis;

            // Update values
            timeAxis.FirstTimeStepIndex = 3;
            timeAxis.StartTimeOffset    = 6;
            timeAxis.StartDateTime      = new DateTime(2009, 2, 2, 21, 43, 00);
            timeAxis.TimeUnit           = eumUnit.eumUminute;
            timeAxis.TimeStep           = 1;

            dfsFile.Close();
        }
Beispiel #24
0
        public void PercentileTest3()
        {
            DFSBase target = DfsFileFactory.OpenFile(@"c:\temp\KFT-SJ_inv_3DSZ.dfs3");

            double[] Percentiles = new double[] { 0.1, 0.5, 0.9 };
            DFSBase  outf        = DfsFileFactory.CreateFile(@"c:\temp\TestDataSet_percentiles_limit.dfs3", Percentiles.Count());
            DFSBase  outf2       = DfsFileFactory.CreateFile(@"c:\temp\TestDataSet_percentiles.dfs3", Percentiles.Count());

            outf.CopyFromTemplate(target);
            outf2.CopyFromTemplate(target);
            int Item = 1;

            int k = 0;

            //Create the items
            foreach (double j in Percentiles)
            {
                outf.Items[k].EumItem  = target.Items[Item - 1].EumItem;
                outf.Items[k].EumUnit  = target.Items[Item - 1].EumUnit;
                outf.Items[k].Name     = j.ToString() + " Percentile";
                outf2.Items[k].EumItem = target.Items[Item - 1].EumItem;
                outf2.Items[k].EumUnit = target.Items[Item - 1].EumUnit;
                outf2.Items[k].Name    = j.ToString() + " Percentile";
                k++;
            }


            int[] TSteps = new int[target.NumberOfTimeSteps];
            for (int i = 0; i < target.NumberOfTimeSteps; i++)
            {
                TSteps[i] = i;
            }

            Stopwatch sw = new Stopwatch();

            sw.Start();
            target.Percentile(Item, TSteps, outf, Percentiles, 300);
            sw.Stop();
            TimeSpan el = sw.Elapsed;

            sw.Reset();
            sw.Start();
            target.Percentile(Item, TSteps, outf2, Percentiles, 100);
            sw.Stop();
            TimeSpan el2 = sw.Elapsed;

            outf.Dispose();
            outf2.Dispose();
            target.Dispose();
        }
Beispiel #25
0
        public static void MonthlyStats(XElement OperationData)
        {
            string  File1      = OperationData.Element("DFSFileName").Value;
            DFSBase dfs        = DfsFileFactory.OpenFile(File1);
            var     outfile    = OperationData.Element("DFSOutputFileName").Value;
            int     itemnumber = int.Parse(OperationData.Element("Item").Value);
            DFSBase dfsout     = DfsFileFactory.CreateFile(outfile, 3);

            dfsout.CopyFromTemplate(dfs);

            dfsout.TimeOfFirstTimestep = new DateTime(dfs.TimeOfFirstTimestep.Year, dfs.TimeOfFirstTimestep.Month, 15);
            dfsout.TimeStep            = TimeSpan.FromDays(30);
            dfs.MonthAggregation(itemnumber, dfsout);
            dfsout.Dispose();
        }
        void v_SimulationFinished(object sender, EventArgs e)
        {
            Model mshe = sender as Model;
            var   dfs  = DfsFileFactory.OpenFile(mshe.Files.SZ3DFileName);

            double[] percentiles = new double[] { 0.1 };
            string   filename    = Path.Combine(mshe.Files.ResultsDirectory, "SZ3D_percentiles.dfs3");
            var      dfsout      = DfsFileFactory.CreateFile(filename, percentiles.Count());

            dfsout.CopyFromTemplate(dfs);
            dfs.Percentile(1, dfsout, percentiles, 80000000);
            dfsout.Dispose();
            DFS3 dfsout2 = new DFS3(filename);

            Console.WriteLine(dfsout2.GetData(0, 1)[10, 10, 0]);
            dfsout2.Dispose();

            RunNext(mshe);
        }
Beispiel #27
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);
            }
        }
Beispiel #28
0
        /// <summary>
        /// Updates the item info.
        /// <para>
        /// The method assumes that the OresundHD.dfs2 test file
        /// (or preferably a copy of it) is the input file.
        /// </para>
        /// </summary>
        /// <param name="filename">path and name of OresundHD.dfs2 test file</param>
        public static void DynamicItemInfoModify(string filename)
        {
            IDfsFile dfsFile = DfsFileFactory.DfsGenericOpenEdit(filename);

            IDfsDynamicItemInfo itemInfo = dfsFile.ItemInfo[2];

            // Update the values
            // old name: "Q Flux m^3/s/m". New name: "ShortD        " (padded with spaces)
            // old quantity: (eumItem.eumIFlowFlux, eumUnit.eumUm3PerSecPerM)
            // old ValueType: Instantaneous
            itemInfo.Name      = "ShortD";
            itemInfo.Quantity  = eumQuantity.Create(eumItem.eumIDischarge, eumUnit.eumUm3PerSec);
            itemInfo.ValueType = DataValueType.MeanStepBackward;

            // Old reference coordinates and orientation is -1.00000002e-35f
            itemInfo.SetReferenceCoordinates(1, 2, 3);
            itemInfo.SetOrientation(4, 5, 6);

            dfsFile.Close();
        }
Beispiel #29
0
        public void Run(string inputfile, string outputfile)
        {
            if (!File.Exists(inputfile))
            {
                throw new Exception(String.Format("Input file {0} does not exist!", inputfile));
            }

            try
            {
                _dfsInput  = DfsFileFactory.DfsGenericOpen(inputfile);
                _dfsOutput = DfsOutput.CreateFromTemplate(_dfsInput, outputfile);

                ProcessAllTimeSteps(_dfsOutput);
            }
            finally
            {
                _dfsInput.Close();
                _dfsOutput.Close();
            }
        }
Beispiel #30
0
        /// <summary>
        /// Example of how to modify data of a certain item and time
        /// step in a dfs2 file.
        /// <para>
        /// The method assumes that the Landuse.dfs2 test file
        /// (or preferably a copy of it) is the input file.
        /// </para>
        /// </summary>
        /// <param name="filename">Path and name of Landuse.dfs2 test file</param>
        public static void ModifyDfs2FileData(string filename)
        {
            // Open the file for editing
            IDfs2File file = DfsFileFactory.Dfs2FileOpenEdit(filename);

            // Load and modify data from the first item and timestep
            IDfsItemData2D data2D = file.ReadItemTimeStepNext();

            data2D[21, 61] = 7f;
            data2D[21, 62] = 6f;
            data2D[21, 63] = 5f;
            data2D[21, 64] = 4f;
            data2D[21, 65] = 3f;

            // Write modified data back
            file.WriteItemTimeStep(1, 0, data2D.Time, data2D.Data);

            // done
            file.Close();
        }