Exemple #1
0
        public static double[, ,] ReadFieldData3D(string fileName)
        {
            H5FileId     fileId      = H5F.open(fileName, H5F.OpenMode.ACC_RDONLY);
            H5DataSetId  fDataSetId  = H5D.open(fileId, "/FieldData/FD/f0");
            H5DataTypeId fDataTypeId = H5D.getType(fDataSetId);

            if (!H5T.equal(fDataTypeId, H5T.copy(H5T.H5Type.NATIVE_FLOAT)))
            {
                Console.WriteLine("Error: Invalid dataset type, expected {0}", H5T.H5Type.NATIVE_FLOAT);
            }

            long[] dims = H5S.getSimpleExtentDims(H5D.getSpace(fDataSetId)).ToArray();
            if (dims.Length != 3)
            {
                Console.WriteLine("Error: Invalid field data dimensions");
            }

            float[, ,] data = new float[dims[0], dims[1], dims[2]];
            H5D.read(fDataSetId, fDataTypeId, new H5Array <float>(data));

            // Reorder
            double[, ,] fieldValues = new double[dims[2], dims[1], dims[0]];
            for (int i = 0; i < dims[0]; i++)
            {
                for (int j = 0; j < dims[1]; j++)
                {
                    for (int k = 0; k < dims[2]; k++)
                    {
                        fieldValues[k, j, i] = data[i, j, k];
                    }
                }
            }

            return(fieldValues);
        }
Exemple #2
0
        //Load weights from hdf5 file. Weights must be saved as a vector per layer
        public static float[] loadH5(string path, string dsname)
        {
            //Get file id
            var h5fid = H5F.open(path, H5F.OpenMode.ACC_RDONLY);
            //Get dataset id
            var h5did = H5D.open(h5fid, dsname);
            //Dataset size
            var h5space = H5D.getSpace(h5did);
            var h5size  = H5S.getSimpleExtentDims(h5space);

            //Dataset size to array
            var S = h5size.ToArray();

            //Empty double array for the data
            double[] data = new double[S[0]];

            //Read the dataset

            var h5array = new H5Array <double>(data);
            var h5dtype = H5D.getType(h5did);

            H5D.read(h5did, h5dtype, h5array);

            //Convert to float
            float[] newarray = new float[data.Length];

            Parallel.For(0, data.Length, (k) =>
            {
                newarray[k] = (float)data[k];
            });

            return(newarray);
        }
Exemple #3
0
        public void H5DreadTest1()
        {
            byte[] rdata = new byte[512];

            hid_t mem_type = H5T.copy(H5T.C_S1);

            Assert.IsTrue(H5T.set_size(mem_type, new IntPtr(2)) >= 0);

            GCHandle hnd = GCHandle.Alloc(rdata, GCHandleType.Pinned);

            Assert.IsTrue(H5D.read(m_v0_ascii_dset, mem_type, H5S.ALL,
                                   H5S.ALL, H5P.DEFAULT, hnd.AddrOfPinnedObject()) >= 0);
            for (int i = 0; i < 256; ++i)
            {
                // H5T.FORTRAN_S1 is space (= ASCII dec. 32) padded
                if (i != 32)
                {
                    Assert.IsTrue(rdata[2 * i] == (byte)i);
                }
                else
                {
                    Assert.IsTrue(rdata[64] == (byte)0);
                }
                Assert.IsTrue(rdata[2 * i + 1] == (byte)0);
            }
            hnd.Free();

            Assert.IsTrue(H5T.close(mem_type) >= 0);
        }
        /// <summary>
        /// Returns the entire matrix table
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="matName"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        public T[,] GetMatrix <T>(string matName)
        {
            var data = new T[Shape[0], Shape[1]];

            // check that matrix exists
            if (tables.ContainsKey(matName))
            {
                H5DataSetId matId;
                tables.TryGetValue(matName, out matId);

                H5DataTypeId  matDataId = H5D.getType(matId);
                H5DataSpaceId spaceId   = H5S.create_simple(2, Shape);

                var h5matrix = new H5Array <T>(data);

                long[] start = { 0, 0 };
                long[] count = { Shape[0], Shape[1] };
                H5S.selectHyperslab(spaceId, H5S.SelectOperator.SET, start, count);
                H5DataSpaceId readSpaceId = H5S.create_simple(2, count);

                H5D.read(matId, matDataId, readSpaceId, spaceId, H5P.create(H5P.PropertyListClass.DATASET_XFER), h5matrix);
                H5S.close(spaceId);
                H5S.close(readSpaceId);
            }
            else
            {
                Console.WriteLine("table {0} not found in matrix file", matName);
            }
            return(data);
        }
