public static string GetAttributeValue(H5ObjectWithAttributes objectWithAttributes, string name) { if (objectWithAttributes is null) { throw new ArgumentNullException(nameof(objectWithAttributes)); } if (name is null) { throw new ArgumentNullException(nameof(name)); } H5AttributeId h5AttributeId = H5A.open(objectWithAttributes, name); H5DataTypeId h5DataTypeId = H5A.getType(h5AttributeId); if (H5T.isVariableString(h5DataTypeId)) { VariableLengthString[] variableLengthStrings = new VariableLengthString[1]; H5A.read(h5AttributeId, h5DataTypeId, new H5Array <VariableLengthString> (variableLengthStrings)); H5T.close(h5DataTypeId); H5A.close(h5AttributeId); return(variableLengthStrings[0].ToString()); } byte[] bytes = new byte[H5T.getSize(h5DataTypeId)]; H5A.read(h5AttributeId, h5DataTypeId, new H5Array <byte> (bytes)); H5T.close(h5DataTypeId); H5A.close(h5AttributeId); return(Encoding.ASCII.GetString(bytes)); }
private static void WriteAttribute(H5ObjectWithAttributes target, string name, string value) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Name must not be empty (or null)", "name"); } if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Value must not be empty or null", "value"); } H5DataTypeId dtype; byte[] strdata = EncodeStringData(value, out dtype); H5DataSpaceId spaceId = H5S.create(H5S.H5SClass.SCALAR); H5AttributeId attributeId = H5A.create(target, name, dtype, spaceId); H5A.write(attributeId, dtype, new H5Array <byte>(strdata)); H5A.close(attributeId); H5T.close(dtype); H5S.close(spaceId); }
/// <summary> /// 写数据集属性 /// </summary> public void WriteDatasetAttribute(string datasetName, string attrName, string value) { H5DataSetId datasetId = H5D.open(_fileId, datasetName); H5DataTypeId typeId = H5T.copy(H5T.H5Type.C_S1); H5DataSpaceId spaceId = H5S.create(H5S.H5SClass.SCALAR); H5T.setSize(typeId, value.Length); H5AttributeId attrId = H5A.create(datasetId, attrName, typeId, spaceId); if (value != "") { H5Array <byte> buffer = new H5Array <byte>(Encoding.Default.GetBytes(value)); H5A.write(attrId, typeId, buffer); } if (typeId != null) { H5T.close(typeId); } if (spaceId != null) { H5S.close(spaceId); } if (attrId != null) { H5A.close(attrId); } if (datasetId != null) { H5D.close(datasetId); } }
public static string AttributeAsString(H5AttributeId _attributeId) { H5DataTypeId dataTypeId = H5A.getType(_attributeId); bool isVariableLength = H5T.isVariableString(dataTypeId); if (isVariableLength) { // Variable length string attribute // NOTE: This section only works if the array length is 1 VariableLengthString[] value = new VariableLengthString[1]; H5A.read <VariableLengthString>(_attributeId, dataTypeId, new H5Array <VariableLengthString>(value)); return(value[0].ToString()); } else { // Make length smaller so null termination character is not read int length = (int)H5T.getSize(dataTypeId) - 1; // Fixed length string attribute byte[] valueBytes = new byte[length]; H5A.read <byte>(_attributeId, dataTypeId, new H5Array <byte>(valueBytes)); string value = System.Text.ASCIIEncoding.ASCII.GetString(valueBytes); return(value); } }
private bool getOMXFileAttributes() { string version = "unknown"; // OMX Version H5AttributeId verId = H5A.open(fileId, omxVersionName); H5T.H5TClass verCl = H5T.getClass(H5A.getType(verId)); if (verCl.Equals(H5T.H5TClass.STRING)) { Byte[] buff = getAttribute <byte>(verId); ASCIIEncoding enc = new ASCIIEncoding(); version = enc.GetString(buff); } else if (verCl.Equals(H5T.H5TClass.FLOAT)) { float[] buff = getAttribute <float>(verId); version = buff.ToString(); // produces garbage - bail out from here... throw new NotImplementedException(); } else { throw new NotImplementedException(); } //Console.WriteLine("omx version: {0}", version); this.OmxVersion = version; H5A.close(verId); // matrix shape H5AttributeId shId = H5A.open(fileId, omxShapeAttr); H5T.H5TClass shCl = H5T.getClass(H5A.getType(shId)); if (shCl.Equals(H5T.H5TClass.INTEGER)) { int[] shape = getAttribute <int>(shId); this.Shape[0] = (long)shape[0]; this.Shape[1] = (long)shape[1]; } else if (shCl.Equals(H5T.H5TClass.FLOAT)) { float[] shape = getAttribute <float>(shId); this.Shape[0] = (long)shape[0]; this.Shape[1] = (long)shape[1]; // returns garbage, bail out from here throw new NotImplementedException(); } else { throw new NotImplementedException(); } H5A.close(shId); return(true); }
public static int AttributeAsInt32(H5AttributeId _attributeId) { H5DataTypeId attributeType = H5T.copy(H5T.H5Type.NATIVE_INT); int[] value = new int[1]; H5A.read <int>(_attributeId, attributeType, new H5Array <int>(value)); return(value[0]); }
public static Double AttributeAsDouble(H5AttributeId _attributeId) { H5DataTypeId attributeType = H5T.copy(H5T.H5Type.NATIVE_DOUBLE); double[] value = new double[1]; H5A.read <double>(_attributeId, attributeType, new H5Array <double>(value)); return(value[0]); }
protected T[] getAttribute <T>(H5AttributeId aid) { H5DataTypeId sv = H5A.getType(aid); int size = H5T.getSize(sv); var attValue = new T[size]; H5A.read <T>(aid, sv, new H5Array <T>(attValue)); return(attValue); }
// Generate string attribute // GroupName: target group for the new attribute // AttName: attribute name // AttContent: content for the attribute, has to be a string public static void StringAttributeGenerator(H5GroupId GroupName, string AttName, string AttContent) { char[] AttContentChar = AttContent.ToCharArray(); byte[] asciiStr = ASCIIEncoding.ASCII.GetBytes(AttContentChar); int length = asciiStr.Length; H5AttributeId attributeId = H5A.create(GroupName, AttName, H5T.create(H5T.CreateClass.STRING, length), H5S.create(H5S.H5SClass.SCALAR)); H5A.write(attributeId, H5T.create(H5T.CreateClass.STRING, length), new H5Array <byte>(asciiStr)); H5A.close(attributeId); }
private T[] ReadArray <T>(long size, H5AttributeId attId, H5DataTypeId typeId) { T[] v = new T[size]; if (size == 0) { return(v); } H5A.read <T>(attId, typeId, new H5Array <T>(v)); return(v); }
// Generate floating number attributes // GroupName: target group for the new attribute // AttName: attribute name // AttContent: content for the attribute, has to be a single floating number, here 32bit floating number is used, consider using 64bit double if necessary public static void NumberAttributeGenerator(H5GroupId GroupName, string AttName, float AttContent) { float[] AttArray = new float[1] { AttContent }; long[] dims = new long[1]; dims[0] = AttArray.Length; H5AttributeId attributeId = H5A.create(GroupName, AttName, H5T.copy(H5T.H5Type.NATIVE_FLOAT), H5S.create_simple(1, dims)); H5A.write(attributeId, H5T.copy(H5T.H5Type.NATIVE_FLOAT), new H5Array <float>(AttArray)); H5A.close(attributeId); }
// Generate double attributes // GroupName: target group for the new attribute // AttName: attribute name // AttContent: content for the attribute, has to be a single floating number, here 64bit double is used, to generate subgroups in Data public static void DoubleAttributeGenerator(H5GroupId GroupName, string AttName, double AttContent) { double[] AttArray = new double[1] { AttContent }; long[] dims = new long[1]; dims[0] = AttArray.Length; H5AttributeId attributeId = H5A.create(GroupName, AttName, H5T.copy(H5T.H5Type.NATIVE_DOUBLE), H5S.create_simple(1, dims)); H5A.write(attributeId, H5T.copy(H5T.H5Type.NATIVE_FLOAT), new H5Array <double>(AttArray)); H5A.close(attributeId); }
private static H5AttributeId WriteStringAttribute(H5ObjectWithAttributes fileOrdatasetId, HDFAttributeDef hDFAttributeDef, H5DataSpaceId dataSpaceId, H5DataTypeId dataTypeId) { string attValue = Convert.ToString(hDFAttributeDef.Value); int stringLength = attValue.Length; H5T.setSize(dataTypeId, stringLength); H5AttributeId attributeId = H5A.create(fileOrdatasetId, hDFAttributeDef.Name, dataTypeId, dataSpaceId); byte[] bs = Encoding.Default.GetBytes(attValue); H5A.write(attributeId, dataTypeId, new H5Array <byte>(bs)); return(attributeId); }
static void test_attr_plist() { try { Console.Write("Testing attribute property lists"); hssize_t[] dims = { 256, 512 }; const string PLST_FILE_NAME = ("tattr_plist.h5"); hssize_t[] dims1 = { SPACE1_DIM1, SPACE1_DIM2, SPACE1_DIM3 }; hssize_t[] dims2 = { ATTR1_DIM }; // Create file. H5FileId fileId = H5F.create(PLST_FILE_NAME, H5F.CreateMode.ACC_TRUNC); // Create dataspace for dataset. H5DataSpaceId space1_Id = H5S.create_simple(SPACE1_RANK, dims1); // Create a dataset. H5DataSetId dsetId = H5D.create(fileId, DSET1_NAME, H5T.H5Type.NATIVE_UCHAR, space1_Id); // Create dataspace for attribute. H5DataSpaceId space2_Id = H5S.create_simple(ATTR1_RANK, dims2); // Create default property list for attribute. H5PropertyListId plist = H5P.create(H5P.PropertyListClass.ATTRIBUTE_CREATE); // Create an attribute for the dataset using the property list. H5AttributeId attrId = H5A.create(dsetId, ATTR1_NAME, new H5DataTypeId(H5T.H5Type.NATIVE_INT), space2_Id, plist); // Close all objects. H5S.close(space1_Id); H5S.close(space2_Id); H5P.close(plist); H5A.close(attrId); H5D.close(dsetId); 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_attr_plist
private static void WriteAttribute(H5ObjectWithAttributes target, string name, long value) { H5DataTypeId dtype = H5T.copy(H5T.H5Type.NATIVE_LLONG); H5DataSpaceId spaceId = H5S.create(H5S.H5SClass.SCALAR); H5AttributeId attributeId = H5A.create(target, name, dtype, spaceId); H5A.write(attributeId, dtype, new H5Array <long>(new[] { value })); H5A.close(attributeId); H5T.close(dtype); H5S.close(spaceId); }
private static void WriteAttribute(H5ObjectWithAttributes target, string name, double[] value) { H5DataTypeId dtype = H5T.copy(H5T.H5Type.NATIVE_DOUBLE); H5DataSpaceId spaceId = H5S.create_simple(1, new[] { value.LongCount() }); H5AttributeId attributeId = H5A.create(target, name, dtype, spaceId); H5A.write(attributeId, dtype, new H5Array <double>(value)); H5A.close(attributeId); H5T.close(dtype); H5S.close(spaceId); }
// Function used with H5A.iterate static H5IterationResult MyH5AFunction( H5AttributeId attributeId, String attributeName, H5AttributeInfo info, Object attributeNames) { Console.WriteLine("Iteration attribute is {0}", attributeName); ArrayList nameList = (ArrayList)attributeNames; nameList.Add(attributeName); // Returning SUCCESS means that iteration should continue to the // next attribute (if one exists). return(H5IterationResult.SUCCESS); }
public static void WriteDataCube(H5FileId fileId, UInt16[,,] datacube) { H5GroupId dataGroup = H5G.create(fileId, "/data"); H5GroupId dataSubGroup = H5G.create(dataGroup, "DEsoftware"); long[] dims = new long[3] { datacube.GetLength(0), datacube.GetLength(1), datacube.GetLength(2) }; H5DataSpaceId spaceId = H5S.create_simple(3, dims); H5DataTypeId typeId = H5T.copy(H5T.H5Type.NATIVE_USHORT); H5DataSetId dataSetId = H5D.create(dataSubGroup, "data", typeId, spaceId); // create attribute emd_group_type for dataSubGroup, which is required to have value 1 int par = 1; long[] attdims = new long[1]; int[] AttArray = new int[1] { par }; dims[0] = AttArray.Length; H5AttributeId attributeId = H5A.create(dataSubGroup, "emd_group_type", H5T.copy(H5T.H5Type.NATIVE_UCHAR), H5S.create_simple(1, dims)); H5A.write(attributeId, H5T.copy(H5T.H5Type.NATIVE_INT), new H5Array <int>(AttArray)); H5A.close(attributeId); // write datacube to "data", which contains whole 3D datacube H5D.write <ushort>(dataSetId, typeId, new H5Array <ushort>(datacube)); // create three more array for three dimensions long[] dim1 = new long[1] { datacube.GetLength(0) }; double[] dimarray = new double [datacube.GetLength(0)]; spaceId = H5S.create_simple(3, dim1); typeId = H5T.copy(H5T.H5Type.NATIVE_DOUBLE); dataSetId = H5D.create(dataSubGroup, "dim1", typeId, spaceId); H5D.write <double>(dataSetId, typeId, new H5Array <double>(dimarray)); H5S.close(spaceId); H5T.close(typeId); H5D.close(dataSetId); H5G.close(dataGroup); H5G.close(dataSubGroup); }
static void Main(string[] args) { try { // We will write and read an int array of this length. const int DATA_ARRAY_LENGTH = 12; // Rank is the number of dimensions of the data array. const int RANK = 1; // Create an HDF5 file. // The enumeration type H5F.CreateMode provides only the legal // creation modes. Missing H5Fcreate parameters are provided // with default values. H5FileId fileId = H5F.create("myCSharp.h5", H5F.CreateMode.ACC_TRUNC); // Create a HDF5 group. H5GroupId groupId = H5G.create(fileId, "/cSharpGroup"); H5GroupId subGroup = H5G.create(groupId, "mySubGroup"); // Close the subgroup. H5G.close(subGroup); // Prepare to create a data space for writing a 1-dimensional // signed integer array. long[] dims = new long[RANK]; dims[0] = DATA_ARRAY_LENGTH; // Put descending ramp data in an array so that we can // write it to the file. int[] dset_data = new int[DATA_ARRAY_LENGTH]; for (int i = 0; i < DATA_ARRAY_LENGTH; i++) { dset_data[i] = DATA_ARRAY_LENGTH - i; } // Create a data space to accommodate our 1-dimensional array. // The resulting H5DataSpaceId will be used to create the // data set. H5DataSpaceId spaceId = H5S.create_simple(RANK, dims); // Create a copy of a standard data type. We will use the // resulting H5DataTypeId to create the data set. We could // have used the HST.H5Type data directly in the call to // H5D.create, but this demonstrates the use of H5T.copy // and the use of a H5DataTypeId in H5D.create. H5DataTypeId typeId = H5T.copy(H5T.H5Type.NATIVE_INT); // Find the size of the type int typeSize = H5T.getSize(typeId); Console.WriteLine("typeSize is {0}", typeSize); // Set the order to big endian H5T.setOrder(typeId, H5T.Order.BE); // Set the order to little endian H5T.setOrder(typeId, H5T.Order.LE); // Create the data set. H5DataSetId dataSetId = H5D.create(fileId, "/csharpExample", typeId, spaceId); // Write the integer data to the data set. H5D.write(dataSetId, new H5DataTypeId(H5T.H5Type.NATIVE_INT), new H5Array <int>(dset_data)); // If we were writing a single value it might look like this. // int singleValue = 100; // H5D.writeScalar(dataSetId, // new H5DataTypeId(H5T.H5Type.NATIVE_INT), // ref singleValue); // Create an integer array to receive the read data. int[] readDataBack = new int[DATA_ARRAY_LENGTH]; // Read the integer data back from the data set H5D.read(dataSetId, new H5DataTypeId(H5T.H5Type.NATIVE_INT), new H5Array <int>(readDataBack)); // Echo the data for (int i = 0; i < DATA_ARRAY_LENGTH; i++) { Console.WriteLine(readDataBack[i]); } // Close all the open resources. H5D.close(dataSetId); // Reopen and close the data sets to show that we can. dataSetId = H5D.open(fileId, "/csharpExample"); H5D.close(dataSetId); dataSetId = H5D.open(groupId, "/csharpExample"); H5D.close(dataSetId); H5T.close(typeId); H5G.close(groupId); // Get H5O info H5ObjectInfo objectInfo = H5O.getInfoByName(fileId, "/csharpExample"); Console.WriteLine("header.space.message is {0}", objectInfo.header.space.message); Console.WriteLine("fileNumber is {0}", objectInfo.fileNumber); Console.WriteLine("address is {0}", objectInfo.address); Console.WriteLine("type is {0}", objectInfo.objectType.ToString()); Console.WriteLine("reference count is {0}", objectInfo.referenceCount); Console.WriteLine("modification time is {0}", objectInfo.modificationTime); Console.WriteLine("birth time is {0}", objectInfo.birthTime); Console.WriteLine("access time is {0}", objectInfo.accessTime); Console.WriteLine("change time is {0}", objectInfo.changeTime); Console.WriteLine("number of attributes is {0}", objectInfo.nAttributes); Console.WriteLine("header version is {0}", objectInfo.header.version); Console.WriteLine("header nMessages is {0}", objectInfo.header.nMessages); Console.WriteLine("header nChunks is {0}", objectInfo.header.nChunks); Console.WriteLine("header flags is {0}", objectInfo.header.flags); H5LinkInfo linkInfo = H5L.getInfo(fileId, "/cSharpGroup"); Console.WriteLine( "address: {0:x}, charSet: {1}, creationOrder: {2}", linkInfo.address, linkInfo.charSet, linkInfo.creationOrder); Console.WriteLine("linkType: {0}, softLinkSizeOrUD: {1}", linkInfo.linkType, linkInfo.softLinkSizeOrUD); // Reopen the group id to show that we can. groupId = H5G.open(fileId, "/cSharpGroup"); // Use H5L.iterate to visit links H5LIterateCallback myDelegate; myDelegate = MyH5LFunction; ulong linkNumber = 0; H5IterationResult result = H5L.iterate(groupId, H5IndexType.NAME, H5IterationOrder.INCREASING, ref linkNumber, myDelegate, 0); // Create some attributes H5DataTypeId attributeType = H5T.copy(H5T.H5Type.NATIVE_INT); long[] attributeDims = new long[1]; const int RAMP_LENGTH = 5; attributeDims[0] = RAMP_LENGTH; int[] ascendingRamp = new int[RAMP_LENGTH] { 1, 2, 3, 4, 5 }; int[] descendingRamp = new int[RAMP_LENGTH] { 5, 4, 3, 2, 1 }; int[] randomData = new int[RAMP_LENGTH] { 3, 123, 27, 6, 1 }; int[] readBackRamp = new int[RAMP_LENGTH]; // Call set buffer using H5Memory // Allocate memory from "C" runtime heap (not garbage collected) H5Memory typeConversionBuffer = new H5Memory(new IntPtr(DATA_ARRAY_LENGTH)); H5Memory backgroundBuffer = new H5Memory(new IntPtr(DATA_ARRAY_LENGTH)); // Set the property list type conversion and background buffers. H5PropertyListId myPropertyListId = H5P.create(H5P.PropertyListClass.DATASET_XFER); H5P.setBuffer(myPropertyListId, typeConversionBuffer, backgroundBuffer); // Test use of vlen // Create a vlen data type H5DataTypeId tid1 = H5T.vlenCreate(H5T.H5Type.NATIVE_UINT); H5DataSetId vDataSetId = H5D.create(fileId, "/vlenTest", tid1, spaceId); // Create a jagged array of integers. hvl_t[] vlArray = new hvl_t[DATA_ARRAY_LENGTH]; // HDF5 variable length data types require the use of void // pointers. C# requires that sections of code that deal // directly with pointer be marked // as unsafe. unsafe { for (int i = 0; i < DATA_ARRAY_LENGTH; i++) { IntPtr ptr = new IntPtr((i + 1) * sizeof(int)); // Allocate memory that is not garbage collected. vlArray[i].p = H5CrtHeap.Allocate( new IntPtr((i + 1) * sizeof(int)) ).ToPointer(); // Fill the array with integers = the row number int *intPointer = (int *)vlArray[i].p; for (int j = 0; j < i + 1; j++) { intPointer[j] = (int)i; } if (IntPtr.Size == 8) { vlArray[i].len = (ulong)i + 1; } else { vlArray[i].len = (uint)i + 1; } } // Write the variable length data H5D.write(vDataSetId, tid1, new H5Array <hvl_t>(vlArray)); // Create an array to read back the array. hvl_t[] vlReadBackArray = new hvl_t[DATA_ARRAY_LENGTH]; // Read the array back H5D.read(vDataSetId, tid1, new H5Array <hvl_t>(vlReadBackArray)); // Write the data to the console for (int i = 0; i < DATA_ARRAY_LENGTH; i++) { int *iPointer = (int *)vlReadBackArray[i].p; for (int j = 0; j < i + 1; j++) { Console.WriteLine(iPointer[j]); } } // Reclaim the memory that read allocated H5D.vlenReclaim(tid1, spaceId, new H5PropertyListId(H5P.Template.DEFAULT), new H5Array <hvl_t>(vlReadBackArray)); // Now read it back again using our own memory manager //H5AllocateCallback allocDelegate = new H5AllocCallback(userAlloc); H5FreeCallback freeDelegate = new H5FreeCallback(userFree); H5PropertyListId memManagerPlist = H5P.create(H5P.PropertyListClass.DATASET_XFER); unsafe { H5P.setVlenMemManager(memManagerPlist, userAlloc, IntPtr.Zero, freeDelegate, IntPtr.Zero); } // Read the array back H5D.read(vDataSetId, tid1, new H5DataSpaceId(H5S.H5SType.ALL), new H5DataSpaceId(H5S.H5SType.ALL), memManagerPlist, new H5Array <hvl_t>(vlReadBackArray)); // Write the data to the console for (int i = 0; i < DATA_ARRAY_LENGTH; i++) { int *iPointer = (int *)vlReadBackArray[i].p; for (int j = 0; j < i + 1; j++) { Console.WriteLine(iPointer[j]); } } // Reclaim the memory that read allocated using our free routines H5D.vlenReclaim(tid1, spaceId, memManagerPlist, new H5Array <hvl_t>(vlReadBackArray)); } H5S.close(spaceId); H5DataSpaceId attributeSpace = H5S.create_simple(1, attributeDims); H5AttributeId attributeId = H5A.create(groupId, "ascendingRamp", attributeType, attributeSpace); int offset = H5T.getOffset(attributeType); Console.WriteLine("Offset is {0}", offset); H5DataTypeId float32BE = H5T.copy(H5T.H5Type.IEEE_F32BE); H5T.Norm norm = H5T.getNorm(float32BE); Console.WriteLine("Norm is {0}", norm); int precision = H5T.getPrecision(float32BE); Console.WriteLine("Precision is {0}", precision); H5FloatingBitFields bitFields = H5T.getFields(float32BE); Console.WriteLine("getFields: sign bit position: {0}", bitFields.signBitPosition); Console.WriteLine("getFields: exponent bit position: {0}", bitFields.exponentBitPosition); Console.WriteLine("getFields: number of exponent bits: {0}", bitFields.nExponentBits); Console.WriteLine("getFields: mantissa bit position: {0} ", bitFields.mantissaBitPosition); Console.WriteLine("getFields: number of mantissa bits: {0}", bitFields.nMantissaBits); Console.Write("{0}", bitFields); // Write to an attribute H5A.write <int>(attributeId, attributeType, new H5Array <int>(ascendingRamp)); // Read from an attribute H5A.read <int>(attributeId, attributeType, new H5Array <int>(readBackRamp)); // Echo results Console.WriteLine("ramp elements are: "); foreach (int rampElement in readBackRamp) { Console.WriteLine(" {0}", rampElement); } H5A.close(attributeId); // Create and write two more attributes. attributeId = H5A.createByName(groupId, ".", "descendingRamp", attributeType, attributeSpace); H5A.write <int>(attributeId, attributeType, new H5Array <int>(descendingRamp)); H5A.close(attributeId); attributeId = H5A.createByName(groupId, ".", "randomData", attributeType, attributeSpace); H5A.write <int>(attributeId, attributeType, new H5Array <int>(randomData)); // Read back the attribute data H5A.read <int>(attributeId, attributeType, new H5Array <int>(readBackRamp)); Console.WriteLine("ramp elements are: "); foreach (int rampElement in readBackRamp) { Console.WriteLine(" {0}", rampElement); } H5A.close(attributeId); // Iterate through the attributes. long position = 0; H5AIterateCallback attributeDelegate; attributeDelegate = MyH5AFunction; H5ObjectInfo groupInfo = H5O.getInfo(groupId); Console.WriteLine( "fileNumber: {0}, total space: {1}, referceCount: {2}, modification time: {3}", groupInfo.fileNumber, groupInfo.header.space.total, groupInfo.referenceCount, groupInfo.modificationTime); // While iterating, collect the names of all the attributes. ArrayList attributeNames = new ArrayList(); H5A.iterate(groupId, H5IndexType.CRT_ORDER, H5IterationOrder.INCREASING, ref position, attributeDelegate, (object)attributeNames); // Write out the names of the attributes foreach (string attributeName in attributeNames) { Console.WriteLine("attribute name is {0}", attributeName); } // Demonstrate H5A.openName attributeId = H5A.openName(groupId, "descendingRamp"); Console.WriteLine("got {0} by name", H5A.getName(attributeId)); H5A.close(attributeId); // Demonstrate H5A.getNameByIndex string secondAttribute = H5A.getNameByIndex(groupId, ".", H5IndexType.CRT_ORDER, H5IterationOrder.INCREASING, 1); Console.WriteLine("second attribute is named {0}", secondAttribute); // Demonstrate H5G.getInfo H5GInfo gInfo = H5G.getInfo(groupId); Console.WriteLine( "link storage: {0}, max creation order: {1}, nLinks: {2}", gInfo.linkStorageType, gInfo.maxCreationOrder, gInfo.nLinks); // Demonstrate H5A.getSpace //attributeId = H5A.openByName(groupId, ".", "descendingRamp"); attributeId = H5A.open(groupId, "descendingRamp"); H5DataSpaceId rampSpaceId = H5A.getSpace(attributeId); H5S.close(rampSpaceId); // Demonstrate H5A.getType H5DataTypeId rampTypeId = H5A.getType(attributeId); Console.WriteLine("size of ramp data type is {0} bytes.", H5T.getSize(rampTypeId)); H5T.close(rampTypeId); // Demonstrate H5A.getInfo H5AttributeInfo rampInfo = H5A.getInfo(attributeId); Console.WriteLine( "characterset: {0}, creationOrder: {1}, creationOrderValid: {2}, dataSize: {3}", rampInfo.characterSet, rampInfo.creationOrder, rampInfo.creationOrderValid, rampInfo.dataSize); // Demonstrate H5A.Delete H5A.Delete(groupId, "descendingRamp"); //H5A.DeleteByName(groupId, ".", "descendingRamp"); // Iterate through the attributes to show that the deletion // was successful. position = 0; ArrayList namesAfterDeletion = new ArrayList(); H5A.iterate(groupId, H5IndexType.CRT_ORDER, H5IterationOrder.DECREASING, ref position, attributeDelegate, (object)namesAfterDeletion); H5G.close(groupId); H5F.close(fileId); // Reopen and reclose the file. H5FileId openId = H5F.open("myCSharp.h5", H5F.OpenMode.ACC_RDONLY); H5F.close(openId); // Set the function to be called on error. unsafe { H5AutoCallback myErrorDelegate = new H5AutoCallback(myErrorFunction); H5E.setAuto(0, myErrorDelegate, IntPtr.Zero); } // Uncomment the next line if you want to generate an error to // test H5E.setAuto // H5G.open(openId, "noGroup"); } // This catches all the HDF exception classes. Because each call // generates a unique exception, different exception can be handled // separately. For example, to catch open errors we could have used // catch (H5FopenException openException). catch (HDFException e) { Console.WriteLine(e.Message); } Console.WriteLine("Processing complete!"); Console.ReadLine(); }
} // test_attr_basic_write static void test_attr_basic_read() { try { Console.Write("Testing basic reading attribute functions"); // Make an integer type object to use in various calls (instead of copying like in test_attr_basic_write) H5DataTypeId inttype = new H5DataTypeId(H5T.H5Type.NATIVE_INT); // Open file H5FileId fileId = H5F.open(FILE_NAME, H5F.OpenMode.ACC_RDWR); // Open dataset DSET1_NAME. H5DataSetId dsetId = H5D.open(fileId, DSET1_NAME); // Verify the correct number of attributes. H5ObjectInfo oinfo = H5O.getInfo(dsetId); if (oinfo.nAttributes != 2) { Console.WriteLine("\ntest_attr_basic_read: incorrect number of attributes: read {0} - should be {1}", oinfo.nAttributes, 2); nerrors++; } // Open first attribute for the dataset. H5AttributeId attrId = H5A.open(dsetId, D1ATTR1_NAME); // Read attribute data. int[] read_data1 = new int[3]; H5A.read(attrId, inttype, new H5Array <int>(read_data1)); // Verify values read in. int[] attr_data1 = new int[] { 512, -234, 98123 }; /* Test data for 1st attribute */ int ii; for (ii = 0; ii < ATTR1_DIM; ii++) { if (attr_data1[ii] != read_data1[ii]) { Console.WriteLine("\ntest_attr_basic_read:check2: read value differs from input: read {0} - input {1}", read_data1[ii], attr_data1[ii]); nerrors++; } } H5A.close(attrId); // Open second attribute for the dataset. attrId = H5A.open(dsetId, D1ATTR2_NAME); // Read attribute data. H5A.read(attrId, inttype, new H5Array <int>(read_data1)); // Verify values read in. int[] attr_data2 = new int[] { 256, 11945, -22107 }; // Data to test second attribute of dataset. for (ii = 0; ii < ATTR1_DIM; ii++) { if (attr_data2[ii] != read_data1[ii]) { Console.WriteLine("\ntest_attr_basic_read: check3: read value differs from input: read {0} - input {1}", read_data1[ii], attr_data2[ii]); nerrors++; } } // Close the attribute and dataset. H5A.close(attrId); H5D.close(dsetId); /* Checking group's attribute */ // Open the group. H5GroupId groupId = H5G.open(fileId, GROUP1_NAME); // Verify the correct number of attributes for this group. oinfo = H5O.getInfo(groupId); if (oinfo.nAttributes != 1) { Console.WriteLine("\ntest_attr_basic_read: incorrect number of attributes: read {0} - should be {1}", oinfo.nAttributes, 1); nerrors++; } // Open the attribute for the group. attrId = H5A.open(groupId, GATTR_NAME); // Read attribute information. int[,] read_data2 = new int[GATTR_DIM1, GATTR_DIM2]; H5A.read(attrId, new H5DataTypeId(H5T.H5Type.NATIVE_INT), new H5Array <int>(read_data2)); // Verify values read in. int jj; for (ii = 0; ii < GATTR_DIM1; ii++) { for (jj = 0; jj < GATTR_DIM2; jj++) { if (gattr_data[ii, jj] != read_data2[ii, jj]) { Console.WriteLine("\ntest_attr_basic_read: check4: read value differs from input: read {0} - input {1}", read_data2[ii, jj], gattr_data[ii, jj]); nerrors++; } } } // Close attribute, group, and file. H5A.close(attrId); H5G.close(groupId); H5F.close(fileId); Console.WriteLine("\t\tPASSED"); } catch (HDFException anyHDF5E) { Console.WriteLine(anyHDF5E.Message); nerrors++; } catch (System.Exception sysE) { Console.WriteLine(sysE.TargetSite); Console.WriteLine(sysE.Message); nerrors++; } } // test_attr_basic_read
//private string ArrayToString<T>(T[] v) //{ // StringBuilder sb = new StringBuilder(); // //sb.Append("["); // foreach (T t in v) // { // sb.Append(t.ToString()); // sb.Append(","); // } // if (sb.Length > 1) // sb.Remove(sb.Length - 1, 1); // //sb.Append("]"); // return sb.ToString(); //} private object GetAttributeValue(H5ObjectWithAttributes obj, string attributeName) { H5AttributeId attId = null; attId = H5A.open(obj, attributeName); if (attId == null) { return(null); } H5DataTypeId typeId = null; H5DataTypeId dtId = null; H5AttributeInfo attInfo = null; H5DataSpaceId spaceId = null; H5DataTypeId oldTypeId = null; object retObject = null; try { typeId = H5A.getType(attId); attInfo = H5A.getInfo(attId); dtId = H5A.getType(attId); spaceId = H5A.getSpace(attId); int dataSize = H5T.getSize(dtId); // oldTypeId = typeId; typeId = H5T.getNativeType(typeId, H5T.Direction.DEFAULT); H5T.H5TClass typeClass = H5T.getClass(typeId); long[] dims = H5S.getSimpleExtentDims(spaceId); long dimSize = 1; if (dims.Length == 0) { dimSize = 1; } else { foreach (long dim in dims) { dimSize *= dim; } } switch (typeClass) { case H5T.H5TClass.STRING: long size = attInfo.dataSize; byte[] chars = ReadArray <byte>(size, attId, typeId); retObject = Encoding.ASCII.GetString(chars); break; case H5T.H5TClass.INTEGER: H5T.Sign sign = H5T.Sign.TWOS_COMPLEMENT; sign = H5T.getSign(oldTypeId); switch (dataSize) { case 1: retObject = ReadArray <byte>(dimSize, attId, typeId); break; case 2: switch (sign) { case H5T.Sign.TWOS_COMPLEMENT: retObject = ReadArray <Int16>(dimSize, attId, typeId); break; case H5T.Sign.UNSIGNED: retObject = ReadArray <UInt16>(dimSize, attId, typeId); break; } break; case 4: switch (sign) { case H5T.Sign.TWOS_COMPLEMENT: retObject = ReadArray <Int32>(dimSize, attId, typeId); break; case H5T.Sign.UNSIGNED: retObject = ReadArray <UInt32>(dimSize, attId, typeId); break; } break; case 8: switch (sign) { case H5T.Sign.TWOS_COMPLEMENT: retObject = ReadArray <Int64>(dimSize, attId, typeId); break; case H5T.Sign.UNSIGNED: retObject = ReadArray <UInt64>(dimSize, attId, typeId); break; } break; } break; case H5T.H5TClass.FLOAT: switch (dataSize) { case 4: retObject = ReadArray <float>(dimSize, attId, typeId); break; case 8: retObject = ReadArray <double>(dimSize, attId, typeId); break; } break; } return(retObject); } finally { if (spaceId != null) { H5S.close(spaceId); } if (attId != null) { H5A.close(attId); } if (oldTypeId != null) { H5T.close(oldTypeId); } if (typeId != null) { H5T.close(typeId); } if (dtId != null) { H5T.close(dtId); } } }
public object ReadFile(string filename, Recording recording) { RecordingConfig recordingConfig = recording.parameters; byte[] byteArray; double[] doubleArray = new double[1]; string result = ""; //This list will contain the positions of the movements to load. List<int> positionSelection; try { H5FileId fileId = H5F.open(filename, H5F.OpenMode.ACC_RDONLY); H5GroupId groupId = H5G.open(fileId, "/recSession"); H5ObjectInfo objectInfo = H5O.getInfoByName(fileId, "/recSession"); int nAttributes = (int)objectInfo.nAttributes; H5AttributeId[] attributeIds = new H5AttributeId[nAttributes]; //Attribute extraction and filling of the RecordingConfig object for (int i = 0; i < nAttributes; i++) { attributeIds[i] = H5A.openByIndex(groupId, "/recSession", H5IndexType.CRT_ORDER, H5IterationOrder.INCREASING, (long)i); string attributeName = H5A.getName(attributeIds[i]); H5DataTypeId attributeType = H5A.getType(attributeIds[i]); H5AttributeInfo attributeInfo = H5A.getInfo(attributeIds[i]); int dataSize = (int)attributeInfo.dataSize; int typeSize = H5T.getSize(attributeType); if ((attributeName == "mov") || (attributeName == "dev") || (attributeName == "cmt")) { byteArray = new byte[typeSize]; H5Array<byte> byteBuffer = new H5Array<byte>(byteArray); H5A.read<byte>(attributeIds[i], attributeType, byteBuffer); result = System.Text.Encoding.UTF8.GetString(byteArray); } else { doubleArray = new double[(int)(dataSize / typeSize)]; H5Array<double> doubleBuffer = new H5Array<double>(doubleArray); H5A.read<double>(attributeIds[i], attributeType, doubleBuffer); } switch (attributeName) { case "cT": //contraction time recordingConfig.scheduleItemTime = (float)doubleArray[0]; break; case "rT": //rest time _restTime = doubleArray[0]; break; case "cmt": //comments _comments = result; break; case "date": _date = doubleArray; break; case "dev": //device name _deviceName = result; break; case "mov": //list of movements //TODO: Extract it to a label sequence. We will use these labels to construct the frame sequence //Beware: each movement will possibly include rest periods. We can use the value of rT to determine //if that is the case -- to guess where the rests are and label them as such! //it seems that all movement recordings in Matlab exports begin with a CONTRACTION _movements = result.Split(';'); //plan: concatenate all movements on all channels one after another //This list will be used when writing MPTCE files as a way to store the movements known //by the program. NOT ALL THE MOVEMENTS WILL NORMALLY APPEAR ON A SINGLE RECORDING. //For the BioPatRec samples, it seems that this list actually holds the movements //encoded in the data structure. That would mean that the only way to describe the movement //would be the string content itself! break; case "nCh": //number of channels recordingConfig.nChannels = (uint)doubleArray[0]; break; case "nM": //number of movements //Redundant with list of movements? _numMovs = doubleArray[0]; break; case "nR": //number of repetitions recordingConfig.repetitions = (uint)doubleArray[0]; break; case "sF": //sampling frequency recordingConfig.sampleFreq = (uint)doubleArray[0]; break; case "sT": //sample time -> duration of the recording for each movement, including rests (?) _partialDuration = doubleArray[0]; break; // The following are MPTCE-specific attributes not present in BioPatRec files case "version": //Format version. If defined, this means that some version of MPTCE created it. If not, it // surely is a Matlab export. _version = doubleArray[0]; break; case "mV": recordingConfig.minVoltage = doubleArray[0]; _minmaxDefined = true; break; case "MV": recordingConfig.maxVoltage = doubleArray[0]; _minmaxDefined = true; break; case "movSeq": //Array defining the sequence of and which movements listed in mov were recorded _movSeq = doubleArray; break; default: break; } H5A.close(attributeIds[i]); } //Now we do the data reading H5DataSetId dataSetId = H5D.open(groupId, "tdata"); H5DataTypeId dataSetType = H5D.getType(dataSetId); int dataTypeSize = (int)H5T.getSize(dataSetType); H5DataSpaceId dataSpaceId = H5D.getSpace(dataSetId); int nDims = H5S.getSimpleExtentNDims(dataSpaceId); long[] dims = H5S.getSimpleExtentDims(dataSpaceId); //On Matlab-created HDF5 files, the dimensions are as follows: // 0 -> number of movement // 1 -> number of channel // 2-> samples per movement double[, ,] data = new double[dims[0], dims[1], dims[2]]; H5Array<double> dataBuffer = new H5Array<double>(data); H5D.read<double>(dataSetId, dataSetType, dataBuffer); H5D.close(dataSetId); H5G.close(groupId); H5F.close(fileId); //We try to identify the movements stored in the data array with a known movement in MPTCE List<ScheduleItem> movCodes = GuessMovs(_movements, knownMovements, allowedComplexMovements); //With this list, we can now select which movements we want to load. If requestedMovements is defined //and has elements, we satisfy that request and load only those movements. Otherwise we present some kind //of dialog, so that users can select the movements that they want if (requestedMovements != null && requestedMovements.Count > 0) { //Initialize positionSelection with the position of each of the desired movements //in the data array positionSelection = FindMovPositions(requestedMovements, movCodes); } else { //Prompt for movements movementSelector.movementNames = knownMovements; movementSelector.availableMovements = movCodes; positionSelection = FindMovPositions(_movementSelector.SelectMovements(), movCodes); } //We have the information needed to compose our recording data recordingConfig.scheduleActive = false; FillRecording(data, recording, positionSelection,movCodes); } catch (HDFException e) { throw new IFileReadWriterException("Error while reading HDF5 file.", e); } return recording; }
internal HDF5Attribute(H5ObjectWithAttributes _parentObjectId, string _name) { m_ParentObjectId = _parentObjectId; m_AttributeId = H5A.open(_parentObjectId, _name); m_AttributeInfo = H5A.getInfo(m_AttributeId); }
public static void WriteAttribute(HDFAttributeDef hDFAttributeDef, H5DataTypeId dataTypeId, H5AttributeId attributeId) { if (hDFAttributeDef.Value == null || hDFAttributeDef.Value.ToString() == "") { return; } H5A.write <T>(attributeId, dataTypeId, new H5Array <T>(hDFAttributeDef.Value as T[])); }
} // test_attr_compound_write static void test_attr_compound_read() { try { Console.Write("Testing read attribute with compound datatype"); // Open file. H5FileId fileId = H5F.open(COMP_FNAME, H5F.OpenMode.ACC_RDWR); // Open the dataset. H5DataSetId dsetId = H5D.open(fileId, DSET1_NAME); // Verify the correct number of attributes for this dataset. H5ObjectInfo oinfo = H5O.getInfo(dsetId); if (oinfo.nAttributes != 1) { Console.WriteLine("\ntest_attr_basic_read: incorrect number of attributes: read {0} - should be {1}", oinfo.nAttributes, 1); nerrors++; } // Open first attribute for the dataset. H5AttributeId attrId = H5A.openByIndex(dsetId, ".", H5IndexType.CRT_ORDER, H5IterationOrder.INCREASING, 0); // Verify dataspace. H5DataSpaceId spaceId = H5A.getSpace(attrId); int rank = H5S.getSimpleExtentNDims(spaceId); if (rank != ATTR4_RANK) { Console.WriteLine("\ntest_attr_compound_read: incorrect rank = {0} - should be {1}", rank, ATTR4_RANK); nerrors++; } long[] dims = H5S.getSimpleExtentDims(spaceId); if (dims[0] != ATTR4_DIM1) { Console.WriteLine("\ntest_attr_compound_read: incorrect dim[0] = {0} - should be {1}", dims[0], ATTR4_DIM1); nerrors++; } if (dims[1] != ATTR4_DIM2) { Console.WriteLine("\ntest_attr_compound_read: incorrect dim[1] = {0} - should be {1}", dims[1], ATTR4_DIM2); nerrors++; } // Close dataspace. H5S.close(spaceId); // Verify datatype of the attribute. H5DataTypeId typeId = H5A.getType(attrId); H5T.H5TClass t_class = H5T.getClass(typeId); if (t_class != H5T.H5TClass.COMPOUND) { Console.WriteLine("test_compound_dtypes: H5T.getMemberClass and H5T.getClass return different classes for the same type."); nerrors++; } int nfields = H5T.getNMembers(typeId); if (nfields != 3) { Console.WriteLine("test_compound_dtypes: H5T.getMemberClass and H5T.getClass return different classes for the same type."); nerrors++; } // Check name against this list string[] memb_names = { ATTR4_FIELDNAME1, ATTR4_FIELDNAME2, ATTR4_FIELDNAME3 }; int[] memb_offsets = { 0, 1, 5 }; // list of member offsets H5DataTypeId mtypeId; // member type H5T.H5TClass memb_cls1; // member classes retrieved different ways string memb_name; // member name int memb_idx; // member index int memb_offset, idx; // member offset, loop index // how to handle int versus uint for memb_idx and idx??? // For each member, check its name, class, index, and size. for (idx = 0; idx < nfields; idx++) { // Get the type of the ith member to test other functions later. mtypeId = H5T.getMemberType(typeId, idx); // Get the name of the ith member. memb_name = H5T.getMemberName(typeId, idx); if (memb_name != memb_names[idx]) { Console.WriteLine("test_compound_dtypes: incorrect member name, {0}, for member no {1}", memb_name, idx); nerrors++; } // Get the class of the ith member and then verify the class. memb_cls1 = H5T.getMemberClass(typeId, idx); if (memb_cls1 != H5T.H5TClass.INTEGER) { Console.WriteLine("test_compound_dtypes: incorrect class, {0}, for member no {1}", memb_cls1, idx); nerrors++; } // Get member's index back using its name and verify it. memb_idx = H5T.getMemberIndex(typeId, memb_name); if (memb_idx != idx) { Console.WriteLine("test_attr_compound_read: H5T.getMemberName and/or H5T.getMemberIndex returned false values."); nerrors++; } // Get member's offset and verify it. memb_offset = H5T.getMemberOffset(typeId, idx); if (memb_offset != memb_offsets[idx]) { Console.WriteLine("test_attr_compound_read: H5T.getMemberOffset returned incorrect value - {0}, should be {1}", memb_offset, memb_offsets[idx]); nerrors++; } // Get member's size and verify it. int tsize = H5T.getSize(mtypeId); switch (idx) { case 0: if (tsize != H5T.getSize(H5T.H5Type.STD_U8LE)) { Console.WriteLine("test_attr_compound_read: H5T.getSize returned incorrect value."); nerrors++; } break; case 1: if (tsize != H5T.getSize(H5T.H5Type.NATIVE_INT)) { Console.WriteLine("test_attr_compound_read: H5T.getSize returned incorrect value."); nerrors++; } break; case 2: if (tsize != H5T.getSize(H5T.H5Type.STD_I64BE)) { Console.WriteLine("test_attr_compound_read: H5T.getSize returned incorrect value."); nerrors++; } break; default: Console.WriteLine("test_attr_compound_read: We should only have 3 members."); nerrors++; break; } // end switch // Close current member type. H5T.close(mtypeId); } // end for // Prepare the check array to verify read data. It should be the same as the attr_data4 array // in the previous test function test_attr_compound_write. attr4_struct[,] check = new attr4_struct[ATTR4_DIM1, ATTR4_DIM2]; // Initialize the dataset int ii, jj, nn; for (ii = nn = 0; ii < ATTR4_DIM1; ii++) { for (jj = 0; jj < ATTR4_DIM2; jj++) { check[ii, jj].c = 't'; check[ii, jj].i = nn++; check[ii, jj].l = (ii * 10 + jj * 100) * nn; } } // Read attribute information. attr4_struct[,] read_data4 = new attr4_struct[ATTR4_DIM1, ATTR4_DIM2]; H5A.read(attrId, typeId, new H5Array <attr4_struct>(read_data4)); // Verify values read in. for (ii = 0; ii < ATTR4_DIM1; ii++) { for (jj = 0; jj < ATTR4_DIM2; jj++) { if ((check[ii, jj].c != read_data4[ii, jj].c) || (check[ii, jj].i != read_data4[ii, jj].i) || (check[ii, jj].l != read_data4[ii, jj].l)) { Console.WriteLine("test_attr_compound_read: Incorrect read data: {0}, should be {1}", read_data4[ii, jj], check[ii, jj]); nerrors++; } } } // Close resources. H5T.close(typeId); H5A.close(attrId); H5D.close(dsetId); H5F.close(fileId); Console.WriteLine("\t\tPASSED"); } catch (HDFException anyHDF5E) { Console.WriteLine(anyHDF5E.Message); nerrors++; } catch (System.Exception sysE) { Console.WriteLine(sysE.TargetSite); Console.WriteLine(sysE.Message); nerrors++; } } // test_attr_compound_read
static void test_attr_basic_write() { try { Console.Write("Testing Basic Scalar Attribute Writing Functions"); // Create a new file using H5F_ACC_TRUNC access, // default file creation properties, and default file // access properties. H5FileId fileId = H5F.create(FILE_NAME, H5F.CreateMode.ACC_TRUNC); // Copy datatype for use. H5DataTypeId typeId = H5T.copy(H5T.H5Type.NATIVE_INT); // Open the root group. H5GroupId groupId = H5G.open(fileId, "/"); // Create dataspace for attribute. hssize_t[] gdims = { GATTR_DIM1, GATTR_DIM2 }; H5DataSpaceId gspace_Id = H5S.create_simple(GATTR_RANK, gdims); // Create an attribute for the group. H5AttributeId attrId = H5A.create(groupId, RGATTR_NAME, typeId, gspace_Id); H5A.close(attrId); H5G.close(groupId); // Create a group in this file. groupId = H5G.create(fileId, GROUP1_NAME); // Create an attribute for group /Group1. attrId = H5A.create(groupId, GATTR_NAME, typeId, gspace_Id); H5A.write(attrId, typeId, new H5Array <int>(gattr_data)); // Create the dataspace. hssize_t[] dims1 = { SPACE1_DIM1, SPACE1_DIM2 }; H5DataSpaceId space1_Id = H5S.create_simple(SPACE1_RANK, dims1); // Create a dataset using default properties. H5DataSetId dsetId = H5D.create(fileId, DSET1_NAME, H5T.H5Type.NATIVE_UCHAR, space1_Id); // Close objects and file. H5A.close(attrId); H5D.close(dsetId); H5G.close(groupId); H5F.close(fileId); // Open the file again. fileId = H5F.open(FILE_NAME, H5F.OpenMode.ACC_RDWR); // Open the root group. groupId = H5G.open(fileId, "/"); // Open attribute again. attrId = H5A.open(groupId, RGATTR_NAME); // Close attribute and root group. H5A.close(attrId); H5G.close(groupId); // Open dataset. dsetId = H5D.open(fileId, DSET1_NAME); // Create the dataspace for dataset's attribute. hssize_t[] attdims = { ATTR1_DIM }; H5DataSpaceId attspaceId = H5S.create_simple(ATTR1_RANK, attdims); // Create an attribute for the dataset. attrId = H5A.create(dsetId, D1ATTR1_NAME, typeId, attspaceId); // Try to create the same attribute again (should fail.) try { H5AttributeId attr_twice = H5A.create(dsetId, D1ATTR1_NAME, typeId, attspaceId); // should fail, but didn't, print an error message. Console.WriteLine("\ntest_attr_basic_write: Attempting to create an existing attribute."); nerrors++; } catch (HDFException) { } // does nothing, it should fail // Write attribute information. int[] attr_data1 = new int[] { 512, -234, 98123 }; /* Test data for 1st attribute */ H5A.write(attrId, typeId, new H5Array <int>(attr_data1)); // Create another attribute for the dataset. H5AttributeId attr2Id = H5A.create(dsetId, D1ATTR2_NAME, typeId, attspaceId); // Write attribute information. int[] attr_data2 = new int[] { 256, 11945, -22107 }; H5A.write(attr2Id, typeId, new H5Array <int>(attr_data2)); // Read attribute information immediately, without closing attribute. int[] read_data1 = new int[3]; H5A.read(attrId, typeId, new H5Array <int>(read_data1)); // Verify values read in. int ii; for (ii = 0; ii < ATTR1_DIM; ii++) { if (attr_data1[ii] != read_data1[ii]) { Console.WriteLine("\ntest_attr_basic_write: check1: read value differs from input: read {0} - input {1}", read_data1[ii], attr_data1[ii]); nerrors++; } } // Close attributes. H5A.close(attrId); H5A.close(attr2Id); // Open attribute again and verify its name. attrId = H5A.openIndex(dsetId, 0); string attr_name = H5A.getName(attrId); if (attr_name != D1ATTR1_NAME) { Console.WriteLine("\ntest_attr_basic_write: attribute name incorrect: is {0} - should be {1}", attr_name, D1ATTR1_NAME); nerrors++; } // Close attribute. H5A.close(attrId); // Open the second attribute again and verify its name. attr2Id = H5A.openIndex(dsetId, 1); attr_name = H5A.getName(attr2Id); if (attr_name != D1ATTR2_NAME) { Console.WriteLine("\ntest_attr_basic_write: attribute name incorrect: is {0} - should be {1}", attr_name, D1ATTR2_NAME); nerrors++; } // Close all objects. H5A.close(attr2Id); H5S.close(space1_Id); H5S.close(gspace_Id); H5D.close(dsetId); H5F.close(fileId); Console.WriteLine("\tPASSED"); } // end try block catch (HDFException anyHDF5E) { Console.WriteLine(anyHDF5E.Message); nerrors++; } catch (System.Exception sysE) { Console.WriteLine(sysE.TargetSite); Console.WriteLine(sysE.Message); nerrors++; } } // test_attr_basic_write
/// <summary> /// 得到指定属性集合中指定属性名的属性值,未对异常进行处理 /// </summary> /// <param name="obj"></param> /// <param name="attributeName"></param> /// <returns></returns> private String getAttributeValue(H5ObjectWithAttributes obj, String attributeName) { H5AttributeId attId = null; attId = H5A.open(obj, attributeName); if (attId == null) { return(null); } H5DataTypeId typeId = null; H5DataTypeId dtId = null; H5AttributeInfo attInfo = null; H5DataSpaceId spaceId = null; object attributeVal = null; typeId = H5A.getType(attId); attInfo = H5A.getInfo(attId); dtId = H5A.getType(attId); spaceId = H5A.getSpace(attId); int dataSize = H5T.getSize(dtId); typeId = H5T.getNativeType(typeId, H5T.Direction.DEFAULT); H5T.H5TClass typeClass = H5T.getClass(typeId); long[] dims = H5S.getSimpleExtentDims(spaceId); if (dims.Length == 0) { dims = new long[1]; dims[0] = 1; } switch (typeClass) { case H5T.H5TClass.STRING: long size = attInfo.dataSize; byte[] chars = readAttribute <byte>(size, attId, typeId); attributeVal = Encoding.ASCII.GetString(chars); break; case H5T.H5TClass.INTEGER: H5T.Sign sign = H5T.Sign.TWOS_COMPLEMENT; sign = H5T.getSign(typeId); switch (dataSize) { case 1: attributeVal = readAttribute <byte>(dims[0], attId, typeId); break; case 2: switch (sign) { case H5T.Sign.TWOS_COMPLEMENT: attributeVal = readAttribute <Int16>(dims[0], attId, typeId); break; case H5T.Sign.UNSIGNED: attributeVal = readAttribute <UInt16>(dims[0], attId, typeId); break; } break; case 4: switch (sign) { case H5T.Sign.TWOS_COMPLEMENT: attributeVal = readAttribute <Int32>(dims[0], attId, typeId); break; case H5T.Sign.UNSIGNED: attributeVal = readAttribute <UInt32>(dims[0], attId, typeId); break; } break; case 8: switch (sign) { case H5T.Sign.TWOS_COMPLEMENT: attributeVal = readAttribute <Int64>(dims[0], attId, typeId); break; case H5T.Sign.UNSIGNED: attributeVal = readAttribute <UInt64>(dims[0], attId, typeId); break; } break; } break; case H5T.H5TClass.FLOAT: switch (dataSize) { case 4: attributeVal = readAttribute <float>(dims[0], attId, typeId); break; case 8: attributeVal = readAttribute <double>(dims[0], attId, typeId); break; } break; } if (spaceId != null) { H5S.close(spaceId); } if (attId != null) { H5A.close(attId); } if (typeId != null) { H5T.close(typeId); } if (dtId != null) { H5T.close(dtId); } return(arrayToString(attributeVal)); }
} // test_attr_plist static void test_attr_compound_write() { try { Console.Write("Testing write attributes with compound datatype"); const int NX = 256; // data set dimension const int NY = 512; // Create a file. H5FileId fileId = H5F.create(COMP_FNAME, H5F.CreateMode.ACC_TRUNC); // Create dataspace for dataset. hssize_t[] dims = { NX, NY }; H5DataSpaceId spaceId = H5S.create_simple(SPACE1_RANK, dims); // Create a dataset. H5DataSetId dsetId = H5D.create(fileId, DSET1_NAME, H5T.H5Type.NATIVE_UCHAR, spaceId); // Close dataset's dataspace H5S.close(spaceId); // this number 16 needs to be verified. // Create the attribute datatype. H5DataTypeId typeId = H5T.create(H5T.CreateClass.COMPOUND, 16); //tid1 = H5Tcreate(H5T_COMPOUND, sizeof(struct attr4_struct)); int attr4_field1_off = 0; int attr4_field2_off = 1; int attr4_field3_off = 5; H5T.insert(typeId, "c", attr4_field1_off, H5T.H5Type.STD_U8LE); H5T.insert(typeId, "i", attr4_field2_off, H5T.H5Type.NATIVE_INT); H5T.insert(typeId, "l", attr4_field3_off, H5T.H5Type.STD_I64BE); // Create dataspace for first attribute. hssize_t[] dims2 = { ATTR4_DIM1, ATTR4_DIM2 }; spaceId = H5S.create_simple(ATTR4_RANK, dims2); // Create complex attribute for the dataset. H5AttributeId attrId = H5A.create(dsetId, ATTR4_NAME, typeId, spaceId); // Try to create the same attribute again (should fail.) try { attrId = H5A.create(dsetId, ATTR4_NAME, typeId, spaceId); // should fail, but didn't, print an error message. Console.WriteLine("\ntest_attr_compound_write: Attempting to create an existing attribute."); nerrors++; } catch (HDFException) { } // does nothing, it should fail // Allocate space for the points & check arrays attr4_struct[,] attr_data4 = new attr4_struct[ATTR4_DIM1, ATTR4_DIM2]; // Initialize the dataset int ii, jj, nn; for (ii = nn = 0; ii < ATTR4_DIM1; ii++) { for (jj = 0; jj < ATTR4_DIM2; jj++) { attr_data4[ii, jj].c = 't'; attr_data4[ii, jj].i = nn++; attr_data4[ii, jj].l = (ii * 10 + jj * 100) * nn; } } // Write complex attribute data. H5A.write(attrId, typeId, new H5Array <attr4_struct>(attr_data4)); // Close all objects and file. H5A.close(attrId); H5S.close(spaceId); H5T.close(typeId); H5D.close(dsetId); H5F.close(fileId); Console.WriteLine("\t\tPASSED"); } catch (HDFException anyHDF5E) { Console.WriteLine(anyHDF5E.Message); nerrors++; } catch (System.Exception sysE) { Console.WriteLine(sysE.TargetSite); Console.WriteLine(sysE.Message); nerrors++; } } // test_attr_compound_write
static void test_attr_delete() { try { Console.Write("Testing deleting attributes"); // Open file. H5FileId fileId = H5F.open(FILE_NAME, H5F.OpenMode.ACC_RDWR); // Open the dataset. H5DataSetId dsetId = H5D.open(fileId, DSET1_NAME); // Verify the correct number of attributes for this dataset. H5ObjectInfo oinfo = H5O.getInfo(dsetId); if (oinfo.nAttributes != 2) { Console.WriteLine("\ntest_attr_delete: incorrect number of attributes: read {0} - should be {1}", oinfo.nAttributes, 2); nerrors++; } // Try to delete non-existing attribute, should fail. try { H5A.Delete(dsetId, "Bogus"); // should fail, but didn't, print an error message. Console.WriteLine("\ntest_attr_delete: Attempting to delete a non-existing attribute, Bogus."); nerrors++; } catch (HDFException) { } // does nothing, it should fail // Verify the correct number of attributes after the false deletion. oinfo = H5O.getInfo(dsetId); if (oinfo.nAttributes != 2) { Console.WriteLine("\ntest_attr_delete: incorrect number of attributes: read {0} - should be {1}", oinfo.nAttributes, 2); nerrors++; } // Delete middle (2nd) attribute. H5A.Delete(dsetId, D1ATTR2_NAME); // Verify the correct number of attributes after the deletion, checking both functions. oinfo = H5O.getInfo(dsetId); if (oinfo.nAttributes != 1) { Console.WriteLine("\ntest_attr_delete: incorrect number of attributes: read {0} - should be {1}", oinfo.nAttributes, 1); nerrors++; } // Open first attribute for the dataset. H5AttributeId attrId = H5A.openByIndex(dsetId, ".", H5IndexType.CRT_ORDER, H5IterationOrder.INCREASING, 0); // Verify attribute name. string attr_name = H5A.getName(attrId); if (attr_name != D1ATTR1_NAME) { Console.WriteLine("\ntest_delete_attr: attribute name different: {0}, should be {1}", attr_name, ATTR1_NAME); nerrors++; } // Close first attribute. H5A.close(attrId); // Delete first attribute. H5A.Delete(dsetId, D1ATTR1_NAME); // Verify that there are no more attribute for this dataset. oinfo = H5O.getInfo(dsetId); if (oinfo.nAttributes != 0) { Console.WriteLine("\ntest_attr_basic_read: incorrect number of attributes: read {0} - should be {1}", oinfo.nAttributes, 0); nerrors++; } // Close dataset and file. H5D.close(dsetId); 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++; } }
public static void WriteHdfAttribute(H5ObjectWithAttributes fileOrdatasetId, HDFAttributeDef hDFAttributeDef) { H5DataSpaceId dataSpaceId = H5S.create_simple(1, new long[] { (long)hDFAttributeDef.Size }); H5DataTypeId dataTypeId = null; H5AttributeId attributeId = null; try { switch (Type.GetTypeCode(hDFAttributeDef.Type)) { case TypeCode.Byte: dataTypeId = H5T.copy(H5T.H5Type.STD_U8LE); attributeId = H5A.create(fileOrdatasetId, hDFAttributeDef.Name, dataTypeId, dataSpaceId); WriteTAttribute <byte> .WriteAttribute(hDFAttributeDef, dataTypeId, attributeId); break; case TypeCode.Char: dataTypeId = H5T.copy(H5T.H5Type.STD_U8LE); attributeId = H5A.create(fileOrdatasetId, hDFAttributeDef.Name, dataTypeId, dataSpaceId); WriteTAttribute <char> .WriteAttribute(hDFAttributeDef, dataTypeId, attributeId); break; case TypeCode.Double: //dataTypeId = H5T.copy(H5T.H5Type.IEEE_F64BE); dataTypeId = H5T.copy(H5T.H5Type.IEEE_F64LE); attributeId = H5A.create(fileOrdatasetId, hDFAttributeDef.Name, dataTypeId, dataSpaceId); WriteTAttribute <double> .WriteAttribute(hDFAttributeDef, dataTypeId, attributeId); break; case TypeCode.Int16: dataTypeId = H5T.copy(H5T.H5Type.STD_I16LE); attributeId = H5A.create(fileOrdatasetId, hDFAttributeDef.Name, dataTypeId, dataSpaceId); WriteTAttribute <Int16> .WriteAttribute(hDFAttributeDef, dataTypeId, attributeId); break; case TypeCode.Int32: dataTypeId = H5T.copy(H5T.H5Type.STD_I32LE); attributeId = H5A.create(fileOrdatasetId, hDFAttributeDef.Name, dataTypeId, dataSpaceId); WriteTAttribute <Int32> .WriteAttribute(hDFAttributeDef, dataTypeId, attributeId); break; case TypeCode.Int64: dataTypeId = H5T.copy(H5T.H5Type.STD_I64LE); attributeId = H5A.create(fileOrdatasetId, hDFAttributeDef.Name, dataTypeId, dataSpaceId); WriteTAttribute <Int64> .WriteAttribute(hDFAttributeDef, dataTypeId, attributeId); break; case TypeCode.Object: dataTypeId = H5T.copy(H5T.H5Type.STD_REF_OBJ); attributeId = H5A.create(fileOrdatasetId, hDFAttributeDef.Name, dataTypeId, dataSpaceId); WriteTAttribute <object> .WriteAttribute(hDFAttributeDef, dataTypeId, attributeId); break; case TypeCode.Single: dataTypeId = H5T.copy(H5T.H5Type.IEEE_F32LE); attributeId = H5A.create(fileOrdatasetId, hDFAttributeDef.Name, dataTypeId, dataSpaceId); WriteTAttribute <Single> .WriteAttribute(hDFAttributeDef, dataTypeId, attributeId); break; case TypeCode.String: dataTypeId = H5T.copy(H5T.H5Type.C_S1); dataSpaceId = H5S.create(H5S.H5SClass.SCALAR); attributeId = WriteStringAttribute(fileOrdatasetId, hDFAttributeDef, dataSpaceId, dataTypeId); break; case TypeCode.UInt16: dataTypeId = H5T.copy(H5T.H5Type.STD_U16LE); attributeId = H5A.create(fileOrdatasetId, hDFAttributeDef.Name, dataTypeId, dataSpaceId); WriteTAttribute <UInt16> .WriteAttribute(hDFAttributeDef, dataTypeId, attributeId); break; case TypeCode.UInt32: dataTypeId = H5T.copy(H5T.H5Type.STD_U32LE); attributeId = H5A.create(fileOrdatasetId, hDFAttributeDef.Name, dataTypeId, dataSpaceId); WriteTAttribute <UInt32> .WriteAttribute(hDFAttributeDef, dataTypeId, attributeId); break; case TypeCode.UInt64: dataTypeId = H5T.copy(H5T.H5Type.STD_U64LE); attributeId = H5A.create(fileOrdatasetId, hDFAttributeDef.Name, dataTypeId, dataSpaceId); WriteTAttribute <UInt64> .WriteAttribute(hDFAttributeDef, dataTypeId, attributeId); break; } } catch (Exception ex) { int i = 9; int j = i; } finally { if (attributeId != null) { H5A.close(attributeId); } } }
public AttributeValue GetAttribute(H5FileId fileId, string attributeName) { H5AttributeId attributeId = H5A.openName(fileId, attributeName); //根据属性名称得到属性Id H5DataTypeId attributeType = H5A.getType(attributeId); //得到属性数据类型 int size = H5T.getSize(attributeType); H5T.H5TClass typeClass = H5T.getClass(attributeType); H5DataSpaceId spaceId = H5A.getSpace(attributeId); long[] dims = H5S.getSimpleExtentDims(spaceId); int rank = H5S.getSimpleExtentNDims(spaceId); H5T.H5Type h5type; Type dataType = null; AttributeValue atrributeData = new AttributeValue(); atrributeData.dataValue = null; atrributeData.valueType = DataValueType.EMPTY; atrributeData.rank = rank; switch (typeClass) { case H5T.H5TClass.FLOAT: h5type = H5T.H5Type.NATIVE_FLOAT; if (rank == 1) { float[] floatDatatmp = new float[dims[0]]; H5A.read(attributeId, new H5DataTypeId(h5type), new H5Array <float>(floatDatatmp)); atrributeData.dataValue = floatDatatmp; } else if (rank == 2) { float[,] floatDatatmp = new float[dims[0], dims[1]]; H5A.read(attributeId, new H5DataTypeId(h5type), new H5Array <float>(floatDatatmp)); atrributeData.dataValue = floatDatatmp; } atrributeData.valueType = DataValueType.FLOAT; break; case H5T.H5TClass.INTEGER: h5type = H5T.H5Type.NATIVE_INT; // int[,] intDatatmp = null; if (rank == 1) { int[] intDatatmp = new int[dims[0]]; H5A.read(attributeId, new H5DataTypeId(h5type), new H5Array <int>(intDatatmp)); atrributeData.dataValue = intDatatmp; } else if (rank == 2) { int[,] intDatatmp = new int[dims[0], dims[1]]; H5A.read(attributeId, new H5DataTypeId(h5type), new H5Array <int>(intDatatmp)); atrributeData.dataValue = intDatatmp; } atrributeData.valueType = DataValueType.INT; break; case H5T.H5TClass.STRING: h5type = H5T.H5Type.C_S1; if (rank == 0) { string[] stringDatatmp = new string[1]; byte[] bytedata = new byte[255]; H5A.read(attributeId, attributeType, new H5Array <byte>(bytedata)); //H5A.read(attributeId, new H5DataTypeId(h5type), new H5Array<string>(stringDatatmp)); stringDatatmp[0] = Encoding.Default.GetString(bytedata).Trim('\0'); atrributeData.dataValue = stringDatatmp; } else if (rank == 1) { string[] stringDatatmp = new string[dims[0]]; // string stringDatatmp = ""; // byte[] bytedata = new byte[255]; // byte[,] bytedata = new byte[2,255]; // H5DataTypeId memtype = H5T.copy(H5T.H5Type.C_S1); //H5T.setVariableSize(memtype); //H5T.setSize(attributeType, size); // H5A.read(attributeId, memtype, new H5Array<string>(stringDatatmp)); // H5A.read(attributeId, new H5DataTypeId(h5type), new H5Array<string>(stringDatatmp)); // stringDatatmp[0] = Encoding.Default.GetString(bytedata).Trim('\0'); //string test = Encoding.Default.GetString(bytedata).Trim('\0'); // atrributeData.dataValue = stringDatatmp; // VariableLengthString[] value = new VariableLengthString[1]; atrributeData.dataValue = stringDatatmp; } else if (rank == 2) { string[,] stringDatatmp = new string[dims[0], dims[1]]; //H5DataTypeId memtype = H5T.copy(H5T.H5Type.C_S1); //H5T.setVariableSize(memtype); //H5A.read(attributeId, memtype, new H5Array<string>(stringDatatmp)); atrributeData.dataValue = stringDatatmp; } atrributeData.valueType = DataValueType.STRING; break; default: h5type = H5T.H5Type.C_S1; break; } H5T.close(attributeType); H5S.close(spaceId); H5A.close(attributeId); return(atrributeData); }