Exemplo n.º 1
0
        public static DfsFile CreateFromTemplate(IDfsFile dfsTemplate, string outputfile, int nRepeats)
        {
            IDfsFileInfo fi = dfsTemplate.FileInfo;
            //this._AnalyzeDfsInputItems(dfsTemplate.ItemInfo);
            var builder = DfsBuilder.Create(fi.FileTitle, fi.ApplicationTitle, fi.ApplicationVersion);

            CreateHeader(fi, builder);

            var isDfsu3d = _IsDfsu3d(dfsTemplate.ItemInfo);

            if (nRepeats > 1)
            {
                if (isDfsu3d)
                {
                    builder.AddDynamicItem(dfsTemplate.ItemInfo[0]);
                }

                _CreateRepeatedDynamicItems(builder, dfsTemplate.ItemInfo, nRepeats);
            }
            else
            {
                var items = Enumerable.Range(0, _NumberItems(dfsTemplate.ItemInfo)).ToList();
                CreateDynamicItems(builder, dfsTemplate.ItemInfo, items);
            }
            builder.CreateFile(outputfile);

            IDfsStaticItem staticItem;

            while ((staticItem = dfsTemplate.ReadStaticItemNext()) != null)
            {
                builder.AddStaticItem(staticItem);
            }

            return(builder.GetFile());
        }
Exemplo n.º 2
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();
        }
Exemplo n.º 3
0
        /// <summary>
        /// Bulk read the times and data for a dfs0 file, putting it all in
        /// a matrix structure.
        /// <para>
        /// First column in the result are the times, then a column for each
        /// item in the file. There are as many rows as there are timesteps.
        /// All item data are converted to doubles.
        /// </para>
        /// </summary>
        public static double[,] ReadDfs0DataDouble(IDfsFile dfs0File)
        {
            int itemCount     = dfs0File.ItemInfo.Count;
            int timestepCount = dfs0File.FileInfo.TimeAxis.NumberOfTimeSteps;

            double[,] res = new double[timestepCount, itemCount + 1];

            // Preload a set of item data
            IDfsItemData[] itemDatas = new IDfsItemData[itemCount];
            for (int j = 0; j < itemCount; j++)
            {
                itemDatas[j] = dfs0File.CreateEmptyItemData(j + 1);
            }
            dfs0File.Reset();

            for (int i = 0; i < timestepCount; i++)
            {
                for (int j = 0; j < itemCount; j++)
                {
                    IDfsItemData itemData = itemDatas[j];
                    dfs0File.ReadItemTimeStep(itemData, i);
                    // First column is time, remaining colums are data
                    if (j == 0)
                    {
                        res[i, 0] = itemData.TimeInSeconds(dfs0File.FileInfo.TimeAxis);
                    }
                    res[i, j + 1] = Convert.ToDouble(itemData.Data.GetValue(0));
                }
            }
            return(res);
        }
Exemplo n.º 4
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();
            }
        }
Exemplo n.º 5
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();
            }
        }
Exemplo n.º 6
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();
        }
Exemplo n.º 7
0
        /// <summary>
        /// Bulk read the times and data for a dfs0 file, putting it all in
        /// a matrix structure.
        /// <para>
        /// First column in the result are the times, then a column for each 
        /// item in the file. There are as many rows as there are timesteps.
        /// All item data are converted to doubles.
        /// </para>
        /// </summary>
        public static double[,] ReadDfs0DataDouble(IDfsFile dfs0File)
        {
            int itemCount = dfs0File.ItemInfo.Count;
              int timestepCount = dfs0File.FileInfo.TimeAxis.NumberOfTimeSteps;
              double[,] res = new double[timestepCount,itemCount+1];

              // Preload a set of item data
              IDfsItemData[] itemDatas = new IDfsItemData[itemCount];
              for (int j = 0; j < itemCount; j++)
              {
            itemDatas[j] = dfs0File.CreateEmptyItemData(j+1);
              }
              dfs0File.Reset();

              for (int i = 0; i < timestepCount; i++)
              {
            for (int j = 0; j < itemCount; j++)
            {
              IDfsItemData itemData = itemDatas[j];
              dfs0File.ReadItemTimeStep(itemData, i);
              // First column is time, remaining colums are data
              if (j == 0)
              {
            res[i, 0] = itemData.TimeInSeconds(dfs0File.FileInfo.TimeAxis);
              }
              res[i, j+1] = Convert.ToDouble(itemData.Data.GetValue(0));
            }
              }
              return (res);
        }
