/// <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();
        }
Exemple #2
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());
        }
Exemple #3
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);
        }
        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();
            }
        }
Exemple #5
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());
        }
Exemple #6
0
        private void btnDFS0Fromlist_Click(object sender, EventArgs e)
        {
            if (fileName == "")
            {
                MessageBox.Show("No files have been selected for processing...\nPlease Load a file first.");
            }
            else
            {
                string[] requiredDFS0File = File.ReadAllLines((fileName.Substring(0, fileName.Length - 6) + ".txt"));
                string[] availableDFS0    = File.ReadAllLines((fileName.Substring(0, fileName.Length - 6) + "_xy.txt"));
                foreach (string element in requiredDFS0File)
                {
                    for (int i = 0; i < availableDFS0.Length; i++)
                    {
                        if (element == availableDFS0[i])
                        {
                            string itemType = element.Substring(0, 2);

                            if (itemType == "WL")
                            {
                                DfsFactory factory     = new DfsFactory();
                                string     filename    = dfs0Path + @"\" + element + ".dfs0";
                                DfsBuilder filecreator = DfsBuilder.Create(element, element, 2012);
                                filecreator.SetDataType(1);
                                filecreator.SetGeographicalProjection(factory.CreateProjectionUndefined());
                                filecreator.SetTemporalAxis(factory.CreateTemporalNonEqCalendarAxis(eumUnit.eumUsec, new DateTime(dfsDate[0].Year, dfsDate[0].Month, dfsDate[0].Day, dfsDate[0].Hour, dfsDate[0].Minute, dfsDate[0].Second)));
                                filecreator.SetItemStatisticsType(StatType.RegularStat);
                                DfsDynamicItemBuilder item = filecreator.CreateDynamicItemBuilder();
                                item.Set(element, eumQuantity.Create(eumItem.eumIWaterLevel, eumUnit.eumUmeter), 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 < dfsDate.Count; j++)
                                {
                                    file.WriteItemTimeStepNext((dfsDate[j] - dfsDate[0]).TotalSeconds, new float[] { dfsData[j, i] });
                                }
                                file.Close();
                            }
                            else if (itemType == "Q,")
                            {
                                DfsFactory factory     = new DfsFactory();
                                string     filename    = dfs0Path + @"\" + element + ".dfs0";
                                DfsBuilder filecreator = DfsBuilder.Create(element, element, 2014);
                                filecreator.SetDataType(1);
                                filecreator.SetGeographicalProjection(factory.CreateProjectionUndefined());
                                filecreator.SetTemporalAxis(factory.CreateTemporalNonEqCalendarAxis(eumUnit.eumUsec, new DateTime(dfsDate[0].Year, dfsDate[0].Month, dfsDate[0].Day, dfsDate[0].Hour, dfsDate[0].Minute, dfsDate[0].Second)));
                                filecreator.SetItemStatisticsType(StatType.RegularStat);
                                DfsDynamicItemBuilder item = filecreator.CreateDynamicItemBuilder();
                                item.Set(element, 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 < dfsDate.Count; j++)
                                {
                                    file.WriteItemTimeStepNext((dfsDate[j] - dfsDate[0]).TotalSeconds, new float[] { dfsData[j, i] });
                                }
                                file.Close();
                            }
                        }
                    }
                }
                MessageBox.Show("Result file processed suceesssfully.");
            }
        }
Exemple #7
0
        private void btnSingleDFS0_Click(object sender, EventArgs e)
        {
            try
            {
                if (fileName == "")
                {
                    MessageBox.Show("No files have been selected for processing...\nPlease Load a file first.");
                }
                else
                {
                    string itemType = comboBox1.SelectedItem.ToString().Substring(0, 2);

                    if (itemType == "WL")
                    {
                        string     element     = comboBox1.SelectedItem.ToString().Substring(0, comboBox1.SelectedItem.ToString().Length - 4);
                        DfsFactory factory     = new DfsFactory();
                        string     filename    = dfs0Path + @"\" + element + ".dfs0";
                        DfsBuilder filecreator = DfsBuilder.Create(element, element, 2012);
                        filecreator.SetDataType(1);
                        filecreator.SetGeographicalProjection(factory.CreateProjectionUndefined());
                        filecreator.SetTemporalAxis(factory.CreateTemporalNonEqCalendarAxis(eumUnit.eumUsec, new DateTime(dfsDate[0].Year, dfsDate[0].Month, dfsDate[0].Day, dfsDate[0].Hour, dfsDate[0].Minute, dfsDate[0].Second)));
                        filecreator.SetItemStatisticsType(StatType.RegularStat);
                        DfsDynamicItemBuilder item = filecreator.CreateDynamicItemBuilder();
                        item.Set(element, eumQuantity.Create(eumItem.eumIWaterLevel, eumUnit.eumUmeter), 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 < dfsDate.Count; j++)
                        {
                            file.WriteItemTimeStepNext((dfsDate[j] - dfsDate[0]).TotalSeconds, new float[] { dfsData[j, comboBox1.SelectedIndex] });
                        }
                        file.Close();
                    }
                    else if (itemType == "Q,")
                    {
                        string     element     = comboBox1.SelectedItem.ToString();
                        DfsFactory factory     = new DfsFactory();
                        string     filename    = dfs0Path + @"\" + element + ".dfs0";
                        DfsBuilder filecreator = DfsBuilder.Create(element, element, 2014);
                        filecreator.SetDataType(1);
                        filecreator.SetGeographicalProjection(factory.CreateProjectionUndefined());
                        filecreator.SetTemporalAxis(factory.CreateTemporalNonEqCalendarAxis(eumUnit.eumUsec, new DateTime(dfsDate[0].Year, dfsDate[0].Month, dfsDate[0].Day, dfsDate[0].Hour, dfsDate[0].Minute, dfsDate[0].Second)));
                        filecreator.SetItemStatisticsType(StatType.RegularStat);
                        DfsDynamicItemBuilder item = filecreator.CreateDynamicItemBuilder();
                        item.Set(element, 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 < dfsDate.Count; j++)
                        {
                            file.WriteItemTimeStepNext((dfsDate[j] - dfsDate[0]).TotalSeconds, new float[] { dfsData[j, comboBox1.SelectedIndex] });
                        }
                        file.Close();
                    }

                    MessageBox.Show("Result file processed suceesssfully.");
                }
            }
            catch (Exception error)
            {
                MessageBox.Show("HD Model Result files cannot be processed due to an error. Error: " + error.Message);
            }
        }