Exemple #5
0
        public string[] Column(long n)
        {
            using (H5Space file_space = SelectSlice(n, n + 1, axis: 1)) {
                using (H5Space mem_space = H5Space.Create(1, new long[] { Dims[0] })) {
                    using (H5Type dtype = GetDType()) {
                        int      slen        = (int)dtype.Size;
                        byte[]   buf         = new byte[slen * mem_space.Length];
                        GCHandle pinnedArray = GCHandle.Alloc(buf, GCHandleType.Pinned);
                        int      status      = H5D.read(ID, dtype.ID, mem_space.ID, file_space.ID,
                                                        H5P.DEFAULT, pinnedArray.AddrOfPinnedObject());
                        pinnedArray.Free();
                        if (status < 0)
                        {
                            throw new H5LibraryException($"H5D.read() returned ({status})");
                        }

                        string decoded = string1d.Enc.GetString(buf);

                        var rv = new string[mem_space.Length];
                        for (int i = 0; i < rv.Length; i++)
                        {
                            rv[i] = decoded.Substring(i * slen, slen).TrimEnd('\0');
                        }

                        return(rv);
                    }
                }
            }
        }
Exemple #6
0
        public static double[,] ReadFieldData2D(string file, string dataSet)
        {
            H5FileId     fileId      = H5F.open(file, H5F.OpenMode.ACC_RDONLY);
            H5DataSetId  fDataSetId  = H5D.open(fileId, dataSet);
            H5DataTypeId fDataTypeId = H5D.getType(fDataSetId);

            long[] dims = H5S.getSimpleExtentDims(H5D.getSpace(fDataSetId)).ToArray();
            double[,] data = new double[dims[0], dims[1]];
            H5D.read(fDataSetId, fDataTypeId, new H5Array <double>(data));

            double[,] fieldValues = new double[dims[1], dims[0]];
            for (int i = 0; i < dims[1]; i++)
            {
                for (int j = 0; j < dims[0]; j++)
                {
                    fieldValues[i, j] = (double)data[j, i];
                }
            }

            H5T.close(fDataTypeId);
            H5D.close(fDataSetId);
            H5F.close(fileId);

            return(fieldValues);
        }
Exemple #7
0
        public static double[][] ReadMesh(string fileName)
        {
            double[][] meshes    = new double[3][];
            string[]   meshNames = { "x", "y", "z" };

            H5FileId fileId = H5F.open(fileName, H5F.OpenMode.ACC_RDONLY);

            for (int i = 0; i < meshNames.Length; i++)
            {
                H5DataSetId  dsId = H5D.open(fileId, "/Mesh/" + meshNames[i]);
                H5DataTypeId dtId = H5D.getType(dsId);

                if (!H5T.equal(dtId, H5T.copy(H5T.H5Type.NATIVE_FLOAT)))
                {
                    Console.WriteLine("Error: Invalid dataset type, expected {0}", H5T.H5Type.NATIVE_FLOAT);
                }

                float[] mesh = new float[H5D.getStorageSize(dsId) / H5T.getSize(dtId)];
                H5D.read(dsId, dtId, new H5Array <float>(mesh));

                meshes[i] = mesh.Select(x => (double)x * 1000.0).ToArray(); // m -> mm

                H5D.close(dsId);
                H5T.close(dtId);
            }

            H5F.close(fileId);

            return(meshes);
        }
Exemple #8
0
        public void H5DreadTest2()
        {
            hid_t mem_type = H5T.create(H5T.class_t.STRING, H5T.VARIABLE);

            Assert.IsTrue(H5T.set_cset(mem_type, H5T.cset_t.UTF8) >= 0);
            Assert.IsTrue(H5T.set_strpad(mem_type, H5T.str_t.NULLTERM) >= 0);

            hid_t fspace = H5D.get_space(m_v0_utf8_dset);

            Assert.IsTrue(fspace >= 0);

            hssize_t count = H5S.get_simple_extent_npoints(fspace);

            Assert.IsTrue(count > 0);
            Assert.IsTrue(H5S.close(fspace) >= 0);

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

            Assert.IsTrue(H5D.read(m_v0_utf8_dset, mem_type, H5S.ALL, H5S.ALL,
                                   H5P.DEFAULT, hnd.AddrOfPinnedObject()) >= 0);

            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);

                Assert.IsTrue(s == ((string)m_utf8strings[i]));

                Assert.IsTrue(H5.free_memory(rdata[i]) >= 0);
            }

            Assert.IsTrue(H5D.read(m_v2_utf8_dset, mem_type, H5S.ALL, H5S.ALL,
                                   H5P.DEFAULT, hnd.AddrOfPinnedObject()) >= 0);

            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);

                Assert.IsTrue(s == ((string)m_utf8strings[i]));

                Assert.IsTrue(H5.free_memory(rdata[i]) >= 0);
            }

            hnd.Free();
        }
