public static T ReadEnumAttribute <T>(hid_t hid, string key) where T : struct, IConvertible
        {
            var attribute = H5A.open(hid, key);

            if (attribute < 0)
            {
                throw new ArgumentException(string.Format("Attribute {0} not found.", key));
            }

            var type = H5A.get_type(attribute);

            if (type < 0)
            {
                H5A.close(attribute);
                throw new Exception("H5A.get_type failed.");
            }

            var size = H5T.get_size(type).ToInt32();

            if (size == 0)
            {
                H5T.close(type);
                H5A.close(attribute);
                throw new Exception("H5T.get_size failed.");
            }

            var unmanagedBuffer = new UnmanagedBuffer(size);

            H5A.read(attribute, type, unmanagedBuffer);

            H5T.close(type);
            H5A.close(attribute);

            return(unmanagedBuffer.ReadEnum <T>());
        }
Exemplo n.º 2
0
        public bool Contains(string key)
        {
            return(Host.With((objId) =>
            {
                long attrId = 0;
                try
                {
                    attrId = H5A.open(objId, key);
                    if (attrId < 0)
                    {
                        return false;
                    }

                    return true;
                }
                catch
                {
                    return false;
                }
                finally
                {
                    if (attrId > 0)
                    {
                        H5A.close(attrId);
                    }
                }
            }));
        }
Exemplo n.º 3
0
        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));
        }
Exemplo n.º 4
0
 public void H5AopenTest2()
 {
     Assert.IsFalse(
         H5A.open(Utilities.RandomInvalidHandle(), ".") >= 0);
     Assert.IsFalse(
         H5A.open(m_v2_class_file, "") >= 0);
 }
Exemplo n.º 5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="_objectId"></param>
        /// <param name="_attribute"></param>
        public static void UpdateAttribute(Hdf5Identifier _objectId, Hdf5Attribute _attribute)
        {
            Hdf5Identifier attributeId = H5A.open(_objectId.Value, _attribute.Name).ToId();

            if (attributeId.Value > 0)
            {
                Hdf5DataType  type     = TypeHelper.GetDataTypeFromAttribute(attributeId);
                Hdf5DataTypes enumType = TypeHelper.GetDataTypesEnum(_attribute.Value.GetType());

                if (type.Type == enumType)
                {
                    if (enumType == Hdf5DataTypes.String)
                    {
                        H5A.close(attributeId.Value);
                        DeleteAttribute(_objectId, _attribute.Name);
                        Hdf5Attribute attribute = CreateAttribute(_objectId, _attribute.Name, _attribute.Value);

                        if (attribute != null)
                        {
                            _attribute.Id    = attribute.Id;
                            _attribute.Name  = attribute.Name;
                            _attribute.Value = attribute.Value;
                        }
                    }
                    else
                    {
                        WriteObjectValue(type, attributeId, _attribute.Value);
                    }
                }
                else
                {
                    throw new Hdf5TypeMismatchException();
                }
            }
        }
Exemplo n.º 6
0
        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);
        }
Exemplo n.º 7
0
        public static Dictionary <uint, string> GetLabelWorkingSet(long group_id)
        {
            Dictionary <uint, string> labelWorkingSet = new Dictionary <uint, string>();

            H5A.operator_t callBackMethod  = DelegateMethod;
            ArrayList      attrNameArray   = new ArrayList();
            GCHandle       nameArrayAlloc  = GCHandle.Alloc(attrNameArray);
            IntPtr         ptrOnAllocArray = (IntPtr)nameArrayAlloc;
            int            status;
            ulong          beginAt = 0;

            status = H5A.iterate(group_id, H5.index_t.CRT_ORDER, H5.iter_order_t.INC, ref beginAt, callBackMethod, ptrOnAllocArray);

            for (int i = 0; i < attrNameArray.Count; i++)
            {
                string   attr_name  = Convert.ToString(attrNameArray[i]);
                long     attr_id    = H5A.open(group_id, attr_name);
                uint[]   attr_value = { 0 };
                GCHandle valueAlloc = GCHandle.Alloc(attr_value, GCHandleType.Pinned);

                status = H5A.read(attr_id, H5T.NATIVE_UINT32, valueAlloc.AddrOfPinnedObject());
                status = H5A.close(attr_id);
                labelWorkingSet.Add(attr_value[0], attr_name);
            }

            status = H5G.close(group_id);

            return(labelWorkingSet);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Reads the data from the specified attribute.
        /// </summary>
        /// <typeparam name="T">The data type.</typeparam>
        /// <param name="locationId">The location ID.</param>
        /// <param name="attributeName">The name of the attribute.</param>
        /// <returns>Returns a set of type T which represents the read data.</returns>
        public static T[] ReadAttribute <T>(long locationId, string attributeName)
        {
            long attributeId = -1;

            T[] result;

            try
            {
                attributeId = H5A.open(locationId, attributeName);

                if (H5I.is_valid(attributeId) <= 0)
                {
                    throw new Exception(ErrorMessage.IOHelper_CouldNotOpenAttribute);
                }

                result = IOHelper.Read <T>(attributeId, DataContainerType.Attribute);
            }
            finally
            {
                if (H5I.is_valid(attributeId) > 0)
                {
                    H5A.close(attributeId);
                }
            }

            return(result);
        }
Exemplo n.º 9
0
        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);
        }