Exemple #8
0
        private void btnLoadNAM_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Filter = "Mike NAM Result Files|*.RES11";

            if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.Cancel)
            {
                fileName = dialog.FileName;
            }


            var filepath = fileName.Split('\\');

            dfs0Path = filepath[0];
            for (int i = 1; i < filepath.Length - 1; i++)
            {
                dfs0Path = dfs0Path + @"\" + filepath[i];
            }

            IDfsFile     resFile     = DfsFileFactory.DfsGenericOpenEdit(fileName);
            IDfsFileInfo resfileInfo = resFile.FileInfo;

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

            IDfsItemData <float> data;
            int noTimeSteps = resfileInfo.TimeAxis.NumberOfTimeSteps;

            float[] values = new float[noTimeSteps];
            for (int i = 0; i < noTimeSteps; i++)
            {
                dfsDate.Add(startDate.AddHours(resFile.ReadItemTimeStep(1, i).Time));
            }

            for (int j = 0; j < resFile.ItemInfo.Count; j++)
            {
                IDfsSimpleDynamicItemInfo dynamicItemInfo = resFile.ItemInfo[j];
                string nameOftDynamicItem = dynamicItemInfo.Name;
                string checkname          = nameOftDynamicItem.Substring(0, 6);
                if (checkname == "RunOff")
                {
                    string     filename    = dfs0Path + @"\" + nameOftDynamicItem + ".dfs0";
                    DfsFactory factory     = new DfsFactory();
                    DfsBuilder filecreator = DfsBuilder.Create(nameOftDynamicItem, nameOftDynamicItem, 2014);
                    filecreator.SetDataType(1);
                    filecreator.SetGeographicalProjection(factory.CreateProjectionUndefined());
                    //filecreator.SetTemporalAxis(factory.CreateTemporalEqCalendarAxis(eumUnit.eumUsec, new DateTime(2010, 01, 01, 06, 00, 00), 0, 10800));
                    filecreator.SetTemporalAxis(factory.CreateTemporalNonEqCalendarAxis(eumUnit.eumUsec, new DateTime(dfsDate[0].Year, dfsDate[0].Month, dfsDate[0].Day, dfsDate[0].Hour, dfsDate[0].Minute, dfsDate[0].Second)));
                    filecreator.SetItemStatisticsType(StatType.RegularStat);
                    DfsDynamicItemBuilder item = filecreator.CreateDynamicItemBuilder();
                    item.Set(nameOftDynamicItem, 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();

                    for (int i = 0; i < noTimeSteps; i++)
                    {
                        data      = (IDfsItemData <float>)resFile.ReadItemTimeStep(j + 1, i);
                        values[i] = Convert.ToSingle(data.Data[0]);
                        file.WriteItemTimeStepNext((dfsDate[i] - dfsDate[0]).TotalSeconds, new float[] { values[i] });
                    }
                    file.Close();
                }
            }
        }
        /// <summary>
        /// Creates a dfs0 file, with an equidistant time axis and one dynamic item.
        /// <para>
        /// It uses the generic <see cref="DfsBuilder"/>, since currently no specialized
        /// builder exists for the dfs0 files.
        /// </para>
        /// </summary>
        /// <param name="filename">Name of new file</param>
        /// <param name="calendarAxis">boolean specifying whether the temporal axis should be a calendar axis or a time axis</param>
        public static void CreateDfs0FileFromArray(string filename, bool calendarAxis)
        {
            DfsFactory factory = new DfsFactory();
            DfsBuilder builder = DfsBuilder.Create("TemporalAxisTest", "dfs Timeseries Bridge", 10000);

            // Set up file header
            builder.SetDataType(1);
            builder.SetGeographicalProjection(factory.CreateProjectionUndefined());
            if (calendarAxis)
            {
                builder.SetTemporalAxis(factory.CreateTemporalEqCalendarAxis(eumUnit.eumUsec, new DateTime(2010, 01, 04, 12, 34, 00), 4, 10));
            }
            else
            {
                builder.SetTemporalAxis(factory.CreateTemporalEqTimeAxis(eumUnit.eumUsec, 3, 10));
            }
            builder.SetItemStatisticsType(StatType.RegularStat);

            // Set up first item
            DfsDynamicItemBuilder item1 = builder.CreateDynamicItemBuilder();

            item1.Set("WaterLevel item", eumQuantity.Create(eumItem.eumIWaterLevel, eumUnit.eumUmeter),
                      DfsSimpleType.Float);
            item1.SetValueType(DataValueType.Instantaneous);
            item1.SetAxis(factory.CreateAxisEqD0());
            item1.SetReferenceCoordinates(1f, 2f, 3f);
            builder.AddDynamicItem(item1.GetDynamicItemInfo());

            DfsDynamicItemBuilder item2 = builder.CreateDynamicItemBuilder();

            item2.Set("WaterDepth item", eumQuantity.Create(eumItem.eumIWaterDepth, eumUnit.eumUmeter),
                      DfsSimpleType.Float);
            item2.SetValueType(DataValueType.Instantaneous);
            item2.SetAxis(factory.CreateAxisEqD0());
            item2.SetReferenceCoordinates(1f, 2f, 3f);
            builder.AddDynamicItem(item2.GetDynamicItemInfo());

            // Create file
            builder.CreateFile(filename);
            IDfsFile file = builder.GetFile();

            // Time is not important, since it is equidistant
            double[] times = new double[10];
            double[,] values = new double[10, 2];

            // Write data to file
            values[0, 0] = 0f;   // water level
            values[0, 1] = 100f; // water depth
            values[1, 0] = 1f;   // water level
            values[1, 1] = 101f; // water depth
            values[2, 0] = 2f;   // water level
            values[2, 1] = 102f; // water depth
            values[3, 0] = 3f;   // etc...
            values[3, 1] = 103f;
            values[4, 0] = 4f;
            values[4, 1] = 104f;
            values[5, 0] = 5f;
            values[5, 1] = 105f;
            values[6, 0] = 10f;
            values[6, 1] = 110f;
            values[7, 0] = 11f;
            values[7, 1] = 111f;
            values[8, 0] = 12f;
            values[8, 1] = 112f;
            values[9, 0] = 13f;
            values[9, 1] = 113f;

            DHI.Generic.MikeZero.DFS.dfs0.Dfs0Util.WriteDfs0DataDouble(file, times, values);

            file.Close();
        }