Exemplo n.º 8
0
        private void _OpenFiles()
        {
            if (!File.Exists(InputFile))
            {
                throw new Exception(String.Format("Input file {0} does not exist!", InputFile));
            }

            _inputDfs = DfsFileFactory.DfsGenericOpen(InputFile);
        }
Exemplo n.º 9
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);
        }
Exemplo n.º 10
0
    public Res11(string Res11FileName)
    {
      AbsoluteFileName = System.IO.Path.GetFullPath(Res11FileName);
      df = DHI.Generic.MikeZero.DFS.DfsFileFactory.DfsGenericOpen(AbsoluteFileName);

      //For some reason the next line gives an error on one of GEUS' XP-machine. The NumberOfTimeSteps == 0
      TimeSteps = df.FileInfo.TimeAxis.GetDateTimes();

      for (int i = 0; i < df.FileInfo.TimeAxis.NumberOfTimeSteps; i++)
      {
        TimeSteps[i] = TimeSteps[0].AddSeconds(df.ReadItemTimeStep(1, i).TimeInSeconds(df.FileInfo.TimeAxis));
      }
        int offset = 4;
      int nitems=df.ItemInfo.Count()/2;

      Points = new List<Res11Point>();
      for (int j = 0; j < nitems; j++)
      {
        string name = System.Text.Encoding.ASCII.GetString((byte[])StaticData[offset].Data).Replace("\0","");
        string topo = System.Text.Encoding.ASCII.GetString((byte[])StaticData[offset + 1].Data).Replace("\0", "");

        PointType pt = PointType.Discharge;
        int waterlevelcounter = 0;
        int dischargecounter = 0;
        int itemcounter;
        IDfsDynamicItemInfo CurrentItem;
        for (int i = 0; i < StaticData[offset + 2].ElementCount; i++)
        {
          if (pt == PointType.Discharge)
          {
            itemcounter = waterlevelcounter;
            CurrentItem = df.ItemInfo[j];
            waterlevelcounter++;
            pt = PointType.WaterLevel;
          }
          else
          {
            itemcounter = dischargecounter;
            CurrentItem = df.ItemInfo[j + nitems];
            dischargecounter++;
            pt = PointType.Discharge;
          }
          
          double chain = (double)(float)StaticData[offset + 2].Data.GetValue(i);
          double x = (double)(float)StaticData[offset + 3].Data.GetValue(i);
          double y = (double)(float)StaticData[offset + 4].Data.GetValue(i);
          Points.Add(new Res11Point(this, CurrentItem, itemcounter, chain, name, topo, x, y, pt));
        }

        int ncross = ((int[])StaticData[offset + 13].Data).Count(var => var != 0);
        offset = offset + 23 + 4 * ncross;
      }

      StaticData.Clear();
    }
