-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctions.py
More file actions
447 lines (366 loc) · 12.6 KB
/
Functions.py
File metadata and controls
447 lines (366 loc) · 12.6 KB
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
#############################################
# Read File and get dictionary #
#############################################
#
# *INPUT: Name of file
#
# *OUTPUT: 2-D list of dictionaries
# 0th => Reactants : Occurrencies
# 1st => Products : Occurrencies
#
#
############################################
# Read File and get dictionary #
############################################
def file2dict(nameString) :
from collections import Counter
thaFile = open(nameString, 'rU')
log = open("log.out",'w')
allLines = thaFile.readlines()
noLines = len(allLines)
isReact = False
prodOrReact = False
isProd = False
isGood = False
reactants = []
compound = ""
products = []
i = 0
for line in allLines: # Read all file
if not prodOrReact : # line is not part of list of prods/react
if line.find('<listOfProducts>') > 0:
prodOrReact = True
log.write("in")
isProd = True
if line.find('<listOfReactants>') > 0:
prodOrReact = True
log.write("in")
isReact = True
# Look for Compounds if its time for that
if prodOrReact : # inside list of prod/react
# Check is list has ended here
if line.find('</listOfReactants>') > 0:
prodOrReact = False
log.write("out"+'\n')
isReact = False
elif line.find('</listOfProducts>') > 0:
prodOrReact = False
log.write("out"+'\n')
isProd = False
else : # we are in list
isGood = line.find('speciesReference species=')
if isGood > -1:
endProd = line.find('"',isGood+27)
compound = line[isGood+26:endProd]
if isReact :
reactants.append(compound)#Add to reactantsList
elif isProd :
products.append(compound)#Add to products:ist
# Convert list into dictionary of occurences
dictReactants = Counter(reactants)
dictProducts = Counter(products)
compounds = [dictReactants, dictProducts]
thaFile.close()
return compounds
############################################
# Get all Dictionaries from Filenames #
############################################
#
# *INPUT: 1-D list of filenames
#
# *OUTPUT: 2-D list of dictionaries
# 0th => Reactants
# 1st => Products
# Info: Dictionaries are 2-D with
# Key == Name of Bacteria
# Value == Dict of comp : #appear
#
#
############################################
# Get all Dictionaries from Filenames #
############################################
def dict4all(allFiles) :
allProds = {}
allReact = {}
allInDict = []
for currentFile in allFiles :
absPath = 'ExampleFiles/'+currentFile
simpDict = file2dict(absPath)
allReact[currentFile[:-4]] = simpDict[0]
allProds[currentFile[:-4]] = simpDict[1]
allInDict.append(allReact)
allInDict.append(allProds)
return allInDict
############################################
# Get Matches Human-Bateria #
############################################
#
# *INPUT: Dictionary of dictionaries
# Key == Name of Bacteria
# Value == Name comp : #appear
#
# *OUTPUT: Dictionary of Compounds in
# humansANDbacteria
# Compound name: # bacterias
#
# Info: Humans is an entry in dictionary of
# the input list (INPUT['humans'])
#
############################################
# Get Matches Human-Bateria #
############################################
def getMatches(everyCompDict) :
from collections import Counter
matches = []
humans = everyCompDict['humans']
del everyCompDict['humans']
for compound in humans :
for bacteria in everyCompDict :
if compound in everyCompDict[bacteria] : # Compounds appears in bacteria and humans
matches.append(compound)
everyCompDict['humans'] = humans
dictMatches = Counter(matches)
return dictMatches
############################################
# Apply cuts on Dictionaries #
############################################
#
# *INPUT: -Dictionary of type:
# dict[Key] == Value
# - Maximum Value allowed
# - Minimum Value allowed
#
# *OUTPUT: Trimmed-down dictionary
#
# Info: -It is required that:
# value == [Number]
# -Remaining entries satisfy:
# value < maxVal
# value > minVal
#
#
############################################
# Apply cuts on Dictionaries #
############################################
def dictCutOff(thisDict, maxVal, minVal) :
import copy
from copy import deepcopy
dictTrim = copy.deepcopy(thisDict)
if maxVal < minVal :
temp = dcopy(maxVal)
maxVal = minVal
minVal = temp
elif maxVal == minVal :
print "Error: Invalid input limits [They are the same you moron]"
return
for compound in thisDict :
if any ([dictTrim[compound] >= maxVal, dictTrim[compound] <= minVal]) :
del dictTrim[compound]
return dictTrim
############################################
# Sum All Dictionary Entries #
############################################
#
# *INPUT: -Dictionary (key : [number])
#
# *OUTPUT: Sum of values [number]
#
#
############################################
# Sum All Dictionary Entries #
############################################
def sumDict(dict2Sum) :
total = 0
for molec in dict2Sum:
total += dict2Sum[molec]
return total*1.0
############################################
# Help-printing for infoMolec #
############################################
#
# *INPUT: -None
#
# *OUTPUT: -None
#
# Info: -Prints information about usage and
# inner workings of infoMolec
# -Information is sorted in 3 topics:
# *input
# *output
# *inner_workings
#
#
############################################
# Help-printing for infoMolec #
############################################
def helpInfoMolec():
print "############################################"
print "# Info-Getter for molecules #"
print "# #"
print "# HELP Section: Information about inner #"
print "# working and usage of infoMolec function #"
print "############################################"
print "#"
print "#-------------------------------------------"
print "# BASIC INFORMATION"
print "#-------------------------------------------"
print "#"
print "# *INPUT: -Name of molecule"
print "# -Dictionary of dictionaries "
print "# for reactants OR products"
print "#"
print "# *OUTPUT: Dictionary of molecule info"
print "# such as:"
print "# _list of bacterias in which "
print "# it appears"
print "# appearances : list[]"
print "# _appearances in humans"
print "# humans : [#, %]"
print "# _appearances in each bacteria"
print "# bacteriaName : [#, %]"
print "# _total appearances in bacteria"
print "# bacterias : #"
print "#"
print "# Extra: Input list of dict of dict in the "
print "# form of list[0] or list[1] from"
print "# OUTPUT in dict4all function"
print "#"
print "#"
print "############################################"
print "# Info-Getter for molecules #"
print "############################################"
print ""
print ""
print " For extra information please select the topic by typing one of the following keywords: "
print " Keywords: input \t output \t inner_workings"
topic = raw_input('Select topic: ')
topicSelected = False
while not topicSelected :
if topic == 'input' :
topicSelected = True
print topic
elif topic == 'output':
topicSelected = True
print topic
elif topic == 'inner_workings':
topicSelected = True
print topic
else :
print "Topic could not be selected, please try again:"
topic = raw_input('Select topic: ')
return
############################################
# Info-Getter for molecules #
############################################
#
# *INPUT: -Name of molecule
# -Dictionary of dictionaries
# for reactants OR products
#
# *OUTPUT: Dictionary of molecule info
# such as:
# _list of bacterias in which
# it appears
# appearances : list[]
# _appearances in humans
# humans : [#, %]
# _appearances in each bacteria
# bacteriaName : [#, %]
# _total appearances in bacteria
# bacterias : #
#
# Info: Input list of dict of dict in the
# form of list[0] or list[1] from
# OUTPUT in dict4all function
#
#
############################################
# Info-Getter for molecules #
############################################
def infoMolec(molecule = 0, dictioData = 0):
if all([dictioData != 0, molecule != 0]):
manyStats = {}
listOfBact = []
humanStats = []
bactStats = {}
tempBactDict = {}
allBactStats = {}
nameLen = 0
'''
List of Bacterias
'''
for bacteria in dictioData :
if molecule in dictioData[bacteria] :
listOfBact.append(bacteria)
if nameLen < len(bacteria) :
nameLen = len(bacteria)
manyStats['allBacteria'] = listOfBact
'''
Appearances in humans
'''
humanStats.append(dictioData['humans'][molecule])
sumHumans = sumDict(dictioData['humans'])
humanStats.append(1.0 * humanStats[0]/sumHumans)
manyStats['humans'] = humanStats
print "Molecule "+molecule+" appears {0} times in human reaction".format(humanStats[0])
print "Represents {0:3f}% of total in humans".format(humanStats[1]*100)
print "=================================="
'''
Total Appearances in all Bacteria
'''
for bacteria in listOfBact :
tempBactDict[bacteria] = dictioData[bacteria][molecule]
totalAppear = sumDict(tempBactDict)
manyStats['appearancesBacteria'] = totalAppear
'''
Appearances in bacterias
'''
for bacteria in tempBactDict :
bactStats[bacteria] = [tempBactDict[bacteria], tempBactDict[bacteria]/totalAppear]
manyStats['bacterias'] = bactStats
#print nameLen
print "Molecule ' "+molecule+" ' appears in: "
print "{0:59} \t Appearances "+'\t'+"Percetange ".format('Bacteria')
for bacteria in bactStats :
print "{0:59} : {1:3} times => {2:3f}% of total appearences".format(bacteria, bactStats[bacteria][0], bactStats[bacteria][1]*100)
print "=================================="
'''
Work done, lay back and enjoy results
'''
return manyStats
'''
On-screen help / manual
'''
if any([molecule == 0, dictioData == 0]):
helpInfoMolec()
return
############################################
# Matching Molecules + 2xCut #
############################################
#
# *INPUT: -Dictionary of all data
# -List of human cuts[max,min]
# -List of bacteria cuts[max,min]
#
# *OUTPUT: Dictionary of molecules
# fulfilling criteriainfo
#
#
############################################
# Info-Getter for molecules #
############################################
def matchAndCut(allData, cutHuman, cutBacteria):
import copy
from copy import deepcopy
theOutput = {}
tempDict = {}
tempAllDict = {}
tempAllDict = copy.deepcopy(allData)
tempAllDict['humans'] = dictCutOff(allData['humans'], cutHuman[0], cutHuman[1])
tempDict = getMatches(tempAllDict)
tempDict = dictCutOff(tempDict, cutBacteria[0], cutBacteria[1])
print "{0:20}: {1:5} {2:5}".format("Molecule", 'Humans', 'Bacterias')
for molecule in tempDict :
theOutput[molecule] = [allData['humans'][molecule], tempDict[molecule]]
print "{0:20}: {1:5} {2:5}".format(molecule, allData['humans'][molecule], tempDict[molecule])
return theOutput