# -*- coding: utf-8 -*-
"""covid19_v2.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1C69d5UJ5dPgWSHwiT9zjtO3RlMLXJ5OY
"""

!wget -c https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh
!chmod +x Miniconda3-latest-Linux-x86_64.sh
!time bash ./Miniconda3-latest-Linux-x86_64.sh -b -f -p /usr/local
!time conda install -q -y -c conda-forge rdkit

!pip install git+https://github.com/samoturk/mol2vec;

# Commented out IPython magic to ensure Python compatibility.
# %matplotlib inline

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
import sys
import os
warnings.filterwarnings("ignore")
sys.path.append('/usr/local/lib/python3.7/site-packages/')

from google.colab import drive
drive.mount("/content/drive")

from sklearn.linear_model import RidgeCV
from sklearn.model_selection import train_test_split

from sklearn.metrics import mean_absolute_error, mean_squared_error
from math import sqrt
def evaluation(model, X_test, y_test):
    prediction = model.predict(X_test)
    mae = mean_absolute_error(y_test, prediction)
    rmse = sqrt(mean_squared_error(y_test, prediction))
    
    plt.figure(figsize=(15, 10))
    plt.plot(prediction[:300], "red", label="prediction", linewidth=1.0)
    plt.plot(y_test[:300], 'green', label="actual", linewidth=1.0)
    plt.legend()
    plt.ylabel('Binding Affinity')
    plt.title("MAE {}, RMSE {}".format(round(mae, 4), round(rmse, 4)))
    plt.show()
    
    print('MAE score:', round(mae, 4))
    print('RMSE score:', round(rmse,4))

#Load the dataset and extract target values
mdf= pd.read_csv('/content/drive/My Drive/covid-19/train.csv');
target = mdf['Binding Affinity']
mdf.drop(columns='Binding Affinity',inplace=True)

from rdkit import Chem 
#Transforming SMILES to MOL
mdf['mol'] = mdf['SMILES sequence'].apply(lambda x: Chem.MolFromSmiles(x))

from gensim.models import word2vec
model = word2vec.Word2Vec.load('/content/drive/My Drive/covid-19/model_300dim.pkl')

from mol2vec.features import mol2alt_sentence, mol2sentence, MolSentence, DfVec, sentences2vec
from gensim.models import word2vec
print('Molecular sentence:', mol2alt_sentence(mdf['mol'][1], radius=1))
print('\nMolSentence object:', MolSentence(mol2alt_sentence(mdf['mol'][1], radius=1)))
print('\nDfVec object:',DfVec(sentences2vec(MolSentence(mol2alt_sentence(mdf['mol'][1], radius=1)), model, unseen='UNK')))

mdf['sentence'] = mdf.apply(lambda x: MolSentence(mol2alt_sentence(x['mol'], 1)), axis=1)

#Extracting embeddings to a numpy.array
#Note that we always should mark unseen='UNK' in sentence2vec() so that model is taught how to handle unknown substructures
mdf['mol2vec'] = [DfVec(x) for x in sentences2vec(mdf['sentence'], model, unseen='UNK')]
X = np.array([x.vec for x in mdf['mol2vec']])
y = target.values

X.shape

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.1, random_state=1)
ridge = RidgeCV(cv=5)
ridge.fit(X_train, y_train)
evaluation(ridge, X_test, y_test)

"""# Test dataset"""

mdf1= pd.read_csv('/content/drive/My Drive/covid-19/test.csv')
mdf1['mol'] = mdf1['SMILES sequence'].apply(lambda x: Chem.MolFromSmiles(x))

print('Molecular sentence:', mol2alt_sentence(mdf1['mol'][1], radius=1))
print('\nMolSentence object:', MolSentence(mol2alt_sentence(mdf1['mol'][1], radius=1)))
print('\nDfVec object:',DfVec(sentences2vec(MolSentence(mol2alt_sentence(mdf1['mol'][1], radius=1)), model, unseen='UNK')))

mdf1['sentence'] = mdf1.apply(lambda x: MolSentence(mol2alt_sentence(x['mol'], 1)), axis=1)

mdf1['mol2vec'] = [DfVec(x) for x in sentences2vec(mdf1['sentence'], model, unseen='UNK')]
X = np.array([x.vec for x in mdf1['mol2vec']])

def evaluation1(model, X):
    prediction = model.predict(X)
    return prediction;

# ridge = RidgeCV(cv=5)
# ridge.fit(X_train, y_train)
predict = evaluation1(ridge, X)

print(predict)

print(type(predict))

ans_df1 = pd.read_csv('/content/drive/My Drive/covid-19/test.csv')
ans_df1 = ans_df1['SMILES sequence']
print(ans_df1)

ans_df = pd.DataFrame(predict, columns=['Binding Affinity'])
print(ans_df)

result = pd.concat([ans_df1, ans_df], axis=1, sort=False)

print(result)

result.to_csv('submission.csv', index=None)