Exemple #9
0
        private static double[,] ReadDataArray(hid_t fileLoc, string name, bool transpose = false)
        {
            hid_t dset   = H5D.open(fileLoc, name);
            hid_t fspace = H5D.get_space(dset);
            hid_t count  = H5S.get_simple_extent_ndims(fspace);

            hid_t type = H5D.get_type(dset);

            hsize_t[] dims    = new hsize_t[count];
            hsize_t[] maxdims = new hsize_t[count];

            H5S.get_simple_extent_dims(fspace, dims, maxdims);
            H5S.close(fspace);


            byte[] rdata = new byte[dims[0] * dims[1] * 8];

            hid_t mem_type = H5T.copy(H5T.NATIVE_DOUBLE);

            H5T.set_size(mem_type, new IntPtr(8));

            GCHandle hnd = GCHandle.Alloc(rdata, GCHandleType.Pinned);

            H5D.read(dset, mem_type, H5S.ALL,
                     H5S.ALL, H5P.DEFAULT, hnd.AddrOfPinnedObject());

            hnd.Free();

            H5T.close(mem_type);

            if (transpose)
            {
                double[,] val = new double[dims[1], dims[0]];
                int cnt = 0;
                for (int i = 0; i < (int)dims[0]; i++)
                {
                    for (int j = 0; j < (int)dims[1]; j++)
                    {
                        val[j, i] = BitConverter.ToDouble(rdata, cnt * 8);
                        cnt++;
                    }
                }
                return(val);
            }
            else
            {
                double[,] val = new double[dims[0], dims[1]];
                int cnt = 0;
                for (int i = 0; i < (int)dims[0]; i++)
                {
                    for (int j = 0; j < (int)dims[1]; j++)
                    {
                        val[i, j] = BitConverter.ToDouble(rdata, cnt * 8);
                        cnt++;
                    }
                }
                return(val);
            }
        }
Exemple #10
0
        public Dictionary <string, string> TryReadDataTable(string datasetName)
        {
            Dictionary <string, string> result = null;
            var subDsDic = ds.GetSubDatasets();

            if (subDsDic.Count > 0)
            {
                H5ID h5FileId  = H5F.open(fileName, H5F.ACC_RDONLY);
                H5ID datasetId = H5D.open(h5FileId, datasetName);
                H5ID typeId    = H5D.get_type(datasetId);
                H5ID spaceId   = H5D.get_space(datasetId);
                if (H5T.get_class(typeId) == H5T.class_t.COMPOUND)
                {
                    int      numCount = H5T.get_nmembers(typeId);
                    var      size     = H5T.get_size(typeId);
                    byte[]   buffer   = new byte[size.ToInt32()];
                    GCHandle hnd      = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                    int      ndims    = H5S.get_simple_extent_ndims(spaceId);
                    if (ndims == 1)
                    {
                        result = new Dictionary <string, string>();
                        H5D.read(datasetId, typeId, H5S.ALL, H5S.ALL, H5P.DEFAULT, hnd.AddrOfPinnedObject());

                        for (uint i = 0; i < numCount; i++)
                        {
                            string name   = Marshal.PtrToStringAnsi(H5T.get_member_name(typeId, i));
                            int    offset = H5T.get_member_offset(typeId, i).ToInt32();

                            H5ID        subTypeId = H5T.get_member_type(typeId, i);
                            H5T.class_t typeClass = H5T.get_member_class(typeId, i);
                            string      value     = ReadBuffer(buffer, offset, typeClass, subTypeId);
                            result.Add(name, value);
                            H5T.close(subTypeId);
                        }
                    }

                    hnd.Free();
                }

                if (spaceId != 0)
                {
                    H5S.close(spaceId);
                }
                if (typeId != 0)
                {
                    H5T.close(typeId);
                }
                if (datasetId != 0)
                {
                    H5D.close(datasetId);
                }
                if (h5FileId != 0)
                {
                    H5F.close(h5FileId);
                }
            }

            return(result);
        }
