/
conformal_skin_prediction.py
803 lines (551 loc) · 27.6 KB
/
conformal_skin_prediction.py
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
# -*- coding: utf-8 -*-
#conformal_skin_prediction.py
__doc__ = """ Description:
With this script you can create and predict conformal models
of skin penetration.
The data is imported from a .csv file separated using ;
Default option is to include data from Baba et al. 2015
DOI: 10.1007/s11095-015-1629-y
The csv file includes the columns:
Compounds - compound names
Observed - Experimental value for skin permeability (log Kp)
Ref - Number that maps the experimental value to a reference article
smiles - Smiles code that characterizes the compound
Use the flag -verbose to get output with descriptions.
Conformal prediction is used to calculate prediction ranges
sklearn.neighbors.KNeighborsRegressor used K = 5 (default setting)
Martin Lindh 2016
"""
##########################################
# Import modules:
import sys
import argparse
import pandas
from pandas import DataFrame
import rdkit
from rdkit import Chem
from rdkit.Chem import Descriptors
import numpy as np
from numpy.core.numeric import asanyarray
from numpy import mean
import nonconformist
from nonconformist.icp import IcpRegressor
from nonconformist.nc import NormalizedRegressorNc
from nonconformist.nc import RegressorNc, abs_error, abs_error_inv
import sklearn
from sklearn.ensemble import RandomForestRegressor
from sklearn.svm import SVR
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
from sklearn.metrics import mean_absolute_error
from sklearn.decomposition import PCA
from sklearn import preprocessing
from math import sqrt
import random
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import dill
import copy
# -----------------------------------------------------------------------------
parser = argparse.ArgumentParser()
parser.add_argument('-verbose', help='Get verbose output', action='store_true')
parser.add_argument('-i','-infile', help='Define the input file. Default:baba_jan_2015_smiles.csv', default='C:\Users\Martin\Documents\Magnus_Lundborg\Nya_data/baba_jan_2015_smiles.csv')
parser.add_argument('-c','-conformal_model', action ='store_true', help='Create a new conformal predictions model')
parser.add_argument('-m', '-model_type', default = 'RF', help = 'Define model algorithm, RF (default) or SVM')
parser.add_argument('-t', '-test_set', default='random', help = 'Use: random (default), full_model, existing, reference')
parser.add_argument('-p', '-predict_model', action='store_true', help="Predict values for one or many smile-codes using single conformal model")
parser.add_argument('-d','-data_file_name', help='Output file name. File with descriptor data', default='data_with_descriptors.csv')
parser.add_argument('-num_models', default='100', help='Number of models to create. Default = 100')
parser.add_argument('-reference', default=1, help='Use this reference as test_set. Default= 1')
parser.add_argument('-significance', default=0.2, help='Set the significance level of the conformal prediction. Default = 0.2')
parser.add_argument('-phys','-physiochemical_descriptors', default = False, help='Print out data about descriptors. Default = false')
parser.add_argument('-smile', default = 'CCO', help ='Smiles for which skin permeability prediction is requested')
parser.add_argument('-plot', action ='store_true', help='Plot experimental versus predicted')
parser.add_argument('-pca','-PCA', action ='store_true', help='Create a PCA')
args = parser.parse_args()
# -----------------------------------------------------------------------------
#Plot version numbers for Python, matplotlib, pandas and numpy
if args.verbose:
print(' ')
print(' ################### Versions ################### ')
print('Python version:\n{}'.format(sys.version))
print('matplotlib version: {}'.format(matplotlib.__version__))
print('pandas version: {}'.format(pandas.__version__))
print('sklearn version: {}'.format(sklearn.__version__))
print('numpy version: {}'.format(np.__version__))
print('RDkit version: {}'.format(rdkit.__version__))
print('nonconformist version: {}'.format(nonconformist.__version__))
print('dill version: {}'.format(dill.__version__))
# -----------------------------------------------------------------------------
def read_data(infile):
"""
Description - Reads CSV-file to create a data frame (Pandas)
"""
if args.verbose:
print('########################## Read CSV-file to create data frame ##########################')
file_data = pandas.read_csv(infile, sep = ';',header=2)
if args.verbose:
print(file_data.columns)
return file_data
def calculate_descriptors(smiles):
"""
Description - Calculate descriptors using RDkit
smile','logP','PSA','MolWt','RingCount','HeavyAtomCount','NumRotatableBonds
"""
if args.verbose:
print('########################## Calculate_Descriptors ##########################')
descriptors_df = DataFrame(columns=('smile','logP','PSA','MolWt','RingCount','HeavyAtomCount','NumRotatableBonds'))
i = 0
for smile in smiles:
#print smile
try:
m = Chem.MolFromSmiles(smile)
except:
print(smile)
print('error')
try:
logP = Chem.Descriptors.MolLogP(m)
PSA = Chem.Descriptors.TPSA(m)
MolWt = Chem.Descriptors.MolWt(m)
RingCount = Chem.Descriptors.RingCount(m)
HeavyAtomCount = Chem.Descriptors.HeavyAtomCount(m)
NumRotatableBonds = Chem.Descriptors.NumRotatableBonds(m)
except:
print('Error computing descriptors')
logP = 0
PSA = 0
MolWt = 0
RingCount = 0
HeavyAtomCount = 0
NumRotatableBonds = 0
descriptors_df.loc[i] = ([smile,logP,PSA,MolWt,RingCount,HeavyAtomCount,NumRotatableBonds])
i +=1
if args.verbose:
print(descriptors_df.columns)
return descriptors_df
def create_indices_test_training_calibration(data):
"""
Description - Create training, calibration and test indices
Use existing test and training set
(file training)*0.8 training
(file training)*0.2 calibration set
(file test) test
Random selection - validation
60 % train
20 % calibrate
20 % test
Reference test-set
x/total %
(total - x)*0.8 train
(total - x)*0.2 calibration
Model creation
80 % train
20 % calibration
"""
train = []
calibrate = []
test = []
if args.verbose:
print('################## Setup training, calibration and test indices ##########')
print(args.t)
if args.t == 'existing':
if args.verbose:
print('Using existing sets')
blob = []
test = data.loc[data['Class'] == 'test'].index.tolist()
blob = data.loc[data['Class'] == 'training'].index.tolist()
calibrate = random.sample(blob, int(len(blob)*0.2))
train = [x for x in blob if x not in calibrate]
if args.t == 'random':
if args.verbose:
print('Creating random sets')
idx = np.random.permutation(len(data))
train = idx[:int(idx.size * 3 / 5)+1]
calibrate = idx[int(idx.size * 3 / 5)+1:int(4 * idx.size / 5 )+1]
test = idx[int(4 * idx.size / 5)+1:]
if args.t == 'reference':
if args.verbose:
print('Creating test set from reference: '+str(args.reference))
#print(data['Ref.'])
test = data.loc[data['Ref.'] == int(args.reference)].index.tolist()
print(len(test))
blob = data.loc[data['Ref.'] != int(args.reference)].index.tolist()
calibrate = random.sample(blob, int(len(blob)*0.2))
train = [x for x in blob if x not in calibrate]
if args.t == 'full_model':
if args.verbose:
print('Creating sets for full model')
test = []
idx = np.random.permutation(len(data))
train = idx[:int(idx.size * 4 / 5)]
calibrate = idx[int(4 * idx.size / 5):]
if args.verbose:
print('Size of sets:')
print('Train: '+str(len(train)))
print('Calibration: '+str(len(calibrate)))
print('Test: '+str(len(test)))
return train, calibrate, test
def create_train_test_calibrate_sets(data, descriptors_df, train_i, calibrate_i, test_i):
"""
Description - Create training and test sets.
Creates X (descriptors) and Y (permeability) values from indices and data.
"""
# print('########################## Create training and test sets. ##########################')
# Create y with permeability data
permiability_y = data['Observed']
ytrain = permiability_y[train_i] #DEBUG
ytest = permiability_y[test_i] #DEBUG
ycalibrate = permiability_y[calibrate_i] #DEBUG
# Create X with calculated descriptor data
data_X = descriptors_df.iloc[:,1:]
Xtrain = data_X.iloc[train_i]
Xtest = data_X.iloc[test_i]
Xcalibrate = data_X.iloc[calibrate_i]
return Xtrain, Xtest, Xcalibrate, ytrain, ytest, ycalibrate
def write_csv_with_data(data, descriptors_df, newfilename):
'''
Description - Writes a csv-file with data two data-frames
'''
print('################## Write data to CSV-file #################')
connected_data = pandas.concat([data, descriptors_df], axis=1)
connected_data.to_csv(newfilename, sep=';')
return True
def randomize_new_indices(train_i, calibrate_i, test_i, data, i):
"""
Description - Create new indices for two indices arrays.
"""
#print('################## Setup new training and calibration and indices ##########')
if args.t == 'reference': # or args.t == 'random':
a = []
for each in train_i:
a.append(each)
b = []
for each in calibrate_i:
b.append(each)
c = []
for each in test_i:
c.append(each)
A = a + b + c
if args.t == 'full_model' or args.t == 'existing' or args.t == 'random':
a = []
for each in train_i:
a.append(each)
b = []
for each in calibrate_i:
b.append(each)
A = a + b
idx = np.random.permutation(A)
if args.t == 'random':
#train = idx[:int(idx.size * 3 / 5)]
#calibrate = idx[int(idx.size * 3 / 5):int(4 * idx.size / 5 )]
#test = idx[int(4 * idx.size / 5):]
#NEW RANDOM
train = idx[:int(idx.size * 4 / 5)]
calibrate = idx[int(4 * idx.size / 5):]
test = test_i
if args.t == 'full_model' or args.t == 'existing':
train = idx[:int(idx.size * 4 / 5)]
calibrate = idx[int(4 * idx.size / 5):]
test = test_i
if args.t == 'reference':
test = data.loc[data['Ref.'] == (int(i) % data['Ref.'].max() + 1)].index.tolist()
blob = data.loc[data['Ref.'] != int(i)].index.tolist()
calibrate = random.sample(blob, int(len(blob)*0.2))
train = [x for x in blob if x not in calibrate]
if args.verbose:
#For DEBUG
#print('Creating new test set from reference: '+str((int(i) % data['Ref.'].max() + 1)))
#print('Compounds in new test set: '+str(test))
pass
return list(train), list(calibrate), list(test)
def calculate_prediction_y_and_error(median_values):
"""
Description - Get median predicted values and size of prediction range
"""
Y_pred_median = []
error_median = []
for each in median_values:
Y_pred_median.append((each[0]+each[1])/2)
error_median.append((abs(each[0])+abs(each[1]))/2 - abs(each[1]))
return Y_pred_median, error_median
def save_models(ICPs):
"""
Description - Saves the classifiers using dill
"""
if args.verbose:
print('########################## Save Classifiers ##########################')
outfile = 'filename.pkl'
with open(outfile, 'wb') as out_strm:
s = dill.dump(ICPs, out_strm)
return True
def load_models():
"""
Description - Load a previosly saved classifier from file using dill
"""
if args.verbose:
print('########################## Load Classifier ##########################')
infile = 'filename.pkl'
with open(infile, 'rb') as in_strm:
icps = dill.load(in_strm)
return icps
def predict_from_smiles_conformal_median(regressor_list, smiles):
"""
Description - Predict value of penetration (kp) from a SMILES-description'
of a molecule using the median of multiple conformal models.
"""
print('########## Predict using multiple conformal models ##############')
print smiles
descriptors_df = calculate_descriptors(smiles)
Xvalues = []
Xvalues = asanyarray(descriptors_df.iloc[:,1:])
print(len(Xvalues))
A = pandas.DataFrame(index = range(len(Xvalues)))
B = pandas.DataFrame(index = range(len(Xvalues)))
C = pandas.DataFrame(index = range(len(Xvalues)))
index = list(xrange(len(smiles)))
i = 0
for regressor in regressor_list:
predicted_skin_permiabillity = regressor.predict(Xvalues, significance = 0.2)
predicted_values = pandas.DataFrame(predicted_skin_permiabillity)
A[i] = predicted_values[0]
B[i] = predicted_values[1]
i +=1
#print(predicted_values) DEBUG
C['median_prediction_0'] = A.median(axis=1)
C['median_prediction_1'] = B.median(axis=1)
C['median_prediction'] = (C['median_prediction_0'] + C['median_prediction_1'])/2
C['median_prediction_size'] = C['median_prediction'] - C['median_prediction_0']
#Y_pred_median_test = C['median_prediction'].dropna()
#median_prediction_size = C['median_prediction_size'].dropna().tolist()
if args.verbose:
print('Number of conformal models used: '+ str(i))
print('Predicted range (first entry): '+str(C['median_prediction_0'][0])+' to '+str(C['median_prediction_1'][0]))
print('Predicted value (first entry): '+str(C['median_prediction'][0]))
print('Predicted range (first entry): '+str(C['median_prediction_size'][0]))
#print('Predicted range (second entry): '+str(C['median_prediction_0'][1])+' - '+str(C['median_prediction_1'][1]))
return C
def create_conformal_model():
"""
Description - Create conformal model - Main loop
"""
#Read data from file
data = read_data(args.i)
#Calculate descriptors using RD-kit
descriptors_df = calculate_descriptors(data['smiles'])
#Assign indices
train_i, calibrate_i, test_i = create_indices_test_training_calibration(data) # Create indices for test,training, calibration sets
test_index_total = [x for x in test_i]
calibrate_index_total = [x for x in calibrate_i]
#Create inductive conformal prediction regressor
if args.m == 'RF':
icp = IcpRegressor(NormalizedRegressorNc(RandomForestRegressor, KNeighborsRegressor, abs_error, abs_error_inv, model_params={'n_estimators': 100}))
if args.m == 'SVM':
#No support vector regressor
print('error - no SVM-regressor avliable')
icp = IcpRegressor(NormalizedRegressorNc(SVR, KNeighborsRegressor, abs_error, abs_error_inv, model_params={'n_estimators': 100}))
#Create DataFrames to store data
A = pandas.DataFrame(index = range(len(data)))
B = pandas.DataFrame(index = range(len(data)))
C = pandas.DataFrame(index = range(len(data)))
iA = pandas.DataFrame(index = range(len(data)))
iB = pandas.DataFrame(index = range(len(data)))
iC = pandas.DataFrame(index = range(len(data)))
if args.verbose:
print('Number of models to create: '+args.num_models)
print('############## Starting calculations ##############')
icp_s = []
for i in range(int(args.num_models)): #DEBUG 100
Xtrain, Xtest, Xcalibrate, ytrain, ytest, ycalibrate = create_train_test_calibrate_sets(data, descriptors_df, train_i, calibrate_i, test_i)
#Create nornal model
icp.fit(Xtrain, ytrain)
#Calibrate normal model
icp.calibrate(asanyarray(Xcalibrate), asanyarray(ycalibrate))
#Predrict test and training sets
prediction_test = icp.predict(asanyarray(Xtest), significance = args.significance) # 0.2
prediction_calibrate = icp.predict(asanyarray(Xcalibrate), significance = args.significance)
#Create DF with data
blob = pandas.DataFrame(prediction_test, index=test_i)
iblob = pandas.DataFrame(prediction_calibrate, index=calibrate_i)
A[i] = blob[0]
B[i] = blob[1]
iA[i] = iblob[0]
iB[i] = iblob[1]
#Create new indices for next model
test_index_total = np.unique(np.concatenate((test_index_total, test_i), axis=0))
calibrate_index_total = np.unique(np.concatenate((calibrate_index_total, calibrate_i), axis=0))
train_i, calibrate_i, test_i = randomize_new_indices(train_i, calibrate_i, test_i, data, i)
#temp = sklearn.base.clone(icp)
icp_s.append(copy.copy(icp))
### Save models ###
save_models(icp_s)
if args.verbose:
print('################## Loop finished, model created, test set predicted #################')
experimental_values = data['Observed'][test_index_total]
iexperimental_values = data['Observed'][calibrate_index_total]
C['median_prediction_0'] = A.median(axis=1)
C['median_prediction_1'] = B.median(axis=1)
C['median_prediction'] = (C['median_prediction_0'] + C['median_prediction_1'])/2
C['median_prediction_size'] = C['median_prediction'] - C['median_prediction_0']
Y_pred_median_test = C['median_prediction'].dropna()
median_prediction_size = C['median_prediction_size'].dropna().tolist()
num_outside_median = 0
for i in range(len(data)):
try:
if C['median_prediction_0'].dropna()[i] < experimental_values[i] < C['median_prediction_1'].dropna()[i]:
pass
else:
num_outside_median +=1
#print('Outside range')
except:
pass #print('error')
#Internal prediction
iC['median_prediction_0'] = iA.median(axis=1)
iC['median_prediction_1'] = iB.median(axis=1)
iC['median_prediction'] = (iC['median_prediction_0'] + iC['median_prediction_1'])/2
iC['median_prediction_size'] = iC['median_prediction'] - iC['median_prediction_0']
iY_pred_median_test = iC['median_prediction'].dropna()
imedian_prediction_size = iC['median_prediction_size'].dropna().tolist()
inum_outside_median = 0
for i in range(len(data)):
try:
if iC['median_prediction_0'].dropna()[i] < iexperimental_values[i] < iC['median_prediction_1'].dropna()[i]:
pass
else:
inum_outside_median +=1
#print('Outside range')
except:
pass #print('error')
if args.verbose:
print('########################## Prediction statistics external test ##########################')
print('')
print('Number of compounds predicted in test set: '+ str(C['median_prediction'].notnull().sum()))
if args.t != 'full_model':
ex_r2_score= r2_score(experimental_values, Y_pred_median_test)
print('R^2 (coefficient of determination): %.3f' % ex_r2_score)
ex_mean_squared_error = mean_squared_error(experimental_values, Y_pred_median_test)
ex_rmse = sqrt(ex_mean_squared_error)
print('RMSE: %.3f' % ex_rmse)
ex_MAE = mean_absolute_error(experimental_values, Y_pred_median_test)
print('Mean absolute error: %.3f' % ex_MAE)
print('Mean squared error: %.3f' % ex_mean_squared_error)
#Average prediction range
print('Mean of median prediction range: %.3f' % mean(median_prediction_size))
percent_num_outside_median = 100*float(num_outside_median)/float(len(experimental_values))
print('Number of compounds outside of prediction range: '+str(num_outside_median))
print('% of compounds predicted outside of prediction range: '+str(percent_num_outside_median) +' %')
print(' ')
#####Internal Prediction ########
print('Number of compounds predicted in training set: '+ str(iC['median_prediction'].notnull().sum()))
iex_r2_score= r2_score(iexperimental_values, iY_pred_median_test)
print('R^2 (coefficient of determination): %.3f' % iex_r2_score)
iex_mean_squared_error = mean_squared_error(iexperimental_values, iY_pred_median_test)
iex_rmse = sqrt(iex_mean_squared_error)
print('RMSE: %.3f' % iex_rmse)
print('Mean squared error: %.3f' % iex_mean_squared_error)
iex_MAE = mean_absolute_error(iexperimental_values, iY_pred_median_test)
print('Mean absolute error: %.3f' % iex_MAE)
#Average prediction range
print('Mean of median prediction range: %.3f' % mean(imedian_prediction_size))
ipercent_num_outside_median = 100*float(inum_outside_median)/float(len(iexperimental_values))
print('Number of compounds outside of prediction range: '+str(inum_outside_median))
print('% of compounds predicted outside of prediction range: '+str(ipercent_num_outside_median) +' %')
print(' ')
#### Plot results - plot test set
if args.plot:
if args.verbose:
print(' ################ Plotting testset #################')
fig, ax = plt.subplots()
ax.errorbar(experimental_values, Y_pred_median_test, yerr=median_prediction_size,
fmt='o', markeredgecolor = 'black', markersize = 6,
mew=1, ecolor='black', elinewidth=0.3, capsize = 3, capthick=1, errorevery = 1)
#Set the size
ax.set_ylim([-10,-3])
ax.set_xlim([-10,-3])
# Plot title and lables
#plt.title('Median predictions with prediction ranges for the testset')
plt.ylabel('Predicted log Kp')
plt.xlabel('Experimental log Kp')
# Draw line
fit = np.polyfit(experimental_values, Y_pred_median_test, 1)
x = [-10,-3]
#Regression line
#ax.plot(experimental_values, fit[0]*asanyarray(experimental_values)+ fit[1], color='black')
#ax.plot(x, fit[0]*asanyarray(x)+ fit[1], color='black')
#Creating colored dots for ref 10
#ref10_experimental = data.loc[data['Ref.'] == 10]['Observed']
#ref10_predicted = C['median_prediction'][ref10_experimental.index]
#ax.scatter(ref10_experimental, ref10_predicted,marker = 'o', color ='red', s = 100)
ax.plot(x, x, color='black')
plt.show()
#Print data in CSV-file
descriptors_df['Median prediction low range'] = C['median_prediction_0']
descriptors_df['Median prediction high range'] = C['median_prediction_1']
descriptors_df['Median prediction'] = C['median_prediction']
descriptors_df['size prediction range'] = C['median_prediction_1'] - C['median_prediction_0']
write_csv_with_data(data,descriptors_df, args.d)
#Calculate min, max and mean values for descriptors
if args.phys:
print(args.phys)
print('Min: ')
print(descriptors_df.min())
print('Max: ')
print(descriptors_df.max())
print('Mean:')
print(descriptors_df.mean())
if args.pca:
print('Starting PCA')
print(descriptors_df[['logP','PSA','MolWt','RingCount','HeavyAtomCount','NumRotatableBonds']].head(3))
print(len(descriptors_df[['size prediction range']]))
#Define typ of PCA
pca = PCA(n_components=2)
#Select desctiptors to use in PCA
df_small = descriptors_df[['logP','PSA','MolWt','RingCount','HeavyAtomCount','NumRotatableBonds']]
#Convert descritor values to numeric/float
df_X = df_small.apply(pandas.to_numeric, errors='raise')
#Scale data
scaler = preprocessing.RobustScaler() #Normalizer() # MaxAbsScaler()
df_X_scaled = scaler.fit_transform(df_X)
#Calculate PCA
pca.fit(df_X_scaled)
X2 = pca.transform(df_X_scaled) #descriptors_df[['logP','PSA','MolWt','RingCount','HeavyAtomCount','NumRotatableBonds']])
#-----------------------------------------------------------
desc_testset_large = descriptors_df.dropna(subset = ['size prediction range'])
desc_testset_small = desc_testset_large[['logP','PSA','MolWt','RingCount','HeavyAtomCount','NumRotatableBonds']]
desc_testset_num = desc_testset_small.apply(pandas.to_numeric, errors='raise')
desc_testset_scaled = scaler.fit_transform(desc_testset_num)
X3 = pca.transform(desc_testset_scaled) #desc_testset[['logP','PSA','MolWt','RingCount','HeavyAtomCount','NumRotatableBonds']])
#-----------------------------------------------------------
#desc_testset = descriptors_df.dropna(subset = ['size prediction range'])
Yerr_num = desc_testset_large[['size prediction range']].apply(pandas.to_numeric, errors='coerce')
#print(pandas.Series(Yerr['size prediction range']))
yerr = list(pandas.Series(Yerr_num['size prediction range'])/4)
plt.errorbar(X3[:,0], X3[:,1], yerr=yerr ,fmt='o', markeredgecolor = 'black', markersize = 6, mew=1, ecolor='black', elinewidth=0.3, capsize = 3, capthick=1, errorevery = 1)
plt.scatter(X2[:,0], X2[:,1])
plt.xlabel('PC1')
plt.ylabel('PC2')
plt.title('PCA of descriptors')
plt.show()
# Percentage of variance explained for each components
#print('explained variance ratio (first two components): %s' % str(pca.explained_variance_ratio_))
# -----------------------------------------------------------------------------
if args.verbose:
print(" Verbose output turned on")
print(' Model Type is: '+args.m) # m = model_type
#print(parser)
if args.c:
#Create conformal models
if args.verbose:
print(' Input data file: ')
print(' '+args.i) # i = input_file
create_conformal_model()
if args.p:
if args.verbose:
print('Predict using earlier models')
try:
classifier_list = load_models()
except:
print('No conformal model found')
smile_code = [args.smile] #args.smiles
predict_from_smiles_conformal_median(classifier_list, smile_code)