Exemplo n.º 11
0
        public Res11(string Res11FileName)
        {
            AbsoluteFileName = System.IO.Path.GetFullPath(Res11FileName);
            df = DHI.Generic.MikeZero.DFS.DfsFileFactory.DfsGenericOpen(AbsoluteFileName);

            //For some reason the next line gives an error on one of GEUS' XP-machine. The NumberOfTimeSteps == 0
            TimeSteps = df.FileInfo.TimeAxis.GetDateTimes();

            for (int i = 0; i < df.FileInfo.TimeAxis.NumberOfTimeSteps; i++)
            {
                TimeSteps[i] = TimeSteps[0].AddSeconds(df.ReadItemTimeStep(1, i).TimeInSeconds(df.FileInfo.TimeAxis));
            }
            int offset = 4;
            int nitems = df.ItemInfo.Count() / 2;

            Points = new List <Res11Point>();
            for (int j = 0; j < nitems; j++)
            {
                string name = System.Text.Encoding.ASCII.GetString((byte[])StaticData[offset].Data).Replace("\0", "");
                string topo = System.Text.Encoding.ASCII.GetString((byte[])StaticData[offset + 1].Data).Replace("\0", "");

                PointType           pt = PointType.Discharge;
                int                 waterlevelcounter = 0;
                int                 dischargecounter  = 0;
                int                 itemcounter;
                IDfsDynamicItemInfo CurrentItem;
                for (int i = 0; i < StaticData[offset + 2].ElementCount; i++)
                {
                    if (pt == PointType.Discharge)
                    {
                        itemcounter = waterlevelcounter;
                        CurrentItem = df.ItemInfo[j];
                        waterlevelcounter++;
                        pt = PointType.WaterLevel;
                    }
                    else
                    {
                        itemcounter = dischargecounter;
                        CurrentItem = df.ItemInfo[j + nitems];
                        dischargecounter++;
                        pt = PointType.Discharge;
                    }

                    double chain = (double)(float)StaticData[offset + 2].Data.GetValue(i);
                    double x     = (double)(float)StaticData[offset + 3].Data.GetValue(i);
                    double y     = (double)(float)StaticData[offset + 4].Data.GetValue(i);
                    Points.Add(new Res11Point(this, CurrentItem, itemcounter, chain, name, topo, x, y, pt));
                }

                int ncross = ((int[])StaticData[offset + 13].Data).Count(var => var != 0);
                offset = offset + 23 + 4 * ncross;
            }

            StaticData.Clear();
        }
Exemplo n.º 12
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();
        }
Exemplo n.º 13
0
        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();
            }
        }
Exemplo n.º 14
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();
        }
Exemplo n.º 15
0
 public void ExtractDateTimes(DateTime dateTime1, DateTime dateTime2)
 {
     try
     {
         _OpenFiles();
         var timesteps = _GetTimeSteps(dateTime1, dateTime2);
         _outputDfs = _CreateFromTemplate(_inputDfs, OutputFile, timesteps, 1);
         _ProcessAllTimeSteps(timesteps);
     }
     finally
     {
         _inputDfs.Close();
         _outputDfs.Close();
     }
 }
Exemplo n.º 16
0
 public void ExtractTimeSteps(List <int> timesteps, int stride)
 {
     try
     {
         _OpenFiles();
         _VerifyStride(timesteps.Last(), stride);
         _outputDfs = _CreateFromTemplate(_inputDfs, OutputFile, timesteps, stride);
         _ProcessAllTimeSteps(timesteps, stride);
     }
     finally
     {
         _inputDfs.Close();
         _outputDfs.Close();
     }
 }
Exemplo n.º 17
0
 public void ExtractTimeSteps(int starttimestep, int endtimestep, int stride)
 {
     try
     {
         _OpenFiles();
         var timesteps = _GetTimeSteps(starttimestep, endtimestep);
         _outputDfs = _CreateFromTemplate(_inputDfs, OutputFile, timesteps, stride);
         _ProcessAllTimeSteps(timesteps, stride);
     }
     finally
     {
         _inputDfs.Close();
         _outputDfs.Close();
     }
 }
