aboutsummaryrefslogtreecommitdiff
path: root/scripts/maintenance/DataAnalyzer.py
blob: 6d14c8da23c2ea08f2d452caa3aecc1fd8833c36 (plain)
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
# Created by Luis Del Mar for GeneNetwork.org
# Email: ladelmar99@gmail.com
# LinkedIn: https://www.linkedin.com/in/luis-del-mar/
# GitHub: https://github.com/ladm99
# This script performs the following normalizations to a specific tab delimited dataset:
# 1. Average 2. Log2 normalize 3. ZScore Normaliza 4. Outlier detection 
#!/usr/bin/env python

from tkinter import Tk
from tkinter.filedialog import askopenfilename
import math
import traceback
import os

# method for file selection
def fileSelector():
	# Code from: https://stackoverflow.com/questions/3579568/choosing-a-file-in-python-with-simple-dialog
	Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
	filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
	return filename

# method for getting skipRow and skipCol
def skips():
	while True:
		skipRow = 0
		skipCol = 0
		r = input('Enter the number of rows that you wish skip (default is 0): ').strip()
		c = input('Enter the number of columns that you wish skip (default is 0): ').strip()
		try:
			if r != '':
				skipRow = int(r)
			if c != '':
				skipCol = int(c)
			return skipRow, skipCol
		except Exception as e:
			input('Enter a valid value')

# gets the mean of an array
def getMean(values):
	mean = 0.0
	for i in values:
		mean+=i
	mean /= len(values)
	return mean

# gets the standard deviation of an array
def getSTD(values):
	mean = getMean(values)
	phi = 0.0

	for i in values:
		phi += abs((i - mean)) ** 2
	phi = math.sqrt((phi/(len(values) - 1)))
	return phi


def log2Normalize(inputFile):
	try:
		skipRow, skipCol = skips()
		print(':Log2 normalize processing...looking for the minimal expression value')
		f = open('%s' % inputFile, 'r')
		# set min to max value
		min = float('inf')

		for i in range(skipRow + 1):
			f.readline()
		while True:
			data =f.readline()
			if not data:
				break
			else:
				s = data.split('\t')
				for j in range(skipCol + 1, len(s)):
					value = 0.0
					try:
						value = float(s[j])
						if min > value:
							min = value
					except Exception as e:
						pass
		f.close()
		print('Log2 normalize processing...calculating')
		f = open('%s' % inputFile, 'r')
		outputFile = os.path.split(inputFile)[1].replace('.txt', '_log2.txt')
		out = open(outputFile,'w')

		offset = 1.0
		if min < 0.0:
			offset = -min + 1.0
		for i in range(skipRow + 1):
			out.write(f.readline())
		linenum = 0
		while True:
			data = f.readline()
			if not data:
				break
			else:
				s = data.split('\t')
				for j in range(skipCol + 1):
					out.write(s[j] + '\t')
				for j in range(skipCol + 1, len(s)):
					try:
						value = math.log(float(s[j]) + offset) / math.log(2.0)
						out.write(str(round(value,3)) + '\t')
					except Exception as e:
						out.write('x')
						out.write('\t')
				out.write('\n')
				linenum +=1
				if linenum % 2500 == 0:
					print('Log2 normalize processing...finished' + str(linenum) + ' lines')
		f.close()
		out.close()
		print('Log2 normalize finished')
	except Exception as e:
		print(traceback.format_exc())

