{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim\n",
    "import sparseconvnet as scn\n",
    "import uproot\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "from model import DeepVtx\n",
    "\n",
    "from timeit import default_timer as timer\n",
    "import csv\n",
    "import util\n",
    "\n",
    "# Use the GPU if there is one and sparseconvnet can use it, otherwise CPU\n",
    "# use_cuda = torch.cuda.is_available() and scn.SCN.is_cuda_build()\n",
    "use_cuda = False\n",
    "torch.set_num_threads(1)\n",
    "\n",
    "device = 'cuda:0' if use_cuda else 'cpu'\n",
    "if use_cuda:\n",
    "    print(\"Using CUDA.\")\n",
    "else:\n",
    "    print(\"Using CPU.\")\n",
    "\n",
    "nIn = 1\n",
    "model = DeepVtx(dimension=3, nIn=nIn, device=device)\n",
    "model.train()\n",
    "\n",
    "model_path = 't48k/m16-l5-lr5d-res0.5/CP24.pth'\n",
    "model.load_state_dict(torch.load(model_path))\n",
    "\n",
    "start_sample = 0\n",
    "max_sample = 1000 + start_sample\n",
    "resolution = 0.5\n",
    "loose_cut = 1.0\n",
    "val_list = 'list/numucc-24k-val.csv'\n",
    "results = []\n",
    "start = timer()\n",
    "with open(val_list) as f:\n",
    "    reader = csv.reader(f, delimiter=' ')\n",
    "    isample = 0\n",
    "    stat = {}\n",
    "    for row in reader:\n",
    "        isample = isample + 1\n",
    "        if isample < start_sample :\n",
    "            continue\n",
    "        if isample > max_sample :\n",
    "            break\n",
    "        print('isample: {} : {}'.format(isample,row[0]))\n",
    "        \n",
    "        coords_np, ft_np = util.load(row, vis=False, resolution=resolution)\n",
    "        coords = torch.LongTensor(coords_np)\n",
    "        truth = torch.FloatTensor(ft_np[:,-1]).to(device)\n",
    "        ft = torch.FloatTensor(ft_np[:,0:-1]).to(device)\n",
    "        prediction = model([coords,ft[:,0:1]])\n",
    "        \n",
    "        pred_np = prediction.cpu().detach().numpy()\n",
    "        pred_np = pred_np[:,1] - pred_np[:,0]\n",
    "        truth_np = truth.cpu().detach().numpy()\n",
    "        \n",
    "        # prediction and vis\n",
    "        result = util.vis_prediction_regseg(\n",
    "            np.column_stack((coords_np, pred_np)),\n",
    "            np.column_stack((coords_np, truth_np)),\n",
    "            vis=True\n",
    "            )\n",
    "        results.append(result)\n",
    "\n",
    "end = timer()\n",
    "print('time: {0:.1f} ms'.format((end-start)/1*1000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib tk\n",
    "fontsize = 24\n",
    "loose_cut = 1.0\n",
    "results = np.array(results)\n",
    "fig = plt.figure(0)\n",
    "ax = fig.add_subplot(111)\n",
    "ax.hist(results[results[:,1]<=loose_cut, 0], 100, range=(0,1), density=True, histtype='step', linewidth=2, cumulative=True, label='<1cm')\n",
    "ax.hist(results[results[:,1]>loose_cut, 0], 100, range=(0,1), density=True, histtype='step', linewidth=2, cumulative=True, label='>1cm')\n",
    "ax.hist(results[results[:,1]<=2, 0], 100, range=(0,1), density=True, histtype='step', linewidth=2, cumulative=True, label='<2cm')\n",
    "ax.hist(results[results[:,1]<=10, 0], 100, range=(0,1), density=True, histtype='step', linewidth=2, cumulative=True, label='<10cm')\n",
    "plt.grid()\n",
    "plt.legend(loc='upper left', fontsize=fontsize)\n",
    "plt.xlabel('DNN Prob.', fontsize=fontsize)\n",
    "plt.ylabel('CDF', fontsize=fontsize)\n",
    "plt.xticks(fontsize=fontsize)\n",
    "plt.yticks(fontsize=fontsize)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.count_nonzero(results[:,1]>loose_cut)"
   ]
  },
  {
   "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.6.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
