Skip to content
hdf5_example.ipynb 9.29 KiB
Newer Older
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## HDF5 Datasets\n",
    "\n",
    "In the following we show some examples on how to create Datasets in HDF5 (whith h5py) and update values\n",
    "\n",
    "### First dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import h5py\n",
    "\n",
    "from timeit import timeit  # To measure execution time\n",
    "import numpy as np # this is the main python numerical library\n",
    "\n",
    "f = h5py.File(\"testdata.hdf5\",'w')\n",
    "\n",
    "# We create a test 2-d array filled with 1s and with 10 rows and 6 columns\n",
    "data = np.ones((10, 6))\n",
    "\n",
    "f[\"dataset_one\"] = data\n",
    "\n",
    "# We now retrieve the dataset from file (it is still in memory in fact)\n",
    "dset = f[\"dataset_one\"]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#The following instructions show some dataset metadata\n",
    "print(dset)\n",
    "print(dset.dtype)\n",
    "print(dset.shape)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Dataset slicing\n",
    "\n",
    "Datasets provide analogous slicing operations as numpy arrays (with h5py). But these selections are translated by h5py to portion of the dataset and then HDF5 reads the data form \"disk\". Slicing into a dataset object returns a NumpPy array.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# The ellipses means \"as many ':' as needed\"\n",
    "# here we use it to get a numpy array of the\n",
    "# entire dataset\n",
    "out = dset[...]\n",
    "\n",
    "print(out)\n",
    "type(out)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dset[1:5, 1] = 0.0\n",
    "dset[...]\n",
    "\n",
    "#but we cannot use negative steps with a dataset\n",
    "try:\n",
    "    dset[0,::-1]\n",
    "except: \n",
    "    print('No no no!')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# random 2d distribution in the range (-1,1)\n",
    "data = np.random.rand(15, 10)*2 - 1\n",
    "\n",
    "dset = f.create_dataset('random', data=data)\n",
    "\n",
    "# print the first 5 even rows and the first two columns\n",
    "out = dset[0:10:2, :2]\n",
    "print(out)\n",
    "\n",
    "# clipping to zero all negative values, using boolean indexing\n",
    "dset[data<0] = 0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Resizable datasets\n",
    "\n",
    "If we don't know in advance the dataset size and we need to append new data several times, we have to create a resizable dataset, then we have to append data in a scalable manner"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "dset = f.create_dataset('dataset_two', (1,1000), dtype=np.float32, \n",
    "                        maxshape=(None, 1000))\n",
    "\n",
    "a = np.ones((1000,1000))\n",
    "\n",
    "num_rows = dset.shape[0]\n",
    "dset.resize((num_rows+a.shape[0], 1000))\n",
    "\n",
    "dset[num_rows:] = a\n",
    "print(dset[1:5,:20])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Groups\n",
    "\n",
    "We can directly create nested groups with a single instruction. For instance to create the group 'nisp_frame', then the subgroup 'detectors' and at last its child group 'det11', we can use the instruction below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grp = f.create_group('nisp_frame/detectors/det11')\n",
    "grp['sci_image'] = np.zeros((2040,2040))\n",
    "\n",
    "print(grp.name)     # the group name property\n",
    "print(grp.parent)   # the parent group property\n",
    "print(grp.file)     # the file property\n",
    "print(grp)          # prints some group information. It has one member, the dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Attributes\n",
    "\n",
    "Attributes can be defined inside a group or in a dataset. Both have the **.attrs** property to access an attribute or define new attributes. With h5py, the attribute type is inferred from the passed value, but it is also possible to explicitly assign a type."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grp = f['nisp_frame']\n",
    "grp.attrs['telescope'] = 'Euclid'\n",
    "grp.attrs['instrument'] = 'NISP'\n",
    "grp.attrs['pointing'] = np.array([8.48223045516, -20.4610801911, 64.8793517547])\n",
    "grp.attrs.create('detector_id', '11', dtype=\"|S2\")\n",
    "\n",
    "print(grp.attrs['pointing'])\n",
    "print(grp.attrs['detector_id'])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f.close()\n",
    "!h5ls -vlr testdata.hdf5"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Tables (compound types)\n",
    "\n",
    "Tables can be stored as datasets where the elements (rows) have the same compound type. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = h5py.File(\"testdata.hdf5\",'a')\n",
    "dt = np.dtype([('source_id', np.uint32), ('ra', np.float32), ('dec', np.float32), ('magnitude', np.float64)])\n",
    "\n",
    "grp = f.create_group('source_catalog/det11')\n",
    "dset = grp.create_dataset('star_catalog', (100,), dtype=dt)\n",
    "\n",
    "dset['source_id', 0] = 1\n",
    "print(dset['source_id', 'ra', :20])\n",
    "print(dset[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## References and Region references\n",
    "\n",
    "In the following instruction we create a reference from the detector 11 scientific image to the corresponding star catalog, which is stored in the same file"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sci_image = f['/nisp_frame/detectors/det11/sci_image']\n",
    "sci_image.attrs['star_catalog'] = dset.ref\n",
    "cat_ref = sci_image.attrs['star_catalog']\n",
    "\n",
    "print(cat_ref)\n",
    "dset = f[cat_ref]\n",
    "print(dset[0])\n",
    "dt = h5py.special_dtype(ref=h5py.Reference)\n",
    "# the above data type dt can be used to create a dataset of references or just an attribute"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "roi = sci_image.regionref[15:20, 36:78]\n",
    "sci_image[roi]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Chuncking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rdata = np.random.randint(0,2**16,(100,2048,2048), dtype=np.uint16)\n",
    "\n",
    "f = h5py.File('image_sequence.hdf5','w')\n",
    "dset = f.create_dataset('nochunk', data=rdata)\n",
    "f.flush()\n",
    "f.close()\n",
    "\n",
    "f = h5py.File('image_sequence_chunked.hdf5','w')\n",
    "dset = f.create_dataset('chunked', data=rdata, chunks=(100,64,64))\n",
    "f.flush()\n",
    "f.close()\n",
    "\n",
    "f = h5py.File('image_sequence.hdf5','r')\n",
    "dset = f['nochunk']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "for i in range(32):\n",
    "    for j in range(32):\n",
    "        block = dset[:,64*i:64*(i+1), 64*j:64*(j+1)]\n",
    "        np.median(block, 0)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f.close()\n",
    "f = h5py.File('image_sequence_chunked.hdf5','r')\n",
    "dset = f['chunked']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "for i in range(32):\n",
    "    for j in range(32):\n",
    "        block = dset[:,64*i:64*(i+1), 64*j:64*(j+1)]\n",
    "        np.median(block, 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f.close()\n",
    "f = h5py.File('image_sequence_chunked.hdf5','a')\n",
    "dset = f.require_dataset('auto_chunked', (2048,2048), dtype=np.float32, compression=\"gzip\")\n",
    "print(dset.compression)\n",
    "print(dset.compression_opts)\n",
    "print(dset.chunks)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}