Exemple #10
0
        /// <summary>
        /// Creates a dfs0 file, with an equidistant time axis and one dynamic item.
        /// <para>
        /// It uses the generic <see cref="DfsBuilder"/>, since currently no specialized
        /// builder exists for the dfs0 files.
        /// </para>
        /// </summary>
        /// <param name="filename">Name of new file</param>
        /// <param name="calendarAxis">boolean specifying whether the temporal axis should be a calendar axis or a time axis</param>
        public static void CreateDfs0File(string filename, bool calendarAxis)
        {
            DfsFactory factory = new DfsFactory();
            DfsBuilder builder = DfsBuilder.Create("TemporalAxisTest", "dfs Timeseries Bridge", 10000);

            // Set up file header
            builder.SetDataType(1);
            builder.SetGeographicalProjection(factory.CreateProjectionUndefined());
            if (calendarAxis)
            {
                builder.SetTemporalAxis(factory.CreateTemporalEqCalendarAxis(eumUnit.eumUsec, new DateTime(2010, 01, 04, 12, 34, 00), 4, 10));
            }
            else
            {
                builder.SetTemporalAxis(factory.CreateTemporalEqTimeAxis(eumUnit.eumUsec, 3, 10));
            }
            builder.SetItemStatisticsType(StatType.RegularStat);

            // Set up first item
            DfsDynamicItemBuilder item1 = builder.CreateDynamicItemBuilder();

            item1.Set("WaterLevel item", eumQuantity.Create(eumItem.eumIWaterLevel, eumUnit.eumUmeter),
                      DfsSimpleType.Float);
            item1.SetValueType(DataValueType.Instantaneous);
            item1.SetAxis(factory.CreateAxisEqD0());
            item1.SetReferenceCoordinates(1f, 2f, 3f);
            builder.AddDynamicItem(item1.GetDynamicItemInfo());

            DfsDynamicItemBuilder item2 = builder.CreateDynamicItemBuilder();

            item2.Set("WaterDepth item", eumQuantity.Create(eumItem.eumIWaterDepth, eumUnit.eumUmeter),
                      DfsSimpleType.Float);
            item2.SetValueType(DataValueType.Instantaneous);
            item2.SetAxis(factory.CreateAxisEqD0());
            item2.SetReferenceCoordinates(1f, 2f, 3f);
            builder.AddDynamicItem(item2.GetDynamicItemInfo());

            // Create file
            builder.CreateFile(filename);
            IDfsFile file = builder.GetFile();

            // Write data to file
            file.WriteItemTimeStepNext(0, new float[] { 0f });   // water level
            file.WriteItemTimeStepNext(0, new float[] { 100f }); // water depth
            file.WriteItemTimeStepNext(0, new float[] { 1f });   // water level
            file.WriteItemTimeStepNext(0, new float[] { 101f }); // water depth
            file.WriteItemTimeStepNext(0, new float[] { 2f });   // water level
            file.WriteItemTimeStepNext(0, new float[] { 102f }); // water depth
            file.WriteItemTimeStepNext(0, new float[] { 3f });   // etc...
            file.WriteItemTimeStepNext(0, new float[] { 103f });
            file.WriteItemTimeStepNext(0, new float[] { 4f });
            file.WriteItemTimeStepNext(0, new float[] { 104f });
            file.WriteItemTimeStepNext(0, new float[] { 5f });
            file.WriteItemTimeStepNext(0, new float[] { 105f });
            file.WriteItemTimeStepNext(0, new float[] { 10f });
            file.WriteItemTimeStepNext(0, new float[] { 110f });
            file.WriteItemTimeStepNext(0, new float[] { 11f });
            file.WriteItemTimeStepNext(0, new float[] { 111f });
            file.WriteItemTimeStepNext(0, new float[] { 12f });
            file.WriteItemTimeStepNext(0, new float[] { 112f });
            file.WriteItemTimeStepNext(0, new float[] { 13f });
            file.WriteItemTimeStepNext(0, new float[] { 113f });

            file.Close();
        }
