<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dr. Phyo Phyo Zin on Medium]]></title>
        <description><![CDATA[Stories by Dr. Phyo Phyo Zin on Medium]]></description>
        <link>https://medium.com/@phyophyokyawzin1?source=rss-ae3a61d0839c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5PknRzzCVQJ3mgSEvYOhHA.jpeg</url>
            <title>Stories by Dr. Phyo Phyo Zin on Medium</title>
            <link>https://medium.com/@phyophyokyawzin1?source=rss-ae3a61d0839c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:54:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@phyophyokyawzin1/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Build Virtual Chemical Libraries with Fragment Analogues: ChemX — Phyo Phyo Kyaw Zin]]></title>
            <link>https://medium.com/@phyophyokyawzin1/how-to-build-virtual-chemical-libraries-with-fragment-analogues-chemx-phyo-phyo-kyaw-zin-d3f1045a30e4?source=rss-ae3a61d0839c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3f1045a30e4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[rdkit]]></category>
            <category><![CDATA[drug-discovery]]></category>
            <category><![CDATA[cheminformatics]]></category>
            <category><![CDATA[chemicals]]></category>
            <dc:creator><![CDATA[Dr. Phyo Phyo Zin]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 05:11:38 GMT</pubDate>
            <atom:updated>2024-01-28T06:03:21.997Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Build Virtual Chemical Libraries with Fragment Analogues: ChemX — Phyo Phyo Kyaw Zin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q-jPzGG9NLSW72RT.png" /></figure><p>I want to introduce you to ChemX, a Python-based program I developed during <a href="https://devpost.com/software/chemx">a hackathon in 2019</a>. You can use it to build virtual chemical libraries using fragment analogues to the building blocks of the target molecule. Using the RDKit library, ChemX assembles chemically similar fragments to create a virtual chemical library.</p><h3>What ChemX Does</h3><p>ChemX takes a target chemical compound and breaks it down into synthetically accessible building blocks. These building blocks are then replaced with others fragments with similar chemical properties. The end result is a virtual chemical library with analogs of the original compound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*sZhSUAkt0x6njoQ5" /></figure><h3>How ChemX was Built</h3><p>ChemX was built in Python, using the RDKit library. The initial step involved creating a chemical database containing 10,000 experimentally synthesizable molecules from the ZINC15 database. These molecules were then fragmented into synthetic building blocks to construct a ‘chemical fragments’ database. ChemX takes a SMILES string (a digital format of a chemical compound) as input, converts it into a molecular object, and performs chemical manipulations to fragment the compound. The program then searches for fragments in the ‘chemical fragments’ database with similar chemical properties, using approximately 200 2D descriptors for comparison. The chosen fragments are used to generate different arrangements, creating new virtual compounds.</p><h3>What’s Next for ChemX</h3><p>ChemX has a lot of room for improvement; such as implementing better approaches for merging fragments, exploring different methods for finding similar substructures, and optimizing the generated chemical library. Some of the compounds enumerated will be junk, and will need additional fine-tuning and filtering to make them drug-like. Future plans involve incorporating additional predictors, evaluating toxicity, and assessing synthetic feasibilities. The agenda also includes developing steps for compound curation, duplicate removal, and refining the controlled joining of fragments.</p><h3>The Code: ChemX in Action</h3><p><strong>Note:</strong> The provided code represents the state of the ChemX project as it was during a hackathon event five years ago. While I updated the paths, I didn’t refine or update the code. However, I got it to run successfully. Use it as a starting point and consider refining it based on your specific needs.</p><p>Now, let’s dive into the code to see ChemX in action. You can also find the code related to this tutorial in this <a href="https://github.com/zinph/ChemX/tree/master">github repository</a>.</p><h4>1. Importing Libraries:</h4><pre>import re<br>import itertools<br>import numpy as np<br>import pandas as pd<br>from rdkit import Chem<br>from itertools import chain<br>from rdkit.Chem import FragmentCatalog<br>from rdkit.Chem import Descriptors<br>from rdkit.ML.Descriptors import MoleculeDescriptors<br>from rdkit.Chem import BRICS<br>import math</pre><p>These lines import various libraries necessary for chemical processing, data manipulation, and mathematical operations.</p><h4>2. ChemX Class Initialization:</h4><pre>class ChemX:<br>    def __init__(self, target_compound, name):<br>        self.target = target_compound<br>        self.calc = MoleculeDescriptors.MolecularDescriptorCalculator([x[0] for x in Descriptors._descList])<br>        self.chembank = open(&#39;data/&#39; + name, &#39;a+&#39;)<br>        self.templates = []<br> <br>        # Initialize the fragment database<br>        self.fragment_database()</pre><p>The ChemX class is defined to include the functionalities of ChemX. The __init__ method initializes key attributes, including the target compound, descriptor calculator, a file for storing generated compounds, and an empty list for templates. It also calls the fragment_database method for initialization.</p><h4>3. Fragment Database Initialization:</h4><pre>def fragment_database(self):<br>    # Load functional groups from file<br>    fName = &#39;data/FunctionalGroups.txt&#39;<br>    fparams = FragmentCatalog.FragCatParams(1, 6, fName)<br>    self.fcat = FragmentCatalog.FragCatalog(fparams)<br> <br>    # Load smiles from the ZINC database<br>    zinc_file = &#39;data/smiles_database.csv&#39;<br>    zinc_suppl = [i.split(&#39;,&#39;)[1] for i in open(zinc_file, &#39;r&#39;).read().splitlines()][1:]<br>    zinc_ms = [Chem.MolFromSmiles(i) for i in zinc_suppl]<br> <br>    # Generate synthetic fragment database<br>    pre_synthetic_frag_database = [BRICS.BRICSDecompose(i) for i in zinc_ms]<br>    self.synthetic_frag_database = list(set(chain.from_iterable(pre_synthetic_frag_database)))</pre><p>The fragment_database method initializes the fragment database by loading functional groups from a file, reading SMILES from the ZINC database, and generating a synthetic fragment database using BRICS decomposition.</p><h4>4. Fragment Writer Method:</h4><pre>def fragment_writer(self):<br>    # Write synthetic fragment database to file<br>    frg_manager = open(&#39;data/ZINC_fragments_10k&#39;, &#39;w&#39;)<br>    to_write = &#39;\n&#39;.join(self.synthetic_frag_database)<br>    frg_manager.write(to_write)<br>    frg_manager.close()</pre><p>The fragment_writer method writes the synthetic fragment database to a file named &#39;ZINC_fragments_10k&#39;.</p><h4>5. Tanimoto Similarity Calculation:</h4><pre>def tanimoto_similarity(self, mol1, mol2):<br>    # Tanimoto similarity calculation<br>    fp1 = AllChem.GetMorganFingerprint(mol1, 2)<br>    fp2 = AllChem.GetMorganFingerprint(mol2, 2)<br>    return DataStructs.TanimotoSimilarity(fp1, fp2)</pre><p>The tanimoto_similarity method calculates the Tanimoto similarity between two molecular fingerprints.</p><h4>6. Get Similar Fragments Method:</h4><pre>def get_similar_fragments(self, target_cpd, n=5, threshold=0.4):<br>    # Find similar fragments in the synthetic fragment database using Tanimoto similarity<br>    score_frg = []<br>    target_mol = Chem.MolFromSmiles(target_cpd)<br>    for i in self.synthetic_frag_database:<br>        cur_frag_mol = Chem.MolFromSmiles(i)<br>        similarity = self.tanimoto_similarity(target_mol, cur_frag_mol)<br>        if similarity &gt;= threshold:<br>            score_frg.append((i, similarity))<br>    sorted_tuples = sorted(score_frg, key=lambda x: x[-1], reverse=True)<br> <br>    chosen_fragments = [k[0] for k in sorted_tuples[:n]]<br>    return chosen_fragments</pre><p>The get_similar_fragments method finds similar fragments in the synthetic fragment database based on Tanimoto similarity, with a specified threshold.</p><h4>7. Fragment Target Method:</h4><pre>def fragment_target(self):<br>    # Decompose the target compound into fragments<br>    self.target_fragments = list(BRICS.BRICSDecompose(Chem.MolFromSmiles(self.target)))</pre><p>The fragment_target method decomposes the target compound into fragments using BRICS decomposition.</p><h4>8. Gather Fragments for All Target Fragments Method:</h4><pre>def gather_fragments_4alltargetfragments(self):<br>    # Gather replaceable fragments for all target fragments<br>    self.all_replaceable_fragments = []<br>    counter = 0<br>    for i in self.target_fragments:<br>        print(&#39;Searching the database for replaceable chemical fragment ...&#39; + str(counter + 1))<br>        target_ds = Chem.MolToSmiles(Chem.MolFromSmiles(i))<br>        self.all_replaceable_fragments.append(self.get_similar_fragments(target_ds, 5))<br>        counter += 1<br>    print(&#39;Populating all the possible fragments for different parts of your target drug ...&#39;)</pre><p>The gather_fragments_4alltargetfragments method collects replaceable fragments for all target fragments.</p><h4>9. Write Fragments File for Target Method:</h4><pre>def write_fragments_file_4Target(self, filename):<br>    # Write replaceable fragments to file<br>    print(&#39;Writing to file all the possible fragments for replacement ...&#39;)<br>    header = [&#39;fragment &#39; + str(u + 1) for u in range(len(self.target_fragments))]<br>    top_row = dict(zip(header, self.target_fragments))<br> <br>    max_len = max(len(fragment_list) for fragment_list in self.all_replaceable_fragments)<br>     <br>    # Create a DataFrame with a sufficient number of columns<br>    df_columns = header + [f&#39;extra_{i+1}&#39; for i in range(max_len - len(header))]<br>    cv_frame = pd.DataFrame(columns=df_columns)<br> <br>    # Populate the DataFrame with available data<br>    for idx, fragment_list in enumerate(self.all_replaceable_fragments):<br>        fragment_dict = dict(zip(header, fragment_list))<br>        fragment_dict.update({f&#39;extra_{i+1}&#39;: &#39;&#39; for i in range(len(fragment_list), max_len)})<br>        cv_frame = cv_frame.append(fragment_dict, ignore_index=True)<br> <br>    # Combine top row and DataFrame<br>    cv_frame = pd.concat([pd.DataFrame([top_row]), cv_frame], ignore_index=True)<br> <br>    # Save DataFrame to CSV<br>    cv_frame.to_csv(&#39;data/&#39; + filename + &#39;_fragments&#39;, index=False)</pre><p>The write_fragments_file_4Target method writes replaceable fragments to a file for further use.</p><h4>10. Generate Fragment Templates Method:</h4><pre>def generate_frag_templates(self):<br>    # Generate potential compound templates<br>    self.potential_cpd_templates = list(itertools.product(*self.all_replaceable_fragments))</pre><p>The generate_frag_templates method creates potential compound templates using the collected replaceable fragments.</p><h4>11. Collect Mini Frags from Each Template Method:</h4><pre>def collect_mini_frags_from_each_template(self, current_template):<br>    # Collect mini fragments from each template<br>    mini_frags = []<br>    for each in current_template:<br>        num_joints = each.count(&#39;*&#39;)<br>        numbers = re.findall(r&#39;\d+&#39;, each)<br>        possible_joints = [&#39;[&#39; + str(m) + &#39;*]&#39; for m in numbers]<br> <br>        for i in range(num_joints):<br>            for j in possible_joints:<br>                if j in each:<br>                    little_ones = each.replace(j, &#39;&#39;).replace(&#39;()&#39;, &#39;,&#39;).rstrip().split(&#39;,&#39;)<br>                    if little_ones not in mini_frags:<br>                        mini_frags.append(little_ones)<br>    mini_frags_flattened = list(itertools.chain(*mini_frags))<br>    return mini_frags_flattened</pre><p>The collect_mini_frags_from_each_template method extracts mini fragments from each compound template.</p><h4>12. Combine Fragments Method:</h4><pre>def combine_frag(self, max_compounds=10):<br>    # Combine fragments to generate compounds, storing only the first 50 compounds for each input<br>    self.generate_frag_templates()<br>    print(&#39;Merging fragments together to generate compounds...&#39;)<br> <br>    for current_template in self.potential_cpd_templates:<br>        fragms = [Chem.MolFromSmiles(x) for x in sorted(current_template)]<br>        ms = BRICS.BRICSBuild(fragms)<br>        for i, prod in enumerate(ms):<br>            if i &gt;= max_compounds:<br>                break<br> <br>            sampler = Chem.MolToSmiles(prod, True)<br>            print(i, sampler)<br>            if sampler not in self.templates:<br>                self.templates.append(sampler)<br>                self.chembank.write(sampler + &#39;\n&#39;)</pre><p>The combine_frag method merges fragments together to generate compounds, avoiding duplicates in the process.</p><h4>13. Main Function:</h4><pre>def main():<br>    # Run ChemX for a sample chemical<br>    mefloquine = &#39;OC(C1CCCCN1)C1=CC(=NC2=C(C=CC=C12)C(F)(F)F)&#39;<br>    print(&#39;Chemical accepted into the program.&#39;)<br> <br>    # Get the name for the chemical library<br>    name = input(&#39;Name of your chemical library: &#39;)<br> <br>    # Initialize and run ChemX<br>    sample = ChemX(mefloquine, name)<br>    sample.fragment_target()<br>    sample.gather_fragments_4alltargetfragments()<br>    sample.write_fragments_file_4Target(name)<br>    sample.combine_frag()<br> <br> <br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>The main function initializes and runs ChemX for a sample chemical, collecting replaceable fragments, writing them to a file, and finally, combining fragments to generate compounds.</p><h3>Conclusion</h3><p>Thanks for checking out ChemX! This simple Python tool, born during a 2019 hackathon, offers a taste of chemical compound exploration and drug discovery using RDKit. Though in early stages, it serves as an entry point for those intrigued by the field.</p><p>I hope you find this blogpost useful. Maybe, it brings a bit of insight and maybe even helps out your drug discovery work.</p><p>And if you’re curious about related projects:</p><ul><li><strong>PKS Enumerator:</strong> Design virtual macrolide libraries by permuting and adding building blocks with user-defined constraints. <a href="https://jcheminf.biomedcentral.com/articles/10.1186/s13321-018-0307-6/tables/1">Read more</a>.</li><li><strong>SIME (Synthetic Insight-based Macrolide Enumerator):</strong> Create in-silico macrolides with sugars, ensuring synthetic feasibility. Design libraries with specific motifs guided by biosynthetic insights. Specify a core structure, identify insertion points, and choose structural motifs and sugars. <a href="https://jcheminf.biomedcentral.com/articles/10.1186/s13321-020-00427-6">Read more</a>.</li></ul><p>For more content on data science, visualization, or cheminformatics, check out <a href="https://drzinph.com/category/cheminformatics/">my other blog posts</a>. Happy coding!</p><p><em>Originally published at </em><a href="https://drzinph.com/how-to-build-virtual-chemical-libraries-with-fragment-analogues-chemx/"><em>https://drzinph.com</em></a><em> on January 28, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3f1045a30e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Highlight Molecular Substructures: Celebrating Commonalities and Differences — Phyo Phyo…]]></title>
            <link>https://medium.com/@phyophyokyawzin1/how-to-highlight-molecular-substructures-celebrating-commonalities-and-differences-phyo-phyo-e13d0784a27d?source=rss-ae3a61d0839c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e13d0784a27d</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[rdkit]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cheminformatics]]></category>
            <dc:creator><![CDATA[Dr. Phyo Phyo Zin]]></dc:creator>
            <pubDate>Sat, 10 Jun 2023 23:37:27 GMT</pubDate>
            <atom:updated>2023-06-10T23:42:05.486Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Highlight Molecular Substructures: Celebrating Commonalities and Differences — Phyo Phyo Kyaw Zin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d52Taj1oKoPkRKde.jpeg" /></figure><h3>Introduction</h3><p>Today, we will dive into molecular substructure highlighting with RDKit — a powerful technique that illuminates the hidden intricacies within molecular compounds.</p><p>In this tutorial, I will be focusing on two things:</p><ol><li>Highlighting a common substructure among molecules.</li><li>Highlighting differences among molecules, given a common substructure.</li></ol><p>If you are interested in more Cheminformatics related tutorials, check my other blog posts <a href="https://drzinph.com/category/cheminformatics/">here</a>.</p><h3>Section 1: Understanding the Power of Structure Highlighting</h3><p>Before we jump into the technical aspects, let’s take a moment to appreciate why structure highlighting is a vital tool in the world of molecular visualization. By highlighting specific parts of a molecule, we can draw attention to key features, bond patterns, and functional groups that are important to the biological endpoint of interest. This technique not only enhances the visual aesthetics but also aids in effective communication of complex molecular structures.</p><h3>Section 2: Setting Up the Environment</h3><p>To get started, make sure you have Python, RDKit, and Pandas installed. The versions I am using are:</p><h3>Section 3: The Code</h3><p>The <a href="https://github.com/zinph/DataVisualizations/blob/master/highlight_substructures/highlight_substructures.ipynb">jupyter notebook</a> containing the tutorial is available in <a href="https://github.com/zinph/DataVisualizations/tree/master/highlight_substructures">github</a>.</p><p>First, import the libraries.</p><pre>from rdkit import Chem <br>from rdkit.Chem import Draw <br>from rdkit.Chem import PandasTools <br>from rdkit.Chem.Scaffolds.MurckoScaffold import GetScaffoldForMol <br>import pandas as pd</pre><p>Then, load a sample file containing Smiles. In this tutorial, I am using the data from one of my PhD projects ( <a href="https://pubs.acs.org/doi/10.1021/acs.jcim.0c00200">MD-QSAR</a> with Imatinib derivatives and pKi against BCR-ABL kinase protein.)</p><pre>df = pd.read_csv(&quot;smiles_pKi.csv&quot;) <br>df.head()</pre><p>Now, let’s add RDKit molecule objects to the pandas dataframe.</p><pre>PandasTools.AddMoleculeColumnToFrame(df,&#39;Smiles&#39;)</pre><p>During the tutorial, we will focus on extracting common substructures. Specifically, I will demonstrate the extraction of Murcko scaffolds from the dataset and work with the largest subset that shares the same Murcko scaffold. In your situation, you have the flexibility to manually specify either a core structure or a common substructure of interest within the molecules you are currently analyzing.</p><p>Let’s extract the Murcko skeletons.</p><pre>MurckoG = []<br>for each_mol in df[&quot;ROMol&quot;]:<br>    try:<br>        MurckoG.append(Chem.MolToSmiles(GetScaffoldForMol(each_mol)))<br>    except:<br>        MurckoG.append(each_mol)<br>df[&quot;Murcko&quot;] = MurckoG<br>df[&quot;Murcko&quot;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*mO7x25oP2YcoxT5s" /></figure><p>Now, let’s shift our attention to the most prevalent scaffold skeleton, which occurs 60 times. To do this, we will create a subset of our dataframe that contains only instances of this particular scaffold. Subsequently, we will visualize this common scaffold within the subset for better understanding and analysis.</p><pre>cur_scaf_smiles = &#39;O=C(Nc1cc2ccc(-c3ccccc3)cc2cn1)C1CC1&#39;<br>cur_scaf_df = df[df[&quot;Murcko&quot;]==cur_scaf_smiles]<br>mol_scaffold_of_interest = Chem.MolFromSmiles(cur_scaf_smiles)</pre><p>Okay, we are now prepared to visualize this scaffold within the subset. To begin, let’s generate a customized legend that incorporates the IDs alongside their corresponding pKi values. This will provide us with a comprehensive and informative visualization.</p><pre>custom_legend = [&#39; : &#39;.join(tup) for tup in list(zip(cur_scaf_df[&#39;ID&#39;], cur_scaf_df[&#39;pKi&#39;].astype(str)))]</pre><h3>Section 3.1. How to Highlight a Common Substructure among Molecules.</h3><p>To highlight the core structure among the molecule series, we proceed as follows:</p><ol><li>For each molecule, we identify the substructure match of the current scaffold and store the resulting matches.</li><li>Next, we generate a series of molecules and highlight the atoms matching the scaffold substructure within each molecule .</li></ol><pre>highlight_scaffold = [mMol.GetSubstructMatch(Chem.MolFromSmiles(cur_scaf_smiles)) for mMol in cur_scaf_df[&#39;ROMol&#39;]]<br>Draw.MolsToGridImage(cur_scaf_df[&#39;ROMol&#39;], <br>                     legends = custom_legend,<br>                     highlightAtomLists = highlight_scaffold, <br>                     molsPerRow=4,<br>                     subImgSize=(300,300), useSVG=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*GdA0mJVkX4qJJEo_" /></figure><h3>Section 3.2. How to Highlight Differences among Molecules.</h3><p>To emphasize the disparities within the series of molecules, we use the following approach:</p><ol><li>For each molecule, we identify and retain the substructure mismatches with the current scaffold. To facilitate this, I have developed a custom function called get_atoms_to_highlight, which enables the seamless visualization of atom differences between two structures.</li><li>In the next step, we generate a series of molecules and highlight the atoms corresponding to the variations within each molecule. This allows for clearer visualization and analysis of the contrasting features present in the molecule series.</li></ol><p>The function get_atoms_to_highlight takes in two molecules: a scaffold of interest and a compound of interest. Its purpose is to identify the atoms within the compound of interest that differ from the scaffold substructure. The function achieves this by first obtaining a complete list of atoms in the compound, then grouping the atoms that match the scaffold substructure. The final step involves subtracting the matched atoms from the complete atom list, resulting in a list of atoms to be highlighted. This list is valuable for conducting further analysis and visualization of the compound.</p><pre>def get_atoms_to_highlight(mol_scaffold_of_interest, mol_compound_of_interest):<br>    atom_list = [i for i in range(mol_compound_of_interest.GetNumAtoms())]<br>    grouped_common_atoms = mol_compound_of_interest.GetSubstructMatches(mol_scaffold_of_interest)<br>    flattened_grouped_common_atoms = list(sum(grouped_common_atoms, ()))<br>    atoms_to_highlight = list(set(atom_list) - set(flattened_grouped_common_atoms))<br>    return atoms_to_highlight</pre><p>In the following code snippet, we iterate through each molecule in the cur_scaf_df[&#39;ROMol&#39;] column, and apply the get_atoms_to_highlight function to identify the atoms that differ from our scaffold of interest. These differing atoms are then stored within each molecule&#39;s __sssAtoms attribute, and their corresponding lists are collected in hl_atom_list.</p><p>Then, we visualize a series of molecules and highlight the atoms corresponding to the variations within each molecule.</p><pre>hl_atom_list = []<br>for each_mol in cur_scaf_df[&#39;ROMol&#39;]:<br>    highlight = get_atoms_to_highlight(mol_scaffold_of_interest, each_mol)<br>    each_mol.__sssAtoms = highlight<br>    hl_atom_list.append(highlight)<br> <br>Draw.MolsToGridImage(cur_scaf_df[&#39;ROMol&#39;].values, <br>                     legends=custom_legend, <br>                     highlightAtomLists = hl_atom_list, <br>                     molsPerRow=5,<br>                     subImgSize=(300,300), <br>                     useSVG=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*BxdY6GHAVhwOAVHa" /></figure><h3>Conclusion:</h3><p>In this python tutorial about molecular substructure highlighting with RDKit, I covered two topics:</p><ul><li>how to highlight a common substructure among molecules by identifying substructure matches and generating a series of molecules with the highlighted scaffold.</li><li>how to highlight differences among molecules by employing a custom function that identifies and highlights the varying atoms between a scaffold of interest and a compound of interest.</li></ul><p>Thanks a lot for reading this blogpost tutorial! I hope you find this post useful. As always, I welcome constructive feedback and suggestions.</p><p><em>Originally published at </em><a href="https://drzinph.com/molecular-substructure-highlighting-with-rdkit/"><em>https://drzinph.com</em></a><em> on June 10, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e13d0784a27d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Generate Chemical Space Visualizations with R & Gephi — Phyo Phyo Kyaw Zin]]></title>
            <link>https://medium.com/@phyophyokyawzin1/how-to-generate-chemical-space-visualizations-with-r-gephi-phyo-phyo-kyaw-zin-1f2ef138e3a2?source=rss-ae3a61d0839c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f2ef138e3a2</guid>
            <category><![CDATA[network-visualization]]></category>
            <category><![CDATA[cheminformatics]]></category>
            <category><![CDATA[hierarchical-clustering]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Dr. Phyo Phyo Zin]]></dc:creator>
            <pubDate>Tue, 05 May 2020 10:30:49 GMT</pubDate>
            <atom:updated>2023-04-18T00:23:25.529Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Generate Chemical Space Visualizations with R &amp; Gephi — Phyo Phyo Kyaw Zin</h3><p>Today, I want to write a tutorial on how to generate chemical space visualizations using a combination of R and Gephi. I have found them to be a powerful way of assessing the chemical data and finding hidden patterns that could be crucial in estimating the biological endpoints of interest. Before we go on, let me hook you with an end result similar to what you will be creating at the end of this tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/0*98x8h354ikERCBT5" /><figcaption><em>Chemical space visualization of MacrolactoneDB using ECFP6 chemical descriptors, Euclidean distance, and Ward’s linkage. Each node is a chemical structure colored by its experimental value in the form of pChEMBL.</em></figcaption></figure><h3>Project Setup</h3><p>First and foremost, you will need to download <a href="https://gephi.org/">Gephi visualization tool,</a> and <a href="https://www.r-project.org/">R statistical language</a> (I use <a href="https://rstudio.com/products/rstudio/">Rstudio</a> for the IDE).</p><p>We will use a <a href="https://github.com/zinph/DataVisualizations/blob/master/network_visualizations/2Drdkit_chembl364.csv">sample chemical dataset</a> provided in this <a href="https://github.com/zinph/DataVisualizations/tree/master/network_visualizations">github repository</a> This file contains ChEMBL IDs, 2D RDKit descriptors generated using open-sourced library <a href="https://www.rdkit.org/docs/GettingStartedInPython.html">RDKit</a> in python, and “Aff” values (negative log of IC50s).</p><p>To generate Gephi networks, you will need two input file containing the following information:</p><ol><li>Node data</li><li>Edge data</li></ol><p>There are other variations like inputting adjacency matrix, but we will do it this way in this tutorial.</p><h3>Generating Network Data With Unsupervised Hierarchical Clustering</h3><p>First, we will perform unsupervised hierarchical clustering and generate network data (i.e. nodes and edges) using these chemical descriptors in R. This method will allow us to group molecules with similar chemical properties and/or structural fragments (depending on what type of chemical descriptors you use). From this, we will generate the edge file required for Gephi networks.</p><p>The R code (along with comments) associated with conducting hierarchical clustering and generating edges has been provided in <a href="https://github.com/zinph/DataVisualizations/blob/master/network_visualizations/gephi_network.R">gephi_network.R.</a></p><h4>Loading the Data Into R and Preparing It</h4><pre>### The code snippet below will allow you to install the required <br>### library &quot;phangorn&quot; if it hasn&#39;t already been installed.<br><br>list.of.packages &lt;- c(&quot;phangorn&quot;)<br>new.packages &lt;- list.of.packages[!(list.of.packages %in% installed.packages()[,&quot;Package&quot;])]<br>if(length(new.packages)) install.packages(new.packages)<br>lapply(list.of.packages, require, character.only = TRUE)<br>rm(list=ls())r</pre><pre>### Then, we load the file containing ChEMBL IDs, <br>### 2D rdkit descriptors and &quot;Aff&quot; values. <br><br>csv_data &lt;- read.csv(&#39;2Drdkit_chembl364.csv&#39;,header=TRUE,sep=&quot;,&quot;)</pre><pre>### We will subset the data so that we are clustering <br>### the chemicals based on 2D RDKit descriptors only. <br>### In other words, we don&#39;t want to include &quot;ID&quot; <br>### and &quot;Aff&quot; column, which is the biological endpoint <br>### that we are interested in predicting. <br><br>myvars &lt;- names(csv_data) %in% c(&quot;ID&quot;,&quot;Aff&quot;) <br>desc &lt;- csv_data[!myvars]</pre><pre>### We will then set the first column as row names. ###<br>rownames(desc) &lt;- csv_data[,1]</pre><p>At this point, we can normalize the columns. Note that if you are using binary data for fingerprints like MACCS or ECFP, you don’t need to do this step.</p><pre># Column normalization<br>matTrans &lt;- scale(desc)</pre><h4>Compute Distance Matrix and Run Unsupervised Hierarchical Clustering</h4><p>After normalizing the columns in the previous step, we will compute the distance matrix for the previously scaled dataset. The default for dist function is Euclidean distance. Based on the dataset and the goal of your project, you can tweak the <a href="https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/dist">distance functions</a> as you see fit.</p><pre>d &lt;- dist(matTrans)</pre><p>Now, we will apply unsupervised hierarchical clustering with ward linkage to our distance matrix.</p><pre>tupgma &lt;- upgma(d, method=&quot;ward.D2&quot;)</pre><h3>Generating Edge Data File</h3><p>At this point, we already have a network structure of our chemical dataset. We will then export the edges from our chemical network and prepare them for Gephi.</p><pre>write.csv2(tupgma$edge, file = &quot;edges.csv&quot;)</pre><p>Hopefully the process has been straightforward to follow so far. You should certainly familiarize yourself with distance methods and clustering algorithms so you can apply appropriate techniques based on your dataset. In this post, I am focusing on how we can generate the chemical network visualizations so I won’t be going over those details at this time.</p><p>Once you get to that point, you can prepare the input file for Gephi network. Open Excel, then go to “Data” tab and click “From Text/CSV”. Next, load the “edges.csv” that you previously generated (screenshot shown below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/0*ixdbsUBMiy4HHVoz" /></figure><p>Now, you will copy the two V1 and V2 columns into a new Microsoft excel file and name them “Source” and “Target” respectively. Then add two more columns named “Type” and “Weight”. Fill “Type” Column to the end of the data with “undirected”, and “Weight” with “1” (screenshot shown below). Save it as “gephi_edges.csv” file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*x6aHVbE3OUaBNbFG" /></figure><h3>Generating the Node Data File</h3><p>You have successfully prepped the edges file (“gephi_edges.csv”) required for generating the gephi network visualization. However, you still need to prep your nodes file but it’s much more straightforward.</p><p>Make a copy of the original file “2Drdkit_chembl364.csv” that you used for conducting unsupervised hierarchical clustering and name it “gephi_nodes.csv”. It should have a list of all the chemicals and their attributes that you might want to get incorporated in the network.</p><p>Insert a new column called “Id” at the very first column. This is specific to our network and different from the ids of compounds. These are node IDs, and Gephi will use that first column to connect the nodes, form edges and eventually a network. Then, fill that very first “Id” column with number series starting from 1 and incrementing with 1. For clarification purposes, we will rename the original “ID” column containing chembl ids to “ChEMBL_IDs” (screenshot shown for prepped nodes file).</p><p>You can remove some columns/attributes that you aren’t interested in incorporating into the network. Every column in that file can be used to color or change the size of the nodes in the gephi chemical network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/0*0GlCBG7EGhG59nc7" /></figure><h3>Importing the Data Into Gephi</h3><p>Now you have both nodes (“gephi_nodes.csv”) and edges (“gephi_edges.csv”) files ready for importing into Gephi.</p><p>Next, open up Gephi and create a new project. In the tab “Data Laboratory”, click “Import Spreadsheet” and upload your “gephi_nodes.csv” file. If you do everything correctly, it should detect that it’s a nodes file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/0*vcOVVDC_cj7T5O4v" /></figure><p>Click “Next” and “Finish” in the next two steps. Make sure to select “Append to existing workspace” when prompted. It may indicate some errors that are shown as SEVERE for some values or columns. In our example case, they come from columns I am not that interested in fixing, so I will ignore them. You can use your best judgement based on the datasets and the nature of the project that you are working on. Then, click “OK”. Now, you have imported your nodes file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/0*GN1Dxb5Vbz52dL1w" /></figure><p>Let’s import the edges file next. Click “Import Spreadsheet” again and select your “gephi_edges.csv” file. If correctly done, it will automatically detect that it’s the Edges table. Click “Next” and “Finish” in the next two steps. In the following step, make sure to choose “Append to existing workspace” and click “OK” (screenshot shown below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/0*1Dn9QcB47AEYTdM8" /></figure><h4>Generate Network Visualizations of Your Data With Gephi</h4><p>Then, go to overview tab. This is where you will manipulate and create network visualizations of your chemicals and how they look like. There are several default algorithms already installed (if not, you can download and install them) that you can apply to your network. Once you get to that point, it becomes your playground for creativity. You can use multiple layouts and adjust a lot of parameters based on your project needs. I usually like Multigravity ForceAtlas 2 and Yifan Hus layout algorithms for my chemical networks. Contraction and expansion are quite useful as well. I have attached several tutorial GIFs below for your convenience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*k5daJy-LITU8fzdI" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*YWI-Vl8iJitVH-pu" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*JDHyI-OuzWkgTWtS" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*xzKOD3ZSy07MPyyI" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*GPSlCYkuxq2-tJTU" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*h7IsIu3wOZOiPYip" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*wxAJSFoLpuPgHhts" /></figure><p>Below are three sample output files generated from this tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*m34zTQUDw7tDCfhT" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*l0fCsC-DBVjmlytX" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/0*eZeCxOPWK-cLVeBD" /></figure><h3>Conclusion</h3><p>Once you get into Gephi, there are already some tutorials out there that specifically focus on what type of visualizations you want, what you can do, etc. As far as I know, there hasn’t been a tutorial on how to actually prepare input chemical data for Gephi and I wanted to provide that missing link for Cheminformatics practitioners.</p><p>Please cite this blog if you use this technique for your research articles.</p><p>I will probably make a tutorial video on the entire process with narration and put it on youtube in the near future for those who prefer watching videos. I hope it has been helpful. Cheers!</p><p><em>Originally published at </em><a href="https://drzinph.com/chemical-space-visualizations/"><em>https://drzinph.com</em></a><em> on May 5, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f2ef138e3a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>