{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "014e630c-5b70-498f-9f48-3fcaa63f51a0",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "ndims = 2\n",
    "k     = 100 \n",
    "\n",
    "with open(\"bb/nodes_50_blobs_more_var.csv\",\"r\") as f:\n",
    "    l = f.readlines() \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "04e0adb2-fce6-460e-8d9a-08d76a0bbead",
   "metadata": {},
   "outputs": [],
   "source": [
    "def parse_lines(l,n_dims):\n",
    "    ll = [line.split(\",\") for line in l]\n",
    "    level = np.array([ int(line[0]) for line in ll])\n",
    "    owner = np.array([ int(line[1]) for line in ll])\n",
    "    split_dim = np.array([ int(line[2]) for line in ll])\n",
    "    split_val = np.array([ float(line[3]) for line in ll])\n",
    "    box_lb = np.array([ [float(el) for el in line[4:(4+n_dims)]] for line in ll])\n",
    "    box_ub = np.array([ [float(el) for el in line[4 + n_dims:]] for line in ll])\n",
    "    return level, owner, split_dim, split_val, box_lb, box_ub"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3f28b2db-7724-4910-b354-2dfcc2b87b3a",
   "metadata": {},
   "outputs": [],
   "source": [
    " level, owner, split_dim, split_val, box_lb, box_ub = parse_lines(l,ndims)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "06da7c7c-672a-40de-ac59-1705bf746dfe",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['0',\n",
       " '-1',\n",
       " '0',\n",
       " '0.433956',\n",
       " '-10.833138',\n",
       " '-11.093356',\n",
       " '10.950541',\n",
       " '10.208630\\n']"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "l[0].split(\",\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "7b4f2721-d1cc-48e0-b166-51bb6ea7f3c2",
   "metadata": {},
   "outputs": [],
   "source": [
    "#x = np.fromfile(\"../../robavaria/50_blobs_more_var.npy\", np.float32)\n",
    "x = np.fromfile(\"./bb/ordered_data.npy\", np.float64)\n",
    "x = x.reshape((x.shape[0]//ndims,ndims))\n",
    "#x = x[:2500]\n",
    "#plt.scatter(x[:,0],x[:,1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c9bfa54e-ec8c-4926-a40f-6d15ea55bb51",
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_boxes(x,d0,d1,owner, split_dim, split_val, box_lb, box_ub, ratio = 0.7):\n",
    "    from matplotlib.patches import Rectangle\n",
    "    fig, ax = plt.subplots(figsize = (12 * ratio,10 * ratio))\n",
    "    ax.scatter(x[:,d0],x[:,d1], s = 0.1)\n",
    "    procs = np.where(owner != -1)\n",
    "    for p in procs[0]:\n",
    "        lbx = box_lb[p,d0]\n",
    "        ubx = box_ub[p,d0]\n",
    "        lby = box_lb[p,d1]\n",
    "        uby = box_ub[p,d1]\n",
    "        bw  = ubx - lbx\n",
    "        bh  = uby - lby\n",
    "        col = (np.random.rand(),np.random.rand(),np.random.rand(),0.5)\n",
    "        ax.add_patch(Rectangle((lbx,lby),bw,bh, facecolor = col, label = owner[p]))\n",
    "    plt.legend(loc = \"lower left\")\n",
    "        #ax.add_patch(Rectangle((lbx,lby),2,2, facecolor = (np.random.rand(),np.random.rand(),np.random.rand(),0.3)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c9d51bc6-48e4-494f-8cbf-c50972b49a2b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 172012 characters]",
      "text/plain": [
       "<Figure size 840x700 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plot_boxes(x,0,1,owner,split_dim,split_val,box_lb,box_ub)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3ab30d54-e4b4-4215-9669-16bebd1ebf7a",
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_planes(x,d0,d1,owner, split_dim, split_val, box_lb, box_ub, ratio=0.7):\n",
    "    from matplotlib.patches import Rectangle\n",
    "    fig, ax = plt.subplots(figsize = (12 * ratio,10 * ratio))\n",
    "    ax.scatter(x[:,d0],x[:,d1], s = 0.1)\n",
    "    procs = np.where(owner == -1)[0]\n",
    "    for p in procs:\n",
    "        if split_dim[p] == d0:\n",
    "            line_bounds = [box_lb[p,d1],box_ub[p,d1]]\n",
    "            line_coord  = split_val[p] \n",
    "            #print(\"vline\",split_dim[p],split_dim[p], line_bounds, line_coord)\n",
    "            plt.vlines(line_coord, line_bounds[0], line_bounds[1], color = \"y\")\n",
    "        elif split_dim[p] == d1:\n",
    "            line_bounds = [box_lb[p,d0],box_ub[p,d0]]\n",
    "            line_coord  = split_val[p] \n",
    "            #print(\"hline\",split_dim[p],split_dim[p], line_bounds, line_coord)\n",
    "            plt.hlines(line_coord, line_bounds[0], box_ub[p,d0], color = \"y\")\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "b0fca2ef-a2f3-42c9-af04-bea56a4138ae",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 181988 characters]",
      "text/plain": [
       "<Figure size 840x700 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plot_planes(x,0,1,owner,split_dim,split_val,box_lb,box_ub)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "1ac6d1bd-98fe-4ee5-b553-50b30d056a4c",
   "metadata": {},
   "outputs": [],
   "source": [
    "ngbh = []\n",
    "p = 12\n",
    "for pp in range(p):\n",
    "    ngbh.append(np.fromfile(f\"./bb/rank_{pp}.ngbh\", dtype = [(\"value\",\"f8\"),(\"array_idx\",\"u8\")]))\n",
    "ngbh = np.concatenate(ngbh)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "9a87f1a8-aef1-47a6-addb-c9e42e381fc2",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.neighbors import NearestNeighbors\n",
    "nn = NearestNeighbors(n_jobs=-1,n_neighbors=k)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "e33788e7-9ae8-41d6-b597-3ee84ef27018",
   "metadata": {},
   "outputs": [],
   "source": [
    "nn.fit(x)\n",
    "dist, idx = nn.kneighbors(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "38520a52-d4b0-449d-8170-63b748209c3a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([5.06114932e-05, 5.66400017e-05])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(dist[83812]**2)[5:7]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "f2f1d9eb-dc83-4d24-9ab5-f086b615c591",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([54790, 50627])"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "(idx[83812])[5:7]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "bb0b7e8e-58a6-47b1-8118-e5368edd7297",
   "metadata": {},
   "outputs": [],
   "source": [
    "idx_c = ngbh[\"array_idx\"]\n",
    "idx_c.shape\n",
    "dist_c = ngbh[\"value\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "89795bef-a6a7-4c13-b880-3eaa11159141",
   "metadata": {},
   "outputs": [],
   "source": [
    "idx_c = idx_c.reshape((len(idx_c)//k,k))\n",
    "dist_c = dist_c.reshape((len(dist_c)//k,k))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "0a37296e-40a6-4780-9319-baf2c0744a61",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "for i in range(len(idx_c)):\n",
    "    r1 = idx[i]\n",
    "    r2 = idx_c[i]\n",
    "    w = np.where(r1 != r2)\n",
    "    if len(w[0]) > 0:\n",
    "        d1 = dist[i,w[0][0]]\n",
    "        d2 = dist[i,w[0][1]]\n",
    "        #print(i, w[0])\n",
    "        if not np.isclose(d1,d2):\n",
    "            print(i, w[0], d1, d2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5c2ce3b5-d205-44ea-958f-d606975ec747",
   "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.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