b8f4ac8ce7176e6b058eb0e1bce22d97a7a2ca38
# -*- coding: utf-8 -*-
"""covid19_v2.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1C69d5UJ5dPgWSHwiT9zjtO3RlMLXJ5OY
"""

!wget -c https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh
!chmod +x Miniconda3-latest-Linux-x86_64.sh
!time bash ./Miniconda3-latest-Linux-x86_64.sh -b -f -p /usr/local
!time conda install -q -y -c conda-forge rdkit

!pip install git+https://github.com/samoturk/mol2vec;

# Commented out IPython magic to ensure Python compatibility.
# %matplotlib inline

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
import sys
import os
warnings.filterwarnings("ignore")
sys.path.append('/usr/local/lib/python3.7/site-packages/')

from google.colab import drive
drive.mount("/content/drive")

from sklearn.linear_model import RidgeCV
from sklearn.model_selection import train_test_split

from sklearn.metrics import mean_absolute_error, mean_squared_error
from math import sqrt
def evaluation(model, X_test, y_test):
    prediction = model.predict(X_test)
    mae = mean_absolute_error(y_test, prediction)
    rmse = sqrt(mean_squared_error(y_test, prediction))
    
    plt.figure(figsize=(15, 10))
    plt.plot(prediction[:300], "red", label="prediction", linewidth=1.0)
    plt.plot(y_test[:300], 'green', label="actual", linewidth=1.0)
    plt.legend()
    plt.ylabel('Binding Affinity')
    plt.title("MAE {}, RMSE {}".format(round(mae, 4), round(rmse, 4)))
    plt.show()
    
    print('MAE score:', round(mae, 4))
    print('RMSE score:', round(rmse,4))

#Load the dataset and extract target values
mdf= pd.read_csv('/content/drive/My Drive/covid-19/train.csv');
target = mdf['Binding Affinity']
mdf.drop(columns='Binding Affinity',inplace=True)

from rdkit import Chem 
#Transforming SMILES to MOL
mdf['mol'] = mdf['SMILES sequence'].apply(lambda x: Chem.MolFromSmiles(x))

from gensim.models import word2vec
model = word2vec.Word2Vec.load('/content/drive/My Drive/covid-19/model_300dim.pkl')

from mol2vec.features import mol2alt_sentence, mol2sentence, MolSentence, DfVec, sentences2vec
from gensim.models import word2vec
print('Molecular sentence:', mol2alt_sentence(mdf['mol'][1], radius=1))
print('\nMolSentence object:', MolSentence(mol2alt_sentence(mdf['mol'][1], radius=1)))
print('\nDfVec object:',DfVec(sentences2vec(MolSentence(mol2alt_sentence(mdf['mol'][1], radius=1)), model, unseen='UNK')))

mdf['sentence'] = mdf.apply(lambda x: MolSentence(mol2alt_sentence(x['mol'], 1)), axis=1)

#Extracting embeddings to a numpy.array
#Note that we always should mark unseen='UNK' in sentence2vec() so that model is taught how to handle unknown substructures
mdf['mol2vec'] = [DfVec(x) for x in sentences2vec(mdf['sentence'], model, unseen='UNK')]
X = np.array([x.vec for x in mdf['mol2vec']])
y = target.values

X.shape

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.1, random_state=1)
ridge = RidgeCV(cv=5)
ridge.fit(X_train, y_train)
evaluation(ridge, X_test, y_test)

"""# Test dataset"""

mdf1= pd.read_csv('/content/drive/My Drive/covid-19/test.csv')
mdf1['mol'] = mdf1['SMILES sequence'].apply(lambda x: Chem.MolFromSmiles(x))

print('Molecular sentence:', mol2alt_sentence(mdf1['mol'][1], radius=1))
print('\nMolSentence object:', MolSentence(mol2alt_sentence(mdf1['mol'][1], radius=1)))
print('\nDfVec object:',DfVec(sentences2vec(MolSentence(mol2alt_sentence(mdf1['mol'][1], radius=1)), model, unseen='UNK')))

mdf1['sentence'] = mdf1.apply(lambda x: MolSentence(mol2alt_sentence(x['mol'], 1)), axis=1)

mdf1['mol2vec'] = [DfVec(x) for x in sentences2vec(mdf1['sentence'], model, unseen='UNK')]
X = np.array([x.vec for x in mdf1['mol2vec']])

def evaluation1(model, X):
    prediction = model.predict(X)
    return prediction;

# ridge = RidgeCV(cv=5)
# ridge.fit(X_train, y_train)
predict = evaluation1(ridge, X)

print(predict)

print(type(predict))

ans_df1 = pd.read_csv('/content/drive/My Drive/covid-19/test.csv')
ans_df1 = ans_df1['SMILES sequence']
print(ans_df1)

ans_df = pd.DataFrame(predict, columns=['Binding Affinity'])
print(ans_df)

result = pd.concat([ans_df1, ans_df], axis=1, sort=False)

print(result)

result.to_csv('submission.csv', index=None)