Exemplo n.º 10
0
        public static bool WriteScalarNumericAttribute <T>(hid_t hid, string key, T value, hid_t type) where T : struct
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            var exists = H5A.exists(hid, key);

            if (exists < 0)
            {
                throw new Exception("H5A.exists failed");
            }

            if (exists == 0)
            {
                var space = H5S.create(H5S.class_t.SCALAR);
                if (space < 0)
                {
                    throw new Exception("Failed to create scalar space");
                }

                var attribute = H5A.create(hid, key, type, space);
                if (attribute < 0)
                {
                    H5S.close(space);
                    throw new Exception(string.Format("Failed to create attribute \"{0}\"", key));
                }

                H5S.close(space);

                object boxedValue = value;
                H5A.write(attribute, type, new PinnedObject(boxedValue));

                H5A.close(attribute);

                return(true);
            }
            else
            {
                var attribute = H5A.open(hid, key);
                if (attribute < 0)
                {
                    throw new Exception(string.Format("Failed to open attribute \"{0}\"", key));
                }

                try
                {
                    return(WriteScalarNumericAttribute(attribute, value, type));
                }
                finally
                {
                    H5A.close(attribute);
                }
            }
        }
Exemplo n.º 11
0
        public object this[string key]
        {
            get
            {
                return(Host.With <object>((objId) =>
                {
                    long attrId = 0;
                    long dtypeId = 0;
                    try
                    {
                        attrId = H5A.open(objId, key);
                        if (attrId < 0)
                        {
                            throw new ArgumentException($"Unknown Attribute: {key}", nameof(key));
                        }
                        dtypeId = H5A.get_type(attrId);
                        int size = H5T.get_size(dtypeId).ToInt32();

                        IntPtr iPtr = Marshal.AllocHGlobal(size);
                        int result = H5A.read(attrId, dtypeId, iPtr);
                        if (result < 0)
                        {
                            throw new IOException("Failed to read attribute");
                        }

                        if (H5T.equal(dtypeId, H5T.NATIVE_INT64) > 0)
                        {
                            var dest = new long[1];
                            Marshal.Copy(iPtr, dest, 0, 1);
                            Marshal.FreeHGlobal(iPtr);
                            return dest[0];
                        }
                        else // Must be a string...
                        {
                            var dest = new byte[size];
                            Marshal.Copy(iPtr, dest, 0, size);
                            Marshal.FreeHGlobal(iPtr);
                            return Encoding.ASCII.GetString(dest).TrimEnd((Char)0);
                        }

//                        return null;
                    }
                    finally
                    {
                        if (attrId > 0)
                        {
                            H5A.close(attrId);
                        }
                        if (dtypeId > 0)
                        {
                            H5T.close(dtypeId);
                        }
                    }
                }));
            }
        }