Exemplo n.º 18
0
        private void ProcessAllTimeSteps(IDfsFile outputDfs)
        {
            var nTimes = _dfsInput.FileInfo.TimeAxis.NumberOfTimeSteps;
            var nItems = _dfsInput.ItemInfo.Count;

            List <float[]> outdatalist = new List <float[]>();

            int timestep0 = 0;

            for (int item = 1; item <= nItems; ++item)
            {
                var indatatime = _dfsInput.ReadItemTimeStep(item, timestep0);
                var indata     = (float[])indatatime.Data;
                outdatalist.Add(indata);
            }

            // from step 1 and onwards
            for (int timestep = 1; timestep < nTimes; timestep++)
            {
                for (int item = 1; item <= nItems; ++item)
                {
                    var indatatime = _dfsInput.ReadItemTimeStep(item, timestep);
                    var indata     = (float[])indatatime.Data;

                    // sum data
                    outdatalist[item - 1] = outdatalist[item - 1].Zip(indata, (x, y) => x + y).ToArray();
                }
            }

            for (int item = 1; item <= nItems; ++item)
            {
                outdatalist[item - 1] = outdatalist[item - 1].Select(
                    x => x / Convert.ToSingle(nTimes)).ToArray();
                outputDfs.WriteItemTimeStepNext(timestep0, outdatalist[item - 1]);
            }

            // write all steps (the same)
            for (int timestep = 0; timestep < nTimes; timestep++)
            {
                for (int item = 1; item <= nItems; ++item)
                {
                    var indatatime = _dfsInput.ReadItemTimeStep(item, timestep);
                    //outputDfs.WriteItemTimeStepNext(timestep, outdatalist[item - 1]);  // indatatime.Time
                    outputDfs.WriteItemTimeStep(item, timestep, indatatime.Time, outdatalist[item - 1]);  // indatatime.Time
                }
            }
        }
Exemplo n.º 19
0
 public void ExtractItems(List <int> items)
 {
     try
     {
         _OpenFiles();
         var starttimestep = 0;
         var endtimestep   = _inputDfs.FileInfo.TimeAxis.NumberOfTimeSteps - 1;
         var stride        = 1;
         var timesteps     = _GetTimeSteps(starttimestep, endtimestep);
         _outputDfs = _CreateFromTemplate(_inputDfs, OutputFile, timesteps, stride, items);
         _ProcessAllTimeSteps(timesteps, stride, items);
     }
     finally
     {
         _inputDfs.Close();
         _outputDfs.Close();
     }
 }
