{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8e4c3dd9",
   "metadata": {},
   "source": [
    "# Using ClusterFile"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "38941595",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "import numpy as np \n",
    "import matplotlib.pyplot as plt\n",
    "import boost_histogram as bh\n",
    "import time\n",
    "\n",
    "#Python cluster reader\n",
    "from creader import ClusterFile\n",
    "path = Path('/mnt/sls_det_storage/moench_data/cluster_reader_test/')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bc0ae735",
   "metadata": {},
   "source": [
    "## Read clusters from file and plot a histogram\n",
    "\n",
    "- Passing chunk, to the cluster reader to set the default amount of clusters to be read\n",
    "- Using the context manager to manage the file closing\n",
    "- Looping over chunks in the file (reads chunksize until a zero read)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e69f82da",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.legend.Legend at 0x7f4b6c136d10>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 16940 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fname = 'beam_En700eV_-40deg_300V_10us_d0_f0_100.clust'\n",
    "\n",
    "# Create the histogram\n",
    "n_bins = 100\n",
    "xmin = -100\n",
    "xmax = 1e4\n",
    "hist1 = bh.Histogram(bh.axis.Regular(n_bins, xmin, xmax))\n",
    "\n",
    "# Read clusters and fill the histogram with pixel values\n",
    "with ClusterFile(path/fname, chunk = 10000) as f:\n",
    "    for clusters in f:\n",
    "        hist1.fill(clusters['data'].flat)\n",
    "\n",
    "\n",
    "#Plotting\n",
    "fig, ax = plt.subplots()\n",
    "ax.bar(hist1.axes[0].centers, hist1.values(), width=hist1.axes[0].widths, label = 'data')\n",
    "ax.set_yscale('log')\n",
    "ax.set_xlabel('ADU [1]')\n",
    "ax.set_ylabel('Intensity [a.u.]')\n",
    "ax.legend()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f7fd30b5",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.11.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
