File size: 4,381 Bytes
8af1909
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from rdkit import Chem
from rdkit.Chem import AllChem
import h2o
from h2o.estimators import H2OGradientBoostingEstimator
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay

# Initialize H2O
h2o.init()

def featurize_smiles(smiles):
    try:
        mol = Chem.MolFromSmiles(smiles)
        fingerprint = AllChem.GetMorganFingerprintAsBitVect(mol, radius=2, nBits=1024)
        features = np.array(fingerprint)
        return features
    except Exception as e:
        print(f"Error featurizing SMILES: {smiles} -> {e}")
        return np.zeros(1024)  # Return a zero vector if there's an issue

# Specify the input and output column indices
input_column_index1 = 5  # Replace with index for the first reactant SMILES
input_column_index2 = 6  # Replace with index for the second reactant SMILES
output_column_index = 3  # Replace with your output (product) column index

# Prepare a H2OFrame for the first train-test split
file_path = '/Users/colestephens/Desktop/CodeFolders/ML_Dataset_Curation_Project/Split_data/buchwald.xlsx'
splits = pd.ExcelFile(file_path)

# Let's use the first split as an example
train_key = 'train_split_0'
test_key = 'test_split_0'

# Read the train and test sets
train_df = pd.read_excel(splits, sheet_name=train_key)
test_df = pd.read_excel(splits, sheet_name=test_key)

# Determine the column names using indices
input_column_name1 = train_df.columns[input_column_index1]
input_column_name2 = train_df.columns[input_column_index2]
output_column_name = train_df.columns[output_column_index]

# Featurize the SMILES columns for both reactants and concatenate the features
train_features1 = np.array([featurize_smiles(smiles) for smiles in train_df[input_column_name1]])
train_features2 = np.array([featurize_smiles(smiles) for smiles in train_df[input_column_name2]])
train_features = np.hstack((train_features1, train_features2))

test_features1 = np.array([featurize_smiles(smiles) for smiles in test_df[input_column_name1]])
test_features2 = np.array([featurize_smiles(smiles) for smiles in test_df[input_column_name2]])
test_features = np.hstack((test_features1, test_features2))

# Print message after successful featurization
print("Successfully converted SMILES to Morgan fingerprints for train and test sets.")

# Convert to H2OFrames
train_X = pd.DataFrame(train_features)
test_X = pd.DataFrame(test_features)

# Combine features with the target column
train_h2o = h2o.H2OFrame(pd.concat([train_X, train_df[[output_column_name]]], axis=1))
test_h2o = h2o.H2OFrame(pd.concat([test_X, test_df[[output_column_name]]], axis=1))

# Set the target and features
y = output_column_name
X = train_h2o.columns[:-1]  # All columns except the last one

# Initialize and train a Gradient Boosting model
gbm_model = H2OGradientBoostingEstimator(
    ntrees=50,
    max_depth=6,
    learn_rate=0.1,
    seed=1
)

gbm_model.train(x=X, y=y, training_frame=train_h2o)

# Evaluate model performance
performance = gbm_model.model_performance(test_data=test_h2o)
print(performance)

# Visualization: Variable Importance
gbm_model.varimp_plot()
plt.show()

# Obtain predictions and visualize the confusion matrix
predictions = gbm_model.predict(test_h2o).as_data_frame()
conf_matrix = confusion_matrix(test_df[output_column_name], predictions['predict'])

# Display confusion matrix
disp = ConfusionMatrixDisplay(confusion_matrix=conf_matrix)
disp.plot(cmap=plt.cm.Blues)
plt.title('Confusion Matrix')
plt.show()

# Function to predict the product from two input SMILES
def predict_product_from_smiles(smiles_str1, smiles_str2):
    features1 = featurize_smiles(smiles_str1)
    features2 = featurize_smiles(smiles_str2)
    features = np.hstack((features1, features2))
    feature_df = pd.DataFrame([features])
    feature_h2o = h2o.H2OFrame(feature_df)
    prediction = gbm_model.predict(feature_h2o)
    predicted_value = prediction.as_data_frame()['predict'][0]
    print(f"Predicted output for input SMILES '{smiles_str1}' + '{smiles_str2}': {predicted_value}")

# Example usage
#example_smiles1 = 'CCO'  # Replace with a first reactant SMILES string
#example_smiles2 = 'O=O'  # Replace with a second reactant SMILES string
#predict_product_from_smiles(example_smiles1, example_smiles2)

# Shutdown H2O
h2o.shutdown(prompt=False)