def ZScoreNormalize(inputFile):
	try:
		skipRow, skipCol = skips()
		print('ZScore normalize processing...calculating means')
		f = open('%s' % inputFile, 'r')
		for n in range(skipRow):
			f.readline()
		# skip first row which is just headers
		s = f.readline().split('\t')	
		col = len(s) - skipCol - 1
		# mean and phi lists are filled with 0.00
		mean = [0.00] * col
		phi = [0.00] * col

		row = 0

		# read to the end of the file
		while True:
			data = 	f.readline()
			if not data:
				break
			else:
				# put values into a list
				s = data.split('\t')
				for m in range(skipCol + 1, len(s)):
					try:
						mean[m - skipCol - 1] = mean[m - skipCol - 1] + float(s[m])
					except Exception as e:
						pass
				row+=1

		f.close()

		for m in range(col):
			mean[m] = mean[m] / row
		print('ZScore normalize processing...calculating standard divisions')
		f = open('%s' % inputFile, 'r')
		for k in range(skipRow + 1):
			# skip headers
			f.readline()
		while True:
			data = f.readline()
			if not data:
				break
			else:
				s = data.split('\t')
				for i1 in range(skipCol + 1, len(s)):
					value = 0.0
					try:
						value = float(s[i1])
						phi[i1 - skipCol - 1] = phi[i1 - skipCol - 1] + (value - mean[i1 - skipCol - 1]) ** 2
					except Exception as e:
						pass
					
		f.close()
		for j in range(col):
			phi[j] = math.sqrt(phi[j] / (row - 1))
			# print(str(mean[j]) + '\t' + str(phi[j]))

		outputFile = os.path.split(inputFile)[1].replace('.txt', '_Z.txt')
		f = open('%s' % inputFile, 'r')
		out = open(outputFile,'w')

		for i in range(skipRow + 1):
			out.write(f.readline())

		row = 0
		while True:
			data = f.readline()
			if not data:
				break
			else:
				s = data.split('\t')
				for i1 in range(skipRow + 1):
					out.write(s[i1] + '\t')
				for i1 in range(skipCol + 1, len(s)):
					try:
						value = float(s[i1])
						value = 2.0 * (value - mean[i1 - skipCol - 1]) / phi[i1 - skipCol - 1] + 8.0
						out.write(str(round(value, 3)) + '\t')
					except Exception as e:
						out.write('x' + '\t')
					

				out.write('\n')
				row+=1
				if row % 2500 == 0:
					print('ZScore normalize processing...finished ' + str(row) + ' lines')

		f.close()
		out.close()
		print('ZScore normalize finished')
	except Exception as e:
		print(e)

# find the average of values with column names that are the same
def average(inputFile, needSE):
	try:
		skipRow, skipCol = skips()
		f = open('%s' % inputFile, 'r')
		outputFile = os.path.split(inputFile)[1].replace('.txt', '_Avg.txt')
		out = open(outputFile,'w')

		titleList = [] # will hold all of the titles, used for getting indices for values
		itemList = [] # will hold all the unique titles

		# skips the appropriate amount of rows
		for i in range(skipRow):
			s = f.readline()
			out.write(s + '\n')

		s = f.readline().split('\t')
		for i in range(len(s)):
			s[i] = s[i].strip()
			titleList.append(s[i])
			if s[i] not in itemList and i > skipCol:
				itemList.append(s[i])

		for i in range(skipCol + 1):
			out.write(titleList[i])
			out.write('\t')

		for i in range(len(itemList)):
			out.write(itemList[i])
			if i < len(itemList) - 1:
				out.write('\t')
		out.write('\n')

		line = 0
		while True:
			data = f.readline()
			if not data:
				break
			else:
				s = data.split('\t')
				for j in range(skipCol + 1):
					out.write(str(s[j]) + '\t')

				for j in range(len(itemList)):
					avgItemValue = 0.0
					n = 0
					at = titleList.index(itemList[j])
					while(at >= 0):
						try:
							avgItemValue += float(s[at])
							n+=1
							at = titleList.index(itemList[j], at + 1)
						except Exception as e:
							at = -1
					if n == 0:
						out.write('x\t')
					else:
						avgItemValue /= n
						out.write(str(round(avgItemValue, 4)))
					if j < len(itemList) - 1:
						out.write('\t')

				out.write('\n')
				line +=1

				if line % 1000 == 0:
					print('Processing average...' + str(line) + ' lines\n')

		f.close()
		out.close()
	except Exception as e:
		print(traceback.format_exc())

	if needSE:
		getSE(inputFile, skipRow, skipCol)

