public static double ReadAttribute(string file, string dataSetOrGroup, string attribute) { double attr = Double.NaN; try { H5FileId fileId = H5F.open(file, H5F.OpenMode.ACC_RDONLY); H5ObjectInfo objectInfo = H5O.getInfoByName(fileId, dataSetOrGroup); H5GroupId groupId = null; H5DataSetId dataSetId = null; H5AttributeId attrId; if (objectInfo.objectType == H5ObjectType.GROUP) { groupId = H5G.open(fileId, dataSetOrGroup); attrId = H5A.open(groupId, attribute); } else { dataSetId = H5D.open(fileId, dataSetOrGroup); attrId = H5A.open(dataSetId, attribute); } H5DataTypeId attrTypeId = H5A.getType(attrId); double[] dAttrs = new double[] { }; if (H5T.equal(attrTypeId, H5T.copy(H5T.H5Type.NATIVE_FLOAT))) { float[] fAttrs = new float[H5S.getSimpleExtentNPoints(H5A.getSpace(attrId))]; H5A.read(attrId, attrTypeId, new H5Array <float>(fAttrs)); dAttrs = (from f in fAttrs select(double) f).ToArray(); } else if (H5T.equal(attrTypeId, H5T.copy(H5T.H5Type.NATIVE_DOUBLE))) { dAttrs = new double[H5S.getSimpleExtentNPoints(H5A.getSpace(attrId))]; H5A.read(attrId, attrTypeId, new H5Array <double>(dAttrs)); } H5T.close(attrTypeId); H5A.close(attrId); if (groupId != null) { H5G.close(groupId); } if (dataSetId != null) { H5D.close(dataSetId); } H5F.close(fileId); return((double)dAttrs[0]); } catch (HDFException e) { Console.WriteLine("Error: Unhandled HDF5 exception"); Console.WriteLine(e.Message); } return(attr); }
private static void ConvertHdf4To5(Hdf4FileAttrs hdf4FileAttrs, string f5name, Action <string, int, int> messageAction) { try { // Create a new file using H5F_ACC_TRUNC access, // default file creation properties, and default file // access properties. H5FileId fileId = H5F.create(f5name, H5F.CreateMode.ACC_TRUNC); int nxf5 = hdf4FileAttrs.Hdf4FileAttr.XDim; int nyf5 = hdf4FileAttrs.Hdf4FileAttr.YDim; int rank = 2; //测试读取的科学数据集及其属性 int sdscount = hdf4FileAttrs.Hdf4FileAttr.DataFields.Count; for (int k = 0; k < sdscount; k++) { ConvertHdf4To5BySds(hdf4FileAttrs, messageAction, k, nyf5, nxf5, rank, fileId); } HDFAttributeDef[] attributeDef5s = hdf4FileAttrs.GetHDFAttributeDefs(); foreach (HDFAttributeDef attributeDef5 in attributeDef5s) { WriteHdfAttributes.WriteHdfAttribute(fileId, attributeDef5); } H5F.close(fileId); } catch (Exception ex) { throw new Exception("拼接Hdf4时出错,具体信息:" + ex.Message, ex); } }
public void Close() { if (m_fileId != null) { H5F.close(m_fileId); } }
public void Cleanup() { file_.Close(); H5D.close(dataSet_); H5F.close(h5file_); }
} // make_table static void test_getting_info() { try { Console.Write("Testing getting table/field information"); // Open the file to check on the table. H5FileId fileId = H5F.open(FILE_NAME, H5F.OpenMode.ACC_RDWR); hssize_t nfields = 0, nrecords = 0; string[] field_names = { "c", "i", "l" }; // Get the table info. TableInfo table = H5TB.getTableInfo(fileId, TABLE_NAME); if (table.nFields != N_FIELDS) { Console.WriteLine("\ntest_getting_info: incorrect number of fields: read {0} - should be {1}", nfields, N_FIELDS); nerrors++; } if (table.nRecords != N_RECORDS) { Console.WriteLine("\ntest_getting_info: incorrect number of fields: read {0} - should be {1}", nrecords, N_RECORDS); nerrors++; } // Get field info. int [] sizes = new int[N_FIELDS]; int [] offsets = new int[N_FIELDS]; TableFieldInfo tablefield = H5TB.getFieldInfo(fileId, TABLE_NAME); int ii; for (ii = 0; ii < N_FIELDS; ii++) { if (tablefield.fieldName[ii] != field_names[ii]) { Console.WriteLine("\ntest_getting_info: field #{0} has incorrect name: read {0} - should be {1}", ii, field_names[ii], tablefield.fieldName[ii]); nerrors++; } } H5F.close(fileId); Console.WriteLine("\t\t\tPASSED"); } catch (HDFException anyHDF5E) { Console.WriteLine(anyHDF5E.Message); nerrors++; } catch (System.Exception sysE) { Console.WriteLine(sysE.TargetSite); Console.WriteLine(sysE.Message); nerrors++; } } // test_getting_info
public override void CloseDocument() { if (fileId != null && fileId.Id > 0 && !_fileClosed) { foreach (var group in EpochGroupsIDs) { try { H5G.close(group.GroupId); H5G.close(group.SubGroupsId); H5G.close(group.EpochsId); } catch (H5GcloseException ex) { log.DebugFormat("HDF5 group already closed: {0}", ex); } } try { H5F.close(fileId); } catch (H5FcloseException ex) { log.DebugFormat("HDF5 file already closed: {0}", ex); } Interlocked.Decrement(ref _openHdf5FileCount); _fileClosed = true; } }
public static T GetMetadata <T>(string filename, string path) { H5FileId zFile = null; if (!File.Exists(filename)) { throw new Exception("File not found."); } try { zFile = H5F.open(filename, H5F.OpenMode.ACC_RDONLY); return((T)HDFExtensions.ReadScalar <T>(zFile, path)); } catch { throw new Exception("Path not found"); } finally { if (zFile != null) { H5F.close(zFile); } } }
private static Hdf5Container_LidarDaimler ReadContainer(string sFilePath_inp) { int status = 0; long file_id = H5F.open(sFilePath_inp, H5F.ACC_RDWR); long testDataset_id = H5D.open(file_id, "distance"); long testDataspace_id = H5D.get_space(testDataset_id); ulong[] dims = new ulong[2]; status = H5S.get_simple_extent_dims(testDataspace_id, dims, null); int rows = Convert.ToInt32(dims[0]); int cols = Convert.ToInt32(dims[1]); Hdf5Container_LidarDaimler outContainer = new Hdf5Container_LidarDaimler(rows, cols) { _distances = Hdf5IO.GetFloatDataset(H5D.open(file_id, "distance"), rows, cols), _intensity = Hdf5IO.GetFloatDataset(H5D.open(file_id, "intensity"), rows, cols), _labelProbabilities = Hdf5IO.GetFloatDataset(H5D.open(file_id, "labelProbabilities"), rows, cols), _labelWorkingSet = Hdf5IO.GetLabelWorkingSet(H5G.open(file_id, "labelWorkingSet")), _labels = Hdf5IO.GetUintDataset(H5D.open(file_id, "labels"), rows, cols), _pointValid = Hdf5IO.GetIntDataset(H5D.open(file_id, "pointValid"), rows, cols), _sensorX = Hdf5IO.GetFloatDataset(H5D.open(file_id, "sensorX"), rows, cols), _sensorY = Hdf5IO.GetFloatDataset(H5D.open(file_id, "sensorY"), rows, cols), _sensorZ = Hdf5IO.GetFloatDataset(H5D.open(file_id, "sensorZ"), rows, cols), _vehicleX = Hdf5IO.GetFloatDataset(H5D.open(file_id, "vehicleX"), rows, cols), _vehicleY = Hdf5IO.GetFloatDataset(H5D.open(file_id, "vehicleY"), rows, cols), _vehicleZ = Hdf5IO.GetFloatDataset(H5D.open(file_id, "vehicleZ"), rows, cols) }; status = H5F.close(file_id); return(outContainer); }
public static void UpdateCampaignInfoSet() { long vdsFileId = -1; long vdsMetaFileId = -1; long groupId = -1; lock (_lock) { try { if (File.Exists(_options.VdsFilePath)) { vdsFileId = H5F.open(_options.VdsFilePath, H5F.ACC_RDONLY); vdsMetaFileId = H5F.open(_options.VdsMetaFilePath, H5F.ACC_RDONLY); Program.CampaignInfoSet = GeneralHelper.GetCampaignInfoSet(vdsFileId, false); } else { Program.CampaignInfoSet = new List <CampaignInfo>(); } Program.CampaignDescriptionSet = Program.CampaignInfoSet.ToDictionary(campaignInfo => campaignInfo.Name, campaignInfo => { if (IOHelper.CheckLinkExists(vdsMetaFileId, campaignInfo.Name)) { try { groupId = H5G.open(vdsMetaFileId, campaignInfo.Name); if (H5A.exists(groupId, "description") > 0) { return(IOHelper.ReadAttribute <string>(groupId, "description").First()); } } finally { if (H5I.is_valid(groupId) > 0) { H5G.close(groupId); } } } return("no description available"); }); } finally { if (H5I.is_valid(vdsFileId) > 0) { H5F.close(vdsFileId); } if (H5I.is_valid(vdsMetaFileId) > 0) { H5F.close(vdsMetaFileId); } } } }
public static double[,] ReadFieldData2D(string file, string dataSet) { H5FileId fileId = H5F.open(file, H5F.OpenMode.ACC_RDONLY); H5DataSetId fDataSetId = H5D.open(fileId, dataSet); H5DataTypeId fDataTypeId = H5D.getType(fDataSetId); long[] dims = H5S.getSimpleExtentDims(H5D.getSpace(fDataSetId)).ToArray(); double[,] data = new double[dims[0], dims[1]]; H5D.read(fDataSetId, fDataTypeId, new H5Array <double>(data)); double[,] fieldValues = new double[dims[1], dims[0]]; for (int i = 0; i < dims[1]; i++) { for (int j = 0; j < dims[0]; j++) { fieldValues[i, j] = (double)data[j, i]; } } H5T.close(fDataTypeId); H5D.close(fDataSetId); H5F.close(fileId); return(fieldValues); }
public static double[][] ReadMesh(string fileName) { double[][] meshes = new double[3][]; string[] meshNames = { "x", "y", "z" }; H5FileId fileId = H5F.open(fileName, H5F.OpenMode.ACC_RDONLY); for (int i = 0; i < meshNames.Length; i++) { H5DataSetId dsId = H5D.open(fileId, "/Mesh/" + meshNames[i]); H5DataTypeId dtId = H5D.getType(dsId); if (!H5T.equal(dtId, H5T.copy(H5T.H5Type.NATIVE_FLOAT))) { Console.WriteLine("Error: Invalid dataset type, expected {0}", H5T.H5Type.NATIVE_FLOAT); } float[] mesh = new float[H5D.getStorageSize(dsId) / H5T.getSize(dtId)]; H5D.read(dsId, dtId, new H5Array <float>(mesh)); meshes[i] = mesh.Select(x => (double)x * 1000.0).ToArray(); // m -> mm H5D.close(dsId); H5T.close(dtId); } H5F.close(fileId); return(meshes); }
private static void WriteFile(string filePath) { var file = H5F.create(filePath, H5F.CreateMode.ACC_TRUNC); var group = H5G.create(file, "/group"); H5G.close(group); const int RANK = 2; const int DIM0 = 3; const int DIM1 = 4; var dims = new long[RANK] { DIM0, DIM1 }; var dataSpace = H5S.create_simple(RANK, dims); var dataSet = H5D.create(file, "/group/dataset", H5T.H5Type.NATIVE_INT, dataSpace); H5S.close(dataSpace); var data = new int[DIM0, DIM1] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; H5D.write(dataSet, new H5DataTypeId(H5T.H5Type.NATIVE_INT), new H5Array <int>(data)); var dataType = new H5DataTypeId(H5T.H5Type.NATIVE_INT); dataSpace = H5S.create(H5S.H5SClass.SCALAR); var integerAttribute = H5A.create(dataSet, "int", dataType, dataSpace); H5A.write(integerAttribute, dataType, new H5Array <int>(new int[1] { 42 })); H5A.close(integerAttribute); H5S.close(dataSpace); //H5T.close(dataType); // Read-only. var str = "Hello, world!"; var strBytes = Encoding.ASCII.GetBytes(str); // There is a H5T.get_cset, but there does not seem to be a way of setting the character encoding, i.e. set_cset. dataType = H5T.copy(H5T.H5Type.C_S1); H5T.setSize(dataType, strBytes.Length); dataSpace = H5S.create(H5S.H5SClass.SCALAR); var stringAttribute = H5A.create(dataSet, "string", dataType, dataSpace); H5A.write(stringAttribute, dataType, new H5Array <byte>(strBytes)); H5A.close(stringAttribute); H5S.close(dataSpace); H5T.close(dataType); H5D.close(dataSet); H5F.close(file); }
public Dictionary <string, string> TryReadDataTable(string datasetName) { Dictionary <string, string> result = null; var subDsDic = ds.GetSubDatasets(); if (subDsDic.Count > 0) { H5ID h5FileId = H5F.open(fileName, H5F.ACC_RDONLY); H5ID datasetId = H5D.open(h5FileId, datasetName); H5ID typeId = H5D.get_type(datasetId); H5ID spaceId = H5D.get_space(datasetId); if (H5T.get_class(typeId) == H5T.class_t.COMPOUND) { int numCount = H5T.get_nmembers(typeId); var size = H5T.get_size(typeId); byte[] buffer = new byte[size.ToInt32()]; GCHandle hnd = GCHandle.Alloc(buffer, GCHandleType.Pinned); int ndims = H5S.get_simple_extent_ndims(spaceId); if (ndims == 1) { result = new Dictionary <string, string>(); H5D.read(datasetId, typeId, H5S.ALL, H5S.ALL, H5P.DEFAULT, hnd.AddrOfPinnedObject()); for (uint i = 0; i < numCount; i++) { string name = Marshal.PtrToStringAnsi(H5T.get_member_name(typeId, i)); int offset = H5T.get_member_offset(typeId, i).ToInt32(); H5ID subTypeId = H5T.get_member_type(typeId, i); H5T.class_t typeClass = H5T.get_member_class(typeId, i); string value = ReadBuffer(buffer, offset, typeClass, subTypeId); result.Add(name, value); H5T.close(subTypeId); } } hnd.Free(); } if (spaceId != 0) { H5S.close(spaceId); } if (typeId != 0) { H5T.close(typeId); } if (datasetId != 0) { H5D.close(datasetId); } if (h5FileId != 0) { H5F.close(h5FileId); } } return(result); }
/// <summary> /// Release all resources uses. /// </summary> public void Dispose() { if (m_file != null) { H5F.close(m_file); m_file = null; } }
public void Cleanup() { // close the test-local files Assert.IsTrue(H5F.close(m_v0_test_file) >= 0); Assert.IsTrue(H5F.close(m_v2_test_file) >= 0); File.Delete(m_v0_test_file_name); File.Delete(m_v2_test_file_name); }
public static void ClassCleanup() { // close the global test files Assert.IsTrue(H5F.close(m_v0_class_file) >= 0); Assert.IsTrue(H5F.close(m_v2_class_file) >= 0); File.Delete(m_v0_class_file_name); File.Delete(m_v2_class_file_name); }
/// <summary> /// Closes the HDF file handle if still open and resets the handle. /// </summary> public void Close() { if (this.h5FileId > -1) { this.h5FileId = H5F.close(this.h5FileId); this.h5FileId = -1; } }
/// <summary> /// 释放资源 /// </summary> public void Dispose() { if (_fileId != null) { H5F.close(_fileId); _fileId = null; } }
static void test_file_open() { try { // Output message about test being performed. Console.Write("Testing file opening I/O"); // First ensure the file does not exist File.Delete(FILE2); // Try opening a non-existent file. This should fail. try { H5FileId non_exist_file = H5F.open(FILE2, H5F.OpenMode.ACC_RDWR); // should fail, but didn't, print out the error message. Console.WriteLine("\ntest_file_open: Attempting to open a non-existent file."); nerrors++; } catch (H5FopenException) { } // does nothing, it should fail // Open the file. H5FileId fileId = H5F.open(FILE1, H5F.OpenMode.ACC_RDWR); // Create dataspace for the dataset in the file. hssize_t[] dims = { 20 }; H5DataSpaceId dspace = H5S.create_simple(RANK, dims); // Create a group. H5GroupId groupId = H5G.create(fileId, GROUP_NAME); // Create a dataset using file as location. H5DataSetId dset1Id = H5D.create(fileId, DSET1_NAME, H5T.H5Type.NATIVE_INT, dspace); // Create a dataset using group as location. H5DataSetId dset2Id = H5D.create(groupId, DSET2_NAME, H5T.H5Type.NATIVE_SHORT, dspace); // Close objects and files. H5D.close(dset1Id); H5D.close(dset2Id); H5S.close(dspace); H5G.close(groupId); H5F.close(fileId); Console.WriteLine("\t\t\t\tPASSED"); } catch (HDFException anyHDF5E) { Console.WriteLine(anyHDF5E.Message); nerrors++; } catch (System.Exception sysE) { Console.WriteLine(sysE.TargetSite); Console.WriteLine(sysE.Message); nerrors++; } } // test_file_open
private static void cleanupVDS() { Assert.IsTrue(H5F.close(m_vds_class_file) >= 0); File.Delete(m_vds_class_file_name); File.Delete(m_a_class_file_name); File.Delete(m_b_class_file_name); File.Delete(m_c_class_file_name); }
/// <summary> /// WARNING: ADVANCED USE ONLY!! Loads a 2D generic dataset from an H5 file. /// The generic loaders only loads data in non-Unity friendly types, such as bytes, uints, longs etc... /// You'll have to know the correct cast to retrieve usable data. /// /// Created With help from https://github.com/LiorBanai/HDF5-CSharp/blob/master/HDF5-CSharp/Hdf5Dataset.cs /// </summary> /// <param name="filePath"></param> /// <param name="datasetName"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> /// <exception cref="FileNotFoundException"></exception> static T[,] Load2DDataset <T>(string filePath, string datasetName) { if (!File.Exists(filePath)) { throw new FileNotFoundException($"Loading dataset {datasetName} from file that doesn't exist {filePath}"); } long fileId = H5F.open(filePath, H5F.ACC_RDONLY); T[,] resultArray = new T[2, 2]; try { ulong[] start = { 0, 0 }; ulong[] count = { 0, 0 }; long datasetId = H5D.open(fileId, datasetName); var datatype = H5D.get_type(datasetId); var spaceId = H5D.get_space(datasetId); int rank = H5S.get_simple_extent_ndims(spaceId); ulong[] maxDims = new ulong[rank]; ulong[] dims = new ulong[rank]; H5S.get_simple_extent_dims(spaceId, dims, maxDims); count[0] = dims[0]; count[1] = dims[1]; // Define file hyperslab. long status = H5S.select_hyperslab(spaceId, H5S.seloper_t.SET, start, null, count, null); // Define the memory dataspace. resultArray = new T[dims[0], dims[1]]; var memId = H5S.create_simple(rank, dims, null); // Define memory hyperslab. status = H5S.select_hyperslab(memId, H5S.seloper_t.SET, start, null, count, null); // Read data from hyperslab in the file into the hyperslab in // memory and display. GCHandle handle = GCHandle.Alloc(resultArray, GCHandleType.Pinned); try { H5D.read(datasetId, datatype, memId, spaceId, H5P.DEFAULT, handle.AddrOfPinnedObject()); } finally { handle.Free(); H5S.close(status); H5S.close(memId); H5S.close(spaceId); H5D.close(datatype); H5D.close(datasetId); } } finally { H5F.close(fileId); } return(resultArray); }
public bool FileExistsApi(string source, string filename) { var fileId = H5F.open(source, H5F.OpenMode.ACC_RDONLY); var result = H5L.Exists(fileId, filename); H5F.close(fileId); return(result); }
private void Menu_2(Dictionary <string, string> settings) // edit variable name { long fileId; long groupId; string variableGroupPath; string attributeName; string[] attributeContentSet; List <string> filePathSet; // settings = this.PromptEditVariableNameData(settings); if (settings.ContainsKey("DirectoryPath")) { filePathSet = Directory.GetFiles(settings["DirectoryPath"], settings["SearchPattern"], settings["IncludeSubDirectories"] == "Yes" ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).ToList(); } else { filePathSet = new List <string>() { settings["FilePath"] }; } variableGroupPath = settings["VariableGroupPath"]; attributeName = "name_set"; attributeContentSet = new string[] { settings["VariableName"] }; foreach (string filePath in filePathSet) { fileId = H5F.open(filePath, H5F.ACC_RDWR, 0); if (IOHelper.CheckLinkExists(fileId, variableGroupPath)) { groupId = H5G.open(fileId, variableGroupPath); if (settings["AppendMode"] == "Append") { IOHelper.PrepareAttribute(groupId, attributeName, attributeContentSet, new ulong[] { H5S.UNLIMITED }, true); } else { IOHelper.WriteAttribute(groupId, attributeName, attributeContentSet); } // clean up H5G.close(groupId); } // clean up H5F.close(fileId); } }
private void Menu_2() { long vdsFileId = -1; long vdsMetaFileId = -1; long fcPropertyId = -1; string vdsFilePath; string vdsMetaFilePath; List <CampaignInfo> campaignInfoSet; IList <HdfElementBase> currentList; // vdsFilePath = Path.Combine(Program.BaseDirectoryPath, "VDS.h5"); vdsMetaFilePath = Path.Combine(Program.BaseDirectoryPath, "VDS_META.h5"); try { if (File.Exists(vdsFilePath)) { vdsFileId = H5F.open(vdsFilePath, H5F.ACC_RDONLY); } else { return; } if (File.Exists(vdsMetaFilePath)) { vdsMetaFileId = H5F.open(vdsMetaFilePath, H5F.ACC_RDWR); } if (vdsMetaFileId == -1) { fcPropertyId = H5P.create(H5P.FILE_CREATE); H5P.set_file_space(fcPropertyId, H5F.file_space_type_t.ALL_PERSIST); vdsMetaFileId = H5F.create(vdsMetaFilePath, H5F.ACC_TRUNC, fcPropertyId); } campaignInfoSet = GeneralHelper.GetCampaignInfoSet(vdsFileId, true); currentList = campaignInfoSet.Cast <HdfElementBase>().ToList(); new VdsMetaNavigator(vdsFileId, vdsMetaFileId, "/", currentList); } finally { if (H5I.is_valid(vdsFileId) > 0) { H5F.close(vdsFileId); } if (H5I.is_valid(vdsMetaFileId) > 0) { H5F.close(vdsMetaFileId); } } }
public void Cleanup() { #if HDF5_VER1_10 // close the test-local files Assert.IsTrue(H5F.close(m_v3_test_file_no_swmr) >= 0); File.Delete(m_v3_test_file_name_no_swmr); Assert.IsTrue(H5F.close(m_v3_test_file_swmr) >= 0); File.Delete(m_v3_test_file_name_swmr); #endif }
public void Close() { var result = H5F.close(h5ID); if (result < 0) { throw new IOException($"Error closing HDF5 File: {Filename}, error code {result}"); } closed = true; }
public void H5Fis_hdf5Test1() { string fname = Path.GetTempFileName(); hid_t file = H5F.create(fname, H5F.ACC_TRUNC); Assert.IsTrue(file >= 0); Assert.IsTrue(H5F.close(file) >= 0); Assert.IsTrue(H5F.is_hdf5(fname) > 0); File.Delete(fname); }
public static void ClassCleanup() { Assert.IsTrue(H5P.close(m_acpl) >= 0); // close the global test files Assert.IsTrue(H5F.close(m_v0_class_file) >= 0); Assert.IsTrue(H5F.close(m_v2_class_file) >= 0); Assert.IsTrue(H5S.close(m_space_null) >= 0); Assert.IsTrue(H5S.close(m_space_scalar) >= 0); File.Delete(m_v0_class_file_name); File.Delete(m_v2_class_file_name); }
public static void ClassCleanup() { #if HDF5_VER1_10 Assert.IsTrue(H5P.close(m_lcpl) >= 0); Assert.IsTrue(H5P.close(m_lcpl_utf8) >= 0); // close the global test files Assert.IsTrue(H5F.close(m_v3_class_file) >= 0); File.Delete(m_v3_class_file_name); #endif }
public void Close() { closeTables(); closeIndexMaps(); if (fileId != null) { H5F.close(fileId); } this.IsValid = false; this.Shape = new long[] { 0, 0 }; }