Exemple #11
0
        public static (bool success, IEnumerable <string> result) ReadStrings(long groupId, string name, string alternativeName)
        {
            long 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 = H5D.open(groupId, Hdf5Utils.NormalizedName(name));

            if (datasetId < 0) //does not exist?
            {
                datasetId = H5D.open(groupId, Hdf5Utils.NormalizedName(alternativeName));
            }

            if (datasetId <= 0)
            {
                Hdf5Utils.LogError?.Invoke($"Error reading {groupId}. Name:{name}. AlternativeName:{alternativeName}");
                return(false, Array.Empty <string>());
            }
            long spaceId = H5D.get_space(datasetId);

            long count = H5S.get_simple_extent_npoints(spaceId);

            H5S.close(spaceId);

            var strs = new List <string>();

            if (count >= 0)
            {
                IntPtr[] rdata = new IntPtr[count];
                GCHandle hnd   = GCHandle.Alloc(rdata, GCHandleType.Pinned);
                H5D.read(datasetId, datatype, H5S.ALL, H5S.ALL,
                         H5P.DEFAULT, hnd.AddrOfPinnedObject());

                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);
            H5D.close(datasetId);
            return(true, strs);
        }
Exemple #12
0
        /// <summary>
        /// WARNING: ADVANCED USE ONLY!! Loads a 2D generic dataset from an H5 file.
        /// The generic loaders only loads data in non-Unity friendly types, such as bytes, uints, longs etc...
        /// You'll have to know the correct cast to retrieve usable data.
        ///
        /// Created With help from https://github.com/LiorBanai/HDF5-CSharp/blob/master/HDF5-CSharp/Hdf5Dataset.cs
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="datasetName"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        /// <exception cref="FileNotFoundException"></exception>
        static T[,] Load2DDataset <T>(string filePath, string datasetName)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException($"Loading dataset {datasetName} from file that doesn't exist {filePath}");
            }
            long fileId = H5F.open(filePath, H5F.ACC_RDONLY);

            T[,] resultArray = new T[2, 2];
            try {
                ulong[] start = { 0, 0 };
                ulong[] count = { 0, 0 };

                long    datasetId = H5D.open(fileId, datasetName);
                var     datatype  = H5D.get_type(datasetId);
                var     spaceId   = H5D.get_space(datasetId);
                int     rank      = H5S.get_simple_extent_ndims(spaceId);
                ulong[] maxDims   = new ulong[rank];
                ulong[] dims      = new ulong[rank];
                H5S.get_simple_extent_dims(spaceId, dims, maxDims);

                count[0] = dims[0];
                count[1] = dims[1];

                // Define file hyperslab.
                long status = H5S.select_hyperslab(spaceId, H5S.seloper_t.SET, start, null, count, null);

                // Define the memory dataspace.
                resultArray = new T[dims[0], dims[1]];
                var memId = H5S.create_simple(rank, dims, null);

                // Define memory hyperslab.
                status = H5S.select_hyperslab(memId, H5S.seloper_t.SET, start, null,
                                              count, null);

                // Read data from hyperslab in the file into the hyperslab in
                // memory and display.
                GCHandle handle = GCHandle.Alloc(resultArray, GCHandleType.Pinned);

                try {
                    H5D.read(datasetId, datatype, memId, spaceId,
                             H5P.DEFAULT, handle.AddrOfPinnedObject());
                }
                finally {
                    handle.Free();
                    H5S.close(status);
                    H5S.close(memId);
                    H5S.close(spaceId);
                    H5D.close(datatype);
                    H5D.close(datasetId);
                }
            }
            finally {
                H5F.close(fileId);
            }
            return(resultArray);
        }
        void LoadRowData()
        {
            var dtype = H5D.getType(Id);
            var size  = H5T.getSize(dtype);

            _row_data = new byte[FindNumberOfRows(), size];
            H5D.read(Id, dtype, new H5Array <byte>(_row_data));

            //TODO: Does this work with more than one row? Dunno. Probs not.
        }
