<jupyter_start><jupyter_text>**Installing Conda and rdkit**
 rdkit will enable us to calculate molecular descriptors<jupyter_code>! wget https://repo.anaconda.com/miniconda/Miniconda3-py37_4.8.2-Linux-x86_64.sh
! chmod +x Miniconda3-py37_4.8.2-Linux-x86_64.sh
! bash ./Miniconda3-py37_4.8.2-Linux-x86_64.sh -b -f -p /usr/local
! conda install -c rdkit rdkit -y
import sys
sys.path.append('/usr/local/lib/python3.7/site-packages/')<jupyter_output>--2021-01-07 06:00:51--  https://repo.anaconda.com/miniconda/Miniconda3-py37_4.8.2-Linux-x86_64.sh
Resolving repo.anaconda.com (repo.anaconda.com)... 172.16.31.10, 172.16.31.10, fc00:db20:35b:7399::5:8203, ...
Connecting to repo.anaconda.com (repo.anaconda.com)|172.16.31.10|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 85055499 (81M) [application/x-sh]
Saving to: ‘Miniconda3-py37_4.8.2-Linux-x86_64.sh.1’

Miniconda3-py37_4.8 100%[===================>]  81.12M   135MB/s    in 0.6s    

2021-01-07 06:00:52 (135 MB/s) - ‘Miniconda3-py37_4.8.2-Linux-x86_64.sh.1’ saved [85055499/85055499]

PREFIX=/usr/local
Unpacking payload ...
Collecting package metadata (current_repodata.json): - \ done
Solving environment: / - \ | / - \ | / - \ | failed with initial frozen solve. Retrying with flexible solve.
Solving environment: - \ | / - \ | / failed with repodata from current_repodata.json, will retry with next repodata source.
Collect[...]<jupyter_text>Loading the Bioactivity data<jupyter_code>import pandas as pd
from google.colab import drive
drive.mount('/content/drive', force_remount=True)
df = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/data/acetylcholinesterase_bioactivity_data_curated.csv')
df
! wget https://raw.githubusercontent.com/dataprofessor/data/master/acetylcholinesterase_03_bioactivity_data_curated.csv
DF = pd.read_csv('acetylcholinesterase_03_bioactivity_data_curated.csv')
DF
DF_no_smiles = DF.drop(columns = 'canonical_smiles')
smiles = []

for i in DF.canonical_smiles.tolist():
  cpd = str(i).split('.')
  cpd_max = max(cpd, key = len)
  smiles.append(cpd_max)

smiles = pd.Series(smiles, name = 'canonical_smiles')
DF_clean_smiles = pd.concat([DF_no_smiles,smiles], axis=1)
DF_clean_smiles<jupyter_output><empty_output><jupyter_text>**Calculate Lipinski descriptors**

Lipinski descriptor originates from the fact that <NAME> who is a scientist at Pfizer came up with a set of rules called the rule of five which was used to evaluate the **drug likeness** of compounds

The drug likeness is based on the key pharmacokinetic properties comprising of **absorption, distribution, metabolism and excretion** which has an acronym of **ADME** and this is also known as the **pharmacokinetic profiles** and so what essentially at me will tell us is that it will tell us the relative drug likeness of the compound whether it can be absorbed into the body distributed to the proper tissue and organs and become metabolized and eventually become excreted from the body.

The Lipinski's Rule stated the following:

*   Molecular weight < 500 Dalton
*   Octanol-water partition coefficient (LogP) < 5
*   Hydrogen bond donors < 5
*   Hydrogen bond acceptors < 10<jupyter_code>import numpy as np
from rdkit import Chem
from rdkit.Chem import Descriptors, Lipinski<jupyter_output><empty_output><jupyter_text>**Calculate descriptors**<jupyter_code>def lipinski(smiles, verbose=False): 

    moldata= []
    for elem in smiles:
        mol=Chem.MolFromSmiles(elem) 
        moldata.append(mol)
       
    baseData= np.arange(1,1)
    i=0  
    for mol in moldata:        
       
        desc_MolWt = Descriptors.MolWt(mol)
        desc_MolLogP = Descriptors.MolLogP(mol)
        desc_NumHDonors = Lipinski.NumHDonors(mol)
        desc_NumHAcceptors = Lipinski.NumHAcceptors(mol)
           
        row = np.array([desc_MolWt,
                        desc_MolLogP,
                        desc_NumHDonors,
                        desc_NumHAcceptors])   
    
        if(i==0):
            baseData=row
        else:
            baseData=np.vstack([baseData, row])
        i=i+1      
    
    columnNames=["MW","LogP","NumHDonors","NumHAcceptors"]   
    descriptors = pd.DataFrame(data=baseData,columns=columnNames)
    
    return descriptors
DF_lipinski = lipinski(DF_clean_smiles.canonical_smiles)
DF_lipinski
DFnew = pd.concat([DF,DF_lipinski], axis=1)
DFnew<jupyter_output><empty_output><jupyter_text>**Converting IC50 to pIC50**
To allow IC50 data to be more uniformly distributed, we will convert IC50 to the negative logarithmic scale which is essentially -log10(IC50).<jupyter_code># Will Take the IC50 values from the standard_value column and converts it from nM to M by multiplying the value by 10^-9
def pIC50(input):
    pIC50 = []

    for i in input['standard_value_norm']:
        molar = i*(10**-9) # Converts nM to M
        pIC50.append(-np.log10(molar))

    input['pIC50'] = pIC50
    x = input.drop('standard_value_norm', 1)
        
    return x
-np.log10( (10**-9)* 100000000 )

-np.log10( (10**-9)* 10000000000 )
# To normalize standard_value column
def norm_value(input):
    norm = []

    for i in input['standard_value']:
        if i > 100000000:
          i = 100000000
        norm.append(i)

    input['standard_value_norm'] = norm
    x = input.drop('standard_value', 1)
        
    return x
DF_norm = norm_value(DFnew)
DF_norm
DF_final = pIC50(DF_norm)
DF_final
DF_final.pIC50.describe()
DF_final.to_csv('acetylcholinesterase_04_bioactivity_data_pIC50.csv')
from google.colab import drive
drive.mount('/content/drive', force_remount=True)
!cp "/content/acetylcholinesterase_04_bioactivity_data_pIC50.csv" "/content/drive/My Drive/Colab Notebooks/data"
!ls
DF_ActInAct = DF_final[DF_final['class'] != 'intermediate']
DF_ActInAct
DF_ActInAct.to_csv('acetylcholinesterase_05_bioactivity_data_ActInAct_pIC50.csv')
!cp "/content/acetylcholinesterase_05_bioactivity_data_ActInAct_pIC50.csv" "/content/drive/My Drive/Colab Notebooks/data"<jupyter_output><empty_output><jupyter_text>**Exlploratory Data Analysis (Chemical Space Analysis) via Lepinski Descriptors**<jupyter_code>import seaborn as sns
sns.set(style='ticks')
import matplotlib.pyplot as plt<jupyter_output><empty_output><jupyter_text>**Frequency plot of Active and Inactive classes**<jupyter_code>plt.figure(figsize=(5.5, 5.5))

sns.countplot(x='class', data=DF_ActInAct)

plt.xlabel('Bioactivity class', fontweight='bold')
plt.ylabel('Frequency', fontweight='bold')

plt.savefig('plot_bioactivity_class.pdf')<jupyter_output><empty_output><jupyter_text>**Scatter plot - MW vs LogP**<jupyter_code>plt.figure(figsize=(5.5, 5.5))

sns.scatterplot(x='MW', y='LogP', data=DF_ActInAct, hue='class', size='pIC50', alpha=0.7)

plt.xlabel('MW', fontweight='bold')
plt.ylabel('LogP', fontweight='bold')
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0)
plt.savefig('plot_MW_vs_LogP.pdf')<jupyter_output><empty_output><jupyter_text>**Statistical Test - Mann Whitney U Test**<jupyter_code>def mannwhitney(descriptor, verbose=False):
  # Motivation - https://machinelearningmastery.com/nonparametric-statistical-significance-tests-in-python/
  from numpy.random import seed
  from numpy.random import randn
  from scipy.stats import mannwhitneyu