Exemplo n.º 12
0
        public static bool WriteStringAttribute(hid_t hid, string key, string value, bool utf8 = true, bool variable = true)
        {
            if (H5A.exists(hid, key) == 0)
            {
                // Attribute doesn't exist.
                return(variable ? CreateOrOverwriteVariableStringAttribute(hid, key, new string[] { value }, utf8)
                    : CreateOrOverwriteFixedStringAttribute(hid, key, value, utf8));
            }
            else
            {
                var attribute = H5A.open(hid, key);
                if (attribute < 0)
                {
                    return(false);
                }

                var type = H5A.get_type(attribute);
                if (type < 0)
                {
                    H5A.close(attribute);
                    return(false);
                }

                var typeClass = H5T.get_class(type);
                if (typeClass == H5T.class_t.NO_CLASS)
                {
                    H5T.close(type);
                    H5T.close(attribute);
                    return(false);
                }

                if (typeClass != H5T.class_t.STRING)
                {
                    H5T.close(type);
                    H5T.close(attribute);
                    throw new ArgumentException("H5T.get_class(type) != H5T.class_t.STRING");
                }

                utf8 = H5T.get_cset(type) == H5T.cset_t.UTF8;

                bool ok;
                if (H5T.is_variable_str(type) > 0)
                {
                    ok = CreateOrOverwriteVariableStringAttribute(hid, key, new string[] { value }, utf8);
                }
                else
                {
                    ok = CreateOrOverwriteFixedStringAttribute(hid, key, value, utf8);
                }

                H5T.close(type);
                H5T.close(attribute);

                return(ok);
            }
        }
        public static bool WriteFixedStringAttribute(hid_t hid, string key, string value, bool utf8)
        {
            var exists = H5A.exists(hid, key);

            if (exists < 0)
            {
                throw new Exception("H5A.exists failed");
            }

            if (exists == 0) // Attribute doesn't exist
            {
                var bytes = value.ToBytes(utf8);

                var type = CreateFixedStringType(bytes, utf8);

                var space = H5S.create(H5S.class_t.SCALAR);
                if (space < 0)
                {
                    H5T.close(type);
                    throw new Exception("Failed to create scalar space");
                }

                var attribute = H5A.create(hid, key, type, space);
                if (attribute < 0)
                {
                    H5S.close(space);
                    H5T.close(type);
                    throw new Exception(string.Format("Failed to create attribute \"{0}\"", key));
                }

                H5A.write(attribute, type, new PinnedObject(bytes));

                H5A.close(attribute);
                H5S.close(space);
                H5T.close(type);

                return(true);
            }
            else
            {
                var attribute = H5A.open(hid, key);
                if (attribute < 0)
                {
                    throw new Exception(string.Format("Failed to open attribute \"{0}\"", key));
                }

                try
                {
                    return(WriteFixedStringAttribute(attribute, value, utf8));
                }
                finally
                {
                    H5A.close(attribute);
                }
            }
        }
Exemplo n.º 14
0
        static void ReadFile(string filePath)
        {
            var file = H5F.open(filePath, H5F.ACC_RDONLY);

            var dataSet = H5D.open(file, "/group/dataset");

            var dataSpace = H5D.get_space(dataSet);

            var rank = H5S.get_simple_extent_ndims(dataSpace);

            if (rank == 2)
            {
                var dims = new ulong[2];
                H5S.get_simple_extent_dims(dataSpace, dims, null);

                var data = new int[dims[0], dims[1]];
                H5D.read(dataSet, H5T.NATIVE_INT, H5S.ALL, H5S.ALL, H5P.DEFAULT, new PinnedObject(data));

                for (int i = 0; i < data.GetLength(0); ++i)
                {
                    for (int j = 0; j < data.GetLength(1); ++j)
                    {
                        Write($"{data[i,j],3}");
                    }
                    WriteLine();
                }
            }

            H5S.close(dataSpace);

            var doubleAttribute = H5A.open(dataSet, "double");

#if false
            double pi     = 0.0;
            var    handle = GCHandle.Alloc(pi, GCHandleType.Pinned);
            H5A.read(doubleAttribute, H5T.NATIVE_DOUBLE, handle.AddrOfPinnedObject());
            handle.Free();
            WriteLine($"PI = {pi}");
#else
            var values = new double[1];
            H5A.read(doubleAttribute, H5T.NATIVE_DOUBLE, new PinnedObject(values));
            WriteLine($"PI = {values[0]}");
#endif
            H5A.close(doubleAttribute);

            WriteLine($"string: {ReadStringAttribute(dataSet, "string")}");
            WriteLine($"string-ascii: {ReadStringAttribute(dataSet, "string-ascii")}");
            WriteLine($"string-vlen: {ReadStringAttribute(dataSet, "string-vlen")}");

            H5D.close(dataSet);
            H5F.close(file);
        }
