public static IDfsDynamicItemInfo CloneDynamicItem(DfsBuilder dfsBuilder, IDfsDynamicItemInfo dynamicItem) { DfsDynamicItemBuilder itemBuilder = dfsBuilder.CreateDynamicItemBuilder(); itemBuilder.Set(dynamicItem.Name, dynamicItem.Quantity, dynamicItem.DataType); itemBuilder.SetValueType(dynamicItem.ValueType); itemBuilder.SetAxis(dynamicItem.SpatialAxis); itemBuilder.SetReferenceCoordinates(dynamicItem.ReferenceCoordinateX, dynamicItem.ReferenceCoordinateY, dynamicItem.ReferenceCoordinateZ); return(itemBuilder.GetDynamicItemInfo()); }
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(); } }
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."); } }
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); } }
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(); }
/// <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(); }
/// <summary> /// Example of how to copy static data to dynamic item data in a Dfs file. /// <para> /// Static data is by default not visible in many tools and editors. This is a way to make static data visible as dynamic data. /// </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 CopyStaticToDynamicDfsFile(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 static items IDfsStaticItem sourceStaticItem; while (null != (sourceStaticItem = source.ReadStaticItemNext())) { DfsDynamicItemBuilder dynStatItem = builder.CreateDynamicItemBuilder(); dynStatItem.Set(sourceStaticItem.Name, sourceStaticItem.Quantity, sourceStaticItem.DataType); dynStatItem.SetAxis(sourceStaticItem.SpatialAxis); dynStatItem.SetValueType(DataValueType.Instantaneous); builder.AddDynamicItem(dynStatItem.GetDynamicItemInfo()); } // Create file builder.CreateFile(filename); // Get the file DfsFile file = builder.GetFile(); source.Reset(); // Copy static data to dynamic item data while (null != (sourceStaticItem = source.ReadStaticItemNext())) { file.WriteItemTimeStepNext(0, sourceStaticItem.Data); } source.Close(); file.Close(); }
/// /// <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"); }
/// <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(); } } }
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); }