Exemplo n.º 20
0
        private void ProcessAllTimeSteps(IDfsFile outputDfs)
        {
            var nTimes = _dfsInput.FileInfo.TimeAxis.NumberOfTimeSteps;
            var nItems = _dfsInput.ItemInfo.Count;

            for (int timestep = 0; timestep < nTimes; timestep++)
            {
                for (int item = 1; item <= nItems; ++item)
                {
                    var indatatime = _dfsInput.ReadItemTimeStep(item, timestep);
                    var indata     = (float[])indatatime.Data;
                    var time       = indatatime.Time;

                    //var outdata = indata.Select(r => r * fac + constant).ToArray();

                    //outputDfs.WriteItemTimeStepNext(time, outdata);
                }
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Bulk write the times and data for a dfs0 file.
        /// <para>
        /// The <paramref name="data"/> contains a column for each
        /// item in the file. There are as many rows as there are timesteps.
        /// </para>
        /// </summary>
        public static void WriteDfs0DataDouble(IDfsFile dfs0File, double[] times, double[,] data)
        {
            int itemCount = dfs0File.ItemInfo.Count;

            if (times.Length != data.GetLength(0))
            {
                throw new ArgumentException("Number of time steps does not match number of data rows");
            }

            if (itemCount != data.GetLength(1))
            {
                throw new ArgumentException("Number of items does not match number of data columns");
            }

            bool[] isFloatItem = new bool[itemCount];
            for (int j = 0; j < itemCount; j++)
            {
                isFloatItem[j] = dfs0File.ItemInfo[j].DataType == DfsSimpleType.Float;
            }

            float[]  fdata = new float[1];
            double[] ddata = new double[1];

            dfs0File.Reset();

            for (int i = 0; i < times.Length; i++)
            {
                for (int j = 0; j < itemCount; j++)
                {
                    if (isFloatItem[j])
                    {
                        fdata[0] = (float)data[i, j];
                        dfs0File.WriteItemTimeStepNext(times[i], fdata);
                    }
                    else
                    {
                        ddata[0] = data[i, j];
                        dfs0File.WriteItemTimeStepNext(times[i], ddata);
                    }
                }
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Bulk read the times and data for a dfs0 file, putting it all in
        /// a matrix structure.
        /// <para>
        /// First column in the result are the times, then a column for each
        /// item in the file. There are as many rows as there are timesteps.
        /// All item data are converted to doubles.
        /// </para>
        /// </summary>
        public static double[,] ReadDfs0DataDouble(IDfsFile dfs0File)
        {
            int itemCount     = dfs0File.ItemInfo.Count;
            int timestepCount = dfs0File.FileInfo.TimeAxis.NumberOfTimeSteps;

            double[,] res = new double[timestepCount, itemCount + 1];

            // Preload a set of item data
            IDfsItemData[] itemDatas = new IDfsItemData[itemCount];
            for (int j = 0; j < itemCount; j++)
            {
                itemDatas[j] = dfs0File.CreateEmptyItemData(j + 1);
            }
            dfs0File.Reset();

            // Check if time axis is really a time axis, or if it is a non-time axis
            eumUnit timeUnit   = dfs0File.FileInfo.TimeAxis.TimeUnit;
            bool    isTimeUnit = EUMWrapper.eumUnitsEqv((int)eumUnit.eumUsec, (int)timeUnit);

            for (int i = 0; i < timestepCount; i++)
            {
                for (int j = 0; j < itemCount; j++)
                {
                    IDfsItemData itemData = itemDatas[j];
                    dfs0File.ReadItemTimeStep(itemData, i);
                    // First column is time, remaining colums are data
                    if (j == 0)
                    {
                        if (isTimeUnit)
                        {
                            res[i, 0] = itemData.TimeInSeconds(dfs0File.FileInfo.TimeAxis);
                        }
                        else // not a time-unit, just return the value
                        {
                            res[i, 0] = itemData.Time;
                        }
                    }
                    res[i, j + 1] = Convert.ToDouble(itemData.Data.GetValue(0));
                }
            }
            return(res);
        }
Exemplo n.º 23
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();
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Updates information in the header - <see cref="IDfsFileInfo"/>.
        /// <para>
        /// The method assumes that the OresundHD.dfs2 test file
        /// (or preferably a copy of it) is the input file.
        /// </para>
        /// <para>
        /// Strings are padded with zeros, when too short, and truncated when too long.
        /// </para>
        /// </summary>
        /// <param name="filename">path and name of OresundHD.dfs2 test file</param>
        public static void FileInfoModify(string filename)
        {
            IDfsFile dfsFile = DfsFileFactory.DfsGenericOpenEdit(filename);

            IDfsFileInfo fileInfo = dfsFile.FileInfo;

            // Modify values
            fileInfo.FileTitle          = "ups";
            fileInfo.ApplicationTitle   = "Short title";
            fileInfo.ApplicationVersion = 12;
            fileInfo.DataType           = 10101;

            fileInfo.DeleteValueFloat       = -5.5e-25f;
            fileInfo.DeleteValueByte        = 7;
            fileInfo.DeleteValueDouble      = -7.7e-114;
            fileInfo.DeleteValueInt         = -123456;
            fileInfo.DeleteValueUnsignedInt = 123456;

            dfsFile.Close();
        }
Exemplo n.º 25
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();
        }
Exemplo n.º 26
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));
            }

            var ext1 = Path.GetExtension(inputfile1).ToLower();
            var ext2 = Path.GetExtension(inputfile2).ToLower();

            if (ext1 != ext2)
            {
                throw new Exception("Input files must have same extension!");
            }
            var ext_out = Path.GetExtension(outputfile).ToLower();

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

            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();
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Introductory example of how to load a dfs0 file.
        /// <para>
        /// The method assumes that the Rain_stepaccumulated.dfs0 test file
        /// is the input file.
        /// </para>
        /// </summary>
        /// <param name="filename">path and name of Rain_stepaccumulated.dfs0 test file</param>
        public static double ReadDfs0File(string filename)
        {
            // Open the file as a generic dfs file
            IDfsFile dfs0File = DfsFileFactory.DfsGenericOpen(filename);

            // Header information is contained in the IDfsFileInfo
            IDfsFileInfo fileInfo = dfs0File.FileInfo;
            int          steps    = fileInfo.TimeAxis.NumberOfTimeSteps; // 19

            // Information on each of the dynamic items, here the first one
            IDfsSimpleDynamicItemInfo dynamicItemInfo = dfs0File.ItemInfo[0];
            string        nameOfFirstDynamicItem      = dynamicItemInfo.Name;     // "Rain"
            DfsSimpleType typeOfFirstDynamicItem      = dynamicItemInfo.DataType; // Double
            ValueType     valueType = dynamicItemInfo.ValueType;                  // StepAccumulated

            // Read data of first item, third time step (items start by 1, timesteps by 0),
            IDfsItemData datag  = dfs0File.ReadItemTimeStep(1, 2);
            double       value1 = System.Convert.ToDouble(datag.Data.GetValue(0)); // 0.36
            // Assuming this is a double value, the item data object can be converted to the correct type
            IDfsItemData <double> data = (IDfsItemData <double>)datag;
            double value2 = data.Data[0];                                  // 0.36

            // This iterates through all timesteps and items in the file
            // For performance reasons it is important to iterate over time steps
            // first and items second.
            double sum = 0;

            for (int i = 0; i < steps; i++)
            {
                for (int j = 1; j <= dfs0File.ItemInfo.Count; j++)
                {
                    data = (IDfsItemData <double>)dfs0File.ReadItemTimeStep(j, i);
                    double value = data.Data[0];
                    sum += value;
                }
            }

            dfs0File.Close();
            return(sum);
        }
