├── .gitignore ├── images ├── edge_diff_0.png ├── node_diff_0.png ├── edge_diff_20.png └── node_diff_20.png ├── __pycache__ ├── molecules.cpython-35.pyc └── plotting.cpython-35.pyc ├── .idea ├── workspace.xml ├── misc.xml ├── inspectionProfiles │ └── profiles_settings.xml ├── modules.xml └── shape-of-molecules.iml ├── plotting.py ├── molecules.py ├── README.md ├── HIV-inhibitors.ipynb ├── .ipynb_checkpoints └── HIV-checkpoint.ipynb └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.pickle 2 | .idea 3 | *.arff 4 | -------------------------------------------------------------------------------- /images/edge_diff_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giotto-ai/the-shape-of-chemical-functions/master/images/edge_diff_0.png -------------------------------------------------------------------------------- /images/node_diff_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giotto-ai/the-shape-of-chemical-functions/master/images/node_diff_0.png -------------------------------------------------------------------------------- /images/edge_diff_20.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giotto-ai/the-shape-of-chemical-functions/master/images/edge_diff_20.png -------------------------------------------------------------------------------- /images/node_diff_20.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giotto-ai/the-shape-of-chemical-functions/master/images/node_diff_20.png -------------------------------------------------------------------------------- /__pycache__/molecules.cpython-35.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giotto-ai/the-shape-of-chemical-functions/master/__pycache__/molecules.cpython-35.pyc -------------------------------------------------------------------------------- /__pycache__/plotting.cpython-35.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giotto-ai/the-shape-of-chemical-functions/master/__pycache__/plotting.cpython-35.pyc -------------------------------------------------------------------------------- /.idea/workspace.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/shape-of-molecules.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /plotting.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import numpy as np 5 | import matplotlib.pyplot as plt 6 | import networkx as nx 7 | 8 | 9 | def plot_entropies(entropies, s_list): 10 | 11 | """ 12 | Utility function to plot entropies as a function of time steps 13 | """ 14 | 15 | colors = ['blue', 'red', 'black', 'yellow', 'orange', 'green', 'grey', 16 | 'brown'] 17 | 18 | for i in s_list: 19 | # plot entropies Vs temporal indexes 20 | hs1 = entropies[i] 21 | _ = plt.plot(hs1, label="clique " + str(i), color=colors[i % len(colors)]) 22 | 23 | plt.xticks() 24 | plt.title('Entropy profiles of different cliques') 25 | plt.legend() 26 | 27 | return 28 | 29 | 30 | def plot_network_diffusion(G, pos, node_vector=None, edge_vector=None, 31 | node_labels=False, edge_labels=False): 32 | 33 | # Find edge labels 34 | l_e = list(G.edges) 35 | e = dict((tuple(sorted(l_e[x])), x) for x in range(0, len(l_e))) 36 | e_labels = {tuple(x): 'e' + str(y) for x, y in e.items()} 37 | 38 | if edge_vector is not None: 39 | colors_edge = np.squeeze(np.asarray(edge_vector)) 40 | _ = nx.draw_networkx_edges(G, pos, edge_color=colors_edge, 41 | width=3, with_labels=False) 42 | else: 43 | _ = nx.draw_networkx_edges(G, pos, edge_color="gray", 44 | width=2, with_labels=False) 45 | 46 | if node_vector is not None: 47 | colors_node = np.squeeze(np.asarray(node_vector)) 48 | _ = nx.draw_networkx_nodes(G, pos, node_color=colors_node, 49 | with_labels=False, node_size=500) 50 | else: 51 | _ = nx.draw_networkx_nodes(G, pos, node_color="blue", 52 | with_labels=False, node_size=500) 53 | 54 | if edge_labels: 55 | _ = nx.draw_networkx_edge_labels(G, pos, e_labels, alpha=1) 56 | if node_labels: 57 | _ = nx.draw_networkx_labels(G, pos) 58 | 59 | return 60 | -------------------------------------------------------------------------------- /molecules.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import networkx as nx 3 | from giotto.graphs.create_clique_complex import CreateLaplacianMatrices, \ 4 | CreateCliqueComplex 5 | from giotto.graphs.heat_diffusion import HeatDiffusion 6 | from giotto.graphs.graph_entropy import GraphEntropy 7 | 8 | 9 | def mol_to_nx(mol): 10 | g = nx.Graph() 11 | for atom in mol.GetAtoms(): 12 | g.add_node(atom.GetIdx(), 13 | atomic_num=atom.GetAtomicNum(), 14 | formal_charge=atom.GetFormalCharge(), 15 | chiral_tag=atom.GetChiralTag(), 16 | hybridization=atom.GetHybridization(), 17 | num_explicit_hs=atom.GetNumExplicitHs(), 18 | is_aromatic=atom.GetIsAromatic()) 19 | for bond in mol.GetBonds(): 20 | g.add_edge(bond.GetBeginAtomIdx(), 21 | bond.GetEndAtomIdx(), 22 | bond_type=bond.GetBondType()) 23 | return g 24 | 25 | 26 | def compute_node_edge_entropy(g, i, taus_n, taus_e): 27 | cd = CreateCliqueComplex(graph=g).create_complex_from_graph() 28 | lap = CreateLaplacianMatrices().fit_transform(cd, (0, 1)) 29 | n_diff = HeatDiffusion().fit_transform(lap[0], taus_n) 30 | e_diff = HeatDiffusion().fit_transform(lap[1], taus_e) 31 | mh_n = GraphEntropy().fit_transform(n_diff).T 32 | mh_e = GraphEntropy().fit_transform(e_diff).T 33 | 34 | if i % 10000 == 0: 35 | print("Atoms and Bonds of {} molecules have been embedded...". 36 | format(i)) 37 | 38 | return [mh_n, mh_e] 39 | 40 | 41 | def bonds_type_to_edge(g_mol): 42 | for i, g in enumerate(g_mol): 43 | d_e = dict() 44 | for e in g.edges(): 45 | b = int(g.get_edge_data(e[0], e[1])['bond_type']) 46 | d_e[e] = np.zeros(4) 47 | if b == 12: 48 | d_e[e][3] = 1 49 | else: 50 | d_e[e][b-1] = 1 51 | nx.set_edge_attributes(g, name='bonds_one_hot', values=d_e) 52 | 53 | 54 | def bonds_type(g_mol): 55 | for g in g_mol: 56 | d_n = dict() 57 | for n in g.nodes(): 58 | d_n[n] = np.zeros(4) 59 | 60 | for i in g.neighbors(n): 61 | # encoding type 62 | edge_type = int(g.get_edge_data(n, i)['bond_type']) 63 | if edge_type == 12: 64 | d_n[n][3] += 1 65 | else: 66 | d_n[n][edge_type - 1] += 1 67 | nx.set_node_attributes(g, name='bonds_one_hot', values=d_n) 68 | 69 | 70 | def graph_to_points(g_mol, n): 71 | j = 0 72 | d = list() 73 | for i in range(len(g_mol)): 74 | if n == 0: 75 | d.append(np.arange(j, j + g_mol[i].number_of_nodes())) 76 | j += g_mol[i].number_of_nodes() 77 | else: 78 | d.append(np.arange(j, j + g_mol[i].number_of_edges())) 79 | j += g_mol[i].number_of_edges() 80 | 81 | return d 82 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![logo](https://raw.githubusercontent.com/giotto-ai/giotto-tda/master/doc/images/tda_logo.svg) 2 | 3 | # The-shape-of-chemical-functions 4 | The application of Machine Learning for biological data is one of the 5 | most promising and fascinating research direction of AI. In this notebook 6 | we want to give a baseline indication to show how topological data analysis 7 | tools can be exploited to analyze molecules. More importantly, we show empirically 8 | that shapes matter, in the sense that it is possible to match properties of objects with 9 | their shapes. 10 | 11 | The task of this use case is to classify molecules with respect to their 12 | inhibition property for the HIV virus. In order to achieve it, we propose a method 13 | to embed molecules into points of an Euclidean Space and so to represent chemical 14 | compounds with vectors. The method, which is based on TDA concepts, represents the 15 | most important part of the pipeline by learning meaningful features of molecules. Once 16 | the vector representation are obtained, they are used as input for a calssificator function 17 | which is parametrized by a simple 2-hidden-layers nerual network. 18 | 19 | Have a lok at out [blog post](https://towardsdatascience.com/the-shape-of-chemical-functions-d1e1568d020) 20 | to learn more. 21 | 22 | ## Data 23 | The HIV dataset was introduced by the Drug 24 | Therapeutics Program (DTP) AIDS Antiviral Screen, which 25 | tested the ability to inhibit HIV replication for over 40 000 26 | compounds. In the original dataset the chemical compounds were classified 27 | into 3 different classes: confirmed inactive (CI), confirmed active (CA) 28 | and confirmed moderately active (CM). As done in this [paper](https://pubs.rsc.org/en/content/articlehtml/2018/sc/c7sc02664a), 29 | the two classes CA and CM were grouped into one single class "Active". 30 | 31 | ## Feature Creation 32 | The innovative part of using TDA in this classification problem consists in finding meaningful structural features for molecules. The idea is to embed molecules into an Euclidean Space where the Euclidean distance reflects the notion of structural dissimilarity. 33 | 34 | In 35 | 36 | 37 | ## Model 38 | We cross-validated a fully connected neural network with 2 hidden layers: the hidden neurons present a ReLu activation function whereas the single output neuron has a sigmoid activation which represent the probability for an input molecule to be a HIV-inhibitor. 39 | 40 | ## Results 41 | Our results show that the structural features found contain good quality informations on the inhibition property for the HIV viruses providing AUC-ROC scores comparable with the state-of-the-art solutions reported [here](https://pubs.rsc.org/en/content/articlehtml/2018/sc/c7sc02664a). 42 | 43 | ## Notebook overview 44 | In this notebook we want to show how structural features can be inferred by using topological tools. In particolar, we provide atoms and bonds embedding for each molecules and, following the pipeline, we show that the classification procedure goes to very good results. Moreover, we let the user play with the hyperparameters and classificator model to see if other interesting results appear. 45 | 46 | 47 | ## Requirements 48 | In order to run the notebook, the following python packages are required: 49 | 50 | - scikit-learn 0.21.3 51 | - numpy 1.14.0 52 | - networkx 2.4 53 | - giotto-learn-nightly 54 | - rdkit 2018.03.4.0 55 | - deepchem 2.2.1.dev54 56 | - keras 2.3.1 57 | - pandas 0.25.2 58 | 59 | To install rdkit and deepchem with conda: 60 | 61 | 62 | conda install -c deepchem -c rdkit 63 | 64 | 65 | -------------------------------------------------------------------------------- /HIV-inhibitors.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Shape of Molecules #\n", 8 | "\n", 9 | "In this notebook we provide an innovative pipeline that makes it possible to find interesting and meaningful structural features for chiemical compounds by exploiting the package $\\href{https://giotto.ai/}{giotto learn}$. The task of this notebook is to classify chemical compunds as HIV inhibitors or non-inhibitors for the HIV virus. The problem is a benchmark for molecules graph representation as stated in this $\\href{https://pubs.rsc.org/en/content/articlehtml/2018/sc/c7sc02664a}{paper}$. The novel idea of this notebook is that of exploiting heat diffusion defined over any-order graph cliques (here nodes and edges) to embed the entire graph. In order to defined such diffusion processes we use the definition of higher-order laplcians matrices of clique complexes (special case of simplicial complexes).\n", 10 | "\n", 11 | "### Example of heat diffusion over nodes sampled at two different points ###\n", 12 | "\n", 13 | "\n", 14 | " \"Drawing\" \n", 15 | " \"Drawing\" \n", 16 | "\n", 17 | "\n", 18 | "### Example of heat diffusion over edges sampled at two different points ###\n", 19 | "\n", 20 | "\n", 21 | " \"Drawing\" \n", 22 | " \"Drawing\" \n", 23 | "" 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": null, 29 | "metadata": {}, 30 | "outputs": [], 31 | "source": [ 32 | "#Import statements\n", 33 | "import warnings; warnings.simplefilter('ignore')\n", 34 | "import random \n", 35 | "\n", 36 | "\n", 37 | "import numpy as np\n", 38 | "import networkx as nx\n", 39 | "import pandas as pd\n", 40 | "import matplotlib.pyplot as plt\n", 41 | "\n", 42 | "from sklearn.cluster import KMeans\n", 43 | "\n", 44 | "from giotto.graphs.create_clique_complex import CreateCliqueComplex, CreateBoundaryMatrices, CreateLaplacianMatrices \n", 45 | "from giotto.graphs.heat_diffusion import HeatDiffusion\n", 46 | "from giotto.graphs.graph_entropy import GraphEntropy\n", 47 | "\n", 48 | "from molecules import mol_to_nx, compute_node_edge_entropy, bonds_type, graph_to_points, bonds_type_to_edge\n", 49 | "from plotting import plot_entropies, plot_network_diffusion\n", 50 | "\n", 51 | "from rdkit import Chem \n", 52 | "from rdkit.Chem import Draw\n" 53 | ] 54 | }, 55 | { 56 | "cell_type": "markdown", 57 | "metadata": {}, 58 | "source": [ 59 | "## Import and Convert data to networkx Graph ##" 60 | ] 61 | }, 62 | { 63 | "cell_type": "markdown", 64 | "metadata": {}, 65 | "source": [ 66 | "Import molecules dataset and convert them: $\\textit{smiles}$ --> $\\textit{rdkit.Chem.rdchem.Mol}$ --> $\\textit{networkx.graph}$." 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": null, 72 | "metadata": {}, 73 | "outputs": [], 74 | "source": [ 75 | "#Import and convert data\n", 76 | "df = pd.read_csv('hiv.csv')\n", 77 | "df['g_mol'] = df['smiles'].apply(lambda x: Chem.MolFromSmiles(x))\n", 78 | "df.drop(\"smiles\", axis=1, inplace=True)\n", 79 | "g_mol = [mol_to_nx(df['g_mol'][i]) for i in range(df.shape[0]) if i != 559 and i!= 8097 ]" 80 | ] 81 | }, 82 | { 83 | "cell_type": "markdown", 84 | "metadata": {}, 85 | "source": [ 86 | "## Create Embeddings for all atoms and bonds in the dataset ##\n", 87 | "\n", 88 | "Here the embeddings for all atoms and bonds in the dataset are computed. The idea at the core of the procedure is that to embed a specific node (and so atom) $a_i$ , we study the heat diffusion process that has as initial condition a delta function with 1 on node $a_i$ and 0 otherwise. In order to characterize the diffusion process we sample it at different points in time, generating different snapshots. The values of the diffusion process at each snapshot is then treated as a probability distribution over the nodes of the graph (and so atoms of the molecule) and its entropy is computed. At the end, the embedding vector is populated with the entropy values computed over different points in time. In this step it is possible to tune two different hyperparameters: the number of points in time at which the heat diffusion has to be sampled and the last point instant. In this example the different samples are linearly spaced in time but of course it is possible to choose them differently. By exploiting the higher-order laplacians for clique complexes and the giotto-learn package it is possible to apply the same procedure to the edges of the graph and, in general, to higher order cliques. We then compute the same representation for each edge of all molecules, which represent bonds between two atoms. " 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "execution_count": null, 94 | "metadata": {}, 95 | "outputs": [], 96 | "source": [ 97 | "# Hyperparameters\n", 98 | "taus_n = np.linspace(0,2,20)\n", 99 | "taus_e = np.linspace(0,2,20)" 100 | ] 101 | }, 102 | { 103 | "cell_type": "markdown", 104 | "metadata": {}, 105 | "source": [ 106 | "Here the embeddings are computed. It is possible to save time and load them directly from $\\textit{openML}$ in the subsequent cell. " 107 | ] 108 | }, 109 | { 110 | "cell_type": "code", 111 | "execution_count": null, 112 | "metadata": {}, 113 | "outputs": [], 114 | "source": [ 115 | "# Embedding\n", 116 | "embeds = [compute_node_edge_entropy(x,i, taus_n, taus_e) for i,x in enumerate(g_mol) ]" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": null, 122 | "metadata": {}, 123 | "outputs": [], 124 | "source": [ 125 | "# Create list with node and edge embeddings\n", 126 | "universal_nodes = list()\n", 127 | "for i in range(len(embeds)):\n", 128 | " universal_nodes.extend(np.split(embeds[i][0][:,:].T, embeds[i][0][0,:].shape[0]))\n", 129 | "universal_nodes = np.squeeze(np.array(universal_nodes))\n", 130 | "\n", 131 | "universal_edges = list()\n", 132 | "for i in range(len(embeds)):\n", 133 | " universal_edges.extend(np.split(embeds[i][1][:,:].T, embeds[i][1][0,:].shape[0]))\n", 134 | "universal_edges = np.squeeze(np.array(universal_edges))\n", 135 | "\n" 136 | ] 137 | }, 138 | { 139 | "cell_type": "markdown", 140 | "metadata": {}, 141 | "source": [ 142 | "Once the embeddings have been found, this code can store them in .arff, the format adopted by $\\textit{openML}$." 143 | ] 144 | }, 145 | { 146 | "cell_type": "code", 147 | "execution_count": null, 148 | "metadata": {}, 149 | "outputs": [], 150 | "source": [ 151 | "# Save the new node embeddings as arff\n", 152 | "import arff\n", 153 | "\n", 154 | "dim_n = 30\n", 155 | "attributes_n = [('n{}'.format(e), 'REAL') for e in range(dim_n)]\n", 156 | " \n", 157 | "node_dict = {\n", 158 | " 'relation': 'Node_embedding_hiv',\n", 159 | " 'description': 'This dataset contains the embedding for all nodes of moelcules in HIV inhibitors dataset',\n", 160 | " 'attributes': attributes_n,\n", 161 | " 'data': universal_nodes.tolist()\n", 162 | "}\n", 163 | "\n", 164 | "_= arff.dump(node_dict, open(\"node_embedding_hiv.arff\", \"w+\"))" 165 | ] 166 | }, 167 | { 168 | "cell_type": "code", 169 | "execution_count": null, 170 | "metadata": {}, 171 | "outputs": [], 172 | "source": [ 173 | "# Save the new edge embeddings as arff\n", 174 | "import arff\n", 175 | "\n", 176 | "dim_e = 30\n", 177 | "attributes_e = [('e{}'.format(e), 'REAL') for e in range(dim_e)]\n", 178 | " \n", 179 | "edge_dict = {\n", 180 | " 'relation': 'Edge_embedding_hiv',\n", 181 | " 'description': 'This dataset contains the embedding for all edges of moelcules in HIV inhibitors dataset',\n", 182 | " 'attributes': attributes_e,\n", 183 | " 'data': universal_edges.tolist()\n", 184 | "}\n", 185 | "\n", 186 | "_ = arff.dump(edge_dict, open(\"edge_embedding_hiv.arff\", \"w+\"))" 187 | ] 188 | }, 189 | { 190 | "cell_type": "markdown", 191 | "metadata": {}, 192 | "source": [ 193 | "## Load Pre-Generated Embeddings ##\n", 194 | "\n", 195 | "Here the previously found embeddings can be loaded from the $\\textit{OpenML}$ site." 196 | ] 197 | }, 198 | { 199 | "cell_type": "code", 200 | "execution_count": null, 201 | "metadata": {}, 202 | "outputs": [], 203 | "source": [ 204 | "import arff\n", 205 | "import openml" 206 | ] 207 | }, 208 | { 209 | "cell_type": "code", 210 | "execution_count": null, 211 | "metadata": {}, 212 | "outputs": [], 213 | "source": [ 214 | "# Load nodes (atoms) embedding\n", 215 | "data_n = openml.datasets.get_dataset(42218)" 216 | ] 217 | }, 218 | { 219 | "cell_type": "code", 220 | "execution_count": null, 221 | "metadata": {}, 222 | "outputs": [], 223 | "source": [ 224 | "# Load edges (bonds) embedding\n", 225 | "data_e = openml.datasets.get_dataset(42220)" 226 | ] 227 | }, 228 | { 229 | "cell_type": "code", 230 | "execution_count": null, 231 | "metadata": {}, 232 | "outputs": [], 233 | "source": [ 234 | "universal_nodes = np.array(data_n.get_data()[0])\n", 235 | "universal_edges = np.array(data_e.get_data()[0])" 236 | ] 237 | }, 238 | { 239 | "cell_type": "code", 240 | "execution_count": null, 241 | "metadata": {}, 242 | "outputs": [], 243 | "source": [ 244 | "print(\"Check shape atoms dataset: {}\".format(universal_nodes.shape))\n", 245 | "print(\"Check shape edges dataset: {}\".format(universal_edges.shape))" 246 | ] 247 | }, 248 | { 249 | "cell_type": "markdown", 250 | "metadata": {}, 251 | "source": [ 252 | "## Plot Entropies Example ##" 253 | ] 254 | }, 255 | { 256 | "cell_type": "markdown", 257 | "metadata": {}, 258 | "source": [ 259 | "We can see now one example of heat diffuion's entropy profiles on nodes: first of all several entropy profiles are plotted for different nodes (0-cliques). We then plot the molecule graph in which each node has its label attached. It is possible to observe the local graphical structure and the related diffusion etropy profile. We can see how the heat diffusion entropy depends on the position and so on the role one node has within the network. For example, node 4 is a hub for the molecule and it can easily diffuse heat immediately. This effect is captured by the fact that entropy blows up in the first time samples. On the other hand, node 0 is almost isolated and again the slow spreading effect is captured by the almost flat entropy curve. " 260 | ] 261 | }, 262 | { 263 | "cell_type": "markdown", 264 | "metadata": {}, 265 | "source": [ 266 | "Double check that can be useful later to embed entire molecules." 267 | ] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "execution_count": null, 272 | "metadata": {}, 273 | "outputs": [], 274 | "source": [ 275 | "mol_to_atom = graph_to_points(g_mol, 0)\n", 276 | "mol_to_bonds = graph_to_points(g_mol, 1)" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": null, 282 | "metadata": {}, 283 | "outputs": [], 284 | "source": [ 285 | "# Node Analysis\n", 286 | "plt.figure(figsize=(20,6))\n", 287 | "\n", 288 | "plt.subplot(1, 2, 1)\n", 289 | "mol_id = 0\n", 290 | "node_ids = [0, 4, 7, 15]\n", 291 | "mol = g_mol[mol_id]\n", 292 | "\n", 293 | "entropies = [ universal_nodes[x] for x in mol_to_atom[mol_id] ]\n", 294 | "plot_entropies( entropies, node_ids)\n", 295 | "\n", 296 | "# Node Plotting\n", 297 | "plt.subplot(1, 2, 2)\n", 298 | "plot_network_diffusion(mol, pos=nx.spring_layout(mol, iterations=1000), node_labels=True)\n", 299 | "_ = plt.title('Molecule as networkx object')" 300 | ] 301 | }, 302 | { 303 | "cell_type": "markdown", 304 | "metadata": {}, 305 | "source": [ 306 | "# Adding Bonds information #\n", 307 | "\n", 308 | "We now add one piece of chemical information to the problem. The first two methods attach to each molecule graph the information about the type of chemical bonds. In particular, each edge is equipped with a one-hot-encoded vector representation with the number 1 in the position of the corresponding bond type: \n", 309 | "\n", 310 | "$0 --> single$\n", 311 | "\n", 312 | "$1 --> double$\n", 313 | "\n", 314 | "$2 --> triple$\n", 315 | "\n", 316 | "$3 --> aromatic$\n", 317 | "\n", 318 | "For nodes the vector is obtained by summing up all the one-hot-encoded vectors representing the incidence edges." 319 | ] 320 | }, 321 | { 322 | "cell_type": "code", 323 | "execution_count": null, 324 | "metadata": {}, 325 | "outputs": [], 326 | "source": [ 327 | "bonds_type(g_mol)\n", 328 | "bonds_type_to_edge(g_mol)\n", 329 | "\n", 330 | "#Create a list with all nodes \n", 331 | "freq_type_bonds = list()\n", 332 | "for g in g_mol:\n", 333 | " freq_type_bonds.extend(list(nx.get_node_attributes(g, 'bonds_one_hot').values()))\n", 334 | "\n", 335 | "# Create a list with all edges\n", 336 | "freq_type_bonds_edge = list()\n", 337 | "for g in g_mol:\n", 338 | " freq_type_bonds_edge.extend(list(nx.get_edge_attributes(g, 'bonds_one_hot').values()))\n", 339 | "\n", 340 | "# Check how many atoms and bonds \n", 341 | "freq_type_bonds = np.array(freq_type_bonds)\n", 342 | "freq_type_bonds_edge = np.array(freq_type_bonds_edge)\n", 343 | "print(\"Total number of atoms in the dataset: {}\".format(freq_type_bonds.shape[0]))\n", 344 | "print(\"Total number of bonds in the dataset: {}\".format(freq_type_bonds_edge.shape[0]))" 345 | ] 346 | }, 347 | { 348 | "cell_type": "markdown", 349 | "metadata": {}, 350 | "source": [ 351 | "# Universal Node + Bond Types Embeddding #" 352 | ] 353 | }, 354 | { 355 | "cell_type": "markdown", 356 | "metadata": {}, 357 | "source": [ 358 | "We split the molecule embedding list and create one big list with one extended entry per node contaning both the topological features taken from the entropy embedding and the chemical features related to the bond types." 359 | ] 360 | }, 361 | { 362 | "cell_type": "code", 363 | "execution_count": null, 364 | "metadata": {}, 365 | "outputs": [], 366 | "source": [ 367 | "uni_frq_nodes = [np.hstack([universal_nodes[x,:], freq_type_bonds[x,:]]) for x in range(universal_nodes.shape[0])]\n", 368 | "uni_frq_nodes = np.array(uni_frq_nodes)" 369 | ] 370 | }, 371 | { 372 | "cell_type": "markdown", 373 | "metadata": {}, 374 | "source": [ 375 | "We now cluster all molecules into $\\textit{n_clusters}$ different classes which is another hyperparamter of the pipeline. Moreover, centroids for all classes are stored. They'll be used later to generate the final embedding." 376 | ] 377 | }, 378 | { 379 | "cell_type": "code", 380 | "execution_count": null, 381 | "metadata": {}, 382 | "outputs": [], 383 | "source": [ 384 | "# Kmeans clustering\n", 385 | "n_clusters=10\n", 386 | "kmeans_n = KMeans(n_clusters)\n", 387 | "universal_class_nodes = kmeans_n.fit_transform(uni_frq_nodes)\n", 388 | " \n", 389 | "centroids_n = kmeans_n.cluster_centers_" 390 | ] 391 | }, 392 | { 393 | "cell_type": "markdown", 394 | "metadata": {}, 395 | "source": [ 396 | "We now popoulate, for each atom, a vector which contains the probability for that atom of belonging to the different $\\textit{n_clusters}$ classes. Once this is obtained, we generate the embedding for a molecule by taking the element-wise sum of the embeddings coming from all its atoms." 397 | ] 398 | }, 399 | { 400 | "cell_type": "code", 401 | "execution_count": null, 402 | "metadata": {}, 403 | "outputs": [], 404 | "source": [ 405 | "# Soft Encoded\n", 406 | "soft_encoded_node = [[ np.exp( - (np.linalg.norm(uni_frq_nodes[x]- centroids_n[c], 2) ** 2) / 2) for c in range(n_clusters)] for x in range(uni_frq_nodes.shape[0])]\n", 407 | "soft_encoded_node = np.array(soft_encoded_node)\n", 408 | "\n", 409 | "# Create node data for each graph\n", 410 | "x_data_node = [ np.sum([soft_encoded_node[n] for n in mol_to_atom[i]], axis=0) for i in range(len(g_mol))]\n", 411 | "x_data_node = np.array(x_data_node)\n", 412 | "print(\"Check shape of x_data_node: {}\".format(x_data_node.shape))" 413 | ] 414 | }, 415 | { 416 | "cell_type": "markdown", 417 | "metadata": {}, 418 | "source": [ 419 | "# Universal Edge + Bond Types Embeddding #" 420 | ] 421 | }, 422 | { 423 | "cell_type": "markdown", 424 | "metadata": {}, 425 | "source": [ 426 | "Exatcly the same procedure is applied to the edges of the dataset." 427 | ] 428 | }, 429 | { 430 | "cell_type": "code", 431 | "execution_count": null, 432 | "metadata": {}, 433 | "outputs": [], 434 | "source": [ 435 | "uni_frq_edges = [np.hstack([universal_edges[x,:], freq_type_bonds_edge[x,:]]) for x in range(universal_edges.shape[0])]\n", 436 | "uni_frq_edges = np.array(uni_frq_edges)" 437 | ] 438 | }, 439 | { 440 | "cell_type": "code", 441 | "execution_count": null, 442 | "metadata": {}, 443 | "outputs": [], 444 | "source": [ 445 | "# Kmeans clustering\n", 446 | "e_clusters = 10\n", 447 | "kmeans_e = KMeans(e_clusters)\n", 448 | "universal_class_edge = kmeans_e.fit_transform(uni_frq_edges)\n", 449 | "\n", 450 | "centroids_e = kmeans_e.cluster_centers_" 451 | ] 452 | }, 453 | { 454 | "cell_type": "code", 455 | "execution_count": null, 456 | "metadata": {}, 457 | "outputs": [], 458 | "source": [ 459 | "# Soft Encoded\n", 460 | "soft_encoded_edge = [[ np.exp( - (np.linalg.norm(uni_frq_edges[x]- centroids_e[c], 2) ** 2) / 2) for c in range(e_clusters)] for x in range(universal_edges.shape[0])]\n", 461 | "soft_encoded_edge = np.array(soft_encoded_edge)\n", 462 | "\n", 463 | "# Create edge data for each graph\n", 464 | "x_data_edge = [ np.sum([soft_encoded_edge[n] for n in mol_to_bonds[i]], axis=0) for i in range(len(g_mol))]\n", 465 | "x_data_edge = np.array(x_data_edge)\n", 466 | "print(\"Check shape of x_data_edge: {}\".format(x_data_edge.shape))" 467 | ] 468 | }, 469 | { 470 | "cell_type": "markdown", 471 | "metadata": {}, 472 | "source": [ 473 | "# Classification Model and Evaluation#" 474 | ] 475 | }, 476 | { 477 | "cell_type": "markdown", 478 | "metadata": {}, 479 | "source": [ 480 | "This part of the notebook contains the classificator model and training." 481 | ] 482 | }, 483 | { 484 | "cell_type": "code", 485 | "execution_count": null, 486 | "metadata": {}, 487 | "outputs": [], 488 | "source": [ 489 | "# Prepare x_data\n", 490 | "x_data = np.hstack([x_data_node, x_data_edge])\n", 491 | "x_data -= np.mean(x_data, axis=0)\n", 492 | "x_data /= (np.max(x_data, axis=0) - np.min(x_data, axis=0))\n", 493 | "\n", 494 | "print(\"Check shape of x_data: {}\".format(x_data.shape))\n", 495 | "\n", 496 | "#Prepare y_data\n", 497 | "y_data = [df['HIV_active'][i] for i in range(df.shape[0]) if i != 8079 and i != 559]\n", 498 | "y_data = np.array(y_data)\n", 499 | "\n" 500 | ] 501 | }, 502 | { 503 | "cell_type": "code", 504 | "execution_count": null, 505 | "metadata": {}, 506 | "outputs": [], 507 | "source": [ 508 | "import random\n", 509 | "\n", 510 | "f = np.arange(41911)\n", 511 | "# Change random seed for different experiments\n", 512 | "random.Random(10).shuffle(f)\n", 513 | "train = f[:36000]" 514 | ] 515 | }, 516 | { 517 | "cell_type": "markdown", 518 | "metadata": {}, 519 | "source": [ 520 | "We split data into training and test sets. The model has been previously chosen by adopting the usual cross-validation procedure. From this point on, it is possible to play with different models and spot differences." 521 | ] 522 | }, 523 | { 524 | "cell_type": "code", 525 | "execution_count": null, 526 | "metadata": {}, 527 | "outputs": [], 528 | "source": [ 529 | "np.random.shuffle(train)\n", 530 | "\n", 531 | "i_train = train[:36000]\n", 532 | "i_test = f[36000:]\n", 533 | "\n", 534 | "x_train = x_data[i_train, :]\n", 535 | "y_train = y_data[i_train]\n", 536 | "\n", 537 | "x_test = np.array([np.array(x_data[i,:]) for i in f[36000:]])\n", 538 | "y_test = np.array([y_data[i] for i in f[36000:]])" 539 | ] 540 | }, 541 | { 542 | "cell_type": "code", 543 | "execution_count": null, 544 | "metadata": {}, 545 | "outputs": [], 546 | "source": [ 547 | "from keras.models import Sequential\n", 548 | "from keras.layers import Dense, Dropout, BatchNormalization\n", 549 | "from keras import optimizers\n", 550 | "\n", 551 | "from sklearn.metrics import roc_auc_score" 552 | ] 553 | }, 554 | { 555 | "cell_type": "code", 556 | "execution_count": null, 557 | "metadata": {}, 558 | "outputs": [], 559 | "source": [ 560 | "# define the keras model\n", 561 | "model = Sequential()\n", 562 | "\n", 563 | "model.add(Dense(32, activation='relu'))\n", 564 | "model.add(Dropout(rate=0.4))\n", 565 | "model.add(BatchNormalization())\n", 566 | "\n", 567 | "model.add(Dense(64, activation='relu'))\n", 568 | "model.add(Dropout(rate=0.4))\n", 569 | "model.add(BatchNormalization())\n", 570 | "\n", 571 | "model.add(Dense(1, activation='sigmoid'))" 572 | ] 573 | }, 574 | { 575 | "cell_type": "code", 576 | "execution_count": null, 577 | "metadata": {}, 578 | "outputs": [], 579 | "source": [ 580 | "adam = optimizers.Adam(lr=0.001)\n", 581 | "model.compile(loss='binary_crossentropy', optimizer=adam, metrics=['accuracy'])" 582 | ] 583 | }, 584 | { 585 | "cell_type": "code", 586 | "execution_count": null, 587 | "metadata": {}, 588 | "outputs": [], 589 | "source": [ 590 | "model.fit(x_train, y_train, epochs=100, batch_size=128)" 591 | ] 592 | }, 593 | { 594 | "cell_type": "markdown", 595 | "metadata": {}, 596 | "source": [ 597 | "We validate here the classification model by adopting the $\\href{https://it.wikipedia.org/wiki/Receiver_operating_characteristic}{AUC-ROC}$ score as quality metric. " 598 | ] 599 | }, 600 | { 601 | "cell_type": "code", 602 | "execution_count": null, 603 | "metadata": {}, 604 | "outputs": [], 605 | "source": [ 606 | "# evaluate the keras model\n", 607 | "pe, accuracy = model.evaluate(x_test, y_test)\n", 608 | "print('Accuracy: %.2f' % (accuracy*100))\n", 609 | "\n", 610 | "p_train = model.predict(x_train)\n", 611 | "p_test = model.predict(x_test)\n", 612 | "\n", 613 | "print(\" Train AUC-ROC : {}\".format(roc_auc_score(y_train, p_train)))\n", 614 | "\n", 615 | "print(\" Test AUC-ROC : {}\".format(roc_auc_score(y_test, p_test)))\n" 616 | ] 617 | } 618 | ], 619 | "metadata": { 620 | "kernelspec": { 621 | "display_name": "Python (py35)", 622 | "language": "python", 623 | "name": "py35" 624 | }, 625 | "language_info": { 626 | "codemirror_mode": { 627 | "name": "ipython", 628 | "version": 3 629 | }, 630 | "file_extension": ".py", 631 | "mimetype": "text/x-python", 632 | "name": "python", 633 | "nbconvert_exporter": "python", 634 | "pygments_lexer": "ipython3", 635 | "version": "3.5.6" 636 | } 637 | }, 638 | "nbformat": 4, 639 | "nbformat_minor": 2 640 | } 641 | -------------------------------------------------------------------------------- /.ipynb_checkpoints/HIV-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Shape of Molecules #\n", 8 | "\n", 9 | "In this notebook we provide an innovative pipeline that makes it possible to find interesting and meaningful structural features for chiemical compounds by exploiting the package $\\href{https://giotto.ai/}{giotto learn}$. The task of this notebook is to classify chemical compunds as HIV inhibitors or non-inhibitors for the HIV virus. The problem is a benchmark for molecules graph representation as stated in this $\\href{https://pubs.rsc.org/en/content/articlehtml/2018/sc/c7sc02664a}{paper}$. The novel idea of this notebook is that of exploiting heat diffusion defined over any-order graph cliques (here nodes and edges) to embed the entire graph. In order to defined such diffusion processes we use the definition of higher-order laplcians matrices of clique complexes (special case of simplicial complexes).\n", 10 | "\n", 11 | "### Example of heat diffusion over nodes sampled at two different points ###\n", 12 | "\n", 13 | "\n", 14 | " \"Drawing\" \n", 15 | " \"Drawing\" \n", 16 | "\n", 17 | "\n", 18 | "### Example of heat diffusion over edges sampled at two different points ###\n", 19 | "\n", 20 | "\n", 21 | " \"Drawing\" \n", 22 | " \"Drawing\" \n", 23 | "" 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": null, 29 | "metadata": {}, 30 | "outputs": [], 31 | "source": [ 32 | "#Import statements\n", 33 | "import warnings; warnings.simplefilter('ignore')\n", 34 | "import random \n", 35 | "\n", 36 | "\n", 37 | "import numpy as np\n", 38 | "import networkx as nx\n", 39 | "import pandas as pd\n", 40 | "import matplotlib.pyplot as plt\n", 41 | "\n", 42 | "from sklearn.cluster import KMeans\n", 43 | "\n", 44 | "from giotto.graphs.create_clique_complex import CreateCliqueComplex, CreateBoundaryMatrices, CreateLaplacianMatrices \n", 45 | "from giotto.graphs.heat_diffusion import HeatDiffusion\n", 46 | "from giotto.graphs.graph_entropy import GraphEntropy\n", 47 | "\n", 48 | "from molecules import mol_to_nx, compute_node_edge_entropy, bonds_type, graph_to_points, bonds_type_to_edge\n", 49 | "from plotting import plot_entropies, plot_network_diffusion\n", 50 | "\n", 51 | "from rdkit import Chem \n", 52 | "from rdkit.Chem import Draw\n" 53 | ] 54 | }, 55 | { 56 | "cell_type": "markdown", 57 | "metadata": {}, 58 | "source": [ 59 | "## Import and Convert data to networkx Graph ##" 60 | ] 61 | }, 62 | { 63 | "cell_type": "markdown", 64 | "metadata": {}, 65 | "source": [ 66 | "Import molecules dataset and convert them: $\\textit{smiles}$ --> $\\textit{rdkit.Chem.rdchem.Mol}$ --> $\\textit{networkx.graph}$." 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": null, 72 | "metadata": {}, 73 | "outputs": [], 74 | "source": [ 75 | "#Import and convert data\n", 76 | "df = pd.read_csv('hiv.csv')\n", 77 | "df['g_mol'] = df['smiles'].apply(lambda x: Chem.MolFromSmiles(x))\n", 78 | "df.drop(\"smiles\", axis=1, inplace=True)\n", 79 | "g_mol = [mol_to_nx(df['g_mol'][i]) for i in range(df.shape[0]) if i != 559 and i!= 8097 ]" 80 | ] 81 | }, 82 | { 83 | "cell_type": "markdown", 84 | "metadata": {}, 85 | "source": [ 86 | "## Create Embeddings for all atoms and bonds in the dataset ##\n", 87 | "\n", 88 | "Here the embeddings for all atoms and bonds in the dataset are computed. The idea at the core of the procedure is that to embed a specific node (and so atom) $a_i$ , we study the heat diffusion process that has as initial condition a delta function with 1 on node $a_i$ and 0 otherwise. In order to characterize the diffusion process we sample it at different points in time, generating different snapshots. The values of the diffusion process at each snapshot is then treated as a probability distribution over the nodes of the graph (and so atoms of the molecule) and its entropy is computed. At the end, the embedding vector is populated with the entropy values computed over different points in time. In this step it is possible to tune two different hyperparameters: the number of points in time at which the heat diffusion has to be sampled and the last point instant. In this example the different samples are linearly spaced in time but of course it is possible to choose them differently. By exploiting the higher-order laplacians for clique complexes and the giotto-learn package it is possible to apply the same procedure to the edges of the graph and, in general, to higher order cliques. We then compute the same representation for each edge of all molecules, which represent bonds between two atoms. " 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "execution_count": null, 94 | "metadata": {}, 95 | "outputs": [], 96 | "source": [ 97 | "# Hyperparameters\n", 98 | "taus_n = np.linspace(0,2,20)\n", 99 | "taus_e = np.linspace(0,2,20)" 100 | ] 101 | }, 102 | { 103 | "cell_type": "markdown", 104 | "metadata": {}, 105 | "source": [ 106 | "Here the embeddings are computed. It is possible to save time and load them directly from $\\textit{openML}$ in the subsequent cell. " 107 | ] 108 | }, 109 | { 110 | "cell_type": "code", 111 | "execution_count": null, 112 | "metadata": {}, 113 | "outputs": [], 114 | "source": [ 115 | "# Embedding\n", 116 | "embeds = [compute_node_edge_entropy(x,i, taus_n, taus_e) for i,x in enumerate(g_mol) ]" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": null, 122 | "metadata": {}, 123 | "outputs": [], 124 | "source": [ 125 | "# Create list with node and edge embeddings\n", 126 | "universal_nodes = list()\n", 127 | "for i in range(len(embeds)):\n", 128 | " universal_nodes.extend(np.split(embeds[i][0][:,:].T, embeds[i][0][0,:].shape[0]))\n", 129 | "universal_nodes = np.squeeze(np.array(universal_nodes))\n", 130 | "\n", 131 | "universal_edges = list()\n", 132 | "for i in range(len(embeds)):\n", 133 | " universal_edges.extend(np.split(embeds[i][1][:,:].T, embeds[i][1][0,:].shape[0]))\n", 134 | "universal_edges = np.squeeze(np.array(universal_edges))\n", 135 | "\n" 136 | ] 137 | }, 138 | { 139 | "cell_type": "markdown", 140 | "metadata": {}, 141 | "source": [ 142 | "Once the embeddings have been found, this code can store them in .arff, the format adopted by $\\textit{openML}$." 143 | ] 144 | }, 145 | { 146 | "cell_type": "code", 147 | "execution_count": null, 148 | "metadata": {}, 149 | "outputs": [], 150 | "source": [ 151 | "# Save the new node embeddings as arff\n", 152 | "import arff\n", 153 | "\n", 154 | "dim_n = 30\n", 155 | "attributes_n = [('n{}'.format(e), 'REAL') for e in range(dim_n)]\n", 156 | " \n", 157 | "node_dict = {\n", 158 | " 'relation': 'Node_embedding_hiv',\n", 159 | " 'description': 'This dataset contains the embedding for all nodes of moelcules in HIV inhibitors dataset',\n", 160 | " 'attributes': attributes_n,\n", 161 | " 'data': universal_nodes.tolist()\n", 162 | "}\n", 163 | "\n", 164 | "_= arff.dump(node_dict, open(\"node_embedding_hiv.arff\", \"w+\"))" 165 | ] 166 | }, 167 | { 168 | "cell_type": "code", 169 | "execution_count": null, 170 | "metadata": {}, 171 | "outputs": [], 172 | "source": [ 173 | "# Save the new edge embeddings as arff\n", 174 | "import arff\n", 175 | "\n", 176 | "dim_e = 30\n", 177 | "attributes_e = [('e{}'.format(e), 'REAL') for e in range(dim_e)]\n", 178 | " \n", 179 | "edge_dict = {\n", 180 | " 'relation': 'Edge_embedding_hiv',\n", 181 | " 'description': 'This dataset contains the embedding for all edges of moelcules in HIV inhibitors dataset',\n", 182 | " 'attributes': attributes_e,\n", 183 | " 'data': universal_edges.tolist()\n", 184 | "}\n", 185 | "\n", 186 | "_ = arff.dump(edge_dict, open(\"edge_embedding_hiv.arff\", \"w+\"))" 187 | ] 188 | }, 189 | { 190 | "cell_type": "markdown", 191 | "metadata": {}, 192 | "source": [ 193 | "## Load Pre-Generated Embeddings ##\n", 194 | "\n", 195 | "Here the previously found embeddings can be loaded from the $\\textit{OpenML}$ site." 196 | ] 197 | }, 198 | { 199 | "cell_type": "code", 200 | "execution_count": null, 201 | "metadata": {}, 202 | "outputs": [], 203 | "source": [ 204 | "import arff\n", 205 | "import openml" 206 | ] 207 | }, 208 | { 209 | "cell_type": "code", 210 | "execution_count": null, 211 | "metadata": {}, 212 | "outputs": [], 213 | "source": [ 214 | "# Load nodes (atoms) embedding\n", 215 | "data_n = openml.datasets.get_dataset(42218)" 216 | ] 217 | }, 218 | { 219 | "cell_type": "code", 220 | "execution_count": null, 221 | "metadata": {}, 222 | "outputs": [], 223 | "source": [ 224 | "# Load edges (bonds) embedding\n", 225 | "data_e = openml.datasets.get_dataset(42220)" 226 | ] 227 | }, 228 | { 229 | "cell_type": "code", 230 | "execution_count": null, 231 | "metadata": {}, 232 | "outputs": [], 233 | "source": [ 234 | "universal_nodes = np.array(data_n.get_data()[0])\n", 235 | "universal_edges = np.array(data_e.get_data()[0])" 236 | ] 237 | }, 238 | { 239 | "cell_type": "code", 240 | "execution_count": null, 241 | "metadata": {}, 242 | "outputs": [], 243 | "source": [ 244 | "print(\"Check shape atoms dataset: {}\".format(universal_nodes.shape))\n", 245 | "print(\"Check shape edges dataset: {}\".format(universal_edges.shape))" 246 | ] 247 | }, 248 | { 249 | "cell_type": "markdown", 250 | "metadata": {}, 251 | "source": [ 252 | "## Plot Entropies Example ##" 253 | ] 254 | }, 255 | { 256 | "cell_type": "markdown", 257 | "metadata": {}, 258 | "source": [ 259 | "We can see now one example of heat diffuion's entropy profiles on nodes: first of all several entropy profiles are plotted for different nodes (0-cliques). We then plot the molecule graph in which each node has its label attached. It is possible to observe the local graphical structure and the related diffusion etropy profile. We can see how the heat diffusion entropy depends on the position and so on the role one node has within the network. For example, node 4 is a hub for the molecule and it can easily diffuse heat immediately. This effect is captured by the fact that entropy blows up in the first time samples. On the other hand, node 0 is almost isolated and again the slow spreading effect is captured by the almost flat entropy curve. " 260 | ] 261 | }, 262 | { 263 | "cell_type": "markdown", 264 | "metadata": {}, 265 | "source": [ 266 | "Double check that can be useful later to embed entire molecules." 267 | ] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "execution_count": null, 272 | "metadata": {}, 273 | "outputs": [], 274 | "source": [ 275 | "mol_to_atom = graph_to_points(g_mol, 0)\n", 276 | "mol_to_bonds = graph_to_points(g_mol, 1)" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": null, 282 | "metadata": {}, 283 | "outputs": [], 284 | "source": [ 285 | "# Node Analysis\n", 286 | "plt.figure(figsize=(20,6))\n", 287 | "\n", 288 | "plt.subplot(1, 2, 1)\n", 289 | "mol_id = 0\n", 290 | "node_ids = [0, 4, 7, 15]\n", 291 | "mol = g_mol[mol_id]\n", 292 | "\n", 293 | "entropies = [ universal_nodes[x] for x in mol_to_atom[mol_id] ]\n", 294 | "plot_entropies( entropies, node_ids)\n", 295 | "\n", 296 | "# Node Plotting\n", 297 | "plt.subplot(1, 2, 2)\n", 298 | "plot_network_diffusion(mol, pos=nx.spring_layout(mol, iterations=1000), node_labels=True)\n", 299 | "_ = plt.title('Molecule as networkx object')" 300 | ] 301 | }, 302 | { 303 | "cell_type": "markdown", 304 | "metadata": {}, 305 | "source": [ 306 | "# Adding Bonds information #\n", 307 | "\n", 308 | "We now add one piece of chemical information to the problem. The first two methods attach to each molecule graph the information about the type of chemical bonds. In particular, each edge is equipped with a one-hot-encoded vector representation with the number 1 in the position of the corresponding bond type: \n", 309 | "\n", 310 | "$0 --> single$\n", 311 | "\n", 312 | "$1 --> double$\n", 313 | "\n", 314 | "$2 --> triple$\n", 315 | "\n", 316 | "$3 --> aromatic$\n", 317 | "\n", 318 | "For nodes the vector is obtained by summing up all the one-hot-encoded vectors representing the incidence edges." 319 | ] 320 | }, 321 | { 322 | "cell_type": "code", 323 | "execution_count": null, 324 | "metadata": {}, 325 | "outputs": [], 326 | "source": [ 327 | "bonds_type(g_mol)\n", 328 | "bonds_type_to_edge(g_mol)\n", 329 | "\n", 330 | "#Create a list with all nodes \n", 331 | "freq_type_bonds = list()\n", 332 | "for g in g_mol:\n", 333 | " freq_type_bonds.extend(list(nx.get_node_attributes(g, 'bonds_one_hot').values()))\n", 334 | "\n", 335 | "# Create a list with all edges\n", 336 | "freq_type_bonds_edge = list()\n", 337 | "for g in g_mol:\n", 338 | " freq_type_bonds_edge.extend(list(nx.get_edge_attributes(g, 'bonds_one_hot').values()))\n", 339 | "\n", 340 | "# Check how many atoms and bonds \n", 341 | "freq_type_bonds = np.array(freq_type_bonds)\n", 342 | "freq_type_bonds_edge = np.array(freq_type_bonds_edge)\n", 343 | "print(\"Total number of atoms in the dataset: {}\".format(freq_type_bonds.shape[0]))\n", 344 | "print(\"Total number of bonds in the dataset: {}\".format(freq_type_bonds_edge.shape[0]))" 345 | ] 346 | }, 347 | { 348 | "cell_type": "markdown", 349 | "metadata": {}, 350 | "source": [ 351 | "# Universal Node + Bond Types Embeddding #" 352 | ] 353 | }, 354 | { 355 | "cell_type": "markdown", 356 | "metadata": {}, 357 | "source": [ 358 | "We split the molecule embedding list and create one big list with one extended entry per node contaning both the topological features taken from the entropy embedding and the chemical features related to the bond types." 359 | ] 360 | }, 361 | { 362 | "cell_type": "code", 363 | "execution_count": null, 364 | "metadata": {}, 365 | "outputs": [], 366 | "source": [ 367 | "uni_frq_nodes = [np.hstack([universal_nodes[x,:], freq_type_bonds[x,:]]) for x in range(universal_nodes.shape[0])]\n", 368 | "uni_frq_nodes = np.array(uni_frq_nodes)" 369 | ] 370 | }, 371 | { 372 | "cell_type": "markdown", 373 | "metadata": {}, 374 | "source": [ 375 | "We now cluster all molecules into $\\textit{n_clusters}$ different classes which is another hyperparamter of the pipeline. Moreover, centroids for all classes are stored. They'll be used later to generate the final embedding." 376 | ] 377 | }, 378 | { 379 | "cell_type": "code", 380 | "execution_count": null, 381 | "metadata": {}, 382 | "outputs": [], 383 | "source": [ 384 | "# Kmeans clustering\n", 385 | "n_clusters=10\n", 386 | "kmeans_n = KMeans(n_clusters)\n", 387 | "universal_class_nodes = kmeans_n.fit_transform(uni_frq_nodes)\n", 388 | " \n", 389 | "centroids_n = kmeans_n.cluster_centers_" 390 | ] 391 | }, 392 | { 393 | "cell_type": "markdown", 394 | "metadata": {}, 395 | "source": [ 396 | "We now popoulate, for each atom, a vector which contains the probability for that atom of belonging to the different $\\textit{n_clusters}$ classes. Once this is obtained, we generate the embedding for a molecule by taking the element-wise sum of the embeddings coming from all its atoms." 397 | ] 398 | }, 399 | { 400 | "cell_type": "code", 401 | "execution_count": null, 402 | "metadata": {}, 403 | "outputs": [], 404 | "source": [ 405 | "# Soft Encoded\n", 406 | "soft_encoded_node = [[ np.exp( - (np.linalg.norm(uni_frq_nodes[x]- centroids_n[c], 2) ** 2) / 2) for c in range(n_clusters)] for x in range(uni_frq_nodes.shape[0])]\n", 407 | "soft_encoded_node = np.array(soft_encoded_node)\n", 408 | "\n", 409 | "# Create node data for each graph\n", 410 | "x_data_node = [ np.sum([soft_encoded_node[n] for n in mol_to_atom[i]], axis=0) for i in range(len(g_mol))]\n", 411 | "x_data_node = np.array(x_data_node)\n", 412 | "print(\"Check shape of x_data_node: {}\".format(x_data_node.shape))" 413 | ] 414 | }, 415 | { 416 | "cell_type": "markdown", 417 | "metadata": {}, 418 | "source": [ 419 | "# Universal Edge + Bond Types Embeddding #" 420 | ] 421 | }, 422 | { 423 | "cell_type": "markdown", 424 | "metadata": {}, 425 | "source": [ 426 | "Exatcly the same procedure is applied to the edges of the dataset." 427 | ] 428 | }, 429 | { 430 | "cell_type": "code", 431 | "execution_count": null, 432 | "metadata": {}, 433 | "outputs": [], 434 | "source": [ 435 | "uni_frq_edges = [np.hstack([universal_edges[x,:], freq_type_bonds_edge[x,:]]) for x in range(universal_edges.shape[0])]\n", 436 | "uni_frq_edges = np.array(uni_frq_edges)" 437 | ] 438 | }, 439 | { 440 | "cell_type": "code", 441 | "execution_count": null, 442 | "metadata": {}, 443 | "outputs": [], 444 | "source": [ 445 | "# Kmeans clustering\n", 446 | "e_clusters = 10\n", 447 | "kmeans_e = KMeans(e_clusters)\n", 448 | "universal_class_edge = kmeans_e.fit_transform(uni_frq_edges)\n", 449 | "\n", 450 | "centroids_e = kmeans_e.cluster_centers_" 451 | ] 452 | }, 453 | { 454 | "cell_type": "code", 455 | "execution_count": null, 456 | "metadata": {}, 457 | "outputs": [], 458 | "source": [ 459 | "# Soft Encoded\n", 460 | "soft_encoded_edge = [[ np.exp( - (np.linalg.norm(uni_frq_edges[x]- centroids_e[c], 2) ** 2) / 2) for c in range(e_clusters)] for x in range(universal_edges.shape[0])]\n", 461 | "soft_encoded_edge = np.array(soft_encoded_edge)\n", 462 | "\n", 463 | "# Create edge data for each graph\n", 464 | "x_data_edge = [ np.sum([soft_encoded_edge[n] for n in mol_to_bonds[i]], axis=0) for i in range(len(g_mol))]\n", 465 | "x_data_edge = np.array(x_data_edge)\n", 466 | "print(\"Check shape of x_data_edge: {}\".format(x_data_edge.shape))" 467 | ] 468 | }, 469 | { 470 | "cell_type": "markdown", 471 | "metadata": {}, 472 | "source": [ 473 | "# Classification Model and Evaluation#" 474 | ] 475 | }, 476 | { 477 | "cell_type": "markdown", 478 | "metadata": {}, 479 | "source": [ 480 | "This part of the notebook contains the classificator model and training." 481 | ] 482 | }, 483 | { 484 | "cell_type": "code", 485 | "execution_count": null, 486 | "metadata": {}, 487 | "outputs": [], 488 | "source": [ 489 | "# Prepare x_data\n", 490 | "x_data = np.hstack([x_data_node, x_data_edge])\n", 491 | "x_data -= np.mean(x_data, axis=0)\n", 492 | "x_data /= (np.max(x_data, axis=0) - np.min(x_data, axis=0))\n", 493 | "\n", 494 | "print(\"Check shape of x_data: {}\".format(x_data.shape))\n", 495 | "\n", 496 | "#Prepare y_data\n", 497 | "y_data = [df['HIV_active'][i] for i in range(df.shape[0]) if i != 8079 and i != 559]\n", 498 | "y_data = np.array(y_data)\n", 499 | "\n" 500 | ] 501 | }, 502 | { 503 | "cell_type": "code", 504 | "execution_count": null, 505 | "metadata": {}, 506 | "outputs": [], 507 | "source": [ 508 | "import random\n", 509 | "\n", 510 | "f = np.arange(41911)\n", 511 | "# Change random seed for different experiments\n", 512 | "random.Random(10).shuffle(f)\n", 513 | "train = f[:36000]" 514 | ] 515 | }, 516 | { 517 | "cell_type": "markdown", 518 | "metadata": {}, 519 | "source": [ 520 | "We split data into training and test sets. The model has been previously chosen by adopting the usual cross-validation procedure. From this point on, it is possible to play with different models and spot differences." 521 | ] 522 | }, 523 | { 524 | "cell_type": "code", 525 | "execution_count": null, 526 | "metadata": {}, 527 | "outputs": [], 528 | "source": [ 529 | "np.random.shuffle(train)\n", 530 | "\n", 531 | "i_train = train[:36000]\n", 532 | "i_test = f[36000:]\n", 533 | "\n", 534 | "x_train = x_data[i_train, :]\n", 535 | "y_train = y_data[i_train]\n", 536 | "\n", 537 | "x_test = np.array([np.array(x_data[i,:]) for i in f[36000:]])\n", 538 | "y_test = np.array([y_data[i] for i in f[36000:]])" 539 | ] 540 | }, 541 | { 542 | "cell_type": "code", 543 | "execution_count": null, 544 | "metadata": {}, 545 | "outputs": [], 546 | "source": [ 547 | "from keras.models import Sequential\n", 548 | "from keras.layers import Dense, Dropout, BatchNormalization\n", 549 | "from keras import optimizers\n", 550 | "\n", 551 | "from sklearn.metrics import roc_auc_score" 552 | ] 553 | }, 554 | { 555 | "cell_type": "code", 556 | "execution_count": null, 557 | "metadata": {}, 558 | "outputs": [], 559 | "source": [ 560 | "# define the keras model\n", 561 | "model = Sequential()\n", 562 | "\n", 563 | "model.add(Dense(32, activation='relu'))\n", 564 | "model.add(Dropout(rate=0.4))\n", 565 | "model.add(BatchNormalization())\n", 566 | "\n", 567 | "model.add(Dense(64, activation='relu'))\n", 568 | "model.add(Dropout(rate=0.4))\n", 569 | "model.add(BatchNormalization())\n", 570 | "\n", 571 | "model.add(Dense(1, activation='sigmoid'))" 572 | ] 573 | }, 574 | { 575 | "cell_type": "code", 576 | "execution_count": null, 577 | "metadata": {}, 578 | "outputs": [], 579 | "source": [ 580 | "adam = optimizers.Adam(lr=0.001)\n", 581 | "model.compile(loss='binary_crossentropy', optimizer=adam, metrics=['accuracy'])" 582 | ] 583 | }, 584 | { 585 | "cell_type": "code", 586 | "execution_count": null, 587 | "metadata": {}, 588 | "outputs": [], 589 | "source": [ 590 | "model.fit(x_train, y_train, epochs=100, batch_size=128)" 591 | ] 592 | }, 593 | { 594 | "cell_type": "markdown", 595 | "metadata": {}, 596 | "source": [ 597 | "We validate here the classification model by adopting the $\\href{https://it.wikipedia.org/wiki/Receiver_operating_characteristic}{AUC-ROC}$ score as quality metric. " 598 | ] 599 | }, 600 | { 601 | "cell_type": "code", 602 | "execution_count": null, 603 | "metadata": {}, 604 | "outputs": [], 605 | "source": [ 606 | "# evaluate the keras model\n", 607 | "pe, accuracy = model.evaluate(x_test, y_test)\n", 608 | "print('Accuracy: %.2f' % (accuracy*100))\n", 609 | "\n", 610 | "p_train = model.predict(x_train)\n", 611 | "p_test = model.predict(x_test)\n", 612 | "\n", 613 | "print(\" Train AUC-ROC : {}\".format(roc_auc_score(y_train, p_train)))\n", 614 | "\n", 615 | "print(\" Test AUC-ROC : {}\".format(roc_auc_score(y_test, p_test)))\n" 616 | ] 617 | } 618 | ], 619 | "metadata": { 620 | "kernelspec": { 621 | "display_name": "Python (py35)", 622 | "language": "python", 623 | "name": "py35" 624 | }, 625 | "language_info": { 626 | "codemirror_mode": { 627 | "name": "ipython", 628 | "version": 3 629 | }, 630 | "file_extension": ".py", 631 | "mimetype": "text/x-python", 632 | "name": "python", 633 | "nbconvert_exporter": "python", 634 | "pygments_lexer": "ipython3", 635 | "version": "3.5.6" 636 | } 637 | }, 638 | "nbformat": 4, 639 | "nbformat_minor": 2 640 | } 641 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2019 L2F SA. 2 | Licensed under the GNU Affero General Public License (the "License"); 3 | you may not use this file except in compliance with the License. 4 | You may obtain a copy of the License below or at https://www.gnu.org/licenses/agpl-3.0.html 5 | 6 | Unless required by applicable law or agreed to in writing, software 7 | distributed under the License is distributed on an "AS IS" BASIS, 8 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | See the License for the specific language governing permissions and 10 | limitations under the License. 11 | 12 | GNU AFFERO GENERAL PUBLIC LICENSE 13 | Version 3, 19 November 2007 14 | 15 | Copyright (C) 2007 Free Software Foundation, Inc. 16 | Everyone is permitted to copy and distribute verbatim copies 17 | of this license document, but changing it is not allowed. 18 | 19 | Preamble 20 | 21 | The GNU Affero General Public License is a free, copyleft license for 22 | software and other kinds of works, specifically designed to ensure 23 | cooperation with the community in the case of network server software. 24 | 25 | The licenses for most software and other practical works are designed 26 | to take away your freedom to share and change the works. By contrast, 27 | our General Public Licenses are intended to guarantee your freedom to 28 | share and change all versions of a program--to make sure it remains free 29 | software for all its users. 30 | 31 | When we speak of free software, we are referring to freedom, not 32 | price. Our General Public Licenses are designed to make sure that you 33 | have the freedom to distribute copies of free software (and charge for 34 | them if you wish), that you receive source code or can get it if you 35 | want it, that you can change the software or use pieces of it in new 36 | free programs, and that you know you can do these things. 37 | 38 | Developers that use our General Public Licenses protect your rights 39 | with two steps: (1) assert copyright on the software, and (2) offer 40 | you this License which gives you legal permission to copy, distribute 41 | and/or modify the software. 42 | 43 | A secondary benefit of defending all users' freedom is that 44 | improvements made in alternate versions of the program, if they 45 | receive widespread use, become available for other developers to 46 | incorporate. Many developers of free software are heartened and 47 | encouraged by the resulting cooperation. However, in the case of 48 | software used on network servers, this result may fail to come about. 49 | The GNU General Public License permits making a modified version and 50 | letting the public access it on a server without ever releasing its 51 | source code to the public. 52 | 53 | The GNU Affero General Public License is designed specifically to 54 | ensure that, in such cases, the modified source code becomes available 55 | to the community. It requires the operator of a network server to 56 | provide the source code of the modified version running there to the 57 | users of that server. Therefore, public use of a modified version, on 58 | a publicly accessible server, gives the public access to the source 59 | code of the modified version. 60 | 61 | An older license, called the Affero General Public License and 62 | published by Affero, was designed to accomplish similar goals. This is 63 | a different license, not a version of the Affero GPL, but Affero has 64 | released a new version of the Affero GPL which permits relicensing under 65 | this license. 66 | 67 | The precise terms and conditions for copying, distribution and 68 | modification follow. 69 | 70 | TERMS AND CONDITIONS 71 | 72 | 0. Definitions. 73 | 74 | "This License" refers to version 3 of the GNU Affero General Public License. 75 | 76 | "Copyright" also means copyright-like laws that apply to other kinds of 77 | works, such as semiconductor masks. 78 | 79 | "The Program" refers to any copyrightable work licensed under this 80 | License. Each licensee is addressed as "you". "Licensees" and 81 | "recipients" may be individuals or organizations. 82 | 83 | To "modify" a work means to copy from or adapt all or part of the work 84 | in a fashion requiring copyright permission, other than the making of an 85 | exact copy. The resulting work is called a "modified version" of the 86 | earlier work or a work "based on" the earlier work. 87 | 88 | A "covered work" means either the unmodified Program or a work based 89 | on the Program. 90 | 91 | To "propagate" a work means to do anything with it that, without 92 | permission, would make you directly or secondarily liable for 93 | infringement under applicable copyright law, except executing it on a 94 | computer or modifying a private copy. Propagation includes copying, 95 | distribution (with or without modification), making available to the 96 | public, and in some countries other activities as well. 97 | 98 | To "convey" a work means any kind of propagation that enables other 99 | parties to make or receive copies. Mere interaction with a user through 100 | a computer network, with no transfer of a copy, is not conveying. 101 | 102 | An interactive user interface displays "Appropriate Legal Notices" 103 | to the extent that it includes a convenient and prominently visible 104 | feature that (1) displays an appropriate copyright notice, and (2) 105 | tells the user that there is no warranty for the work (except to the 106 | extent that warranties are provided), that licensees may convey the 107 | work under this License, and how to view a copy of this License. If 108 | the interface presents a list of user commands or options, such as a 109 | menu, a prominent item in the list meets this criterion. 110 | 111 | 1. Source Code. 112 | 113 | The "source code" for a work means the preferred form of the work 114 | for making modifications to it. "Object code" means any non-source 115 | form of a work. 116 | 117 | A "Standard Interface" means an interface that either is an official 118 | standard defined by a recognized standards body, or, in the case of 119 | interfaces specified for a particular programming language, one that 120 | is widely used among developers working in that language. 121 | 122 | The "System Libraries" of an executable work include anything, other 123 | than the work as a whole, that (a) is included in the normal form of 124 | packaging a Major Component, but which is not part of that Major 125 | Component, and (b) serves only to enable use of the work with that 126 | Major Component, or to implement a Standard Interface for which an 127 | implementation is available to the public in source code form. A 128 | "Major Component", in this context, means a major essential component 129 | (kernel, window system, and so on) of the specific operating system 130 | (if any) on which the executable work runs, or a compiler used to 131 | produce the work, or an object code interpreter used to run it. 132 | 133 | The "Corresponding Source" for a work in object code form means all 134 | the source code needed to generate, install, and (for an executable 135 | work) run the object code and to modify the work, including scripts to 136 | control those activities. However, it does not include the work's 137 | System Libraries, or general-purpose tools or generally available free 138 | programs which are used unmodified in performing those activities but 139 | which are not part of the work. For example, Corresponding Source 140 | includes interface definition files associated with source files for 141 | the work, and the source code for shared libraries and dynamically 142 | linked subprograms that the work is specifically designed to require, 143 | such as by intimate data communication or control flow between those 144 | subprograms and other parts of the work. 145 | 146 | The Corresponding Source need not include anything that users 147 | can regenerate automatically from other parts of the Corresponding 148 | Source. 149 | 150 | The Corresponding Source for a work in source code form is that 151 | same work. 152 | 153 | 2. Basic Permissions. 154 | 155 | All rights granted under this License are granted for the term of 156 | copyright on the Program, and are irrevocable provided the stated 157 | conditions are met. This License explicitly affirms your unlimited 158 | permission to run the unmodified Program. The output from running a 159 | covered work is covered by this License only if the output, given its 160 | content, constitutes a covered work. This License acknowledges your 161 | rights of fair use or other equivalent, as provided by copyright law. 162 | 163 | You may make, run and propagate covered works that you do not 164 | convey, without conditions so long as your license otherwise remains 165 | in force. You may convey covered works to others for the sole purpose 166 | of having them make modifications exclusively for you, or provide you 167 | with facilities for running those works, provided that you comply with 168 | the terms of this License in conveying all material for which you do 169 | not control copyright. Those thus making or running the covered works 170 | for you must do so exclusively on your behalf, under your direction 171 | and control, on terms that prohibit them from making any copies of 172 | your copyrighted material outside their relationship with you. 173 | 174 | Conveying under any other circumstances is permitted solely under 175 | the conditions stated below. Sublicensing is not allowed; section 10 176 | makes it unnecessary. 177 | 178 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 179 | 180 | No covered work shall be deemed part of an effective technological 181 | measure under any applicable law fulfilling obligations under article 182 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 183 | similar laws prohibiting or restricting circumvention of such 184 | measures. 185 | 186 | When you convey a covered work, you waive any legal power to forbid 187 | circumvention of technological measures to the extent such circumvention 188 | is effected by exercising rights under this License with respect to 189 | the covered work, and you disclaim any intention to limit operation or 190 | modification of the work as a means of enforcing, against the work's 191 | users, your or third parties' legal rights to forbid circumvention of 192 | technological measures. 193 | 194 | 4. Conveying Verbatim Copies. 195 | 196 | You may convey verbatim copies of the Program's source code as you 197 | receive it, in any medium, provided that you conspicuously and 198 | appropriately publish on each copy an appropriate copyright notice; 199 | keep intact all notices stating that this License and any 200 | non-permissive terms added in accord with section 7 apply to the code; 201 | keep intact all notices of the absence of any warranty; and give all 202 | recipients a copy of this License along with the Program. 203 | 204 | You may charge any price or no price for each copy that you convey, 205 | and you may offer support or warranty protection for a fee. 206 | 207 | 5. Conveying Modified Source Versions. 208 | 209 | You may convey a work based on the Program, or the modifications to 210 | produce it from the Program, in the form of source code under the 211 | terms of section 4, provided that you also meet all of these conditions: 212 | 213 | a) The work must carry prominent notices stating that you modified 214 | it, and giving a relevant date. 215 | 216 | b) The work must carry prominent notices stating that it is 217 | released under this License and any conditions added under section 218 | 7. This requirement modifies the requirement in section 4 to 219 | "keep intact all notices". 220 | 221 | c) You must license the entire work, as a whole, under this 222 | License to anyone who comes into possession of a copy. This 223 | License will therefore apply, along with any applicable section 7 224 | additional terms, to the whole of the work, and all its parts, 225 | regardless of how they are packaged. This License gives no 226 | permission to license the work in any other way, but it does not 227 | invalidate such permission if you have separately received it. 228 | 229 | d) If the work has interactive user interfaces, each must display 230 | Appropriate Legal Notices; however, if the Program has interactive 231 | interfaces that do not display Appropriate Legal Notices, your 232 | work need not make them do so. 233 | 234 | A compilation of a covered work with other separate and independent 235 | works, which are not by their nature extensions of the covered work, 236 | and which are not combined with it such as to form a larger program, 237 | in or on a volume of a storage or distribution medium, is called an 238 | "aggregate" if the compilation and its resulting copyright are not 239 | used to limit the access or legal rights of the compilation's users 240 | beyond what the individual works permit. Inclusion of a covered work 241 | in an aggregate does not cause this License to apply to the other 242 | parts of the aggregate. 243 | 244 | 6. Conveying Non-Source Forms. 245 | 246 | You may convey a covered work in object code form under the terms 247 | of sections 4 and 5, provided that you also convey the 248 | machine-readable Corresponding Source under the terms of this License, 249 | in one of these ways: 250 | 251 | a) Convey the object code in, or embodied in, a physical product 252 | (including a physical distribution medium), accompanied by the 253 | Corresponding Source fixed on a durable physical medium 254 | customarily used for software interchange. 255 | 256 | b) Convey the object code in, or embodied in, a physical product 257 | (including a physical distribution medium), accompanied by a 258 | written offer, valid for at least three years and valid for as 259 | long as you offer spare parts or customer support for that product 260 | model, to give anyone who possesses the object code either (1) a 261 | copy of the Corresponding Source for all the software in the 262 | product that is covered by this License, on a durable physical 263 | medium customarily used for software interchange, for a price no 264 | more than your reasonable cost of physically performing this 265 | conveying of source, or (2) access to copy the 266 | Corresponding Source from a network server at no charge. 267 | 268 | c) Convey individual copies of the object code with a copy of the 269 | written offer to provide the Corresponding Source. This 270 | alternative is allowed only occasionally and noncommercially, and 271 | only if you received the object code with such an offer, in accord 272 | with subsection 6b. 273 | 274 | d) Convey the object code by offering access from a designated 275 | place (gratis or for a charge), and offer equivalent access to the 276 | Corresponding Source in the same way through the same place at no 277 | further charge. You need not require recipients to copy the 278 | Corresponding Source along with the object code. If the place to 279 | copy the object code is a network server, the Corresponding Source 280 | may be on a different server (operated by you or a third party) 281 | that supports equivalent copying facilities, provided you maintain 282 | clear directions next to the object code saying where to find the 283 | Corresponding Source. Regardless of what server hosts the 284 | Corresponding Source, you remain obligated to ensure that it is 285 | available for as long as needed to satisfy these requirements. 286 | 287 | e) Convey the object code using peer-to-peer transmission, provided 288 | you inform other peers where the object code and Corresponding 289 | Source of the work are being offered to the general public at no 290 | charge under subsection 6d. 291 | 292 | A separable portion of the object code, whose source code is excluded 293 | from the Corresponding Source as a System Library, need not be 294 | included in conveying the object code work. 295 | 296 | A "User Product" is either (1) a "consumer product", which means any 297 | tangible personal property which is normally used for personal, family, 298 | or household purposes, or (2) anything designed or sold for incorporation 299 | into a dwelling. In determining whether a product is a consumer product, 300 | doubtful cases shall be resolved in favor of coverage. For a particular 301 | product received by a particular user, "normally used" refers to a 302 | typical or common use of that class of product, regardless of the status 303 | of the particular user or of the way in which the particular user 304 | actually uses, or expects or is expected to use, the product. A product 305 | is a consumer product regardless of whether the product has substantial 306 | commercial, industrial or non-consumer uses, unless such uses represent 307 | the only significant mode of use of the product. 308 | 309 | "Installation Information" for a User Product means any methods, 310 | procedures, authorization keys, or other information required to install 311 | and execute modified versions of a covered work in that User Product from 312 | a modified version of its Corresponding Source. The information must 313 | suffice to ensure that the continued functioning of the modified object 314 | code is in no case prevented or interfered with solely because 315 | modification has been made. 316 | 317 | If you convey an object code work under this section in, or with, or 318 | specifically for use in, a User Product, and the conveying occurs as 319 | part of a transaction in which the right of possession and use of the 320 | User Product is transferred to the recipient in perpetuity or for a 321 | fixed term (regardless of how the transaction is characterized), the 322 | Corresponding Source conveyed under this section must be accompanied 323 | by the Installation Information. But this requirement does not apply 324 | if neither you nor any third party retains the ability to install 325 | modified object code on the User Product (for example, the work has 326 | been installed in ROM). 327 | 328 | The requirement to provide Installation Information does not include a 329 | requirement to continue to provide support service, warranty, or updates 330 | for a work that has been modified or installed by the recipient, or for 331 | the User Product in which it has been modified or installed. Access to a 332 | network may be denied when the modification itself materially and 333 | adversely affects the operation of the network or violates the rules and 334 | protocols for communication across the network. 335 | 336 | Corresponding Source conveyed, and Installation Information provided, 337 | in accord with this section must be in a format that is publicly 338 | documented (and with an implementation available to the public in 339 | source code form), and must require no special password or key for 340 | unpacking, reading or copying. 341 | 342 | 7. Additional Terms. 343 | 344 | "Additional permissions" are terms that supplement the terms of this 345 | License by making exceptions from one or more of its conditions. 346 | Additional permissions that are applicable to the entire Program shall 347 | be treated as though they were included in this License, to the extent 348 | that they are valid under applicable law. If additional permissions 349 | apply only to part of the Program, that part may be used separately 350 | under those permissions, but the entire Program remains governed by 351 | this License without regard to the additional permissions. 352 | 353 | When you convey a copy of a covered work, you may at your option 354 | remove any additional permissions from that copy, or from any part of 355 | it. (Additional permissions may be written to require their own 356 | removal in certain cases when you modify the work.) You may place 357 | additional permissions on material, added by you to a covered work, 358 | for which you have or can give appropriate copyright permission. 359 | 360 | Notwithstanding any other provision of this License, for material you 361 | add to a covered work, you may (if authorized by the copyright holders of 362 | that material) supplement the terms of this License with terms: 363 | 364 | a) Disclaiming warranty or limiting liability differently from the 365 | terms of sections 15 and 16 of this License; or 366 | 367 | b) Requiring preservation of specified reasonable legal notices or 368 | author attributions in that material or in the Appropriate Legal 369 | Notices displayed by works containing it; or 370 | 371 | c) Prohibiting misrepresentation of the origin of that material, or 372 | requiring that modified versions of such material be marked in 373 | reasonable ways as different from the original version; or 374 | 375 | d) Limiting the use for publicity purposes of names of licensors or 376 | authors of the material; or 377 | 378 | e) Declining to grant rights under trademark law for use of some 379 | trade names, trademarks, or service marks; or 380 | 381 | f) Requiring indemnification of licensors and authors of that 382 | material by anyone who conveys the material (or modified versions of 383 | it) with contractual assumptions of liability to the recipient, for 384 | any liability that these contractual assumptions directly impose on 385 | those licensors and authors. 386 | 387 | All other non-permissive additional terms are considered "further 388 | restrictions" within the meaning of section 10. If the Program as you 389 | received it, or any part of it, contains a notice stating that it is 390 | governed by this License along with a term that is a further 391 | restriction, you may remove that term. If a license document contains 392 | a further restriction but permits relicensing or conveying under this 393 | License, you may add to a covered work material governed by the terms 394 | of that license document, provided that the further restriction does 395 | not survive such relicensing or conveying. 396 | 397 | If you add terms to a covered work in accord with this section, you 398 | must place, in the relevant source files, a statement of the 399 | additional terms that apply to those files, or a notice indicating 400 | where to find the applicable terms. 401 | 402 | Additional terms, permissive or non-permissive, may be stated in the 403 | form of a separately written license, or stated as exceptions; 404 | the above requirements apply either way. 405 | 406 | 8. Termination. 407 | 408 | You may not propagate or modify a covered work except as expressly 409 | provided under this License. Any attempt otherwise to propagate or 410 | modify it is void, and will automatically terminate your rights under 411 | this License (including any patent licenses granted under the third 412 | paragraph of section 11). 413 | 414 | However, if you cease all violation of this License, then your 415 | license from a particular copyright holder is reinstated (a) 416 | provisionally, unless and until the copyright holder explicitly and 417 | finally terminates your license, and (b) permanently, if the copyright 418 | holder fails to notify you of the violation by some reasonable means 419 | prior to 60 days after the cessation. 420 | 421 | Moreover, your license from a particular copyright holder is 422 | reinstated permanently if the copyright holder notifies you of the 423 | violation by some reasonable means, this is the first time you have 424 | received notice of violation of this License (for any work) from that 425 | copyright holder, and you cure the violation prior to 30 days after 426 | your receipt of the notice. 427 | 428 | Termination of your rights under this section does not terminate the 429 | licenses of parties who have received copies or rights from you under 430 | this License. If your rights have been terminated and not permanently 431 | reinstated, you do not qualify to receive new licenses for the same 432 | material under section 10. 433 | 434 | 9. Acceptance Not Required for Having Copies. 435 | 436 | You are not required to accept this License in order to receive or 437 | run a copy of the Program. Ancillary propagation of a covered work 438 | occurring solely as a consequence of using peer-to-peer transmission 439 | to receive a copy likewise does not require acceptance. However, 440 | nothing other than this License grants you permission to propagate or 441 | modify any covered work. These actions infringe copyright if you do 442 | not accept this License. Therefore, by modifying or propagating a 443 | covered work, you indicate your acceptance of this License to do so. 444 | 445 | 10. Automatic Licensing of Downstream Recipients. 446 | 447 | Each time you convey a covered work, the recipient automatically 448 | receives a license from the original licensors, to run, modify and 449 | propagate that work, subject to this License. You are not responsible 450 | for enforcing compliance by third parties with this License. 451 | 452 | An "entity transaction" is a transaction transferring control of an 453 | organization, or substantially all assets of one, or subdividing an 454 | organization, or merging organizations. If propagation of a covered 455 | work results from an entity transaction, each party to that 456 | transaction who receives a copy of the work also receives whatever 457 | licenses to the work the party's predecessor in interest had or could 458 | give under the previous paragraph, plus a right to possession of the 459 | Corresponding Source of the work from the predecessor in interest, if 460 | the predecessor has it or can get it with reasonable efforts. 461 | 462 | You may not impose any further restrictions on the exercise of the 463 | rights granted or affirmed under this License. For example, you may 464 | not impose a license fee, royalty, or other charge for exercise of 465 | rights granted under this License, and you may not initiate litigation 466 | (including a cross-claim or counterclaim in a lawsuit) alleging that 467 | any patent claim is infringed by making, using, selling, offering for 468 | sale, or importing the Program or any portion of it. 469 | 470 | 11. Patents. 471 | 472 | A "contributor" is a copyright holder who authorizes use under this 473 | License of the Program or a work on which the Program is based. The 474 | work thus licensed is called the contributor's "contributor version". 475 | 476 | A contributor's "essential patent claims" are all patent claims 477 | owned or controlled by the contributor, whether already acquired or 478 | hereafter acquired, that would be infringed by some manner, permitted 479 | by this License, of making, using, or selling its contributor version, 480 | but do not include claims that would be infringed only as a 481 | consequence of further modification of the contributor version. For 482 | purposes of this definition, "control" includes the right to grant 483 | patent sublicenses in a manner consistent with the requirements of 484 | this License. 485 | 486 | Each contributor grants you a non-exclusive, worldwide, royalty-free 487 | patent license under the contributor's essential patent claims, to 488 | make, use, sell, offer for sale, import and otherwise run, modify and 489 | propagate the contents of its contributor version. 490 | 491 | In the following three paragraphs, a "patent license" is any express 492 | agreement or commitment, however denominated, not to enforce a patent 493 | (such as an express permission to practice a patent or covenant not to 494 | sue for patent infringement). To "grant" such a patent license to a 495 | party means to make such an agreement or commitment not to enforce a 496 | patent against the party. 497 | 498 | If you convey a covered work, knowingly relying on a patent license, 499 | and the Corresponding Source of the work is not available for anyone 500 | to copy, free of charge and under the terms of this License, through a 501 | publicly available network server or other readily accessible means, 502 | then you must either (1) cause the Corresponding Source to be so 503 | available, or (2) arrange to deprive yourself of the benefit of the 504 | patent license for this particular work, or (3) arrange, in a manner 505 | consistent with the requirements of this License, to extend the patent 506 | license to downstream recipients. "Knowingly relying" means you have 507 | actual knowledge that, but for the patent license, your conveying the 508 | covered work in a country, or your recipient's use of the covered work 509 | in a country, would infringe one or more identifiable patents in that 510 | country that you have reason to believe are valid. 511 | 512 | If, pursuant to or in connection with a single transaction or 513 | arrangement, you convey, or propagate by procuring conveyance of, a 514 | covered work, and grant a patent license to some of the parties 515 | receiving the covered work authorizing them to use, propagate, modify 516 | or convey a specific copy of the covered work, then the patent license 517 | you grant is automatically extended to all recipients of the covered 518 | work and works based on it. 519 | 520 | A patent license is "discriminatory" if it does not include within 521 | the scope of its coverage, prohibits the exercise of, or is 522 | conditioned on the non-exercise of one or more of the rights that are 523 | specifically granted under this License. You may not convey a covered 524 | work if you are a party to an arrangement with a third party that is 525 | in the business of distributing software, under which you make payment 526 | to the third party based on the extent of your activity of conveying 527 | the work, and under which the third party grants, to any of the 528 | parties who would receive the covered work from you, a discriminatory 529 | patent license (a) in connection with copies of the covered work 530 | conveyed by you (or copies made from those copies), or (b) primarily 531 | for and in connection with specific products or compilations that 532 | contain the covered work, unless you entered into that arrangement, 533 | or that patent license was granted, prior to 28 March 2007. 534 | 535 | Nothing in this License shall be construed as excluding or limiting 536 | any implied license or other defenses to infringement that may 537 | otherwise be available to you under applicable patent law. 538 | 539 | 12. No Surrender of Others' Freedom. 540 | 541 | If conditions are imposed on you (whether by court order, agreement or 542 | otherwise) that contradict the conditions of this License, they do not 543 | excuse you from the conditions of this License. If you cannot convey a 544 | covered work so as to satisfy simultaneously your obligations under this 545 | License and any other pertinent obligations, then as a consequence you may 546 | not convey it at all. For example, if you agree to terms that obligate you 547 | to collect a royalty for further conveying from those to whom you convey 548 | the Program, the only way you could satisfy both those terms and this 549 | License would be to refrain entirely from conveying the Program. 550 | 551 | 13. Remote Network Interaction; Use with the GNU General Public License. 552 | 553 | Notwithstanding any other provision of this License, if you modify the 554 | Program, your modified version must prominently offer all users 555 | interacting with it remotely through a computer network (if your version 556 | supports such interaction) an opportunity to receive the Corresponding 557 | Source of your version by providing access to the Corresponding Source 558 | from a network server at no charge, through some standard or customary 559 | means of facilitating copying of software. This Corresponding Source 560 | shall include the Corresponding Source for any work covered by version 3 561 | of the GNU General Public License that is incorporated pursuant to the 562 | following paragraph. 563 | 564 | Notwithstanding any other provision of this License, you have 565 | permission to link or combine any covered work with a work licensed 566 | under version 3 of the GNU General Public License into a single 567 | combined work, and to convey the resulting work. The terms of this 568 | License will continue to apply to the part which is the covered work, 569 | but the work with which it is combined will remain governed by version 570 | 3 of the GNU General Public License. 571 | 572 | 14. Revised Versions of this License. 573 | 574 | The Free Software Foundation may publish revised and/or new versions of 575 | the GNU Affero General Public License from time to time. Such new versions 576 | will be similar in spirit to the present version, but may differ in detail to 577 | address new problems or concerns. 578 | 579 | Each version is given a distinguishing version number. If the 580 | Program specifies that a certain numbered version of the GNU Affero General 581 | Public License "or any later version" applies to it, you have the 582 | option of following the terms and conditions either of that numbered 583 | version or of any later version published by the Free Software 584 | Foundation. If the Program does not specify a version number of the 585 | GNU Affero General Public License, you may choose any version ever published 586 | by the Free Software Foundation. 587 | 588 | If the Program specifies that a proxy can decide which future 589 | versions of the GNU Affero General Public License can be used, that proxy's 590 | public statement of acceptance of a version permanently authorizes you 591 | to choose that version for the Program. 592 | 593 | Later license versions may give you additional or different 594 | permissions. However, no additional obligations are imposed on any 595 | author or copyright holder as a result of your choosing to follow a 596 | later version. 597 | 598 | 15. Disclaimer of Warranty. 599 | 600 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 601 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 602 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 603 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 604 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 605 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 606 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 607 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 608 | 609 | 16. Limitation of Liability. 610 | 611 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 612 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 613 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 614 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 615 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 616 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 617 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 618 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 619 | SUCH DAMAGES. 620 | 621 | 17. Interpretation of Sections 15 and 16. 622 | 623 | If the disclaimer of warranty and limitation of liability provided 624 | above cannot be given local legal effect according to their terms, 625 | reviewing courts shall apply local law that most closely approximates 626 | an absolute waiver of all civil liability in connection with the 627 | Program, unless a warranty or assumption of liability accompanies a 628 | copy of the Program in return for a fee. 629 | 630 | END OF TERMS AND CONDITIONS 631 | 632 | How to Apply These Terms to Your New Programs 633 | 634 | If you develop a new program, and you want it to be of the greatest 635 | possible use to the public, the best way to achieve this is to make it 636 | free software which everyone can redistribute and change under these terms. 637 | 638 | To do so, attach the following notices to the program. It is safest 639 | to attach them to the start of each source file to most effectively 640 | state the exclusion of warranty; and each file should have at least 641 | the "copyright" line and a pointer to where the full notice is found. 642 | 643 | 644 | Copyright (C) 645 | 646 | This program is free software: you can redistribute it and/or modify 647 | it under the terms of the GNU Affero General Public License as published 648 | by the Free Software Foundation, either version 3 of the License, or 649 | (at your option) any later version. 650 | 651 | This program is distributed in the hope that it will be useful, 652 | but WITHOUT ANY WARRANTY; without even the implied warranty of 653 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 654 | GNU Affero General Public License for more details. 655 | 656 | You should have received a copy of the GNU Affero General Public License 657 | along with this program. If not, see . 658 | 659 | Also add information on how to contact you by electronic and paper mail. 660 | 661 | If your software can interact with users remotely through a computer 662 | network, you should also make sure that it provides a way for users to 663 | get its source. For example, if your program is a web application, its 664 | interface could display a "Source" link that leads users to an archive 665 | of the code. There are many ways you could offer source, and different 666 | solutions will be better for different programs; see section 13 for the 667 | specific requirements. 668 | 669 | You should also get your employer (if you work as a programmer) or school, 670 | if any, to sign a "copyright disclaimer" for the program, if necessary. 671 | For more information on this, and how to apply and follow the GNU AGPL, see 672 | . 673 | --------------------------------------------------------------------------------