{"cells":[{"metadata":{},"cell_type":"markdown","source":"Try improving performance of these kernels https://www.kaggle.com/rio114/coulomb-interaction/notebook and https://www.kaggle.com/brandenkmurray/coulomb-interaction-parallelized/notebook"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"structure = pd.read_csv('../input/structures.csv')\ntraindf = pd.read_csv('../input/train.csv')\ntestdf = pd.read_csv('../input/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def compute_all_dist(x):   \n    #Apply compute_all_dist2 to each atom \n    return x.apply(compute_all_dist2,axis=1,x2=x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def compute_all_dist2(x,x2):\n    # atoms in the molecule which are not the processed one\n    notatom = x2[(x2.atom_index != x[\"atom_index\"])].reset_index(drop=True) \n    # processed atom\n    atom = x[[\"x\",\"y\",\"z\"]]\n    \n    # compute distance from to processed atom to each other\n    notatom[\"dist\"] = 1/((notatom[[\"x\",\"y\",\"z\"]].values - atom.values)**2).sum(axis=1)\n    \n    # sort atom per the smallest distance (highest 1/r**2) per group of C/H/N... \n    s = notatom.groupby(\"atom\")[\"dist\"].transform(lambda x : x.sort_values(ascending=False))\n    \n    # keep only the five nearest atoms per group of C/H/N...\n    index0, index1=[],[]\n    for i in notatom.atom.unique():\n        for j in range(notatom[notatom.atom == i].shape[0]):\n            if j < 5:\n                index1.append(\"dist_\" + i + \"_\" + str(j))\n            index0.append(j)\n    s.index = index0\n    s = s[s.index < 5]\n    s.index = index1\n    \n    return s","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def merge_with_struc(df, structure):\n    df = df \\\n        .merge(structure,\n               left_on=[\"molecule_name\",'atom_index_0'],right_on=[\"molecule_name\",\"atom_index\"]) \\\n        .merge(structure, left_on=[\"molecule_name\",'atom_index_1'],right_on=[\"molecule_name\",\"atom_index\"]) \\\n        .drop([\"atom_index_x\",\"atom_index_y\",\"atom_x\",\"atom_x\"],axis=1) \\\n        .sort_values([\"id\"]) \\\n        .reset_index(drop=True)\n    return df","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# First 100 molecules"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n# 10 times faster than the parallelized kernel\nsmallstruct = pd.concat([structure[structure.molecule_name.isin(structure.molecule_name.unique()[:100])][[\"molecule_name\",\"atom_index\",\"atom\"]],\n                         structure[structure.molecule_name.isin(structure.molecule_name.unique()[:100])].groupby(\"molecule_name\").apply(compute_all_dist)],\n                         axis=1).fillna(0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"smallstruct.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nmerge_with_struc(traindf,smallstruct).head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# All molecules in the structure.csv file"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nstructure = \\\n    pd.concat([structure[[\"molecule_name\",\"atom_index\",\"atom\"]],\n               structure.groupby(\"molecule_name\",sort=False).apply(compute_all_dist)], axis=1) \\\n    .fillna(0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"structure.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Merge with train and test"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ntraindf = merge_with_struc(traindf,structure)\ntestdf = merge_with_struc(testdf,structure)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"traindf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}