{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\n\nimport cv2\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-06-14T20:47:44.423428Z","iopub.execute_input":"2022-06-14T20:47:44.423858Z","iopub.status.idle":"2022-06-14T20:47:45.573058Z","shell.execute_reply.started":"2022-06-14T20:47:44.423762Z","shell.execute_reply":"2022-06-14T20:47:45.572199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls ../input/bms-molecular-translation","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"execution":{"iopub.status.busy":"2022-06-14T20:47:46.921686Z","iopub.execute_input":"2022-06-14T20:47:46.922056Z","iopub.status.idle":"2022-06-14T20:47:47.719722Z","shell.execute_reply.started":"2022-06-14T20:47:46.922026Z","shell.execute_reply":"2022-06-14T20:47:47.718297Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Understand dataset with molecular 3D models\n\n## Contents\n\n1. [Introduction](#1)\n1. [Why we check 3D model?](#2)\n1. [About Structual fomula](#3)\n1. [Check 3D molecules on PubChem website](#4)\n1. [Check 3D models on kaggle notebook](#5)\n1. [Points to note for data augmentation with flip](#6)","metadata":{}},{"cell_type":"markdown","source":"<a id=\"1\"></a> <br>\n# <div class=\"alert alert-block alert-info\">Introduction</div>","metadata":{}},{"cell_type":"markdown","source":"## About this notebook\n\nIn this competiton, we have to detect InChI from [Structual fomula](https://en.wikipedia.org/wiki/Structural_formula) of molecules. You may have learned the structural formulae of simple molecules in school, but in this competition, relatively complex structural formulae will be introduced. Especially since data is given in the form of an image, we may feel free to use standard data augmentation methods like flip, but since molecules are essentially three-dimensional structures, there are pitfalls. To help our understand the characteristics of the data more effectively, we will use 3D model of a molecules to illustrate how to read the given image data.","metadata":{}},{"cell_type":"markdown","source":"<a id=\"2\"></a> <br>\n# <div class=\"alert alert-block alert-warning\">Why we check 3D model?</div> \n\n- Even if we are not familiar with chemical notation, it is easy to understand molecules. \n\nSome elements may be omitted in the skeletal stractual formula, so the molecule you imagine may not be actual. For example, hydrogen bonded to carbon may be omitted, but you can see them in the 3D model (3D models often show almost all of them).\n\n- We can develop intuition for molecular structures and aplly them to ML. \n\nItuition for molecular structures is important for this machine learning theme. For examle, if you do data augmentation, you may end up with different molecules ( see [Points to note for data augmentation with flip](#6) ) by inverting the images blindly. On the other hand, we can also come up with ideas for data augmentation methods that are unique to molecular structural expressions. For example, we can change the angle from which you look at molecules. Also, if you know how to write structural expressions, you may be able to generate images with various structural expressions from InChI(This may be too difficult). In short, rotating the 3D model around is essentially equal to data augmentation.","metadata":{}},{"cell_type":"markdown","source":"<a id=\"3\"></a> <br>\n# <div class=\"alert alert-block alert-success\">About Structual fomula</div> \n\nMolecules are made up of atoms bonded together. A structural formula describes the bonds between atoms. \n\nThere are There are many atoms. Knowing what elements (kinds of atoms) are present is necessary for understanding the structural formula. Check [Periodic table](https://en.wikipedia.org/wiki/Periodic_table) for the types of atoms.","metadata":{}},{"cell_type":"code","source":"#From https://www.kaggle.com/ihelon/molecular-translation-exploratory-data-analysis\ndef convert_image_id_2_path(image_id: str) -> str:\n    return \"../input/bms-molecular-translation/train/{}/{}/{}/{}.png\".format(\n        image_id[0], image_id[1], image_id[2], image_id \n    )\n\ndef visualize_train_image(image_id, label):\n    plt.figure(figsize=(10, 8))\n    \n    image = cv2.imread(convert_image_id_2_path(image_id))\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n    plt.imshow(image)\n    plt.title(f\"{label}\", fontsize=14)\n    plt.axis(\"off\")\n    \n    plt.show()\n    \ntrain_labels = pd.read_csv(\"../input/bms-molecular-translation/train_labels.csv\")\nindex = 1\nmolecule_image_id = train_labels[\"image_id\"].iloc[index]\nmolecule_InChI = train_labels[\"InChI\"].iloc[index]\nprint(molecule_image_id)\nprint(molecule_InChI)\n    \nvisualize_train_image(molecule_image_id, molecule_InChI)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-06-14T20:47:52.312190Z","iopub.execute_input":"2022-06-14T20:47:52.312711Z","iopub.status.idle":"2022-06-14T20:48:03.467191Z","shell.execute_reply.started":"2022-06-14T20:47:52.312679Z","shell.execute_reply":"2022-06-14T20:48:03.465917Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The image given as data is called skeletal formulas. It represents a molecule with several kinds of lines and element symbols.  As an example of a structural formula, here is an example of a simple molecule with two carbons. The first row is the name of the molecule, the second row is the carefully written structural formula, and the third row is the skeletal structural formula like the training data.\n\n<img src=\"https://raw.githubusercontent.com/tasotasoso/kaggle_media/main/How_to_check_conformation_of_Structural_formula/Example%20for%20structural%20formulas.png\" width=\"1000\">\n\n\nDepending on the case, more experienced chemists often write skeletal structural formulas because they require less effort to write. How many lines are written in a bond is the difference between [Bond order](https://en.wikipedia.org/wiki/Bond_order). In skeletal structural formulas, carbon or hydrogen are often omitted from the letters.","metadata":{}},{"cell_type":"markdown","source":"\"▼\" may be difficult to understand, but it shows which way the molecules are facing. Compare with the 3D model of a water molecule.\n\n<img src=\"https://raw.githubusercontent.com/tasotasoso/kaggle_media/main/How_to_check_conformation_of_Structural_formula/In%20front%20of%20or%20behind%20page%3F.png\" width=\"800\">\n\nDo you understand? When the molecule is flat on paper, it is written as just a bar line. On the other hand, if the molecule is placed so that it has depth, we use a \"▼\" to indicate this. In this way, it is possible to represent the three-dimensional structure of even complex molecules using only a pen and paper. Also, when considering chemical reaction mechanisms, we use this kind of notation because the 3D structure is one of the very important factor.","metadata":{}},{"cell_type":"markdown","source":"Here is a summary of the main notations introduced. If you know the correspondence between these notations and the 3D models (or actual molecules), you will be able to understand the data of this competition more clearly.\n\n<img src=\"https://raw.githubusercontent.com/tasotasoso/kaggle_media/main/How_to_check_conformation_of_Structural_formula/Main%20notation%20of%20structural%20formula.png\" width=\"800\">","metadata":{}},{"cell_type":"markdown","source":"<a id=\"4\"></a> <br>\n# <div class=\"alert alert-block alert-info\">Check 3D molecules on PubChem website</div> \n\n\nWe can check the chemical & Structual data by [PubChem](https://pubchem.ncbi.nlm.nih.gov). First, we get InChI expression from label. Let's take a look at the 3D model of the very first data (above structural formula) of the training data.\n\n<u>Note</u> \n\nThe PubChem images shown below was obtained on 3/3/2021 from the [official PubChem website](https://pubchem.ncbi.nlm.nih.gov).","metadata":{}},{"cell_type":"markdown","source":"## 0. Get InChI for molecule\n\nGet the InChI of the molecule we want to check as follows.","metadata":{}},{"cell_type":"code","source":"train_labels = pd.read_csv(\"../input/bms-molecular-translation/train_labels.csv\")\ntest_labels = pd.read_csv(\"../input/bms-molecular-translation/sample_submission.csv\")\nindex = 1\nmolecule_image_id = train_labels[\"image_id\"].iloc[index]\nmolecule_InChI = train_labels[\"InChI\"].iloc[index]\nprint(molecule_InChI)","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:48:14.671396Z","iopub.execute_input":"2022-06-14T20:48:14.671757Z","iopub.status.idle":"2022-06-14T20:48:23.240273Z","shell.execute_reply.started":"2022-06-14T20:48:14.671723Z","shell.execute_reply":"2022-06-14T20:48:23.239455Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Let's go PubChem site and search the molecure.\n\n## 1. Enter InChI to search box. And search.","metadata":{}},{"cell_type":"markdown","source":"<img src=\"https://raw.githubusercontent.com/tasotasoso/kaggle_media/main/How_to_check_conformation_of_Structural_formula/search_on_pubchem.JPG\" width=\"***500***\">","metadata":{}},{"cell_type":"markdown","source":"## 2. Select molecule","metadata":{}},{"cell_type":"markdown","source":"<img src=\"https://raw.githubusercontent.com/tasotasoso/kaggle_media/main/How_to_check_conformation_of_Structural_formula/search_result.JPG\" width=\"***500***\">","metadata":{}},{"cell_type":"markdown","source":"## 3. Check molecular models\n\nIt may be little hard to tell from the image, but you can check the 3D model in addition to the structural formula. Please click on the link below to check the results.\n[PubChem CID: 124916588](https://pubchem.ncbi.nlm.nih.gov/compound/124916588)","metadata":{}},{"cell_type":"markdown","source":"<img src=\"https://raw.githubusercontent.com/tasotasoso/kaggle_media/main/How_to_check_conformation_of_Structural_formula/indivisual_molecule.JPG\" width=\"***500***\">","metadata":{}},{"cell_type":"markdown","source":"<a id=\"5\"></a> <br>\n# <div class=\"alert alert-block alert-info\">Check 3D models on kaggle notebook</div> ","metadata":{}},{"cell_type":"markdown","source":"We can also check comformation on kaggle notebook with py3Dmol.","metadata":{}},{"cell_type":"code","source":"!pip install py3Dmol #used to create molecular diagarams","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:48:31.193818Z","iopub.execute_input":"2022-06-14T20:48:31.194381Z","iopub.status.idle":"2022-06-14T20:48:39.826529Z","shell.execute_reply.started":"2022-06-14T20:48:31.194334Z","shell.execute_reply":"2022-06-14T20:48:39.825289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import py3Dmol ","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:49:11.183581Z","iopub.execute_input":"2022-06-14T20:49:11.183988Z","iopub.status.idle":"2022-06-14T20:49:11.210874Z","shell.execute_reply.started":"2022-06-14T20:49:11.183938Z","shell.execute_reply":"2022-06-14T20:49:11.209783Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"To query molecure's information, we need PubChem CID. We can get like following. The CID almost asks like an ID to identify the certain molecule.","metadata":{}},{"cell_type":"markdown","source":"<img src=\"https://raw.githubusercontent.com/tasotasoso/kaggle_media/main/How_to_check_conformation_of_Structural_formula/get_pubchem_cid.JPG\" width=\"***500***\">","metadata":{}},{"cell_type":"code","source":"#Enter CID here!!!\ncid_for_query = 'cid:124916588'","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:49:17.170539Z","iopub.execute_input":"2022-06-14T20:49:17.170899Z","iopub.status.idle":"2022-06-14T20:49:17.175822Z","shell.execute_reply.started":"2022-06-14T20:49:17.170868Z","shell.execute_reply":"2022-06-14T20:49:17.174685Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"view = py3Dmol.view(width=680, height=300, query=cid_for_query, linked=False)\nview.setStyle({'stick': {}})\nview.setBackgroundColor('#f9f4fb')\nview.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:49:19.616544Z","iopub.execute_input":"2022-06-14T20:49:19.616873Z","iopub.status.idle":"2022-06-14T20:49:19.624224Z","shell.execute_reply.started":"2022-06-14T20:49:19.616845Z","shell.execute_reply":"2022-06-14T20:49:19.623305Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"It is also possible to view different types of 3D models.","metadata":{}},{"cell_type":"code","source":"view = py3Dmol.view(width=500, height=1000, query=cid_for_query, viewergrid=(3,1), linked=False)\nview.setStyle({'line': {'linewidth': 1}}, viewer=(0,0)) #line 3D model\nview.setStyle({'stick': {}}, viewer=(1,0)) #stick 3D model\nview.setStyle({'sphere': {}}, viewer=(2,0)) #sphere 3D model\nview.setBackgroundColor('#ebf4fb', viewer=(0,0))\nview.setBackgroundColor('#f9f4fb', viewer=(1,0))\nview.setBackgroundColor('#e1e1e1', viewer=(2,0))\nview.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:49:23.698251Z","iopub.execute_input":"2022-06-14T20:49:23.698593Z","iopub.status.idle":"2022-06-14T20:49:23.707762Z","shell.execute_reply.started":"2022-06-14T20:49:23.698562Z","shell.execute_reply":"2022-06-14T20:49:23.706263Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"6\"></a> <br>\n# <div class=\"alert alert-block alert-warning\">Points to note for data augmentation with flip</div> \n\n## There are some rotated data in dataset\n\nAccording to [Data page](https://www.kaggle.com/c/bms-molecular-translation/data).\n\n> The images provided (both in the training data as well as the test data) may be rotated to different angles, be at various resolutions, and have different noise levels.\n\nThere are not many, but if we check the data carefully, we can find that there are some rotated data.","metadata":{}},{"cell_type":"code","source":"#From https://www.kaggle.com/ihelon/molecular-translation-exploratory-data-analysis\ndef convert_image_id_2_path(image_id: str) -> str:\n    return \"../input/bms-molecular-translation/train/{}/{}/{}/{}.png\".format(\n        image_id[0], image_id[1], image_id[2], image_id \n    )\n\ndef visualize_train_image(image_id, label):\n    plt.figure(figsize=(10, 8))\n    \n    image = cv2.imread(convert_image_id_2_path(image_id))\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n    plt.imshow(image)\n    plt.title(f\"{label}\", fontsize=14)\n    plt.axis(\"off\")\n    \n    plt.show()\n    \ndef visualize_train_image_with_hflip(image_id, label):\n    plt.figure(figsize=(10, 8))\n    \n    image = cv2.imread(convert_image_id_2_path(image_id))\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    image = cv2.flip(image, 0) #this piece of code flips the data so it is on its correct side\n\n    plt.imshow(image)\n    plt.title(f\"InChI=????\", fontsize=14)\n    plt.axis(\"off\")\n    \n    plt.show()\n    \ndef convert_image_id_2_path_test(image_id: str) -> str:\n    return \"../input/bms-molecular-translation/test/{}/{}/{}/{}.png\".format(\n        image_id[0], image_id[1], image_id[2], image_id \n    )\n\ndef visualize_train_image_test(image_id, label):\n    plt.figure(figsize=(10, 8))\n    \n    image = cv2.imread(convert_image_id_2_path_test(image_id))\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n    plt.imshow(image)\n    plt.title(f\"{label}\", fontsize=14)\n    plt.axis(\"off\")\n    \n    plt.show()","metadata":{"_kg_hide-output":true,"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-06-14T20:49:31.027625Z","iopub.execute_input":"2022-06-14T20:49:31.027997Z","iopub.status.idle":"2022-06-14T20:49:31.038373Z","shell.execute_reply.started":"2022-06-14T20:49:31.027949Z","shell.execute_reply":"2022-06-14T20:49:31.037194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### train data","metadata":{}},{"cell_type":"code","source":"index = 1516695\nmolecule_image_id = train_labels[\"image_id\"].iloc[index]\nmolecule_InChI = train_labels[\"InChI\"].iloc[index]\nprint(molecule_InChI)\n    \nvisualize_train_image(molecule_image_id, molecule_InChI)\n#rotated diagram","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:49:36.713267Z","iopub.execute_input":"2022-06-14T20:49:36.713615Z","iopub.status.idle":"2022-06-14T20:49:36.948920Z","shell.execute_reply.started":"2022-06-14T20:49:36.713585Z","shell.execute_reply":"2022-06-14T20:49:36.947904Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### test data","metadata":{}},{"cell_type":"code","source":"index = 1009387\nmolecule_image_id_test = test_labels[\"image_id\"].iloc[index]\nmolecule_InChI_test = test_labels[\"InChI\"].iloc[index]\nprint(molecule_InChI_test)\n    \nvisualize_train_image_test(molecule_image_id_test, molecule_InChI_test)\n#This diagram is rotated","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:49:45.728297Z","iopub.execute_input":"2022-06-14T20:49:45.729229Z","iopub.status.idle":"2022-06-14T20:49:46.014017Z","shell.execute_reply.started":"2022-06-14T20:49:45.729176Z","shell.execute_reply":"2022-06-14T20:49:46.012879Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"To solve this problem, we can think of two strategies to start with.\n\n1. Add more rotated data to the training data.\n\n1. Return all test data to the correct (being able to read characters) orientation.\n\nThe strategy1 is a common way, but I expect that some augmentation method may cause bad results. I will explain why.","metadata":{}},{"cell_type":"markdown","source":"## Flip may cause bad effect?\n\nWe often use vertical and holizontal flip when we try rotation, like following.","metadata":{}},{"cell_type":"code","source":"index = 945\nmolecule_image_id = train_labels[\"image_id\"].iloc[index]\nmolecule_InChI = train_labels[\"InChI\"].iloc[index]\nprint(molecule_InChI)\n    \nvisualize_train_image(molecule_image_id, molecule_InChI)\n\n#presenting a sample visual","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:49:50.100639Z","iopub.execute_input":"2022-06-14T20:49:50.101017Z","iopub.status.idle":"2022-06-14T20:49:50.224062Z","shell.execute_reply.started":"2022-06-14T20:49:50.100965Z","shell.execute_reply":"2022-06-14T20:49:50.223102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-block alert-warning\">↓↓↓holizontal flip↓↓↓</div>","metadata":{}},{"cell_type":"code","source":"visualize_train_image_with_hflip(molecule_image_id, molecule_InChI)\n#horizontal flip rotation","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:49:57.324832Z","iopub.execute_input":"2022-06-14T20:49:57.325264Z","iopub.status.idle":"2022-06-14T20:49:57.430226Z","shell.execute_reply.started":"2022-06-14T20:49:57.325227Z","shell.execute_reply":"2022-06-14T20:49:57.429367Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The fact that the atomic symbols have been reversed this time may be problematic, but there are another pitfalls unique to this theme. This is because they are actually two different molecules. Original one is \"Methyl (2S)-2-amino-3-(4-fluorophenyl)sulfanylpropanoate\" and fliped one is \"Methyl (2R)-2-amino-3-(4-fluorophenyl)sulfanylpropanoate\".\n\n## What is Enantiomer?\n\n[Enantiomer](https://en.wikipedia.org/wiki/Enantiomer) is the stereoisomer that are mirror images of each other. They are considered completely different compounds. Not only do they differ geometrically, but they may also have different chemical properties.\n\nSimplifying, it can be described by the following tetrahedron. It's vertices of the tetrahedron are labeled A ~ D. We will think another tetrahedron with a mirrored surface. If you put them side by side, they will look like the figure below.","metadata":{}},{"cell_type":"markdown","source":"<img src=\"https://raw.githubusercontent.com/tasotasoso/kaggle_media/main/How_to_check_conformation_of_Structural_formula/enantiomer1.png\" width=\"700\">","metadata":{}},{"cell_type":"markdown","source":"So are these two the same thing? No, they are not. No matter how hard we try, we can't superimpose the labels of the vertices.\n\nAtoms are arranged to form a tetrahedron around carbon, which has only single bonds. Depending on the type of bonded atoms, phenomena such as the one we saw above can occur. In this molecule, the carbon marked with * is the [Stereocenter](https://en.wikipedia.org/wiki/Stereocenter), which is the center of this tetrahedron.","metadata":{}},{"cell_type":"markdown","source":"<img src=\"https://raw.githubusercontent.com/tasotasoso/kaggle_media/main/How_to_check_conformation_of_Structural_formula/enantiomer3.png\" width=\"300\">","metadata":{}},{"cell_type":"markdown","source":"Now let's compare \"Methyl (2S)-2-amino-3-(4-fluorophenyl)sulfanylpropanoate\" and \"Methyl (2R)-2-amino-3-(4-fluorophenyl)sulfanylpropanoate\". We can see that they are mirror images of each other, although they are different from the previous figure due to their preparation. Since it is a different molecule, we can see that the sublayers starting with /m in the InChI string are different.","metadata":{}},{"cell_type":"markdown","source":"<img src=\"https://raw.githubusercontent.com/tasotasoso/kaggle_media/main/How_to_check_conformation_of_Structural_formula/enantiomer2.png\" width=\"900\">","metadata":{}},{"cell_type":"markdown","source":"I have also prepared 3D models, so please try turning them around and see if the placement around the stereocenter overlaps.","metadata":{}},{"cell_type":"markdown","source":"### Methyl (2S)-2-amino-3-(4-fluorophenyl)sulfanylpropanoate","metadata":{}},{"cell_type":"code","source":"###### Methyl (2S)-2-amino-3-(4-fluorophenyl)sulfanylpropanoate\nview = py3Dmol.view(width=680, height=300, query=\"cid:94054932\", linked=False)\nview.setStyle({'stick': {}})\nview.setBackgroundColor('#f9f4fb')\nview.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:50:11.531540Z","iopub.execute_input":"2022-06-14T20:50:11.531956Z","iopub.status.idle":"2022-06-14T20:50:11.538020Z","shell.execute_reply.started":"2022-06-14T20:50:11.531919Z","shell.execute_reply":"2022-06-14T20:50:11.537172Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Methyl (2R)-2-amino-3-(4-fluorophenyl)sulfanylpropanoate","metadata":{}},{"cell_type":"code","source":"#Methyl (2R)-2-amino-3-(4-fluorophenyl)sulfanylpropanoate\nview = py3Dmol.view(width=680, height=300, query=\"cid:94054933\", linked=False)\nview.setStyle({'stick': {}})\nview.setBackgroundColor('#f9f4fb')\nview.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:50:20.864823Z","iopub.execute_input":"2022-06-14T20:50:20.865472Z","iopub.status.idle":"2022-06-14T20:50:20.871267Z","shell.execute_reply.started":"2022-06-14T20:50:20.865418Z","shell.execute_reply":"2022-06-14T20:50:20.870308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"----------------------","metadata":{}},{"cell_type":"markdown","source":"Takeaway: It's important to understand that mirrored or rotated structures are not the exact same InChl structure as seen by the above examples. There could be a slight change which will distinguish it from its mirrored counterpart.","metadata":{}},{"cell_type":"markdown","source":"I was curious, so I will focus on the length of InChI. Let's look at the longest and shortest molecules. It's hard to say, but it must be related to the size and complexity of the molecule.","metadata":{}},{"cell_type":"markdown","source":"### Shortest one","metadata":{}},{"cell_type":"code","source":"shortest_mol_idx = np.argmin(train_labels[\"InChI\"].apply(lambda x: len(x))) #np.argmin returns the values of the minimium integer value in the list\ntrain_labels[\"InChI\"][shortest_mol_idx]","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:50:25.453950Z","iopub.execute_input":"2022-06-14T20:50:25.454629Z","iopub.status.idle":"2022-06-14T20:50:26.636202Z","shell.execute_reply.started":"2022-06-14T20:50:25.454592Z","shell.execute_reply":"2022-06-14T20:50:26.634954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Methyl (2R)-2-amino-3-(4-fluorophenyl)sulfanylpropanoate\nview = py3Dmol.view(width=680, height=300, query=\"cid:13153\", linked=False)\nview.setStyle({'stick': {}})\nview.setBackgroundColor('#f9f4fb')\nview.show()\n#as seen by the image below, the size of the molecule depends on the string length of the InChI","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:50:28.548554Z","iopub.execute_input":"2022-06-14T20:50:28.548895Z","iopub.status.idle":"2022-06-14T20:50:28.554868Z","shell.execute_reply.started":"2022-06-14T20:50:28.548865Z","shell.execute_reply":"2022-06-14T20:50:28.554070Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Longest one","metadata":{}},{"cell_type":"code","source":"longest_mol_idx = np.argmax(train_labels[\"InChI\"].apply(lambda x: len(x)))\ntrain_labels[\"InChI\"][longest_mol_idx]","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:50:31.812334Z","iopub.execute_input":"2022-06-14T20:50:31.812672Z","iopub.status.idle":"2022-06-14T20:50:32.740238Z","shell.execute_reply.started":"2022-06-14T20:50:31.812645Z","shell.execute_reply":"2022-06-14T20:50:32.739004Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Unfortunately, there doesn't seem to be 3D model.","metadata":{}},{"cell_type":"code","source":"#Methyl (2R)-2-amino-3-(4-fluorophenyl)sulfanylpropanoate\nview = py3Dmol.view(width=680, height=300, query=\"cid:138197614\", linked=False)\nview.setStyle({'stick': {}})\nview.setBackgroundColor('#f9f4fb')\nview.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:50:34.454744Z","iopub.execute_input":"2022-06-14T20:50:34.455385Z","iopub.status.idle":"2022-06-14T20:50:34.462484Z","shell.execute_reply.started":"2022-06-14T20:50:34.455333Z","shell.execute_reply":"2022-06-14T20:50:34.461328Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We can write 2D model by rdkit.","metadata":{}},{"cell_type":"code","source":"!conda install -c rdkit rdkit -y","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2022-06-14T20:50:37.496006Z","iopub.execute_input":"2022-06-14T20:50:37.496395Z","iopub.status.idle":"2022-06-14T20:51:53.345098Z","shell.execute_reply.started":"2022-06-14T20:50:37.496359Z","shell.execute_reply":"2022-06-14T20:51:53.343715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import rdkit\n\n# https://www.kaggle.com/brodzik/drawing-molecules-with-rdkit-inchi-to-png\n\n#because a 3d model for the longest Inchi molecule won't show up, using rdkit we cans ee the 2d model for the longest one\n\nmol = rdkit.Chem.inchi.MolFromInchi(train_labels[\"InChI\"][longest_mol_idx])\nd = rdkit.Chem.Draw.rdMolDraw2D.MolDraw2DCairo(512, 512)\nd.drawOptions().useBWAtomPalette()\nd.DrawMolecule(mol)\nd.WriteDrawingText(\"0.png\")\nimg = cv2.imread(\"0.png\", cv2.IMREAD_GRAYSCALE)\nplt.figure(figsize=(20, 20))\nplt.imshow(img, \"gray\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:53:21.890657Z","iopub.execute_input":"2022-06-14T20:53:21.891092Z","iopub.status.idle":"2022-06-14T20:53:22.511335Z","shell.execute_reply.started":"2022-06-14T20:53:21.891055Z","shell.execute_reply":"2022-06-14T20:53:22.510452Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The distribution of the length of InChI is as follows.","metadata":{}},{"cell_type":"code","source":"sns.distplot(train_labels[\"InChI\"].apply(lambda x: len(x)))","metadata":{"execution":{"iopub.status.busy":"2022-06-14T20:53:32.270574Z","iopub.execute_input":"2022-06-14T20:53:32.271143Z","iopub.status.idle":"2022-06-14T20:53:44.228986Z","shell.execute_reply.started":"2022-06-14T20:53:32.271108Z","shell.execute_reply":"2022-06-14T20:53:44.228246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}