| 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.tree import DecisionTreeClassifier |
| 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 |
|
| 19 |
lineage_file = sys.argv[1] |
| 20 |
|
| 21 |
sequence_file = sys.argv[2] |
| 22 |
|
| 23 |
testing_percentage = 0.0000000001 |
| 24 |
|
| 25 |
relevant_positions = pickle.load(open(sys.argv[5], 'rb')) |
| 26 |
relevant_positions.add(0) |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
referenceFile = sys.argv[3] |
| 31 |
|
| 32 |
|
| 33 |
dataList = [] |
| 34 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 90 |
idToLineage[referenceId] = "A" |
| 91 |
dataList.append(getDataLine(referenceId, referenceSeq)) |
| 92 |
|
| 93 |
|
| 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 |
|
| 110 |
def findColumnsWithoutSNPs(): |
| 111 |
|
| 112 |
|
| 113 |
for index in range(len(dataList[0][1])): |
| 114 |
keep = False |
| 115 |
|
| 116 |
|
| 117 |
for line in dataList: |
| 118 |
|
| 119 |
|
| 120 |
if dataList[0][1][index] != line[1][index] or index == 0: |
| 121 |
keep = True |
| 122 |
break |
| 123 |
|
| 124 |
|
| 125 |
if keep and index in relevant_positions: |
| 126 |
indiciesToKeep[index] = True |
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
def removeOtherIndices(indiciesToKeep): |
| 133 |
|
| 134 |
|
| 135 |
finalList = [] |
| 136 |
|
| 137 |
indicies = list(indiciesToKeep.keys()) |
| 138 |
indicies.sort() |
| 139 |
|
| 140 |
|
| 141 |
while len(dataList) > 0: |
| 142 |
|
| 143 |
|
| 144 |
line = dataList.pop(0) |
| 145 |
seqId = line.pop(0) |
| 146 |
|
| 147 |
line = line[0] |
| 148 |
|
| 149 |
finalLine = [] |
| 150 |
|
| 151 |
for index in indicies: |
| 152 |
if index == 0: |
| 153 |
|
| 154 |
finalLine.append(seqId) |
| 155 |
else: |
| 156 |
|
| 157 |
finalLine.append(line[index]) |
| 158 |
|
| 159 |
|
| 160 |
finalList.append(finalLine) |
| 161 |
|
| 162 |
|
| 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 |
|
| 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 |
|
| 209 |
if not skipRest: |
| 210 |
|
| 211 |
lineageToCounts = dict() |
| 212 |
|
| 213 |
aLineage = False |
| 214 |
|
| 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 |
|
| 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 |
pima = pd.DataFrame(dataList, columns=headers) |
| 272 |
|
| 273 |
|
| 274 |
categories = ['A', 'C', 'G', 'T', '-'] |
| 275 |
|
| 276 |
|
| 277 |
dummyHeaders = headers[1:] |
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
for i in categories: |
| 282 |
line = [i] * len(dataList[0]) |
| 283 |
pima.loc[len(pima)] = line |
| 284 |
|
| 285 |
|
| 286 |
pima = pd.get_dummies(pima, columns=dummyHeaders) |
| 287 |
|
| 288 |
|
| 289 |
pima.drop(pima.tail(len(categories)).index, inplace=True) |
| 290 |
|
| 291 |
feature_cols = list(pima) |
| 292 |
print(feature_cols) |
| 293 |
|
| 294 |
|
| 295 |
h = feature_cols.pop(0) |
| 296 |
X = pima[feature_cols] |
| 297 |
y = pima[h] |
| 298 |
|
| 299 |
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=testing_percentage,random_state=0) |
| 300 |
|
| 301 |
print("training " + datetime.now().strftime("%m/%d/%Y, %H:%M:%S"), flush=True) |
| 302 |
|
| 303 |
header_out = os.path.join(sys.argv[4],"decisionTreeHeaders_v1.joblib") |
| 304 |
joblib.dump(headers, header_out, compress=('lzma', 9)) |
| 305 |
|
| 306 |
|
| 307 |
dt = DecisionTreeClassifier() |
| 308 |
|
| 309 |
|
| 310 |
dt.fit(X,y) |
| 311 |
|
| 312 |
print("testing " + datetime.now().strftime("%m/%d/%Y, %H:%M:%S"), flush=True) |
| 313 |
|
| 314 |
|
| 315 |
y_pred=dt.predict(X_test) |
| 316 |
|
| 317 |
print(y_pred) |
| 318 |
|
| 319 |
|
| 320 |
y_scores = dt.predict_proba(X_test) |
| 321 |
|
| 322 |
print("generating statistics " + datetime.now().strftime("%m/%d/%Y, %H:%M:%S"), flush=True) |
| 323 |
|
| 324 |
|
| 325 |
print("--------------------------------------------") |
| 326 |
print("Confusion Matrix") |
| 327 |
cnf_matrix = metrics.confusion_matrix(y_test, y_pred) |
| 328 |
print(cnf_matrix) |
| 329 |
|
| 330 |
print("--------------------------------------------") |
| 331 |
print("Classification report") |
| 332 |
print(metrics.classification_report(y_test, y_pred, digits=3)) |
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
model_out = os.path.join(sys.argv[4],"decisionTree_v1.joblib") |
| 337 |
joblib.dump(dt, model_out, compress=('lzma', 9)) |
| 338 |
|
| 339 |
|
| 340 |
print("model files created", flush=True) |
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
def classification_report_with_accuracy_score(y_true, y_pred): |
| 345 |
print("--------------------------------------------") |
| 346 |
print("Crossfold Classification Report") |
| 347 |
print(metrics.classification_report(y_true, y_pred, digits=3)) |
| 348 |
return accuracy_score(y_true, y_pred) |
| 349 |
|
| 350 |
|
| 351 |
|