Exemple #11
0
        /// <summary>
        /// Create a new file, being the difference of two files.
        /// <para>
        /// The two input files must be equal in structure, e.g. coming
        /// from the same simulation but giving different results.
        /// Header and static data must be identical, only difference
        /// must be in values of the dynamic data.
        /// </para>
        /// </summary>
        public static void CreateDiffFile(string file1, string file2, string filediff = null)
        {
            IDfsFile dfs1 = DfsFileFactory.DfsGenericOpen(file1);
            IDfsFile dfs2 = DfsFileFactory.DfsGenericOpen(file2);

            // Validate that it has the same number of items.
            if (dfs1.ItemInfo.Count != dfs2.ItemInfo.Count)
            {
                throw new Exception("Number of dynamic items does not match");
            }
            int numItems = dfs1.ItemInfo.Count;

            // In case number of time steps does not match, take the smallest.
            int numTimes = dfs1.FileInfo.TimeAxis.NumberOfTimeSteps;

            if (numTimes > dfs2.FileInfo.TimeAxis.NumberOfTimeSteps)
            {
                numTimes = dfs2.FileInfo.TimeAxis.NumberOfTimeSteps;
                Console.Out.WriteLine("Number of time steps does not match, using the smallest number");
            }

            // For recording max difference for every item
            double[] maxDiff = new double[dfs1.ItemInfo.Count];
            // Index in time (index) of maximum and first difference. -1 if no difference
            int[] maxDiffTime   = new int[dfs1.ItemInfo.Count];
            int[] firstDiffTime = new int[dfs1.ItemInfo.Count];
            for (int i = 0; i < dfs1.ItemInfo.Count; i++)
            {
                maxDiffTime[i]   = -1;
                firstDiffTime[i] = -1;
            }

            // Copy over info from the first file, assuming the second file contains the same data.
            IDfsFileInfo fileInfo = dfs1.FileInfo;

            DfsBuilder builder = null;

            if (!string.IsNullOrEmpty(filediff))
            {
                builder = DfsBuilder.Create(fileInfo.FileTitle, fileInfo.ApplicationTitle, fileInfo.ApplicationVersion);

                // Set up the header
                builder.SetDataType(fileInfo.DataType);
                builder.SetGeographicalProjection(fileInfo.Projection);
                builder.SetTemporalAxis(fileInfo.TimeAxis);
                builder.SetItemStatisticsType(fileInfo.StatsType);
                builder.DeleteValueByte        = fileInfo.DeleteValueByte;
                builder.DeleteValueDouble      = fileInfo.DeleteValueDouble;
                builder.DeleteValueFloat       = fileInfo.DeleteValueFloat;
                builder.DeleteValueInt         = fileInfo.DeleteValueInt;
                builder.DeleteValueUnsignedInt = fileInfo.DeleteValueUnsignedInt;

                // Transfer compression keys.
                if (fileInfo.IsFileCompressed)
                {
                    int[] xkey;
                    int[] ykey;
                    int[] zkey;
                    fileInfo.GetEncodeKey(out xkey, out ykey, out zkey);
                    builder.SetEncodingKey(xkey, ykey, zkey);
                }

                // Copy custom blocks
                foreach (IDfsCustomBlock customBlock in fileInfo.CustomBlocks)
                {
                    builder.AddCustomBlock(customBlock);
                }
            }

            // Copy dynamic item definitions
            bool[] floatItems = new bool[dfs1.ItemInfo.Count];
            for (int i = 0; i < dfs1.ItemInfo.Count; i++)
            {
                var itemInfo = dfs1.ItemInfo[i];

                // Validate item sizes
                var itemInfo2 = dfs2.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 and doubles.
                if (itemInfo.DataType == DfsSimpleType.Float)
                {
                    floatItems[i] = true;
                }
                else if (itemInfo.DataType != DfsSimpleType.Double)
                {
                    throw new Exception("Dynamic item must be double or float, item number " + (i + 1) + " is of type " +
                                        (itemInfo.DataType));
                }

                builder?.AddDynamicItem(itemInfo);
            }

            // Create file
            builder?.CreateFile(filediff);

            if (builder != null)
            {
                // Copy over static items from file 1, assuming the static items of file 2 are identical
                IDfsStaticItem si1;
                while (null != (si1 = dfs1.ReadStaticItemNext()))
                {
                    builder.AddStaticItem(si1);
                }
            }

            // Get the file
            DfsFile diff = builder?.GetFile();

            // Write dynamic data to the file, being the difference between the two
            for (int i = 0; i < numTimes; i++)
            {
                for (int j = 0; j < numItems; j++)
                {
                    if (floatItems[j])
                    {
                        IDfsItemData <float> data1 = dfs1.ReadItemTimeStepNext() as IDfsItemData <float>;
                        IDfsItemData <float> data2 = dfs2.ReadItemTimeStepNext() as IDfsItemData <float>;
                        for (int k = 0; k < data1.Data.Length; k++)
                        {
                            float valuediff = data1.Data[k] - data2.Data[k];
                            data1.Data[k] = valuediff;
                            float absValueDiff = Math.Abs(valuediff);
                            if (absValueDiff > maxDiff[j])
                            {
                                maxDiff[j]     = absValueDiff;
                                maxDiffTime[j] = i;
                                if (firstDiffTime[j] == -1)
                                {
                                    firstDiffTime[j] = i;
                                }
                            }
                        }
                        diff?.WriteItemTimeStepNext(data1.Time, data1.Data);
                    }
                    else
                    {
                        IDfsItemData <double> data1 = dfs1.ReadItemTimeStepNext() as IDfsItemData <double>;
                        IDfsItemData <double> data2 = dfs2.ReadItemTimeStepNext() as IDfsItemData <double>;
                        for (int k = 0; k < data1.Data.Length; k++)
                        {
                            double valuediff = data1.Data[k] - data2.Data[k];
                            data1.Data[k] = valuediff;
                            double absValueDiff = Math.Abs(valuediff);
                            if (absValueDiff > maxDiff[j])
                            {
                                maxDiff[j]     = absValueDiff;
                                maxDiffTime[j] = i;
                                if (firstDiffTime[j] == -1)
                                {
                                    firstDiffTime[j] = i;
                                }
                            }
                        }
                        diff?.WriteItemTimeStepNext(data1.Time, data1.Data);
                    }
                }
            }

            System.Console.WriteLine("Difference statistics:");
            for (int i = 0; i < maxDiffTime.Length; i++)
            {
                if (maxDiffTime[i] < 0)
                {
                    Console.WriteLine("{0,-30}: no difference", dfs1.ItemInfo[i].Name);
                }
                else
                {
                    Console.WriteLine("{0,-30}: Max difference at timestep {1,3}: {2}. First difference at timestep {3}", dfs1.ItemInfo[i].Name, maxDiffTime[i], maxDiff[i], firstDiffTime[i]);
                }
            }

            dfs1.Close();
            dfs2.Close();
            diff?.Close();
        }