Exemplo n.º 28
0
        private void ProcessAllTimeSteps(IDfsFile outputDfs, float fac1, float fac2)
        {
            //int numTimes = _dfsInput1.FileInfo.TimeAxis.NumberOfTimeSteps;
            var numItems = _dfsInput1.ItemInfo.Count;

            for (int timestep = 0; timestep < _nTimes; timestep++)
            {
                for (int item = 1; item <= numItems; ++item)
                {
                    var datatime1 = _dfsInput1.ReadItemTimeStep(item, timestep);
                    var data1     = (float[])datatime1.Data;
                    var time1     = datatime1.Time;
                    var data2     = (float[])_dfsInput2.ReadItemTimeStep(item, timestep).Data;

                    data1 = data1.Select(r => r * fac1).ToArray();
                    data2 = data2.Select(r => r * fac2).ToArray();
                    var outdata = data1.Zip(data2, (x, y) => x + y).ToArray();

                    outputDfs.WriteItemTimeStepNext(time1, outdata);
                }
            }
        }
Exemplo n.º 29
0
        private DfsFile _CreateFromTemplate(IDfsFile dfsTemplate, string outputfile, IEnumerable <int> timesteps, int stride, List <int> items)
        {
            IDfsFileInfo fi = dfsTemplate.FileInfo;
            //this._AnalyzeDfsInputItems(dfsTemplate.ItemInfo);
            var builder = DfsBuilder.Create(fi.FileTitle, fi.ApplicationTitle, fi.ApplicationVersion);

            IDfsTemporalAxis timeAxis = _CorrectTimeAxis(fi.TimeAxis, timesteps.First(), stride);

            DfsOutput.CreateHeader(fi, builder, timeAxis);
            DfsOutput.CreateDynamicItems(builder, dfsTemplate.ItemInfo, items);

            builder.CreateFile(outputfile);

            IDfsStaticItem staticItem;

            while ((staticItem = dfsTemplate.ReadStaticItemNext()) != null)
            {
                builder.AddStaticItem(staticItem);
            }

            return(builder.GetFile());
        }
