reeps

pain in my ass

May 4th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.24 KB | None | 0 0
  1. import os, sys, time, gzip, re, psutil, random
  2. import numpy as np
  3. import pandas as pd
  4. from scipy.spatial import distance
  5. import xgboost as xgb
  6. from termcolor import colored
  7.  
  8.  
  9. from sklearn.metrics import accuracy_score as acs
  10. from sklearn.ensemble import RandomForestClassifier as rfc
  11. from sklearn.svm import SVC as svc
  12.  
  13. acids = ['ALA', 'CYS', 'ASP', 'GLU', 'PHE', 'GLY', 'HIS', 'ILE', 'LYS', 'LEU', 'MET', 'ASN', 'PRO', 'GLN', 'ARG', 'SER', 'THR', 'VAL', 'TRP', 'TYR']
  14.  
  15. #open pdb if res is less than limit and if file exists
  16. def openPDBFile(protein_name, resLim = 2.0):
  17.     pdb = []
  18.     res = None
  19.     flag = False
  20.     name = pathFinder(protein_name)
  21.     if os.path.exists(name):
  22.         with gzip.open(name,'rt') as f:
  23.             for line in f:
  24.                 if flag == False:
  25.                     res = checkResolution(line)
  26.                     flag = True
  27.                     if res > resLim:
  28.                         return None
  29.                 pdb.append(line)
  30.                    
  31.         return pdb     
  32.     else:
  33.         return None
  34.  
  35. #return resolution of prot
  36. def checkResolution(line):
  37.     res = 0
  38.     if ('RESOLUTION.' in line) and ('ANGSTROMS' in line):
  39.         res = [float(s) for s in re.findall(r'-?\d+\.?\d*', line)][1]
  40.     return res
  41.        
  42. #dir where the pdb files are saved
  43. def pathFinder(protein_name):
  44.     path = '/home/artur/a/pdb/' + protein_name[1].lower() + protein_name[2].lower() + '/pdb' + protein_name.lower() + '.ent.gz'
  45.     return path
  46.  
  47.  
  48. def getXYZ(line):
  49.     x = float(line[30:38])
  50.     y = float(line[38:46])
  51.     z = float(line[46:54])
  52.    
  53.     return [x, y, z]
  54.  
  55.  
  56. def getID(line):
  57.     i = int(line[6:11])
  58.     return i
  59.    
  60. #Get atom's name    
  61. def getAtomID(line):
  62.     i = line[13:16]
  63.     return i
  64.  
  65. #Get amino acids name
  66. def getResName(line):
  67.     i = line[17:20]
  68.     return i    
  69.  
  70.  
  71. def getProteinAndWater(pdb):
  72.     protein = []
  73.     water = []
  74.     proteinCoords = []
  75.     for line in pdb:
  76.         if len(line) < 78:
  77.             continue
  78.         if (line[17:20] == "HOH" and line[77] == "O"):
  79.             water.append(getXYZ(line))
  80.         if (line[16] != "A" and line[16] != " ") or (line[27] != "A" and line[27] != " "):
  81.             continue
  82.         if (line[17:20] != "HOH" and line[0:4] == "ATOM"):
  83.             protein.append(line)
  84.     return protein, water
  85.  
  86. def toPdb(xyz,B= 0, atom_id=None, res_id="  0", element= "U"):
  87.     if (B>999):
  88.         B = 999.0
  89.     x = "{:8.3f}".format(xyz[0])
  90.     y = "{:8.3f}".format(xyz[1])
  91.     z = "{:8.3f}".format(xyz[2])
  92.     B = "{:6.2f}".format(float(B))
  93.    
  94.     if res_id != "  0":
  95.         if res_id>999:
  96.             res_id-=int(res_id/1000)*1000
  97.         res_id = str(res_id)
  98.         res_id = " ".join([""]*(3-len(res_id)))+res_id         
  99.     line = "ATOM         "+element+"   "+element * 3+"    "+res_id+"     42.931 -14.533  18.887        0.00           "+element
  100.     line_ = line[:30]+x+y+z+line[54:60]+B+line[66:]+"\n"
  101.     return line_
  102.  
  103.  
  104. def getDistanceBetween(chosenMolecule, molecules):
  105.     return distance.cdist(chosenMolecule, molecules)
  106.    
  107. #get distances between each of water molecules
  108. def getWatersArray(water):
  109.     cd = getDistanceBetween(water, water)
  110.     id_cd = np.where((cd < 4.0) & (cd > 0.0))
  111.     cd_ = cd[id_cd]
  112.     cd_.sort()
  113.     return cd_
  114.  
  115. #get all the carbon, oxygen, nitro atoms from protein
  116. def getCON(protein): #carbon oxygen nitro
  117.     C = []
  118.     O = []
  119.     N = []
  120.     id_C = id_O = id_N = []
  121.    
  122.     for i in protein:
  123.         if i[13] == 'O':
  124.             O.append(getXYZ(i))
  125.             id_O.append(getID(i))
  126.         if i[13] == 'C':
  127.             C.append(getXYZ(i))
  128.             id_C.append(getID(i))
  129.         if i[13] == 'N':
  130.             N.append(getXYZ(i))
  131.             id_N.append(getID(i))
  132.            
  133.     return [C, O, N, id_C, id_O, id_N]
  134.    
  135. #get nearly located C O N atoms from each water molecule
  136. def getAtomsArrays(protein, water):
  137.     global acids
  138.     [C, O, N,  id_C, id_O, id_N] = getCON(protein)
  139.    
  140.     cd_C = getDistanceBetween(water, C)
  141.     cd_O = getDistanceBetween(water, O)
  142.     cd_N = getDistanceBetween(water, N)
  143.    
  144.     id_cd_C = np.where(cd_C < 4.0)
  145.     id_cd_O = np.where(cd_O < 4.0)
  146.     id_cd_N = np.where(cd_N < 4.0) 
  147.    
  148.     cd_C_ = np.array(cd_C[id_cd_C])
  149.     cd_O_ = np.array(cd_O[id_cd_O])
  150.     cd_N_ = np.array(cd_N[id_cd_N])
  151.    
  152.     cd_C_.sort()
  153.     cd_O_.sort()
  154.     cd_N_.sort()
  155.    
  156.     return cd_C_, cd_N_, cd_O_
  157.  
  158. #get fake water molecules
  159. def getFakeWater(water):   
  160.     cd = getDistanceBetween(water, water)
  161.     fwater = []
  162.     id_cd = np.where((cd < 4.0) & (cd > 0))
  163.    
  164.     idx = id_cd[0].tolist()
  165.     jdx = id_cd[1].tolist()
  166.        
  167.     for i in range(len(idx)):
  168.                 if (jdx[i] > idx[i]):                      
  169.                     fwater.append(((np.array(water[idx[i]]) + np.array(water[jdx[i]]) )/ 2))
  170.     return fwater
  171.  
  172. #return the (number = lim) number of randomized prots from different clusters with the short names alike 3y3q_ai
  173. def filterProts(lim):
  174.     file = open('bc-90.out', 'r')
  175.     global forTest
  176.     fprots = []
  177.    
  178.     count = 0
  179.     for line in file:
  180.         count += 1
  181.         prots = line.split(" ")
  182.         for i in prots:
  183.             if len(i) > 6:
  184.                 prots.remove(i) #delete proteins like 3y3q_ai
  185.                
  186.         if lim >= len(prots):      
  187.             fprots.extend(prots)   
  188.         else:
  189.             random = np.random.randint(len(prots), size= lim)
  190.             for i in random:
  191.                 fprots.append(prots[i])
  192.    
  193.     return fprots
  194.  
  195.  
  196. #shuffle and return number of water molecules
  197. def filterWater(water, lim = 100):
  198.     water_ = []
  199.     if len(water) <= lim:
  200.         water_ = water
  201.     else:
  202.         random = np.random.randint(len(water), size= lim)
  203.         for i in random:
  204.             water_.append(water[i])
  205.     return water_
  206.  
  207.  
  208. def prepareData(lim = 1, protsNum = 25):   
  209.  
  210.     global protsUsed
  211.    
  212.     global testProts
  213.     global testCON
  214.     global testFWater
  215.    
  216.     prots = filterProts(lim)
  217.     random.shuffle(prots)
  218.    
  219.     count = 0
  220.     forTest = 2
  221.     #len(prots) < ~10000
  222.     maxp = protsNum
  223.     posData = []
  224.     negData = []
  225.    
  226.     for i in prots:
  227.         name = i[0:4]
  228.         pdb = openPDBFile(name)
  229.         if pdb == None:
  230.             continue
  231.         else:
  232.             try:       
  233.    
  234.                 [protein, water] = getProteinAndWater(pdb)
  235.                 water_ = filterWater(water)
  236.                 fwater = getFakeWater(water_)
  237.                 count += 1
  238.                 if count == maxp:
  239.                     break  
  240.                 [C, O, N] = getAtomsArrays(protein, water_)
  241.                 posData.append([C, O, N])
  242.                 [C1, O1, N1] = getAtomsArrays(protein, fwater)
  243.                 negData.append([C, O, N])
  244.                 protsUsed.append(name)         
  245.             except ValueError:
  246.                 continue
  247.        
  248.     for i in range(forTest):
  249.         testProts.append(protsUsed.pop())
  250.         testCON.append(posData.pop())
  251.         testFWater.append(negData.pop())
  252.    
  253.     return posData, negData
  254.  
  255.  
  256.  
  257.  
  258. def balanceX(x):
  259.     maxLen = max([len(i) for i in x])
  260.     for i in x:
  261.         if len(i) < maxLen:
  262.             i = np.concatenate((np.zeros(maxLen - len(i)),i))
  263.     print x.shape      
  264.     return x
  265.  
  266.  
  267.    
  268. def createXY(posData, negData, maxlen):
  269.     print colored(len(negData), 'green')
  270.     x = posData + negData
  271.     x_= []
  272.     foo = []
  273.     for i in range(len(x)):        
  274.         foo = np.zeros(maxlen - len(x[i][0])).tolist() + x[i][0].tolist() + np.zeros(maxlen - len(x[i][1])).tolist() + x[i][1].tolist() + np.zeros(maxlen - len(x[i][2])).tolist() + x[i][2].tolist()
  275.         x_.append(np.array(foo))
  276.     y = np.zeros(len(x))
  277.     for i in range(len(posData)):
  278.         y[i] = 1   
  279.     return np.array(x_), y
  280.  
  281.  
  282. def getMax(posData, negData, testCON, testFWater):
  283.     x = posData + negData + testCON + testFWater
  284.     maxlen = 0
  285.     for i in x:
  286.         maxx = len(max(i, key = len))
  287.         if maxx > maxlen:
  288.             maxlen = maxx
  289.     return maxlen
  290.    
  291.  
  292.  
  293.  
  294. def createXYHist(posData, negData, bins = 20):
  295.     x = posData + negData
  296.     x_ = []
  297.     y = np.zeros(len(x))
  298.     for i in range(len(posData)):
  299.         y[i] = 1
  300.     for i in range(len(x)):
  301.         histC = np.histogram(x[i][0], bins= bins)
  302.         histO = np.histogram(x[i][1], bins= bins)
  303.         histN = np.histogram(x[i][2], bins= bins)
  304.         foo = np.concatenate((histC[0], histO[0], histN[0]))
  305.         x_.append(foo)
  306.     return np.array(x_), y
  307.    
  308.    
  309.    
  310.    
  311. def printXY(x, y, protsUsed, testProts):
  312.     f = open('log.out', 'w')
  313.     print x.shape
  314.     print y.shape
  315.     f.write('x shape ' + str(x.shape[0]) + ' ' + str(x.shape[1]) + '\n')
  316.     f.write('y shape ' + str(y.shape[0]) + '\n')
  317.     f.write('prots used \n')
  318.    
  319.     for i in protsUsed:
  320.         f.write(i + ' ')
  321.     f.write('\ntest prots \n')
  322.     for i in testProts:
  323.         f.write(i+ ' ')
  324.    
  325.     f.close()
  326.     np.savetxt('testX.out', x)
  327.     np.savetxt('testY.out', y)
  328.    
  329.            
  330. def train(posData, negData):
  331.     global testProts
  332.     global testCON #test posData
  333.     global testFWater # test negData
  334.     global protsUsed
  335.     maxlen = getMax(posData, negData, testCON, testFWater)
  336.     [x0, y0] = createXY(posData, negData, maxlen)
  337.     [xt0, yt0] = createXY(testCON, testFWater, maxlen)
  338.     [x1, y1] = createXYHist(posData, negData)
  339.     [xt1, yt1] = createXYHist(testCON, testFWater)
  340.     printXY(x0, y0, protsUsed, testProts)
  341.     """#xgboost
  342.     model0 = xgb.XGBClassifier()
  343.     model0.fit(x0, y0)
  344.    
  345.     yp0 = model0.predict(xt0)
  346.     predictions0 = [round(value) for value in yp0]
  347.     # evaluate predictions
  348.     accuracy0 = acs(yt0, predictions0)
  349.     print colored('accuracy of prediction xgb ' + str(accuracy0), 'red')
  350.    
  351.     #xgboost hist
  352.     model1 = xgb.XGBClassifier()
  353.     model1.fit(x1, y1)
  354.    
  355.     yp1 = model1.predict(xt1)
  356.     predictions1 = [round(value) for value in yp1]
  357.     # evaluate predictions
  358.     accuracy1 = acs(yt1, predictions1)
  359.     print colored('accuracy of prediction xgb hist ' + str(accuracy1), 'red')
  360.    
  361.     #svc
  362.     model2 = svc(gamma= 'auto')
  363.     model2.fit(x0, y0)
  364.     yp2 = model2.predict(xt0)
  365.     predictions2 = [round(value) for value in yp2]
  366.     accuracy2 = acs(yt0, predictions2)
  367.     print colored('accuracy of pred svm svc ' + str(accuracy2), 'red')
  368.    
  369.     #svc with hist
  370.     model3 = svc(gamma= 'auto')
  371.     model3.fit(x1, y1)
  372.     yp3 = model3.predict(xt1)
  373.     predictions3 = [round(value) for value in yp3]
  374.     accuracy3 = acs(yt1, predictions3)
  375.     print colored('accuracy of pred svm svc with hist ' + str(accuracy3), 'red')
  376.    
  377.     #random forest
  378.     model4 = rfc()
  379.     model4.fit(x0, y0)
  380.     yp4 = model4.predict(xt0)
  381.     predictions4 = [round(value) for value in yp4]
  382.     accuracy4 = acs(yt0, predictions4)
  383.     print colored('accuracy of pred rfc ' + str(accuracy4), 'red')
  384.    
  385.     #random forest hist
  386.     model5 = rfc()
  387.     model5.fit(x1, y1)
  388.     yp5 = model5.predict(xt1)
  389.     predictions5 = [round(value) for value in yp5]
  390.     accuracy5 = acs(yt1, predictions5)
  391.     print colored('accuracy of pred rfc with hist ' + str(accuracy5), 'red')
  392.    
  393.     print 'train complete'"""
  394.  
  395.    
  396.    
  397. #x vectors : c , o, n
  398. #y vector : fake water  
  399. timer = time.time()
  400.  
  401. protsUsed = []
  402. testProts = []
  403. testCON = []
  404. testFWater = []
  405.    
  406. [posData, negData] = prepareData()
  407.  
  408. train(posData, negData)
  409.  
  410. #print colored(testProts, 'yellow')
  411. #print "These", len(protsUsed), "proteins are used for preparing of data"
  412. #print colored(protsUsed, 'cyan')
  413.  
  414.    
  415. print "My program took", time.time() - timer, "to run and memory is used", psutil.virtual_memory()
  416. #fwater = getFakeWater(protein, water)
Advertisement
Add Comment
Please, Sign In to add comment