Exemple #12
0
        /// <summary>
        /// Example of how to copy a Dfs file.
        /// <para>
        /// This example is intended to show how to generically copy a file. In
        /// case a copy with modified data is required, this could be used as a base
        /// for the copy.
        /// </para>
        /// </summary>
        /// <param name="sourceFilename">Path and name of the source dfs file</param>
        /// <param name="filename">Path and name of the new file to create</param>
        public static void CopyDfsFile(string sourceFilename, string filename)
        {
            IDfsFile     source   = DfsFileFactory.DfsGenericOpen(sourceFilename);
            IDfsFileInfo fileInfo = source.FileInfo;

            DfsBuilder builder = DfsBuilder.Create(fileInfo.FileTitle, fileInfo.ApplicationTitle, fileInfo.ApplicationVersion);

            // Set up the header
            builder.SetDataType(fileInfo.DataType);
            builder.SetGeographicalProjection(fileInfo.Projection);
            builder.SetTemporalAxis(fileInfo.TimeAxis);
            builder.SetItemStatisticsType(fileInfo.StatsType);
            builder.DeleteValueByte        = fileInfo.DeleteValueByte;
            builder.DeleteValueDouble      = fileInfo.DeleteValueDouble;
            builder.DeleteValueFloat       = fileInfo.DeleteValueFloat;
            builder.DeleteValueInt         = fileInfo.DeleteValueInt;
            builder.DeleteValueUnsignedInt = fileInfo.DeleteValueUnsignedInt;

            // Transfer compression keys - if any.
            if (fileInfo.IsFileCompressed)
            {
                int[] xkey;
                int[] ykey;
                int[] zkey;
                fileInfo.GetEncodeKey(out xkey, out ykey, out zkey);
                builder.SetEncodingKey(xkey, ykey, zkey);
            }

            // Copy custom blocks - if any
            foreach (IDfsCustomBlock customBlock in fileInfo.CustomBlocks)
            {
                builder.AddCustomBlock(customBlock);
            }

            // Copy dynamic items
            foreach (var itemInfo in source.ItemInfo)
            {
                builder.AddDynamicItem(itemInfo);
            }

            // Create file
            builder.CreateFile(filename);

            // Copy static items
            IDfsStaticItem sourceStaticItem;

            while (null != (sourceStaticItem = source.ReadStaticItemNext()))
            {
                builder.AddStaticItem(sourceStaticItem);
            }

            // Get the file
            DfsFile file = builder.GetFile();

            // Copy dynamic item data
            IDfsItemData sourceData;

            while (null != (sourceData = source.ReadItemTimeStepNext()))
            {
                file.WriteItemTimeStepNext(sourceData.Time, sourceData.Data);
            }

            source.Close();
            file.Close();
        }
