{"cells":[{"metadata":{},"cell_type":"markdown","source":"*not that we need to, but....\n*\n### It seems we can go even faster with [numpy.einsum](https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html)....\nfrom:\n> CPU times: user 140 ms, sys: 84 ms, total: 224 ms <br/>\n> Wall time: 220 ms\n\nto:\n> CPU times: user 108 ms, sys: 4 ms, total: 112 ms <br/>\n> Wall time: 107 ms\n\n---------------------------------------------------------------------\n\n\n**borrowing from** [chanran's kernel](https://www.kaggle.com/seriousran/just-speed-up-calculate-distance-from-benchmark)\n\n---------------------------------------------------------------------\nIn [Atomic Distance Benchmark](https://www.kaggle.com/inversion/atomic-distance-benchmark/output) kernel by [inversion](https://www.kaggle.com/inversion), <br/> I found '#(there's ways to speed this up!)'.\nI tried to find the faster way to calculate distance and share it. <br/>\nLet's research FASTER :)\n\nFrom\n> CPU times: user 7min 19s, sys: 9.25 s, total: 7min 28s <br/>\n> Wall time: 7min 28s\n\nTo\n> CPU times: user 412 ms, sys: 828 ms, total: 1.24 s <br/>\n> Wall time: 1.23 s"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\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":48,"outputs":[{"output_type":"stream","text":"['test.csv', 'mulliken_charges.csv', 'dipole_moments.csv', 'train.csv', 'structures.csv', 'magnetic_shielding_tensors.csv', 'potential_energy.csv', 'sample_submission.csv', 'scalar_coupling_contributions.csv', 'structures']\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\ntrain['dist'] = train.apply(lambda x: dist(x), axis=1)\ntest['dist'] = test.apply(lambda x: dist(x), axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_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":49,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Using np.linalg.norm"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n# This block is SPPED UP\ntrain['dist_speedup'] = np.linalg.norm(tr_a_min_b, axis=1)\ntest['dist_speedup'] = np.linalg.norm(te_a_min_b, axis=1)","execution_count":50,"outputs":[{"output_type":"stream","text":"CPU times: user 140 ms, sys: 84 ms, total: 224 ms\nWall time: 220 ms\n","name":"stdout"}]},{"metadata":{},"cell_type":"markdown","source":"### Using np.einsum"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n# This block is SPED UP a little more\n# np.sqrt(np.einsum('ij,ij->i', a_min_b, a_min_b))\ntrain['dist_speedup_einsum'] = np.sqrt(np.einsum('ij,ij->i', tr_a_min_b, tr_a_min_b))\ntest['dist_speedup_einsum'] = np.sqrt(np.einsum('ij,ij->i', te_a_min_b, te_a_min_b))","execution_count":51,"outputs":[{"output_type":"stream","text":"CPU times: user 108 ms, sys: 4 ms, total: 112 ms\nWall time: 107 ms\n","name":"stdout"}]},{"metadata":{},"cell_type":"markdown","source":"### Verify the Results"},{"metadata":{"trusted":true},"cell_type":"code","source":"train.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}