{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# -*- coding: utf-8 -*-\n",
    "\"\"\"\n",
    "Created on Sun Apr 24 23:40:27 2022\n",
    "\n",
    "@author: Stepan\n",
    "\"\"\"\n",
    "import numpy as np\n",
    "#import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "from urllib.error import HTTPError # recognise the error stemming from missing data\n",
    "#import urllib\n",
    "import urllib.request\n",
    "#from urllib.request import urlopen\n",
    "import time\n",
    "import seaborn as sns #; sns.set_theme()\n",
    "#import plotly.graph_objects as go\n",
    "import collections # OrderedDict is one Python's high-performance containers\n",
    "######################################################################\n",
    "\n",
    "#Define an exception which will be raised if the data is missing and stop the notebook execution\n",
    "class StopExecution(Exception):\n",
    "    def _render_traceback_(self):\n",
    "        pass\n",
    "    \n",
    "shot_no = 0\n",
    "#shot_no = 38897   #test discharge for which the notebook will definitely work\n",
    "shot = shot_no\n",
    "#identifier='E05-W0037_shot_'+str(shot)+'_-450V'\n",
    "\n",
    "detectors= 'E05-W0037 F10-W0049 H03-W0051' #\n",
    "det_list = detectors.split(' ')\n",
    "#print(len(det_list))\n",
    "#print(det_list)\n",
    "detector=det_list\n",
    "#print(detector)\n",
    "\n",
    "#def get_file(shot, identifier):\n",
    "def get_file(shot, detector):\n",
    "    #det_list = detectors.split(' ')\n",
    "    #print(len(detector))\n",
    "    #print(detector)\n",
    "    pom=0 #pomocna promenna pro rozhodnuti,zda ukoncit script\n",
    "    pom1=0\n",
    "    pom2=0\n",
    "    for i in range(0,len(det_list)):\n",
    "        #pom = 0\n",
    "        #identifier=str(det_list[i])+'_shot_'+str(shot)+'_450V'\n", #Si
    "	   identifier=str(det_list[i])+'_shot_'+str(shot)+'_-450V'\n", #CdTe
    "        print(identifier)\n",
    "        #URL = 'http://golem.fjfi.cvut.cz/shots/{shot}/Diagnostics/TimepixDetector/H03/{identifier}.t3pa'\n",
    "        #URL = 'http://golem.fjfi.cvut.cz/shots/{shot}/Diagnostics/TimepixDetector/E05/{identifier}.t3pa'\n",
    "        URL = 'http://golem.fjfi.cvut.cz/shots/{shot}/Diagnostics/TimepixDetector/2xCdTe@TimepixPC/E05/{identifier}.t3pa'\n",
    "        url = URL.format(shot=shot, identifier=identifier)\n",
    "        print(url)\n",
    "        det =det_list[i]\n",
    "        try:\n",
    "            file_name_t3pa=url\n",
    "            with urllib.request.urlopen(file_name_t3pa) as ft3pa:\n",
    "                line = ft3pa.readline()\n",
    "                line = line.decode('utf‐8')\n",
    "                pom=pom+1\n",
    "                print(pom)\n",
    "                if pom>0:\n",
    "                    break\n",
    "            ft3pa.close\n",
    "            \n",
    "            #break\n",
    "                \n",
    "        except HTTPError:\n",
    "            if pom==0:\n",
    "                try:\n",
    "                    \n",
    "                    if (i==(len(detector)-1)) and pom>0:\n",
    "                        print('chyba\\n')#StopExecution\n",
    "                        pom1=1\n",
    "                        break\n",
    "                    \n",
    "                    if (i<(len(detector)-1)) and pom>0:\n",
    "                        print('chyba\\n')#StopExecution\n",
    "                        #print(len(detector))\n",
    "                        continue\n",
    "                    if (i<(len(detector)-1)) and pom==0:\n",
    "                        print('chyba\\n')#StopExecution\n",
    "                        #print(len(detector))\n",
    "                        continue\n",
    "                    \n",
    "                    if (i==(len(detector)-1)) and pom==0:\n",
    "                        pass\n",
    "                    \n",
    "                except:\n",
    "                    raise StopExecution\n",
    "            raise StopExecution\n",
    "            print(pom) \n",
    "            \n",
    "    return file_name_t3pa, det\n",
    "\n",
    "def load_t3pa_file(file_t3pa, hit_map_fig, det):\n",
    "    matrix_index=[]\n",
    "    RowNo=[]\n",
    "    ClmNo=[]\n",
    "    pocet_udalosti = 0\n",
    "    #RowNo=[]\n",
    "    #ClmNo=[]\n",
    "    \n",
    "    count = []\n",
    "    for i in range(0,256):      \n",
    "        pom = [] # pomocne pole\n",
    "        \n",
    "        for j in range(0,256):\n",
    "            pom.append(0)\n",
    "        count.append(pom)\n",
    "    \n",
    "    with urllib.request.urlopen(file_t3pa) as ft3pa:\n",
    "        line = ft3pa.readline()\n",
    "        line = line.decode('utf‐8')\n",
    "        while True:\n",
    "            line = ft3pa.readline()\n",
    "            line = line.decode('utf‐8')\n",
    "            word=line.strip().split('\\t') #v t3pa souboru je oddelovac \\t\n",
    "            #print(word)\n",
    "            #poc=0\n",
    "            if line == '':\n",
    "                break\n",
    "        \n",
    "            \n",
    "            pocet_udalosti = pocet_udalosti + 1\n",
    "            \n",
    "            RowNo.append(int(int(word[1]))//int(256))\n",
    "            ClmNo.append(int(int(word[1]))%int(256))\n",
    "            \n",
    "            x=(int(int(word[1]))//int(256))\n",
    "            y=(int(int(word[1]))%int(256))\n",
    "            \n",
    "            count[x][y]=count[x][y]+1\n",
    "            \n",
    "            \n",
    "    plt.hist2d(RowNo,ClmNo,bins=(256,256),cmap='Blues')\n",
    "    cb=plt.colorbar()\n",
    "    cb.set_label('Counts in bin')\n",
    "    #plt.show()    \n",
    "    plt.savefig(hit_map_fig, dpi = 1000)\n",
    "    plt.savefig(det, dpi = 1000)\n",
    "    plt.clf()\n",
    "    #plt.show()\n",
    "    \n",
    "    ft3pa.close\n",
    "    print('pocet udalosti: '+str(pocet_udalosti))\n",
    "    #print(len(index))\n",
    "    return #matrix_index, pocet_udalosti\n",
    "\n",
    "\n",
    "#soubory, ktere ctu:\n",
    "t3pa, DetName =get_file(shot, detector)\n",
    "\n",
    "#vytvorene soubory:\n",
    "#hit_map_hist='F10-W0049_shot_'+str(shot)+'_-450V.txt'\n",
    "hit_map_fig='icon-fig'\n",
    "#hit_map_fig='RasPi4-c.png'\n",
    "\n",
    "load_t3pa_file(t3pa, hit_map_fig, DetName)"
   ]
  }
 ],
 "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.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}