# find the SE of the average of the values
def getSE(inputFile, skipRow, skipCol):
	try:
		f = open('%s' % inputFile, 'r')
		outputFile = os.path.split(inputFile)[1].replace('.txt', '_Avg_SE.txt')
		out = open(outputFile,'w')

		titleList = [] # will hold all of the titles, used for getting indices for values
		itemList = [] # will hold all the unique titles

		# skips the appropriate amount of rows
		for i in range(skipRow):
			s = f.readline()
			out.write(s + '\n')

		s = f.readline().split('\t')
		for i in range(len(s)):
			s[i] = s[i].strip()
			titleList.append(s[i])
			if s[i] not in itemList and i > skipCol:
				itemList.append(s[i])

		for i in range(skipCol + 1):
			out.write(titleList[i])
			out.write('\t')

		for i in range(len(itemList)):
			out.write(itemList[i])
			if i < len(itemList) - 1:
				out.write('\t')
		out.write('\n')

		line = 0
		while True:
			data = f.readline()
			if not data:
				break
			else:
				s = data.split('\t')
				for j in range(skipCol + 1):
					out.write(str(s[j]) + '\t')

				for j in range(len(itemList)):
					avgItemValue = 0.0
					n = 0
					at = titleList.index(itemList[j])
					while(at >= 0):
						try:
							avgItemValue += float(s[at])
							n+=1
							at = titleList.index(itemList[j], at + 1)
						except Exception as e:
							at = -1
					if n == 0:
						out.write('x\t')
					else:
						avgItemValue /= n
						SE = 0.0
						n = 0
						at = titleList.index(itemList[j])
						while at >= 0:
							try:
								SE += (avgItemValue - float(s[at])) * (avgItemValue - float(s[at]))
								n +=1
								at = titleList.index(itemList[j], at + 1)
							except Exception as e:
								at = -1

						if n > 1:
							SE = math.sqrt(SE / (n - 1))
							SE /= math.sqrt((n-1))
							out.write(str(round(SE, 8)))
							out.write('\t')
						else:
							out.write('\t')

				out.write('\n')
				line +=1

				if line % 1000 == 0:
					print('Processing average... Standard Error... ' + str(line) + ' lines\n')

		f.close()
		out.close()
	except Exception as e:
		print(traceback.format_exc())

# find outliers
def outlier(inputFile):
	try:
		skipRow, skipCol = skips()
		print('Outlier running')
		f = open('%s' % inputFile, 'r')
		outputFile = os.path.split(inputFile)[1].replace('.txt', '_Outlier.txt')
		out = open(outputFile,'w')

		for i in range(skipRow):
			f.readline()
		data = f.readline()
		for i in range(skipCol + 1):
			if data.index('\t') >= 0:
				data = data[data.index('\t'):]
			data = data.strip()

		sampleTitle = data.split('\t')
		sampleNum = len(sampleTitle)
		values = [0.0] * sampleNum
		marks = [0] * sampleNum
		geneNum = 0

		while True:
			data = f.readline()
			if not data:
				break
			else:
				s = data.split('\t')
				for k in range(sampleNum):
					try:
						values[k] = round(float(s[k + skipCol + 1]), 3)

					except Exception as e:
						pass

				mean = getMean(values)
				phi = getSTD(values)
				for k in range(sampleNum):
					if values[k] < (mean - 2.0 * phi) or values[k] > (mean + 2.0 * phi):
						marks[k] += 1
				
				geneNum += 1	
				if geneNum % 1000 == 0:
					print('Outlier running, finished...' + str(geneNum) + ' lines')

		for j in range(sampleNum):
			out.write(sampleTitle[j] + '\t')
			out.write(str(marks[j]) + '\t')
			out.write(str(round(marks[j] * 1.0 / geneNum, 3)))
			out.write('\n')
		out.close
		print('Outlier finished')

	except Exception as e:
		print(traceback.format_exc())

# adds dashes based on how long the filename is, just here to make the selection a little bit nicer
def dashes(string):
	dash = '-------------------------'
	for i in range(len(string)):
		dash+='-'
	return '\n' + dash

def main():
	input('Press Enter to select file')
	filename = fileSelector()

	while True:
		file = os.path.split(filename)[1]
		print('\nEnter Selection for file ' +  file + dashes(file))
		print('1. Average\n2. Log2 Normalize\n3. ZScore Normalize\n4. Outlier\n5. Select a new file\n6. Exit')
		select = input('Enter: ')

		if select == '1':
			needSE = False
			SE = input('Do you want to compute the standard error [Y/N] (default is no)').lower()
			if SE == 'y':
				needSE = True
			average(filename, needSE)
		elif select == '2':
			log2Normalize(filename)
		elif select == '3':
			ZScoreNormalize(filename)
		elif select == '4':
			outlier(filename)
		elif select == '5':
			filename = fileSelector()
		elif select == '6':
			exit()




main()