# seed the random number generator
  seed(1)

# actives and inactives
  selection = [descriptor, 'class']
  DF = DF_ActInAct[selection]
  active = DF[DF['class'] == 'active']
  active = active[descriptor]

  selection = [descriptor, 'class']
  DF = DF_ActInAct[selection]
  inactive = DF[DF['class'] == 'inactive']
  inactive = inactive[descriptor]

# compare samples
  stat, p = mannwhitneyu(active, inactive)
  #print('Statistics=%.3f, p=%.3f' % (stat, p))

# interpret
  alpha = 0.05
  if p > alpha:
    interpretation = 'Same distribution (fail to reject H0)'
  else:
    interpretation = 'Different distribution (reject H0)'
  
  results = pd.DataFrame({'Descriptor':descriptor,
                          'Statistics':stat,
                          'p':p,
                          'alpha':alpha,
                          'Interpretation':interpretation}, index=[0])
  filename = 'mannwhitneyu_' + descriptor + '.csv'
  results.to_csv(filename)

  return results
mannwhitney('pIC50')

mannwhitney('MW')
mannwhitney('LogP')
mannwhitney('NumHDonors')
mannwhitney('NumHAcceptors')<jupyter_output><empty_output><jupyter_text>**Box Plot pIC50 Value**<jupyter_code>plt.figure(figsize=(5.5, 5.5))

sns.boxplot(x = 'class', y = 'pIC50', data = DF_ActInAct)

plt.xlabel('Bioactivity class', fontweight='bold')
plt.ylabel('pIC50 value', fontweight='bold')

plt.savefig('plot_ic50.pdf')<jupyter_output><empty_output><jupyter_text>**Box Plot MW**<jupyter_code>plt.figure(figsize=(5.5, 5.5))

sns.boxplot(x = 'class', y = 'MW', data = DF_ActInAct)

plt.xlabel('Bioactivity class', fontweight='bold')
plt.ylabel('MW', fontweight='bold')

plt.savefig('plot_MW.pdf')<jupyter_output><empty_output><jupyter_text>**Box Plot LogP**<jupyter_code>plt.figure(figsize=(5.5, 5.5))

sns.boxplot(x = 'class', y = 'LogP', data = DF_ActInAct)
plt.xlabel('Bioactivity class', fontweight='bold')
plt.ylabel('LogP', fontweight='bold')

plt.savefig('plot_LogP.pdf')<jupyter_output><empty_output><jupyter_text>**Box plot NumHDonors**<jupyter_code>plt.figure(figsize=(5.5, 5.5))

sns.boxplot(x = 'class', y = 'NumHDonors', data = DF_ActInAct)

plt.xlabel('Bioactivity class', fontweight='bold')
plt.ylabel('NumHDonors', fontweight='bold')

plt.savefig('plot_NumHDonors.pdf')<jupyter_output><empty_output><jupyter_text>**Box plot NumHAcceptors**<jupyter_code>plt.figure(figsize=(5.5, 5.5))

sns.boxplot(x = 'class', y = 'NumHAcceptors', data = DF_ActInAct)

plt.xlabel('Bioactivity class', fontweight='bold')
plt.ylabel('NumHAcceptors', fontweight='bold')

plt.savefig('plot_NumHAcceptors.pdf')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13362541073384446, 'fraction_numerical': 0.03614457831325301, 'mean_word_length': 4.2586387434554975, 'pattern_counts': {'":': 0, '<': 61, '<?xml version=': 0, '>': 60, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 3, 'substrings_counts': 4, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '618502', 'license': 'MIT', 'n_tokens_mistral': 4022, 'n_tokens_neox': 3608, 'n_words': 703, 'path': "Acetylcholinesterase_Lipinski'sDescriptor_Chemical_Space_Analysis.ipynb", 'repo_name': 'kaustubhadixit/BioInformatics', 'size': '10051'}