{"cells":[{"metadata":{},"cell_type":"markdown","source":"This is continuation of this kernel:\nhttps://www.kaggle.com/seriousran/just-speed-up-calculate-distance-from-benchmark\n\nsimple numpy vectorized function gives another 30% +/- performance boost.\n\nAdded even faster method with np.einsum from this kernel:\nhttps://www.kaggle.com/rakibilly/faster-distance-calculation-from-benchmark\n"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport scipy as sp\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n\nimport os\nprint(os.listdir(\"../input\"))\n\nfrom sklearn.model_selection import GroupKFold\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.ensemble import RandomForestRegressor\n\ntrain = pd.read_csv('../input/train.csv', index_col='id')\ntest = pd.read_csv('../input/test.csv', index_col='id')\n\nstructures = pd.read_csv('../input/structures.csv')\n\ndef map_atom_info(df, atom_idx):\n    df = pd.merge(df, structures, how = 'left',\n                  left_on  = ['molecule_name', f'atom_index_{atom_idx}'],\n                  right_on = ['molecule_name',  'atom_index'])\n    \n    df = df.drop('atom_index', axis=1)\n    df = df.rename(columns={'atom': f'atom_{atom_idx}',\n                            'x': f'x_{atom_idx}',\n                            'y': f'y_{atom_idx}',\n                            'z': f'z_{atom_idx}'})\n    return df\n\ntrain = map_atom_info(train, 0)\ntrain = map_atom_info(train, 1)\n\ntest = map_atom_info(test, 0)\ntest = map_atom_info(test, 1)","execution_count":1,"outputs":[{"output_type":"stream","text":"['dipole_moments.csv', 'potential_energy.csv', 'magnetic_shielding_tensors.csv', 'structures.csv', 'scalar_coupling_contributions.csv', 'structures', 'sample_submission.csv', 'mulliken_charges.csv', 'test.csv', 'train.csv']\n","name":"stdout"},{"output_type":"stream","text":"/opt/conda/lib/python3.6/site-packages/numpy/lib/arraysetops.py:569: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison\n  mask |= (ar1 == a)\n","name":"stderr"}]},{"metadata":{},"cell_type":"markdown","source":"# Calculate distance"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n# Engineer a single feature: distance vector between atoms\n#  (there's ways to speed this up!)\n\ndef dist(row):\n    return ( (row['x_1'] - row['x_0'])**2 +\n             (row['y_1'] - row['y_0'])**2 +\n             (row['z_1'] - row['z_0'])**2 ) ** 0.5\n\n#train['dist'] = train.apply(lambda x: dist(x), axis=1)\n#test['dist'] = test.apply(lambda x: dist(x), axis=1)\n# ","execution_count":2,"outputs":[{"output_type":"stream","text":"CPU times: user 0 ns, sys: 0 ns, total: 0 ns\nWall time: 10.5 µs\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n# This block is SPPED UP\n\ntrain_p_0 = train[['x_0', 'y_0', 'z_0']].values\ntrain_p_1 = train[['x_1', 'y_1', 'z_1']].values\ntest_p_0 = test[['x_0', 'y_0', 'z_0']].values\ntest_p_1 = test[['x_1', 'y_1', 'z_1']].values\n\ntr_a_min_b = train_p_0 - train_p_1\nte_a_min_b = test_p_0 - test_p_1","execution_count":3,"outputs":[{"output_type":"stream","text":"CPU times: user 168 ms, sys: 164 ms, total: 332 ms\nWall time: 330 ms\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ntrain['dist_np_linalg'] = np.linalg.norm(train_p_0 - train_p_1, axis=1)\ntest['dist_np_linalg'] = np.linalg.norm(test_p_0 - test_p_1, axis=1)","execution_count":14,"outputs":[{"output_type":"stream","text":"CPU times: user 160 ms, sys: 288 ms, total: 448 ms\nWall time: 448 ms\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n# python vectorized: even faster!\ntrain['dist_numpy'] = np.sqrt(np.sum((train_p_1 - train_p_0)**2, axis=1)) \ntest['dist_numpy'] = np.sqrt(np.sum((test_p_1 - test_p_0)**2, axis=1))","execution_count":12,"outputs":[{"output_type":"stream","text":"CPU times: user 152 ms, sys: 188 ms, total: 340 ms\nWall time: 340 ms\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ntrain['dist_einsum'] = np.sqrt(np.einsum('ij,ij->i', tr_a_min_b, tr_a_min_b))\ntest['dist_einsum'] = np.sqrt(np.einsum('ij,ij->i', te_a_min_b, te_a_min_b))","execution_count":9,"outputs":[{"output_type":"stream","text":"CPU times: user 96 ms, sys: 88 ms, total: 184 ms\nWall time: 180 ms\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":7,"outputs":[{"output_type":"execute_result","execution_count":7,"data":{"text/plain":"      molecule_name  atom_index_0     ...      dist_numpy dist_einsum\n0  dsgdb9nsd_000001             1     ...        1.091953    1.091953\n1  dsgdb9nsd_000001             1     ...        1.783120    1.783120\n2  dsgdb9nsd_000001             1     ...        1.783147    1.783147\n3  dsgdb9nsd_000001             1     ...        1.783157    1.783157\n4  dsgdb9nsd_000001             2     ...        1.091952    1.091952\n\n[5 rows x 16 columns]","text/html":"<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>molecule_name</th>\n      <th>atom_index_0</th>\n      <th>atom_index_1</th>\n      <th>type</th>\n      <th>scalar_coupling_constant</th>\n      <th>atom_0</th>\n      <th>x_0</th>\n      <th>y_0</th>\n      <th>z_0</th>\n      <th>atom_1</th>\n      <th>x_1</th>\n      <th>y_1</th>\n      <th>z_1</th>\n      <th>dist_speedup</th>\n      <th>dist_numpy</th>\n      <th>dist_einsum</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>dsgdb9nsd_000001</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1JHC</td>\n      <td>84.8076</td>\n      <td>H</td>\n      <td>0.002150</td>\n      <td>-0.006031</td>\n      <td>0.001976</td>\n      <td>C</td>\n      <td>-0.012698</td>\n      <td>1.085804</td>\n      <td>0.008001</td>\n      <td>1.091953</td>\n      <td>1.091953</td>\n      <td>1.091953</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>dsgdb9nsd_000001</td>\n      <td>1</td>\n      <td>2</td>\n      <td>2JHH</td>\n      <td>-11.2570</td>\n      <td>H</td>\n      <td>0.002150</td>\n      <td>-0.006031</td>\n      <td>0.001976</td>\n      <td>H</td>\n      <td>1.011731</td>\n      <td>1.463751</td>\n      <td>0.000277</td>\n      <td>1.783120</td>\n      <td>1.783120</td>\n      <td>1.783120</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>dsgdb9nsd_000001</td>\n      <td>1</td>\n      <td>3</td>\n      <td>2JHH</td>\n      <td>-11.2548</td>\n      <td>H</td>\n      <td>0.002150</td>\n      <td>-0.006031</td>\n      <td>0.001976</td>\n      <td>H</td>\n      <td>-0.540815</td>\n      <td>1.447527</td>\n      <td>-0.876644</td>\n      <td>1.783147</td>\n      <td>1.783147</td>\n      <td>1.783147</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>dsgdb9nsd_000001</td>\n      <td>1</td>\n      <td>4</td>\n      <td>2JHH</td>\n      <td>-11.2543</td>\n      <td>H</td>\n      <td>0.002150</td>\n      <td>-0.006031</td>\n      <td>0.001976</td>\n      <td>H</td>\n      <td>-0.523814</td>\n      <td>1.437933</td>\n      <td>0.906397</td>\n      <td>1.783157</td>\n      <td>1.783157</td>\n      <td>1.783157</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>dsgdb9nsd_000001</td>\n      <td>2</td>\n      <td>0</td>\n      <td>1JHC</td>\n      <td>84.8074</td>\n      <td>H</td>\n      <td>1.011731</td>\n      <td>1.463751</td>\n      <td>0.000277</td>\n      <td>C</td>\n      <td>-0.012698</td>\n      <td>1.085804</td>\n      <td>0.008001</td>\n      <td>1.091952</td>\n      <td>1.091952</td>\n      <td>1.091952</td>\n    </tr>\n  </tbody>\n</table>\n</div>"},"metadata":{}}]},{"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}