Exemplo n.º 30
0
        /// <summary>
        /// Find maximum value and time of maximum for a specified item in dfs0 file
        /// </summary>
        /// <param name="filename">Path and name of file, e.g. data_ndr_roese.dfs0 test file</param>
        /// <param name="itemNumber">Item number to find maximum for</param>
        public static double FindMaxValue(string filename, int itemNumber)
        {
            // Open file, using stream class
            Stream   stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            IDfsFile file   = DfsFileFactory.DfsGenericOpen(stream);
            //IDfsFile file = DfsFileFactory.DfsGenericOpen(filename);

            // Extract Start date-time of file - assuming file is equidistant-calendar axis
            IDfsEqCalendarAxis timeAxis      = (IDfsEqCalendarAxis)file.FileInfo.TimeAxis;
            DateTime           startDateTime = timeAxis.StartDateTime;

            // Empty item data, reused when calling ReadItemTimeStep
            IDfsItemData <float> itemData = (IDfsItemData <float>)file.CreateEmptyItemData(itemNumber);

            // max value and time variables
            double   maxValue       = double.MinValue;
            double   maxTimeSeconds = -1;
            DateTime maxDateTime    = DateTime.MinValue;

            // Loop over all times in file
            for (int i = 0; i < file.FileInfo.TimeAxis.NumberOfTimeSteps; i++)
            {
                // Read time step for item, and extract value
                file.ReadItemTimeStep(itemData, i);
                double value = itemData.Data[0];
                // Check if value is larger than maxValue
                if (value > maxValue)
                {
                    maxValue       = value;
                    maxTimeSeconds = itemData.TimeInSeconds(timeAxis);
                    maxDateTime    = itemData.TimeAsDateTime(timeAxis);
                }
            }
            // Report results
            Console.Out.WriteLine("Max Value      : {0} {1}", maxValue, file.ItemInfo[itemNumber - 1].Quantity.UnitAbbreviation);
            Console.Out.WriteLine("Max Value time : {0}", maxDateTime.ToString("yyyy-MM-dd HH:mm:ss"));
            return(maxValue);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Introductory example of how to load a dfs0 file with a non-time axis
        /// as the primary axis. The important part here is to NOT call
        /// the <code>data.TimeInSeconds()</code>, because that will fail.
        /// </summary>
        /// <param name="filename">path and name of Added_Mass.dfs0 test file</param>
        public static double ReadNonTimeAxisDfs0(string filename)
        {
            // Open the file as a generic dfs file
            IDfsFile dfs0File = DfsFileFactory.DfsGenericOpen(filename);

            // Header information is contained in the IDfsFileInfo
            IDfsFileInfo fileInfo = dfs0File.FileInfo;
            // The TimeAxis is not a time axis, but a regular axis
            int          steps        = fileInfo.TimeAxis.NumberOfTimeSteps; // 256
            TimeAxisType timeAxisType = fileInfo.TimeAxis.TimeAxisType;      // TimeNonEquidistant
            eumUnit      timeUnit     = fileInfo.TimeAxis.TimeUnit;          // radian-per-second

            // Information on each of the dynamic items, here the first one
            IDfsSimpleDynamicItemInfo dynamicItemInfo = dfs0File.ItemInfo[0];
            string        nameOfFirstDynamicItem      = dynamicItemInfo.Name;     // "DOF_1-1"
            DfsSimpleType typeOfFirstDynamicItem      = dynamicItemInfo.DataType; // Float
            ValueType     valueType = dynamicItemInfo.ValueType;                  // Instantaneous

            // This iterates through all timesteps and items in the file
            // For performance reasons it is important to iterate over time steps
            // first and items second.
            double sum = 0;

            for (int i = 0; i < steps; i++)
            {
                for (int j = 1; j <= dfs0File.ItemInfo.Count; j++)
                {
                    var data = (IDfsItemData <float>)dfs0File.ReadItemTimeStep(j, i);
                    // The Time axis value is not a time value but in radian-per-second.
                    double axisValue = data.Time;
                    float  value     = data.Data[0];
                    sum += value;
                }
            }

            dfs0File.Close();
            return(sum);
        }
Exemplo n.º 32
0
        private void _VerifyInputSimilarity(IDfsFile _dfsInput1, IDfsFile _dfsInput2)
        {
            // In case number of time steps does not match, take the smallest.
            _nTimes = _dfsInput1.FileInfo.TimeAxis.NumberOfTimeSteps;
            if (_nTimes > _dfsInput2.FileInfo.TimeAxis.NumberOfTimeSteps)
            {
                _nTimes = _dfsInput2.FileInfo.TimeAxis.NumberOfTimeSteps;
                Console.Out.WriteLine("Number of time steps does not match, using the smallest number");
            }

            var numItems1 = _dfsInput1.ItemInfo.Count;
            var numItems2 = _dfsInput2.ItemInfo.Count;

            if (_dfsInput1.ItemInfo.Count != _dfsInput2.ItemInfo.Count)
            {
                throw new Exception("Two input files must have same number of dynamic items!");
            }

            for (int i = 0; i < _dfsInput1.ItemInfo.Count; i++)
            {
                var itemInfo = _dfsInput1.ItemInfo[i];

                // Validate item sizes
                var itemInfo2 = _dfsInput2.ItemInfo[i];
                if (itemInfo.ElementCount != itemInfo2.ElementCount)
                {
                    throw new Exception("Dynamic items must have same size, item number " + (i + 1) +
                                        " has different sizes in the two files");
                }
                // Validate the data type, only supporting floats.
                else if (itemInfo.DataType != DfsSimpleType.Float)
                {
                    throw new Exception("Dynamic item must be float, item number " + (i + 1) + " is of type " +
                                        (itemInfo.DataType));
                }
            }
        }
Exemplo n.º 33
0
        /// <summary>
        /// Bulk write the times and data for a dfs0 file.
        /// <para>
        /// The <paramref name="data"/> contains a column for each 
        /// item in the file. There are as many rows as there are timesteps.
        /// </para>
        /// </summary>
        public static void WriteDfs0DataDouble(IDfsFile dfs0File, double[] times, double[,] data)
        {
            int itemCount = dfs0File.ItemInfo.Count;

              if (times.Length != data.GetLength(0))
            throw new ArgumentException("Number of time steps does not match number of data rows");

              if (itemCount != data.GetLength(1))
            throw new ArgumentException("Number of items does not match number of data columns");

              bool[] isFloatItem = new bool[itemCount];
              for (int j = 0; j < itemCount; j++)
              {
            isFloatItem[j] = dfs0File.ItemInfo[j].DataType == DfsSimpleType.Float;
              }

              float[] fdata = new float[1];
              double[] ddata = new double[1];

              for (int i = 0; i < times.Length; i++)
              {
            for (int j = 0; j < itemCount; j++)
            {
              if (isFloatItem[j])
              {
            fdata[0] = (float)data[i, j];
            dfs0File.WriteItemTimeStepNext(times[i], fdata);
              }
              else
              {
            ddata[0] = data[i, j];
            dfs0File.WriteItemTimeStepNext(times[i], ddata);
              }
            }
              }
        }