Exemple #14
0
        /// <summary>
        /// 重写数据集的值(去条带的数据)
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="dataSetName">数据集的名称</param>
        /// <param name="dataTypeId">数据集的类型ID</param>
        /// <param name="values">去条带之后数据</param>
        /// <param name="BrandNo">在数据集的维度从0开始</param>
        private void ReWriteDataSet <T>(string dataSetName, H5DataTypeId dataTypeId, T[] values, int BrandNo)
        {
            H5FileId      _h5FileId = null;
            H5DataSetId   dataSetId = null;
            H5DataSpaceId spaceid   = null;

            try
            {
                _h5FileId = H5F.open(fileName, H5F.OpenMode.ACC_RDWR);
                //先找出含有指定波段的数据集
                dataSetId = H5D.open(_h5FileId, dataSetName);
                spaceid   = H5D.getSpace(dataSetId);
                long[] dims = H5S.getSimpleExtentDims(spaceid);  //得到数据数组的大小,比如[3,1800,2048]
                int    rank = H5S.getSimpleExtentNDims(spaceid); //得到数据数组的维数,比如3
                H5S.close(spaceid);
                //根据数据集的名字获取数据集的ID
                int size = 0;
                if (rank == 0)
                {
                    size = 1;
                }
                else if (rank == 1)
                {
                    size = Convert.ToInt32(dims[0]);
                }
                else if (rank == 2)
                {
                    size = Convert.ToInt32(dims[0] * dims[1]);
                }
                else if (rank == 3)
                {
                    size = Convert.ToInt32(dims[0] * dims[1] * dims[2]);
                }
                T[] v = new T[size];
                //从数据集中读取原始数据
                H5D.read <T>(dataSetId, dataTypeId, new H5Array <T>(v));
                //将波段校正后的数据读取赋给相应的波段
                for (int i = BrandNo; i < values.Length; i++)
                {
                    v[i] = values[i];
                }
                H5D.write <T>(dataSetId, dataTypeId, new H5Array <T>(v));
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                H5D.close(dataSetId);
                H5F.close(_h5FileId);
            }
        }
    private mData[] ReadData()
    {
        Console.WriteLine("Reading H5 file {0}...", filename);
        H5FileId    fileId    = H5F.open(filename, H5F.OpenMode.ACC_RDONLY);
        H5DataSetId dataSetId = H5D.open(fileId, dataSetName);

        mData[] readDataBack = new mData[count];
        H5D.read(dataSetId, new H5DataTypeId(H5T.H5Type.STD_REF_OBJ), new H5Array <mData>(readDataBack));
        H5D.close(dataSetId);
        H5F.close(fileId);
        return(readDataBack);
    }
Exemple #16
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);
        }
        public static int[,] GetIntDataset(long dataset_id_inp, int rows_inp, int cols_inp)
        {
            int status;

            int[,] dataArray_out = new int[rows_inp, cols_inp];

            GCHandle buf = GCHandle.Alloc(dataArray_out, GCHandleType.Pinned);

            status = H5D.read(dataset_id_inp, H5T.NATIVE_INT, H5S.ALL, H5S.ALL, H5P.DEFAULT, buf.AddrOfPinnedObject());
            H5D.close(dataset_id_inp);

            return(dataArray_out);
        }
Exemple #18
0
        private T[] ReadArray <T>(int size, H5DataSetId dsId, H5DataTypeId typeId, int bandIndex, int outSize)
        {
            T[] v = new T[size];
            H5D.read <T>(dsId, typeId, new H5Array <T>(v));
            T[] outdata = new T[outSize];
            int index   = bandIndex * outSize;

            for (int i = 0; i < outdata.Length; i++)
            {
                outdata[i] = v[i + index];
            }
            return(outdata);
        }
