{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(1, {}), (2, {}), (3, {})]\n",
      "[(1, 2, {}), (2, 1, {}), (3, 1, {})]\n",
      "{2: {}}\n"
     ]
    }
   ],
   "source": [
    "import networkx as nx\n",
    "dg = nx.DiGraph()\n",
    "dg.add_nodes_from([1, 2, 3])\n",
    "dg.add_edges_from([(1, 2), (2, 1), (3, 1)])\n",
    "print(dg.nodes(data=True))\n",
    "print(dg.edges(data=True))\n",
    "print(dg[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import networkx as nx"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def loadCT(filename):\n",
    "    content = open(filename).read().splitlines()\n",
    "    G = nx.Graph(name=str(content[0]))\n",
    "    tmp = content[1].split(\" \")\n",
    "    if tmp[0] == '':\n",
    "        nb_nodes = int(tmp[1])\n",
    "        nb_edges = int(tmp[2])\n",
    "    else:\n",
    "        nb_nodes = int(tmp[0])\n",
    "        nb_edges = int(tmp[1])\n",
    "\n",
    "    for i in range(0, nb_nodes):\n",
    "        tmp = content[i + 2].split(\" \")\n",
    "        tmp = [x for x in tmp if x != '']\n",
    "        G.add_node(i, label=tmp[3])\n",
    "\n",
    "    for i in range(0, nb_edges):\n",
    "        tmp = content[i+G.number_of_nodes()+2].split(\" \")\n",
    "        tmp = [x for x in tmp if x != '']\n",
    "        G.add_edge(int(tmp[0]) - 1, int(tmp[1]) - 1, label=int(tmp[3]))\n",
    "    return G\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def loadDataset(filename):\n",
    "    from os.path import dirname, splitext\n",
    "\n",
    "    dirname_dataset = dirname(filename)\n",
    "    extension = splitext(filename)[1][1:]\n",
    "    data = []\n",
    "    y = []\n",
    "    if(extension == \"ds\"):\n",
    "        content = open(filename).read().splitlines()\n",
    "        for i in range(0, len(content)):\n",
    "            tmp = content[i].split(' ')\n",
    "            data.append(loadCT(dirname_dataset + '/' + tmp[0].replace('#', '', 1)))\n",
    "            y.append(float(tmp[1]))\n",
    "    elif(extension == \"cxl\"):\n",
    "        import xml.etree.ElementTree as ET\n",
    "\n",
    "        tree = ET.parse(filename)\n",
    "        root = tree.getroot()\n",
    "        data = []\n",
    "        y = []\n",
    "        for graph in root.iter('print'):\n",
    "            mol_filename = graph.attrib['file']\n",
    "            mol_class = graph.attrib['class']\n",
    "            data.append(loadGXL(dirname_dataset + '/' + mol_filename))\n",
    "            y.append(mol_class)\n",
    "\n",
    "    return data, y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset, y = loadDataset(\"../../datasets/acyclic/dataset_bps.ds\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "import networkx as nx\n",
    "import numpy as np\n",
    "\n",
    "\n",
    "def getSPLengths(G1):\n",
    "    sp = nx.shortest_path(G1)\n",
    "    distances = np.zeros((G1.number_of_nodes(), G1.number_of_nodes()))\n",
    "    for i in np.keys():\n",
    "        for j in np[i].keys():\n",
    "            distances[i, j] = len(sp[i][j])-1\n",
    "\n",
    "def getSPGraph(G):\n",
    "    \"\"\"Transform graph G to its corresponding shortest-paths graph.\n",
    "    \n",
    "    Parameters\n",
    "    ----------\n",
    "    G : NetworkX graph\n",
    "        The graph to be tramsformed.\n",
    "        \n",
    "    Return\n",
    "    ------\n",
    "    S : NetworkX graph\n",
    "        The shortest-paths graph corresponding to G.\n",
    "        \n",
    "    Notes\n",
    "    ------\n",
    "    For an input graph G, its corresponding shortest-paths graph S contains the same set of nodes as G, while there exists an edge between all nodes in S which are connected by a walk in G. Every edge in S between two nodes is labeled by the shortest distance between these two nodes.\n",
    "    \n",
    "    References\n",
    "    ----------\n",
    "    [1] Borgwardt KM, Kriegel HP. Shortest-path kernels on graphs. InData Mining, Fifth IEEE International Conference on 2005 Nov 27 (pp. 8-pp). IEEE.\n",
    "    \"\"\"\n",
    "    return floydTransformation(G)\n",
    "            \n",
    "def floydTransformation(G):\n",
    "    \"\"\"Transform graph G to its corresponding shortest-paths graph using Floyd-transformation.\n",
    "    \n",
    "    Parameters\n",
    "    ----------\n",
    "    G : NetworkX graph\n",
    "        The graph to be tramsformed.\n",
    "        \n",
    "    Return\n",
    "    ------\n",
    "    S : NetworkX graph\n",
    "        The shortest-paths graph corresponding to G.\n",
    "        \n",
    "    References\n",
    "    ----------\n",
    "    [1] Borgwardt KM, Kriegel HP. Shortest-path kernels on graphs. InData Mining, Fifth IEEE International Conference on 2005 Nov 27 (pp. 8-pp). IEEE.\n",
    "    \"\"\"\n",
    "    spMatrix = nx.floyd_warshall_numpy(G) # @todo weigth label not considered\n",
    "    S = nx.Graph()\n",
    "    S.add_nodes_from(G)\n",
    "    for i in range(0, G.number_of_nodes()):\n",
    "        for j in range(0, G.number_of_nodes()):\n",
    "            print(spMatrix[i, j])\n",
    "            S.add_edge(i, j, cost = spMatrix[i, j])\n",
    "    return S"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0. 2. 3. 1. 2.]]\n",
      "{0: {0: [0], 3: [0, 3], 1: [0, 3, 1], 4: [0, 3, 4], 2: [0, 3, 4, 2]}, 1: {1: [1], 3: [1, 3], 0: [1, 3, 0], 4: [1, 3, 4], 2: [1, 3, 4, 2]}, 2: {2: [2], 4: [2, 4], 3: [2, 4, 3], 0: [2, 4, 3, 0], 1: [2, 4, 3, 1]}, 3: {3: [3], 0: [3, 0], 1: [3, 1], 4: [3, 4], 2: [3, 4, 2]}, 4: {4: [4], 2: [4, 2], 3: [4, 3], 0: [4, 3, 0], 1: [4, 3, 1]}}\n",
      "[[0. 2. 3. 1. 2.]\n",
      " [2. 0. 3. 1. 2.]\n",
      " [3. 3. 0. 2. 1.]\n",
      " [1. 1. 2. 0. 1.]\n",
      " [2. 2. 1. 1. 0.]]\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 14660 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.0\n",
      "2.0\n",
      "3.0\n",
      "1.0\n",
      "2.0\n",
      "2.0\n",
      "0.0\n",
      "3.0\n",
      "1.0\n",
      "2.0\n",
      "3.0\n",
      "3.0\n",
      "0.0\n",
      "2.0\n",
      "1.0\n",
      "1.0\n",
      "1.0\n",
      "2.0\n",
      "0.0\n",
      "1.0\n",
      "2.0\n",
      "2.0\n",
      "1.0\n",
      "1.0\n",
      "0.0\n",
      "{(0, 0): 0.0, (0, 1): 2.0, (0, 2): 3.0, (0, 3): 1.0, (0, 4): 2.0, (1, 1): 0.0, (1, 2): 3.0, (1, 3): 1.0, (1, 4): 2.0, (2, 2): 0.0, (2, 3): 2.0, (2, 4): 1.0, (3, 3): 0.0, (3, 4): 1.0, (4, 4): 0.0}\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 37236 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "dataset, y = loadDataset(\"../../datasets/acyclic/dataset_bps.ds\")\n",
    "G1 = dataset[12]\n",
    "\n",
    "nx.draw_networkx(G1)\n",
    "# print(list(dataset[12][4]))\n",
    "\n",
    "l = nx.shortest_path(G1)\n",
    "\n",
    "l2 = nx.floyd_warshall_numpy(G1)\n",
    "print(np.array(l2[0]))\n",
    "print(l)\n",
    "print(l2)\n",
    "from matplotlib import pyplot as plt\n",
    "plt.show()\n",
    "\n",
    "S = getSPGraph(G1)\n",
    "nx.draw_networkx(S)\n",
    "pos = nx.spring_layout(S)\n",
    "edge_labels = nx.get_edge_attributes(S,'cost')\n",
    "print(edge_labels)\n",
    "nx.draw_networkx_edge_labels(S, pos, edge_labels = edge_labels)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 11344 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 15904 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "G = dataset[155]\n",
    "G.clear()\n",
    "G.add_edges_from([(1, 2), (1, 3)])\n",
    "G.add_node(1)\n",
    "G.add_edge(1, 2)\n",
    "G.add_node(\"spam\")        # adds node \"spam\"\n",
    "G.add_nodes_from(\"spam\")  # adds 4 nodes: 's', 'p', 'a', 'm'\n",
    "G.add_edge(3, 'm')\n",
    "nx.draw_networkx(G)\n",
    "plt.show()\n",
    "\n",
    "K_5 = nx.random_lobster(30, 0.9, 0.9)\n",
    "nx.draw_networkx(K_5)\n",
    "plt.show()\n",
    "G.number_of_nodes()\n",
    "G.number_of_edges()"
   ]
  }
 ],
 "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.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