Exemplo n.º 15
0
        public static void WriteLabelWorkingSet(long fileId_inp, bool overwrite_inp)
        {
            var LabelClassInfos = Labeling.GetAllIdsNamesAndMaterials();

            int status = 0;

            ulong[] dims = new ulong[2];
            dims[0] = 2;
            dims[1] = (ulong)LabelClassInfos.Count;

            long group_id = 0;

            if (overwrite_inp)
            {
                group_id = H5G.open(fileId_inp, "labelWorkingSet");
            }
            else
            {
                group_id = H5G.create(fileId_inp, "labelWorkingSet");
            }

            for (int i = 0; i < LabelClassInfos.Count; i++)
            {
                GCHandle labelID = GCHandle.Alloc(LabelClassInfos.ElementAt(i).Key, GCHandleType.Pinned);

                string labelClassName = LabelClassInfos.ElementAt(i).Value.Item1;

                long attr_id = H5A.open(group_id, labelClassName);

                if (attr_id >= 0)
                {
                    //attribute exists
                    status = H5A.write(attr_id, H5T.NATIVE_UINT32, labelID.AddrOfPinnedObject());
                }
                else
                {
                    //attribute has to be created
                    attr_id = H5A.create(group_id, LabelClassInfos.ElementAt(i).Value.Item1, H5T.NATIVE_UINT32, H5S.create(H5S.class_t.SCALAR));
                    status  = H5A.write(attr_id, H5T.NATIVE_UINT32, labelID.AddrOfPinnedObject());
                }

                status = H5A.close(attr_id);
            }

            status = H5G.close(group_id);
        }