Exemple #19
0
        public string this[long m, long n]
        {
            get
            {
                using (H5Space file_space = SelectPoint(m, n)) {
                    using (H5Space mem_space = H5Space.Create(1, new long[] { 1 })) {
                        using (H5Type dtype = GetDType()) {
                            long     slen        = dtype.Size;
                            byte[]   buf         = new byte[slen];
                            GCHandle pinnedArray = GCHandle.Alloc(buf, GCHandleType.Pinned);
                            int      status      = H5D.read(ID, dtype.ID, mem_space.ID, file_space.ID,
                                                            H5P.DEFAULT, pinnedArray.AddrOfPinnedObject());
                            pinnedArray.Free();
                            if (status < 0)
                            {
                                throw new H5LibraryException($"H5D.read() returned ({status})");
                            }

                            string decoded = string1d.Enc.GetString(buf);

                            return(decoded.TrimEnd('\0'));
                        }
                    }
                }
            }
            set
            {
                using (H5Space file_space = SelectPoint(m, n)) {
                    using (H5Space mem_space = H5Space.Create(1, new long[] { 1 })) {
                        using (H5Type dtype = GetDType()) {
                            long slen = dtype.Size;
                            if (value.Length > slen - 1)
                            {
                                throw new IndexOutOfRangeException($"string longer than ({slen})");
                            }

                            byte[] buf = new byte[slen];
                            Array.Copy(string1d.Enc.GetBytes(value), buf, value.Length);
                            GCHandle pinnedArray = GCHandle.Alloc(buf, GCHandleType.Pinned);
                            int      status      = H5D.write(ID, dtype.ID, mem_space.ID, file_space.ID,
                                                             H5P.DEFAULT, pinnedArray.AddrOfPinnedObject());
                            pinnedArray.Free();
                            if (status < 0)
                            {
                                throw new H5LibraryException($"H5D.read() returned ({status})");
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Reads an n-dimensional dataset.
        /// </summary>
        /// <typeparam name="T">Generic parameter strings or primitive type</typeparam>
        /// <param name="groupId">id of the group. Can also be a file Id</param>
        /// <param name="name">name of the dataset</param>
        /// <returns>The n-dimensional dataset</returns>
        public static Array ReadDatasetToArray <T>(hid_t groupId, string name) //where T : struct
        {
            var datatype = GetDatatype(typeof(T));


            var   datasetId = H5D.open(groupId, name);
            var   spaceId   = H5D.get_space(datasetId);
            int   rank      = H5S.get_simple_extent_ndims(spaceId);
            long  count     = H5S.get_simple_extent_npoints(spaceId);
            Array dset;
            Type  type = typeof(T);

            if (rank >= 0 && count >= 0)
            {
                int     rankChunk;
                ulong[] maxDims   = new ulong[rank];
                ulong[] dims      = new ulong[rank];
                ulong[] chunkDims = new ulong[rank];
                hid_t   memId     = H5S.get_simple_extent_dims(spaceId, dims, maxDims);
                long[]  lengths   = dims.Select(d => Convert.ToInt64(d)).ToArray();
                dset = Array.CreateInstance(type, lengths);
                var typeId   = H5D.get_type(datasetId);
                var mem_type = H5T.copy(datatype);
                if (datatype == H5T.C_S1)
                {
                    H5T.set_size(datatype, new IntPtr(2));
                }

                var propId = H5D.get_create_plist(datasetId);

                if (H5D.layout_t.CHUNKED == H5P.get_layout(propId))
                {
                    rankChunk = H5P.get_chunk(propId, rank, chunkDims);
                }

                memId = H5S.create_simple(rank, dims, maxDims);
                GCHandle hnd = GCHandle.Alloc(dset, GCHandleType.Pinned);
                H5D.read(datasetId, datatype, memId, spaceId,
                         H5P.DEFAULT, hnd.AddrOfPinnedObject());
                hnd.Free();
            }
            else
            {
                dset = Array.CreateInstance(type, new long[1] {
                    0
                });
            }
            H5D.close(datasetId);
            H5S.close(spaceId);
            return(dset);
        }
Exemple #21
0
        /// <summary>
        /// 读取指定数据集,未对异常进行处理
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="datasetName"></param>
        /// <param name="bandN"></param>
        /// <param name="bandH"></param>
        /// <param name="bandW"></param>
        /// <returns></returns>
        public T[] ReadDataArray <T>(String datasetName, ref int bandN, ref int bandH, ref int bandW)
        {
            H5DataSetId   datasetId = null;
            H5DataSpaceId spaceId   = null;
            H5DataTypeId  typeId    = null;

            long[] dims = null;

            if (!String.IsNullOrEmpty(datasetName) && _datasetNames.Contains(datasetName))
            {
                datasetId = H5D.open(_fileId, datasetName);
                spaceId   = H5D.getSpace(datasetId);
                dims      = H5S.getSimpleExtentDims(spaceId);
                if (dims.Length == 2)
                {
                    bandN = 1;
                    bandH = (int)dims[0];
                    bandW = (int)dims[1];
                }
                else if (dims.Length == 3)
                {
                    bandN = (int)dims[0];
                    bandH = (int)dims[1];
                    bandW = (int)dims[2];
                }
                typeId = H5D.getType(datasetId);
                typeId = H5T.getNativeType(typeId, H5T.Direction.DEFAULT);
                T[] dv = new T[bandN * bandH * bandW];
                H5D.read <T>(datasetId, typeId, new H5Array <T>(dv));

                if (typeId != null)
                {
                    H5T.close(typeId);
                }
                if (spaceId != null)
                {
                    H5S.close(spaceId);
                }
                if (datasetId != null)
                {
                    H5D.close(datasetId);
                }
                return(dv);
            }
            else
            {
                throw new Exception("未查到指定数据集!");
            }
        }
        public static IEnumerable <T> ReadCompounds <T>(hid_t groupId, string name) where T : struct
        {
            Type  type   = typeof(T);
            hid_t typeId = 0;
            // open dataset
            var datasetId = H5D.open(groupId, name);

            typeId = CreateType(type);
            var compoundSize = Marshal.SizeOf(type);

            /*
             * Get dataspace and allocate memory for read buffer.
             */
            var spaceId = H5D.get_space(datasetId);
            int rank    = H5S.get_simple_extent_ndims(spaceId);

            ulong[] dims  = new ulong[rank];
            var     ndims = H5S.get_simple_extent_dims(spaceId, dims, null);
            int     rows  = Convert.ToInt32(dims[0]);

            byte[] bytes = new byte[rows * compoundSize];
            // Read the data.
            GCHandle hnd     = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            IntPtr   hndAddr = hnd.AddrOfPinnedObject();

            H5D.read(datasetId, typeId, spaceId, H5S.ALL, H5P.DEFAULT, hndAddr);
            int             counter = 0;
            IEnumerable <T> strcts  = Enumerable.Range(1, rows).Select(i =>
            {
                byte[] select = new byte[compoundSize];
                Array.Copy(bytes, counter, select, 0, compoundSize);
                T s     = fromBytes <T>(select);
                counter = counter + compoundSize;
                return(s);
            });

            /*
             * Close and release resources.
             */
            H5D.vlen_reclaim(typeId, spaceId, H5P.DEFAULT, hndAddr);
            hnd.Free();
            H5D.close(datasetId);
            H5S.close(spaceId);
            H5T.close(typeId);

            return(strcts);
        }
Exemple #23
0
        public static T[,] ReadDataset <T>(int groupId, string name, ulong beginIndex, ulong endIndex) where T : struct
        {
            ulong[]  start = { 0, 0 }, stride = null, count = { 0, 0 },
            block = null, offsetOut = new ulong[] { 0, 0 };
            var      datatype = GetDatatype(typeof(T));

            name = ToHdf5Name(name);

            var      datasetId = H5D.open(groupId, name);
            var      spaceId   = H5D.get_space(datasetId);
            int      rank      = H5S.get_simple_extent_ndims(spaceId);
            ulong[]  maxDims   = new ulong[rank];
            ulong[]  dims      = new ulong[rank];
            ulong[]  chunkDims = new ulong[rank];
            var      memId_n   = H5S.get_simple_extent_dims(spaceId, dims, maxDims);

            start[0] = beginIndex;
            start[1] = 0;
            count[0] = endIndex - beginIndex;
            count[1] = dims[1];

            var      status = H5S.select_hyperslab(spaceId, H5S.seloper_t.SET, start, stride, count, block);


            // Define the memory dataspace.

            T[,] dset = new T[count[0], count[1]];
            var      memId = H5S.create_simple(rank, count, null);

            // Define memory hyperslab.
            status = H5S.select_hyperslab(memId, H5S.seloper_t.SET, offsetOut, null,
                                          count, null);

            /*
             * Read data from hyperslab in the file into the hyperslab in
             * memory and display.
             */
            GCHandle hnd = GCHandle.Alloc(dset, GCHandleType.Pinned);
            H5D.read(datasetId, datatype, memId, spaceId,
                     H5P.DEFAULT, hnd.AddrOfPinnedObject());
            hnd.Free();
            H5D.close(datasetId);
            H5S.close(spaceId);
            H5S.close(memId);
            return(dset);
        }
        /// <summary>
        /// Returns mapping index - assumes that matrices are square and uses first dimension as the map size
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="mapName">Name of index map</param>
        public T[] GetMapping <T>(string mapName)
        {
            var mapData = new T[Shape[0]];

            // check that index map exists
            if (indexMaps.ContainsKey(mapName))
            {
                H5DataSetId mapId;
                indexMaps.TryGetValue(mapName, out mapId);
                H5D.read(mapId, H5D.getType(mapId), new H5Array <T>(mapData));
            }
            else
            {
                Console.WriteLine("index map {0} not found in file", mapName);
            }
            return(mapData);
        }
Exemple #25
0
        public static T[,] Read2DArray <T>(this H5FileId fileId, string dataSetName)
        {
            var dataset  = H5D.open(fileId, dataSetName);
            var space    = H5D.getSpace(dataset);
            var dims     = H5S.getSimpleExtentDims(space);
            var dataType = H5D.getType(dataset);

            if (typeof(T) == typeof(string))
            {
                // this will also need a string hack...
            }
            T[,] dataArray = new T[dims[0], dims[1]];
            var wrapArray = new H5Array <T>(dataArray);

            H5D.read(dataset, dataType, wrapArray);
            return(dataArray);
        }
Exemple #26
0
        public static IEnumerable <string> ReadStrings(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 = H5D.open(groupId, name);
            hid_t spaceId   = H5D.get_space(datasetId);

            long count = H5S.get_simple_extent_npoints(spaceId);

            H5S.close(spaceId);

            var strs = new List <string>();

            if (count >= 0)
            {
                IntPtr[] rdata = new IntPtr[count];
                GCHandle hnd   = GCHandle.Alloc(rdata, GCHandleType.Pinned);
                H5D.read(datasetId, datatype, H5S.ALL, H5S.ALL,
                         H5P.DEFAULT, hnd.AddrOfPinnedObject());

                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);
            H5D.close(datasetId);
            return(strs);
        }
Exemple #27
0
        //Reading and Printing Methods
        private static double[] GetDoubleDataSet(H5FileId dataFile, string path)
        {
            if (H5L.Exists(dataFile, path))
            {
                H5DataSetId      dataSet   = H5D.open(dataFile, path);
                H5DataSpaceId    space     = H5D.getSpace(dataSet);
                long[]           size2     = H5S.getSimpleExtentDims(space);
                long             count     = size2[0];
                double[]         dataArray = new double[count];
                H5Array <double> wrapArray = new H5Array <double>(dataArray);
                H5DataTypeId     tid1      = H5D.getType(dataSet);

                H5D.read(dataSet, tid1, wrapArray);

                return(dataArray);
            }
            return(null);
        }
Exemple #28
0
        public static void GetDataSet <T> (H5FileOrGroupId groupOrFileId, string name, out T[,,,] array, int width, int height, int depth, int number)
        {
            if (groupOrFileId is null)
            {
                throw new ArgumentNullException(nameof(groupOrFileId));
            }
            if (name is null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            H5DataSetId  h5DataSetId  = H5D.open(groupOrFileId, name);
            H5DataTypeId h5DataTypeId = H5D.getType(h5DataSetId);

            array = new T[height, width, depth, number];
            H5D.read(h5DataSetId, h5DataTypeId, new H5Array <T> (array));
            H5T.close(h5DataTypeId);
            H5D.close(h5DataSetId);
        }
Exemple #29
0
        public static void GetDataSet <T> (H5FileOrGroupId groupOrFileId, string name, out T[] array, int length)
        {
            if (groupOrFileId is null)
            {
                throw new ArgumentNullException(nameof(groupOrFileId));
            }
            if (name is null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            array = new T[length];
            H5DataSetId  h5DataSetId  = H5D.open(groupOrFileId, name);
            H5DataTypeId h5DataTypeId = H5D.getType(h5DataSetId);

            H5D.read(h5DataSetId, h5DataTypeId, new H5Array <T> (array));
            H5T.close(h5DataTypeId);
            H5D.close(h5DataSetId);
        }
Exemple #30
0
        private static int[] GetInt32DataSet(H5FileId dataFile, string path)
        {
            if (H5L.Exists(dataFile, path))
            {
                var          dataSet   = H5D.open(dataFile, path);
                var          space     = H5D.getSpace(dataSet);
                var          size2     = H5S.getSimpleExtentDims(space);
                long         count     = size2[0];
                var          dataArray = new Int32[count];
                var          wrapArray = new H5Array <Int32>(dataArray);
                H5DataTypeId tid1      = H5D.getType(dataSet);

                H5D.read(dataSet, tid1, wrapArray);

                return(dataArray);
            }
            return(null);
        }