Debian Codegraph @

pangoLEARN/training/pangoLEARNRandomForest_v1.py

raw symbols SCIP
1 import pandas as pd
2 from sklearn.model_selection import train_test_split
3 from sklearn import metrics
4 from sklearn.datasets import make_classification
5 from sklearn.model_selection import StratifiedShuffleSplit
6 from sklearn.ensemble import RandomForestClassifier
7 from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix, make_scorer
8 from datetime import datetime
9 import joblib
10 import sys
11 import os
12 from sklearn.model_selection import cross_val_score
13 from Bio import SeqIO
14 import pickle
15 import time
16 import os.path
17
18 # file with lineage assignments
19 lineage_file = sys.argv[1]
20 # file with sequences
21 sequence_file = sys.argv[2]
22 # how much of the data will be used for testing, instead of training
23 testing_percentage = 0.0000000001
24
25 relevant_positions = pickle.load(open(sys.argv[5], 'rb'))
26 relevant_positions.add(0)
27
28 # the path to the reference file.
29 # This reference sequence must be the same as is used in the pangolearn script!!
30 referenceFile = sys.argv[3]
31
32 # data storage
33 dataList = []
34 # dict for lookup efficiency
35 indiciesToKeep = dict()
36
37 referenceId = "Wuhan/WH04/2020"
38 referenceSeq = ""
39
40 idToLineage = dict()
41 idToSeq = dict()
42
43 mustKeepIds = []
44 mustKeepLineages = []
45
46
47 # function for handling weird sequence characters
48 def clean(x, loc):
49 x = x.upper()
50
51 if x == 'T' or x == 'A' or x == 'G' or x == 'C' or x == '-':
52 return x
53
54 if x == 'U':
55 return 'T'
56
57 # otherwise return value from reference
58 return referenceSeq[loc]
59
60 def findReferenceSeq():
61 with open(referenceFile) as f:
62 currentSeq = ""
63
64 for line in f:
65 if ">" not in line:
66 currentSeq = currentSeq + line.strip()
67
68 f.close()
69 return currentSeq
70
71
72 def getDataLine(seqId, seq):
73 dataLine = []
74 dataLine.append(seqId)
75
76 newSeq = ""
77
78 # for each character in the sequence
79 for index in range(len(seq)):
80 newSeq = newSeq + clean(seq[index], index)
81
82 dataLine.append(newSeq)
83
84 return dataLine
85
86
87 def readInAndFormatData():
88
89 # add the data line for the reference seq
90 idToLineage[referenceId] = "A"
91 dataList.append(getDataLine(referenceId, referenceSeq))
92
93 # create a dictionary of sequence ids to their assigned lineages
94 lineage_designations = pd.read_csv(lineage_file, delimiter=",", dtype=str)
95 for index, row in lineage_designations.iterrows():
96 idToLineage[row["sequence_name"]] = row["lineage"]
97
98 seq_dict = {rec.id : rec.seq for rec in SeqIO.parse(sequence_file, "fasta")}
99
100 print("files read in, now processing")
101
102 for key in seq_dict.keys():
103 if key in idToLineage:
104 dataList.append(getDataLine(key, seq_dict[key]))
105 else:
106 print("unable to find the lineage classification for: " + key)
107
108
109 # find columns in the data list which always have the same value
110 def findColumnsWithoutSNPs():
111
112 # for each index in the length of each sequence
113 for index in range(len(dataList[0][1])):
114 keep = False
115
116 # loop through all lines
117 for line in dataList:
118
119 # if there is a difference somewhere, then we want to keep it
120 if dataList[0][1][index] != line[1][index] or index == 0:
121 keep = True
122 break
123
124 # otherwise, save it
125 if keep and index in relevant_positions:
126 indiciesToKeep[index] = True
127
128
129 # remove columns from the data list which don't have any SNPs. We do this because
130 # these columns won't be relevant for a logistic regression which is trying to use
131 # differences between sequences to assign lineages
132 def removeOtherIndices(indiciesToKeep):
133
134 # instantiate the final list
135 finalList = []
136
137 indicies = list(indiciesToKeep.keys())
138 indicies.sort()
139
140 # while the dataList isn't empty
141 while len(dataList) > 0:
142
143 # pop the first line
144 line = dataList.pop(0)
145 seqId = line.pop(0)
146
147 line = line[0]
148 # initialize the finalLine
149 finalLine = []
150
151 for index in indicies:
152 if index == 0:
153 # if its the first index, then that's the lineage assignment, so keep it
154 finalLine.append(seqId)
155 else:
156 # otherwise keep everything at the indices in indiciesToKeep
157 finalLine.append(line[index])
158
159 # save the finalLine to the finalList
160 finalList.append(finalLine)
161
162 # return
163 return finalList
164
165 def allEqual(list):
166 entries = dict()
167
168 for i in list:
169 if i not in entries:
170 entries[i] = True
171
172 return len(entries) == 1
173
174 def removeAmbiguous():
175 idsToRemove = set()
176 lineMap = dict()
177 idMap = dict()
178
179 for line in dataList:
180 keyString = ",".join(line[1:])
181
182 if keyString not in lineMap:
183 lineMap[keyString] = []
184 idMap[keyString] = []
185
186 if line[0] in idToLineage:
187 lineMap[keyString].append(idToLineage[line[0]])
188 idMap[keyString].append(line[0])
189 else:
190 print("diagnostics")
191 print(line[0])
192 print(keyString)
193 print(line)
194 for key in lineMap:
195 if not allEqual(lineMap[key]):
196
197 skipRest = False
198
199 # see if any protected lineages are contained in the set, if so keep those ids
200 for lineage in lineMap[key]:
201 if lineage in mustKeepLineages:
202 skipRest = True
203
204 for i in idMap[key]:
205 if lineage != idToLineage[i] and i not in mustKeepIds:
206 idsToRemove.add(i)
207
208 # none of the lineages are protected, fire at will
209 if not skipRest:
210
211 lineageToCounts = dict()
212
213 aLineage = False
214 # find most common lineage
215 for lineage in lineMap[key]:
216 if lineage not in lineageToCounts:
217 lineageToCounts[lineage] = 0
218
219 lineageToCounts[lineage] = lineageToCounts[lineage] + 1
220 aLineage = lineage
221
222 m = aLineage
223 for lineage in lineageToCounts:
224 if lineageToCounts[lineage] > lineageToCounts[m]:
225 m = lineage
226
227
228 for i in idMap[key]:
229 if m != idToLineage[i]:
230 idsToRemove.add(i)
231
232 newList = []
233
234 print("keeping indicies:")
235
236 for line in dataList:
237 if line[0] not in idsToRemove:
238 print(line[0])
239 line[0] = idToLineage[line[0]]
240 newList.append(line)
241
242 return newList
243
244
245 print("reading in data " + datetime.now().strftime("%m/%d/%Y, %H:%M:%S"), flush=True)
246
247 referenceSeq = findReferenceSeq()
248
249 readInAndFormatData()
250
251 print("processing snps, formatting data " + datetime.now().strftime("%m/%d/%Y, %H:%M:%S"), flush=True)
252
253 findColumnsWithoutSNPs()
254
255 dataList = removeOtherIndices(indiciesToKeep)
256
257 print("# sequences before blacklisting")
258 print(len(dataList))
259
260 dataList = removeAmbiguous()
261
262 print("# sequences after blacklisting")
263 print(len(dataList))
264
265 # headers are the original genome locations
266 headers = list(indiciesToKeep.keys())
267 headers[0] = "lineage"
268
269 print("setting up training " + datetime.now().strftime("%m/%d/%Y, %H:%M:%S"), flush=True)
270
271 # checkpoint_file = os.path.join(sys.argv[4], "dataList.pickle")
272 # dataList.to_pickle(checkpoint_file)
273 # headers
274
275 pima = pd.DataFrame(dataList, columns=headers)
276
277 # nucleotide symbols which can appear
278 categories = ['A', 'C', 'G', 'T', '-']
279
280 # one hot encoding of all headers other than the first which is the lineage
281 dummyHeaders = headers[1:]
282
283 # add extra rows to ensure all of the categories are represented, as otherwise
284 # not enough columns will be created when we call get_dummies
285 for i in categories:
286 line = [i] * len(dataList[0])
287 pima.loc[len(pima)] = line
288
289 # get one-hot encoding
290 pima = pd.get_dummies(pima, columns=dummyHeaders)
291
292 # get rid of the fake data we just added
293 pima.drop(pima.tail(len(categories)).index, inplace=True)
294
295 feature_cols = list(pima)
296 print(feature_cols)
297
298 # remove the last column from the data frame. This is because we are trying to predict these values.
299 h = feature_cols.pop(0)
300 X = pima[feature_cols]
301 y = pima[h]
302
303 X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=testing_percentage,random_state=0)
304
305 print("training " + datetime.now().strftime("%m/%d/%Y, %H:%M:%S"), flush=True)
306
307 header_out = os.path.join(sys.argv[4],"randomForestHeaders_v1.joblib")
308 joblib.dump(headers, header_out, compress=('lzma', 9))
309
310 # instantiate the random forest with 50 trees
311 rf = RandomForestClassifier(n_estimators=12, max_features=0.05, min_samples_split=10)
312
313 # fit the model
314 rf.fit(X,y)
315
316 print("testing " + datetime.now().strftime("%m/%d/%Y, %H:%M:%S"), flush=True)
317
318 # classify the test data
319 y_pred=rf.predict(X_test)
320
321 print(y_pred)
322
323 # get the scores from these predictions
324 y_scores = rf.predict_proba(X_test)
325
326 print("generating statistics " + datetime.now().strftime("%m/%d/%Y, %H:%M:%S"), flush=True)
327
328 #print the confusion matrix
329 print("--------------------------------------------")
330 print("Confusion Matrix")
331 cnf_matrix = metrics.confusion_matrix(y_test, y_pred)
332 print(cnf_matrix)
333
334 print("--------------------------------------------")
335 print("Classification report")
336 print(metrics.classification_report(y_test, y_pred, digits=3))
337
338 # save the model files to compressed joblib files
339 # using joblib instead of pickle because these large files need to be compressed
340 model_out = os.path.join(sys.argv[4],"randomForest_v1.joblib")
341 joblib.dump(rf, model_out, compress=('lzma', 9))
342
343
344 print("model files created", flush=True)
345
346 # this method is used below when running 10-fold cross validation. It ensures
347 # that the per-lineage statistics are generated for each cross-fold
348 def classification_report_with_accuracy_score(y_true, y_pred):
349 print("--------------------------------------------")
350 print("Crossfold Classification Report")
351 print(metrics.classification_report(y_true, y_pred, digits=3))
352 return accuracy_score(y_true, y_pred)
353
354 # optionally, run 10-fold cross validation (comment this out if not needed as it takes a while to run)
355 # cross_validation_scores = cross_val_score(rf, X=X, y=y, cv=10, scoring=make_scorer(classification_report_with_accuracy_score))