Exemple #13
0
        /// <summary>
        /// Example of how to merge two or more dfs files. The merger is on dynamic item basis,
        /// i.e. add all dynamic items of a number of dfs files to a new dfs file.
        /// <para>
        /// It is assumed that all files has the same time stepping layout. It will merge
        /// as many time steps as the file with the least number of timesteps.
        /// </para>
        /// <para>
        /// If merging one of the specific types of dfs files, dfs0 or dfs1 or dfs2 or dfs3,
        /// the structure of the files must be identical, i.e. the sizes of the axis must equal.
        /// Otherwise, the outcome will not be a valid dfs0/1/2/3 file.
        /// </para>
        /// </summary>
        /// <param name="targetFilename">Path and name of the new file to create</param>
        /// <param name="sourcesFilenames">Path and name of the source dfs files</param>
        public static void MergeDfsFileItems(string targetFilename, IList <string> sourcesFilenames)
        {
            // List of sources to be merged - in case of more than one, just extend this.
            List <IDfsFile> sources = new List <IDfsFile>();

            for (int i = 0; i < sourcesFilenames.Count; i++)
            {
                sources.Add(DfsFileFactory.DfsGenericOpen(sourcesFilenames[i]));
            }

            // Use the first file as skeleton for header and static items.
            IDfsFile     source   = sources[0];
            IDfsFileInfo fileInfo = source.FileInfo;

            DfsBuilder builder = DfsBuilder.Create(fileInfo.FileTitle, fileInfo.ApplicationTitle, fileInfo.ApplicationVersion);

            // Set up the header
            builder.SetDataType(fileInfo.DataType);
            builder.SetGeographicalProjection(fileInfo.Projection);
            builder.SetTemporalAxis(fileInfo.TimeAxis);
            builder.SetItemStatisticsType(fileInfo.StatsType);
            builder.DeleteValueByte        = fileInfo.DeleteValueByte;
            builder.DeleteValueDouble      = fileInfo.DeleteValueDouble;
            builder.DeleteValueFloat       = fileInfo.DeleteValueFloat;
            builder.DeleteValueInt         = fileInfo.DeleteValueInt;
            builder.DeleteValueUnsignedInt = fileInfo.DeleteValueUnsignedInt;

            // Transfer compression keys - if any.
            if (fileInfo.IsFileCompressed)
            {
                int[] xkey;
                int[] ykey;
                int[] zkey;
                fileInfo.GetEncodeKey(out xkey, out ykey, out zkey);
                builder.SetEncodingKey(xkey, ykey, zkey);
            }

            // Copy custom blocks - if any
            foreach (IDfsCustomBlock customBlock in fileInfo.CustomBlocks)
            {
                builder.AddCustomBlock(customBlock);
            }

            int minNumTimesteps = int.MaxValue;

            // Copy dynamic items for all source files
            for (int j = 0; j < sources.Count; j++)
            {
                if (sources[j].FileInfo.TimeAxis.NumberOfTimeSteps < minNumTimesteps)
                {
                    minNumTimesteps = sources[j].FileInfo.TimeAxis.NumberOfTimeSteps;
                }

                foreach (var itemInfo in sources[j].ItemInfo)
                {
                    builder.AddDynamicItem(itemInfo);
                }
            }

            // Create file
            builder.CreateFile(targetFilename);

            // Copy static items - add only from main file
            IDfsStaticItem sourceStaticItem;

            while (null != (sourceStaticItem = source.ReadStaticItemNext()))
            {
                builder.AddStaticItem(sourceStaticItem);
            }

            // Get the file
            DfsFile file = builder.GetFile();

            // Copy dynamic item data
            IDfsItemData sourceData;

            for (int i = 0; i < minNumTimesteps; i++)
            {
                for (int j = 0; j < sources.Count; j++)
                {
                    IDfsFile sourcej = sources[j];
                    // Copy all items for this source
                    for (int k = 0; k < sourcej.ItemInfo.Count; k++)
                    {
                        sourceData = sourcej.ReadItemTimeStepNext();
                        file.WriteItemTimeStepNext(sourceData.Time, sourceData.Data);
                    }
                }
            }

            foreach (IDfsFile sourcej in sources)
            {
                sourcej.Close();
            }
            file.Close();
        }