Exemplo n.º 16
0
        public static IEnumerable <string> ReadStringAttributes(hid_t groupId, string name)
        {
            hid_t datatype = H5T.create(H5T.class_t.STRING, H5T.VARIABLE);

            H5T.set_cset(datatype, H5T.cset_t.UTF8);
            H5T.set_strpad(datatype, H5T.str_t.NULLTERM);

            //name = ToHdf5Name(name);

            var   datasetId = H5A.open(groupId, name);
            hid_t spaceId   = H5A.get_space(datasetId);

            long count = H5S.get_simple_extent_npoints(spaceId);

            H5S.close(spaceId);

            IntPtr[] rdata = new IntPtr[count];
            GCHandle hnd   = GCHandle.Alloc(rdata, GCHandleType.Pinned);

            H5A.read(datasetId, datatype, hnd.AddrOfPinnedObject());

            var strs = new List <string>();

            for (int i = 0; i < rdata.Length; ++i)
            {
                int len = 0;
                while (Marshal.ReadByte(rdata[i], len) != 0)
                {
                    ++len;
                }
                byte[] buffer = new byte[len];
                Marshal.Copy(rdata[i], buffer, 0, buffer.Length);
                string s = Encoding.UTF8.GetString(buffer);

                strs.Add(s);

                H5.free_memory(rdata[i]);
            }

            hnd.Free();
            H5T.close(datatype);
            H5A.close(datasetId);
            return(strs);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Loads all attributes on an object into the supplied attributes collection.
        /// Assumes that the object is already open.
        /// </summary>
        /// <param name="_attributes"></param>
        public static void LoadAttributes(
            Hdf5Attributes _attributes)
        {
            ulong n = 0;

            AbstractHdf5Object obj = _attributes.ParentObject;

            int id = H5A.iterate(obj.Id.Value, H5.index_t.NAME, H5.iter_order_t.NATIVE, ref n,
                                 delegate(int _id, IntPtr _namePtr, ref H5A.info_t _ainfo, IntPtr _data)
            {
                string attributeName = Marshal.PtrToStringAnsi(_namePtr);

                var attributeId = H5A.open(_id, attributeName).ToId();
                if (attributeId.Value > 0)
                {
                    var attributeTypeId = H5A.get_type(attributeId.Value).ToId();
                    var type            = TypeHelper.GetDataTypeByType(attributeTypeId);

                    if (attributeTypeId.Value > 0)
                    {
                        Hdf5Attribute attribute = null;
                        if (type.NativeType.Value == H5T.C_S1)
                        {
                            attribute = GetStringAttribute(obj.Id, attributeName);
                        }
                        else
                        {
                            attribute = GetAttribute(attributeId, attributeName, type);
                        }

                        if (attribute != null)
                        {
                            _attributes.Add(attribute);
                        }

                        H5T.close(attributeTypeId.Value);
                    }

                    H5A.close(attributeId.Value);
                }

                return(0);
            }, new IntPtr());
        }
Exemplo n.º 18
0
        /// <summary>
        /// Writes data to the specified attribute.
        /// </summary>
        /// <typeparam name="T">The data type.</typeparam>
        /// <param name="locationId">The location ID.</param>
        /// <param name="attributeName">The name of the attribute.</param>
        /// <param name="valueSet">The data to be written.</param>
        public static void WriteAttribute <T>(long locationId, string attributeName, T[] valueSet)
        {
            Contract.Requires(valueSet != null, nameof(valueSet));

            long attributeId = -1;

            try
            {
                attributeId = H5A.open(locationId, attributeName);
                IOHelper.Write <T>(attributeId, valueSet, DataContainerType.Attribute);
            }
            finally
            {
                if (H5I.is_valid(attributeId) > 0)
                {
                    H5A.close(attributeId);
                }
            }
        }
Exemplo n.º 19
0
        public static (long AttributeId, bool IsNew) OpenOrCreateAttribute(long locationId, string name, long attributeTypeId, Func <long> createAttributeCallback)
        {
            long attributeId            = -1;
            long attributeTypeId_actual = -1;

            bool isNew;

            try
            {
                if (H5A.exists(locationId, name) > 0)
                {
                    attributeId            = H5A.open(locationId, name);
                    attributeTypeId_actual = H5A.get_type(attributeId);

                    if (H5T.equal(attributeTypeId_actual, attributeTypeId) <= 0)
                    {
                        throw new Exception($"{ ErrorMessage.IOHelper_DataTypeMismatch } Attribute: '{ name }'.");
                    }

                    isNew = false;
                }
                else
                {
                    attributeId = createAttributeCallback.Invoke();

                    isNew = true;
                }

                if (H5I.is_valid(attributeId) <= 0)
                {
                    throw new Exception($"{ ErrorMessage.IOHelper_CouldNotOpenOrCreateAttribute } Attribute: '{ name }'.");
                }
            }
            finally
            {
                if (H5I.is_valid(attributeTypeId_actual) > 0)
                {
                    H5T.close(attributeTypeId_actual);
                }
            }

            return(attributeId, isNew);
        }
Exemplo n.º 20
0
        public static T[] UpdateAttributeList <T>(long locationId, string attributeName, T[] referenceValueSet)
        {
            long attributeId = -1;

            try
            {
                attributeId = H5A.open(locationId, attributeName);
                IOHelper.PrepareAttributeValueSet(attributeId, ref referenceValueSet, true);
            }
            finally
            {
                if (H5I.is_valid(attributeId) > 0)
                {
                    H5A.close(attributeId);
                }
            }

            return(referenceValueSet);
        }
Exemplo n.º 21
0
        public void H5AopenTest1()
        {
            hid_t att = H5A.create(m_v2_test_file, "A", H5T.IEEE_F64LE,
                                   m_space_scalar);

            Assert.IsTrue(att >= 0);
            Assert.IsTrue(H5A.close(att) >= 0);

            att = H5A.open(m_v2_test_file, "A");
            Assert.IsTrue(att >= 0);
            Assert.IsTrue(H5A.close(att) >= 0);

            att = H5A.create(m_v0_test_file, "A", H5T.IEEE_F64LE,
                             m_space_scalar);
            Assert.IsTrue(att >= 0);
            Assert.IsTrue(H5A.close(att) >= 0);

            att = H5A.open(m_v0_test_file, "A");
            Assert.IsTrue(att >= 0);
            Assert.IsTrue(H5A.close(att) >= 0);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Reads a string scalar attribute value.
        /// Assumes that the parent object is already open.
        /// </summary>
        /// <param name="_objectId"></param>
        /// <param name="_title"></param>
        /// <returns></returns>
        public static Hdf5Attribute GetStringAttribute(Hdf5Identifier _objectId, string _title)
        {
            int attributeId = 0;
            int typeId      = 0;

            attributeId = H5A.open(_objectId.Value, _title);
            typeId      = H5A.get_type(attributeId);
            var sizeData = H5T.get_size(typeId);
            var size     = sizeData.ToInt32();

            byte[] strBuffer = new byte[size];

            var      aTypeMem    = H5T.get_native_type(typeId, H5T.direction_t.ASCEND);
            GCHandle pinnedArray = GCHandle.Alloc(strBuffer, GCHandleType.Pinned);

            H5A.read(attributeId, aTypeMem, pinnedArray.AddrOfPinnedObject());
            pinnedArray.Free();
            H5T.close(aTypeMem);

            string value = System.Text.Encoding.ASCII.GetString(strBuffer, 0, strBuffer.Length - 1);

            var attribute = new Hdf5Attribute
            {
                Id    = attributeId.ToId(),
                Name  = _title,
                Value = value
            };

            if (attributeId > 0)
            {
                H5A.close(attributeId);
            }

            if (typeId > 0)
            {
                H5T.close(typeId);
            }

            return(attribute);
        }
Exemplo n.º 23
0
        public static object ReadAttribute(long locationId, string attributeName)
        {
            long attributeId = -1;
            long typeId      = -1;

            object result;

            try
            {
                attributeId = H5A.open(locationId, attributeName);

                if (H5I.is_valid(attributeId) <= 0)
                {
                    throw new Exception(ErrorMessage.IOHelper_CouldNotOpenAttribute);
                }

                typeId = H5A.get_type(attributeId);

                // invoke HdfHelper.Read
                result = GeneralHelper.InvokeGenericMethod(typeof(IOHelper), null, nameof(IOHelper.Read),
                                                           BindingFlags.Public | BindingFlags.Static,
                                                           TypeConversionHelper.GetTypeFromHdfTypeId(typeId),
                                                           new object[] { attributeId, DataContainerType.Attribute, Type.Missing });
            }
            finally
            {
                if (H5I.is_valid(typeId) > 0)
                {
                    H5T.close(typeId);
                }
                if (H5I.is_valid(attributeId) > 0)
                {
                    H5A.close(attributeId);
                }
            }

            return(result);
        }
Exemplo n.º 24
0
        public static T ReadScalarNumericAttribute <T>(hid_t hid, string key) where T : struct
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            var attribute = H5A.open(hid, key);

            if (attribute < 0)
            {
                throw new Exception(string.Format("Failed to open attribute \"{0}\"", key));
            }

            try
            {
                return(ReadScalarNumericAttribute <T>(attribute));
            }
            finally
            {
                H5A.close(attribute);
            }
        }
Exemplo n.º 25
0
        void FindAttribute(int i)
        {
            var attr_field = "FIELD_" + i + "_NAME";

            var attr  = H5A.open(Id, attr_field);
            var dtype = H5A.getType(attr);
            var size  = H5T.getSize(dtype);

            var mtype  = H5T.create(H5T.CreateClass.STRING, size);
            var buffer = new byte[size];

            H5A.read(attr, mtype, new H5Array <byte>(buffer));

            var attr_datatype = H5T.getMemberType(H5D.getType(Id), i);
            var attr_size     = H5T.getSize(attr_datatype);

            var attr_class = H5T.getMemberClass(H5D.getType(Id), i).ToString();
            var attr_name  = Encoding.GetString(buffer).Replace('\0', ' ').Trim();

            switch (attr_class)
            {
            case "STRING":
                _attributes[i] = new StringAttribute(attr_name, attr_size);
                break;

            case "INTEGER":
                _attributes[i] = new IntegerAttribute(attr_name, attr_size);
                break;

            case "FLOAT":
                _attributes[i] = new FloatingPointAttribute(attr_name, attr_size);
                break;

            default:
                throw new ArgumentException("Unknown attribute type " + attr_class, "attr_type");
            }
        }
Exemplo n.º 26
0
        public static Array ReadPrimitiveAttributes <T>(hid_t groupId, string name) //where T : struct
        {
            Type type     = typeof(T);
            var  datatype = GetDatatype(type);

            var attributeId = H5A.open(groupId, name);
            var spaceId     = H5A.get_space(attributeId);
            int rank        = H5S.get_simple_extent_ndims(spaceId);

            ulong[] maxDims = new ulong[rank];
            ulong[] dims    = new ulong[rank];
            hid_t   memId   = H5S.get_simple_extent_dims(spaceId, dims, maxDims);

            long[] lengths    = dims.Select(d => Convert.ToInt64(d)).ToArray();
            Array  attributes = Array.CreateInstance(type, lengths);

            var typeId   = H5A.get_type(attributeId);
            var mem_type = H5T.copy(datatype);

            if (datatype == H5T.C_S1)
            {
                H5T.set_size(datatype, new IntPtr(2));
            }

            var propId = H5A.get_create_plist(attributeId);

            memId = H5S.create_simple(rank, dims, maxDims);
            GCHandle hnd = GCHandle.Alloc(attributes, GCHandleType.Pinned);

            H5A.read(attributeId, datatype, hnd.AddrOfPinnedObject());
            hnd.Free();
            H5A.close(typeId);
            H5A.close(attributeId);
            H5S.close(spaceId);
            return(attributes);
        }
Exemplo n.º 27
0
        private string GetModelConfig()
        {
            long fileId  = H5F.open(this.fileName, H5F.ACC_RDONLY);
            long attrId  = H5A.open(fileId, @"model_config");
            long typeId  = H5A.get_type(attrId);
            long spaceId = H5A.get_space(attrId);
            long count   = H5S.get_simple_extent_npoints(spaceId);

            H5S.close(spaceId);
            IntPtr[] dest   = new IntPtr[count];
            GCHandle handle = GCHandle.Alloc(dest, GCHandleType.Pinned);

            H5A.read(attrId, typeId, handle.AddrOfPinnedObject());

            var attrStrings = new List <string>();

            for (int i = 0; i < dest.Length; ++i)
            {
                int attrLength = 0;
                while (Marshal.ReadByte(dest[i], attrLength) != 0)
                {
                    ++attrLength;
                }

                byte[] buffer = new byte[attrLength];
                Marshal.Copy(dest[i], buffer, 0, buffer.Length);
                string stringPart = Encoding.UTF8.GetString(buffer);

                attrStrings.Add(stringPart);

                H5.free_memory(dest[i]);
            }

            handle.Free();
            return(attrStrings.ToArray().ToString());
        }
Exemplo n.º 28
0
        /// <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));
        }
        public static string ReadStringAttribute(hid_t hid, string key)
        {
            var attribute = H5A.open(hid, key);

            if (attribute < 0)
            {
                throw new ArgumentException(string.Format("Attribute {0} not found.", key));
            }

            var type = H5A.get_type(attribute);

            if (type < 0)
            {
                H5A.close(attribute);
                throw new Exception("H5A.get_type failed.");
            }

            var typeClass = H5T.get_class(type);

            if (typeClass != H5T.class_t.STRING)
            {
                H5T.close(type);
                throw new Exception("Not a string attribute");
            }

            var utf8  = H5T.get_cset(type) == H5T.cset_t.UTF8;
            var ascii = H5T.get_cset(type) == H5T.cset_t.ASCII;

            if (!utf8 && !ascii)
            {
                H5T.close(type);
                H5A.close(attribute);
                throw new Exception("Neither ASCII nor UTF8.");
            }

            var isVariableString = H5T.is_variable_str(type);

            if (isVariableString < 0)
            {
                H5T.close(type);
                H5A.close(attribute);
                throw new Exception("H5T.is_variable_str failed");
            }

            if (isVariableString > 0)
            {
                var space = H5A.get_space(attribute);
                if (space < 0)
                {
                    H5T.close(type);
                    H5A.close(attribute);
                    throw new Exception("H5A.get_space failed.");
                }

                hid_t count = H5S.get_simple_extent_npoints(space);
                var   rdata = new IntPtr[count];

                H5A.read(attribute, type, new PinnedObject(rdata));

                var attrStrings = new List <string>();
                for (int i = 0; i < rdata.Length; ++i)
                {
                    int attrLength = 0;
                    while (Marshal.ReadByte(rdata[i], attrLength) != 0)
                    {
                        ++attrLength;
                    }

                    byte[] buffer = new byte[attrLength];
                    Marshal.Copy(rdata[i], buffer, 0, buffer.Length);

                    string part = utf8 ? Encoding.UTF8.GetString(buffer)
                        : Encoding.ASCII.GetString(buffer);

                    attrStrings.Add(part);

                    H5.free_memory(rdata[i]);
                }

                H5S.close(space);
                H5T.close(type);
                H5A.close(attribute);

                return(attrStrings[0]);
            }

            // Must be a non-variable length string.
            var size            = H5T.get_size(type).ToInt32();
            var unmanagedBuffer = new UnmanagedBuffer(size);

            int result = H5A.read(attribute, type, unmanagedBuffer);

            if (result < 0)
            {
                H5T.close(type);
                H5D.close(attribute);
                throw new IOException("Failed to read attribute.");
            }

            var bytes = new byte[size];

            unmanagedBuffer.CopyTo(bytes, 0, bytes.Length);

            H5T.close(type);
            H5A.close(attribute);

            var value = utf8 ? Encoding.UTF8.GetString(bytes)
                : Encoding.ASCII.GetString(bytes);

            return(value.TrimEnd('\0'));
        }
        public static bool WriteVariableStringAttribute(hid_t hid, string key, IEnumerable <string> values, bool utf8)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            if (values == null)
            {
                throw new ArgumentNullException("values");
            }

            var exists = H5A.exists(hid, key);

            if (exists < 0)
            {
                throw new Exception("H5A.exists failed");
            }

            if (exists == 0) // Attribute doesn't exist
            {
#if true
                var type = H5T.create(H5T.class_t.STRING, H5T.VARIABLE);
                if (type < 0)
                {
                    throw new Exception("Failed to create string type");
                }
#else
                var type = H5T.copy(H5T.C_S1);
                if (type < 0)
                {
                    throw new Exception("Failed to create string type");
                }

                if (H5T.set_size(type, H5T.VARIABLE) < 0)
                {
                    H5T.close(type);
                    throw new Exception("Failed to set type size");
                }
#endif

                if (utf8)
                {
                    if (H5T.set_cset(type, H5T.cset_t.UTF8) < 0)
                    {
                        H5T.close(type);
                        throw new Exception("Failed to set cset");
                    }
                }

                if (H5T.set_strpad(type, H5T.str_t.NULLTERM) < 0)
                {
                    H5T.close(type);
                    throw new Exception("Failed to set strpad");
                }

                var space = values.Count() == 1 ? H5S.create(H5S.class_t.SCALAR)
                    : H5S.create_simple(1, new ulong[1] {
                    (ulong)values.Count()
                }, null);
                if (space < 0)
                {
                    H5T.close(type);
                    throw new Exception("Failed to create data space");
                }

                var attribute = H5A.create(hid, key, type, space);
                H5S.close(space);
                if (attribute < 0)
                {
                    H5T.close(type);
                    throw new Exception(string.Format("Failed to create attribute \"{0}\"", key));
                }

                var pinnedObjects = new PinnedObject[values.Count()];
                var data          = new IntPtr[values.Count()];
                int count         = 0;
                foreach (string str in values)
                {
                    var bytes = str.ToBytes(utf8);
                    pinnedObjects[count] = new PinnedObject(bytes);
                    data[count]          = pinnedObjects[count];
                    count += 1;
                }

                H5A.write(attribute, type, new PinnedObject(data));

                H5T.close(type);
                H5A.close(attribute);
            }
            else
            {
                // Attribute exists.
                var attribute = H5A.open(hid, key);
                if (attribute < 0)
                {
                    throw new Exception(string.Format("Failed to open attribute \"{0}\"", key));
                }

                var type = H5A.get_type(attribute);
                if (type < 0)
                {
                    H5A.close(attribute);
                    throw new Exception("Failed to get data type");
                }

                var pinnedObjects = new PinnedObject[values.Count()];
                var data          = new IntPtr[values.Count()];
                int count         = 0;
                foreach (string str in values)
                {
                    var bytes = str.ToBytes(utf8);
                    pinnedObjects[count] = new PinnedObject(bytes);
                    data[count]          = pinnedObjects[count];
                    count += 1;
                }

                H5A.write(attribute, type, new PinnedObject(data));

                H5T.close(type);
                H5A.close(attribute);
            }

            return(true);
        }