Exemple #14
0
        ///
        /// <param name="fileName">Output DFS0 file path</param>
        /// <param name="pi">Memory data structure containing TS</param>
        /// <param name="list">List of TS identification selecting  TS to write in file.
        /// </param>
        /// <param name="startTime">Date/time of first time step to be written to
        /// file</param>
        /// <param name="endTime">Date/time of last time step to be written to
        /// file</param>
        /// <param name="parameterType"></param>
        private void  _WriteOneFile(string fileName, PI pi, IList <TsIdentification> list, DateTime startTime, DateTime endTime, string parameterType)
        {
            var allTimeSteps = new List <DateTime>();

            foreach (var ident in list)
            {
                var tsList = pi.GetTS(ident);
                foreach (var ts in tsList)
                {
                    for (int i = 0; i < ts.Values.Count; i++)
                    {
                        foreach (var value in ts.Values.Keys)
                        {
                            if ((value >= startTime) && (value <= endTime))
                            {
                                if (!allTimeSteps.Contains(value))
                                {
                                    allTimeSteps.Add(value);
                                }
                            }
                        }
                    }
                }
            }
            allTimeSteps.Sort();

            var        fullTsList = new List <TimeSeries>();
            DfsFactory factory    = new DfsFactory();
            DfsBuilder builder    = DfsBuilder.Create("FEWS Adaptor", "FEWS Adaptor - Dfs0 writer", 10000);

            builder.SetItemStatisticsType(StatType.RegularStat);
            builder.SetDataType(0);
            builder.SetGeographicalProjection(factory.CreateProjectionUndefined());
            builder.SetItemStatisticsType(StatType.RegularStat);
            IDfsTemporalAxis temporalAxis = factory.CreateTemporalNonEqCalendarAxis(DHI.Generic.MikeZero.eumUnit.eumUsec, allTimeSteps[0]);

            builder.SetTemporalAxis(temporalAxis);
            foreach (var ident in list)
            {
                var tsList = pi.GetTS(ident);
                foreach (var ts in tsList)
                {
                    DfsDynamicItemBuilder item = builder.CreateDynamicItemBuilder();
                    var itemEnum = eumItem.eumIItemUndefined;
                    var unitEum  = eumUnit.eumUUnitUndefined;
                    var array    = ts.ParameterId.Split(';');
                    var itemStr  = array[0];
                    var unitStr  = string.Empty;
                    if (array.Count() > 1)
                    {
                        unitStr = array[1];
                    }
                    if (!Enum.TryParse(itemStr, true, out itemEnum))
                    {
                        itemEnum = eumItem.eumIItemUndefined;
                    }
                    if (!Enum.TryParse(unitStr, true, out unitEum))
                    {
                        unitEum = eumUnit.eumUUnitUndefined;
                    }
                    item.Set(ts.LocationId, eumQuantity.Create(itemEnum, unitEum), DfsSimpleType.Float);
                    if (string.IsNullOrEmpty(parameterType))
                    {
                        item.SetValueType(DataValueType.Instantaneous);
                    }
                    else
                    {
                        switch (parameterType.ToLower())
                        {
                        case "instantaneous":
                            item.SetValueType(DataValueType.Instantaneous);
                            break;

                        case "accumulated":
                            item.SetValueType(DataValueType.Accumulated);
                            break;

                        case "meanstepbackward":
                            item.SetValueType(DataValueType.MeanStepBackward);
                            break;

                        case "meanstepforward":
                            item.SetValueType(DataValueType.MeanStepForward);
                            break;

                        case "stepaccumulated":
                            item.SetValueType(DataValueType.StepAccumulated);
                            break;

                        default:
                            item.SetValueType(DataValueType.Instantaneous);
                            break;
                        }
                    }
                    item.SetAxis(factory.CreateAxisEqD0());
                    builder.AddDynamicItem(item.GetDynamicItemInfo());
                    fullTsList.Add(ts);
                }
            }
            builder.CreateFile(fileName);
            using (IDfsFile file = builder.GetFile())
            {
                if (fullTsList[0].MissVal.HasValue)
                {
                    file.FileInfo.DeleteValueFloat  = (float)fullTsList[0].MissVal.Value;
                    file.FileInfo.DeleteValueDouble = fullTsList[0].MissVal.Value;
                }
                else
                {
                    file.FileInfo.DeleteValueFloat  = -9999.9f;
                    file.FileInfo.DeleteValueDouble = -9999.9;
                }
                float[] oneStepValues = new float[1];
                double  noValue       = file.FileInfo.DeleteValueFloat;
                for (int i = 0; i < allTimeSteps.Count; i++)
                {
                    double doubleTime    = (allTimeSteps[i] - allTimeSteps[0]).TotalSeconds;
                    bool   writeTimeStep = false;
                    int    k             = 0;
                    while (k < fullTsList.Count && !writeTimeStep)
                    {
                        double value = fullTsList[k].GetValue(allTimeSteps[i]);
                        writeTimeStep = (Math.Abs(value - noValue) > double.Epsilon);
                        k++;
                    }
                    if (writeTimeStep)
                    {
                        for (int j = 0; j < fullTsList.Count; j++)
                        {
                            double value = file.FileInfo.DeleteValueFloat;
                            value            = fullTsList[j].GetValue(allTimeSteps[i]);
                            oneStepValues[0] = (float)value;
                            file.WriteItemTimeStepNext(doubleTime, oneStepValues);
                        }
                    }
                }
            }
            Logger.AddLog(Logger.TypeEnum.Info, $"File {fileName} written successfully");
        }
Exemple #15
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();
                }
            }
        }
Exemple #16
0
        public bool GenerateWebTideNode(TVFileModel TVFileModelBC, int WebTideNodeNumb, List <Coord> CoordList, List <TVFileModel> tvFileModelList, int BoundaryConditionCodeNumber, List <List <WaterLevelResult> > AllWLResults, List <IEnumerable <CurrentResult> > AllCurrentResults)
        {
            List <eumItem> eumItemList = new List <eumItem>();

            DfsFactory factory = new DfsFactory();

            IDfsFile dfsOldFile = DfsFileFactory.DfsGenericOpen(TVFileModelBC.ServerFilePath + TVFileModelBC.ServerFileName);

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

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

            DateTime?dateTimeTemp      = null;
            int?     NumberOfTimeSteps = null;
            int?     TimeStepInterval  = null;

            using (PFS pfs = new PFS(base.fi))
            {
                dateTimeTemp = pfs.GetVariableDateTime("FemEngineHD/TIME", "start_time");
                if (dateTimeTemp == null)
                {
                    dfsOldFile.Close();
                    return(false);
                }

                NumberOfTimeSteps = pfs.GetVariable <int>("FemEngineHD/TIME", "number_of_time_steps", 1);
                if (NumberOfTimeSteps == null)
                {
                    dfsOldFile.Close();
                    return(false);
                }

                TimeStepInterval = pfs.GetVariable <int>("FemEngineHD/TIME", "time_step_interval", 1);
                if (TimeStepInterval == null)
                {
                    dfsOldFile.Close();
                    return(false);
                }
            }

            DateTime StartDate = ((DateTime)dateTimeTemp).AddHours(-1);
            DateTime EndDate   = ((DateTime)dateTimeTemp).AddSeconds((int)NumberOfTimeSteps * (int)TimeStepInterval).AddHours(1);

            dfsNewFile.SetDataType(dfsOldFile.FileInfo.DataType);
            dfsNewFile.SetGeographicalProjection(dfsOldFile.FileInfo.Projection);
            dfsNewFile.SetTemporalAxis(factory.CreateTemporalEqCalendarAxis(eumUnit.eumUsec, StartDate, 0, WebTideStepsInMinutes * 60));
            dfsNewFile.SetItemStatisticsType(StatType.RegularStat);

            foreach (IDfsDynamicItemInfo di in dfsOldFile.ItemInfo)
            {
                DfsDynamicItemBuilder ddib = dfsNewFile.CreateDynamicItemBuilder();
                ddib.Set(di.Name, eumQuantity.Create(di.Quantity.Item, di.Quantity.Unit), di.DataType);
                ddib.SetValueType(di.ValueType);
                ddib.SetAxis(factory.CreateAxisEqD1(eumUnit.eumUsec, CoordList.Count, 0, 1));
                ddib.SetReferenceCoordinates(di.ReferenceCoordinateX, di.ReferenceCoordinateY, di.ReferenceCoordinateZ);
                dfsNewFile.AddDynamicItem(ddib.GetDynamicItemInfo());
                eumItemList.Add(di.Quantity.Item);
            }

            dfsOldFile.Close();

            string[]      NewFileErrors = dfsNewFile.Validate();
            StringBuilder sbErr         = new StringBuilder();

            foreach (string s in NewFileErrors)
            {
                sbErr.AppendLine(s);
            }

            if (NewFileErrors.Count() > 0)
            {
                ErrorMessage = string.Format(CSSPDHIRes.CouldNotCreate_, TVFileModelBC.ServerFileName.Replace(".dfs0", "dfs1"));
                OnCSSPDHIChanged(new CSSPDHIEventArgs(new CSSPDHIMessage("Error", -1, false, ErrorMessage)));
                return(false);
            }

            string NewFileNameBC = TVFileModelBC.ServerFileName;

            if (CoordList.Count == 0)
            {
                ErrorMessage = CSSPDHIRes.NumberOfWebTideNodesIsZero;
                OnCSSPDHIChanged(new CSSPDHIEventArgs(new CSSPDHIMessage("Error", -1, false, ErrorMessage)));
                return(false);
            }

            if (eumItemList.Count == 1)
            {
                if (eumItemList[0] == eumItem.eumIWaterLevel || eumItemList[0] == eumItem.eumIWaterDepth)
                {
                    List <WaterLevelResult> WLResults = null;

                    dfsNewFile.CreateFile(TVFileModelBC.ServerFilePath + NewFileNameBC);
                    IDfsFile file = dfsNewFile.GetFile();
                    for (int i = 0; i < WLResults.ToList().Count; i++)
                    {
                        float[] floatArray = new float[AllWLResults.Count];

                        for (int j = 0; j < AllWLResults.Count; j++)
                        {
                            floatArray[j] = ((float)((List <WaterLevelResult>)AllWLResults[j].ToList())[i].WaterLevel);
                        }



                        file.WriteItemTimeStepNext(0, floatArray);  // water level array
                    }
                    file.Close();
                }
                else
                {
                    ErrorMessage = string.Format(CSSPDHIRes.FileContainsOneParamButItsNotOfTypeWLOrWDItIs_, eumItemList[0].ToString());
                    OnCSSPDHIChanged(new CSSPDHIEventArgs(new CSSPDHIMessage("Error", -1, false, ErrorMessage)));
                    return(false);
                }
            }
            else if (eumItemList.Count == 2)
            {
                if (eumItemList[0] == eumItem.eumIuVelocity && eumItemList[1] == eumItem.eumIvVelocity)
                {
                    // read web tide for the required time
                    List <CurrentResult> CurrentResults = null;

                    dfsNewFile.CreateFile(TVFileModelBC.ServerFilePath + NewFileNameBC);
                    IDfsFile file = dfsNewFile.GetFile();
                    for (int i = 0; i < CurrentResults.ToList().Count; i++)
                    {
                        float[] floatArrayX = new float[AllCurrentResults.Count];
                        float[] floatArrayY = new float[AllCurrentResults.Count];

                        for (int j = 0; j < AllCurrentResults.Count; j++)
                        {
                            floatArrayX[j] = ((float)((List <CurrentResult>)AllCurrentResults[j].ToList())[i].x_velocity);
                            floatArrayY[j] = ((float)((List <CurrentResult>)AllCurrentResults[j].ToList())[i].y_velocity);
                        }

                        file.WriteItemTimeStepNext(0, floatArrayX);  // Current xVelocity
                        file.WriteItemTimeStepNext(0, floatArrayY);  // Current yVelocity
                    }
                    file.Close();
                }
                else
                {
                    ErrorMessage = string.Format(CSSPDHIRes.FileContains2ParamButItsNotOfUVAndVVItIs_And_, eumItemList[0].ToString(), eumItemList[1].ToString());
                    OnCSSPDHIChanged(new CSSPDHIEventArgs(new CSSPDHIMessage("Error", -1, false, ErrorMessage)));
                    return(false);
                }
            }
            else
            {
                // this is not a file that is used for Water Level or Currents
            }

            return(false);
        }