-
Notifications
You must be signed in to change notification settings - Fork 1
/
stats.py
executable file
·1808 lines (1316 loc) · 49.5 KB
/
stats.py
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pdb
import sys
import getopt
import operator
import pprint
import os
# begin: jmrc
import matplotlib
matplotlib.use("agg")
#end: jmrc
from numpy import *
from pylab import *
from scipy.stats import norm
import matplotlib.pyplot as plt
import random
import math
#import time
#######################################################
def version():
return "v0.58"
#------------------------------------------------------
# Function to calculate FDR
def fdr_calculator(full_list):
Rank_dic = {}
count = 1
mainlist = []
FDR = 0
## create a dic for the z value with rank =0
for line in full_list:
if str(line[7]).lower() != "nan":
Rank_dic[line[7]] = 0
Rkey = Rank_dic.keys()
Rkey.sort()
## assign rank
for r in Rkey:
Rank_dic[r] = count
count += 1
for line1 in full_list:
if str(line1[7]).lower() == "nan":
FDR = "nan"
else:
Zval = abs(line1[7])
FDR = 2 * (((1 - norm.cdf(Zval)) * float(len(Rank_dic))) / float(Rank_dic[line1[7]]))
line1.append(FDR)
mainlist.append(line1)
return mainlist
#------------------------------------------------------
def graphZij(ZijList,
graphTitle = '',
xLabel = "Zij",
yLabel = "Rank/N",
showGrid = True,
graphLimits = 0,
graphFile = None,
showGraph = True,
dpi = None,
manySigmoids = False,
showLegend = True,
graphFontSize = 8,
lineWidth = 1.0,
labelFontSize = 12,
minimalGraphTicks = False):
# next line is important to prevent SanXoTGauss from printing squares
# instead of Unicode characters, such as Greek letters
matplotlib.rc('font', **{'sans-serif' : 'Arial', 'family' : 'sans-serif'})
graphTitle = graphTitle.strip()
if len(ZijList) < 2: return
if not manySigmoids:
Zij = []
RankN = []
normalDistribution = []
for element in ZijList:
Zij.append(float(element[0]))
RankN.append(element[1])
normalDistribution.append(norm.ppf(element[1]))
plt.plot(Zij, RankN, 'b.', markersize = lineWidth * 2, markeredgewidth = 0.0, label = 'Experimental')
plt.plot(normalDistribution, RankN, 'r', linewidth = lineWidth, markeredgewidth = 0.0, label = 'Theoretical', alpha = 0.8)
else:
# upto 55 colours
# after that, they are all black
defaultColour = "#000000"
plotStyle = ["#FF0000", "#0000FF", "#00FF00", "#FF00FF", "#00FFFF", "#FFFF00", "#800000", "#008000", "#000080", "#808000", "#800080", "#008080", "#808080", "#C00000", "#00C000", "#0000C0", "#C0C000", "#C000C0", "#00C0C0", "#C0C0C0", "#400000", "#004000", "#000040", "#404000", "#400040", "#004040", "#404040", "#200000", "#002000", "#000020", "#202000", "#200020", "#002020", "#202020", "#600000", "#006000", "#000060", "#606000", "#600060", "#006060", "#606060", "#A00000", "#00A000", "#0000A0", "#A0A000", "#A000A0", "#00A0A0", "#A0A0A0", "#E00000", "#00E000", "#0000E0", "#E0E000", "#E000E0", "#00E0E0", "#E0E0E0"]
for j in xrange(len(ZijList)):
i = len(ZijList) - (j + 1)
if i > 0:
graph = ZijList[i]
labelName = splitLabel(graph[0], maxLine = 50)
graphData = graph[1]
if type(graphData) == type([]):
graphX = extractColumns(graphData, 1)
graphY = extractColumns(graphData, 2)
if i < len(plotStyle):
colour = plotStyle[i]
else:
# after max, just keep the last one
colour = plotStyle[-1]
# the .decode(...) is important to avoid problems when text is in Unicode
plt.plot(graphX, graphY, colour,
linewidth = lineWidth, markersize = 2.0, markeredgewidth = 0.0, label = labelName.decode(encoding='UTF-8'))
else:
# theoretical is slightly bolder
graph = ZijList[0]
labelName = splitLabel(graph[0], maxLine = 50)
graphData = graph[1]
graphX = extractColumns(graphData, 1)
graphY = extractColumns(graphData, 2)
bolderLineWidth = 3 * lineWidth
plt.plot(graphX, graphY, plotStyle[0],
linewidth = bolderLineWidth, markersize = 2.0, markeredgewidth = 0.0, label = labelName.decode(encoding='UTF-8'), alpha = 0.8)
plt.xlabel(xLabel, fontsize = labelFontSize)
plt.ylabel(yLabel, fontsize = labelFontSize)
if minimalGraphTicks:
plt.xticks([-graphLimits, 0, graphLimits])
plt.yticks([0, 1])
plt.tick_params(axis = "both", which = "major", labelsize = labelFontSize)
if len(graphTitle) > 0:
plt.title(graphTitle, fontsize = labelFontSize)
plt.grid(showGrid)
if showLegend: plt.legend(loc = 'lower right', prop={'size':graphFontSize})
if graphLimits > 0:
plt.axis([-graphLimits, graphLimits, 0, 1])
plt.tight_layout()
if graphFile:
plt.savefig(graphFile, dpi = dpi)
if showGraph: show()
return
#------------------------------------------------------
def splitLabel(labelName, maxLine = 25, maxLength = 250):
for i in range(maxLength / maxLine)[1:]:
cutLength = (maxLine + 1) * i - 1
if len(labelName) > cutLength:
labelName = labelName[0:cutLength] + "\n" + labelName[cutLength:]
return labelName
#------------------------------------------------------
def joinLocationAndFile(location, file):
location = location.replace("%ProgramFiles%", os.getenv("ProgramFiles"))
location = location.replace("%AppData%", os.getenv("AppData"))
# ... other shortcuts can be added here if needed
if location.startswith("\"") and \
location.endswith("\"") and \
len(location) - len(location.replace("\"", "")):
location = location[1:-1]
if not os.path.isdir(location):
location = os.path.dirname(location)
locationAndFile = os.path.join(location, file)
return locationAndFile
#------------------------------------------------------
def removeDuplicates(inputList):
outputList = inputList[:]
outputList.sort()
i = 0
while i < len(outputList) - 1:
if outputList[i] == outputList[i + 1]:
del outputList[i + 1]
else: i += 1
return outputList
#------------------------------------------------------
def zeroMatrix(x, y = -1, defaultValue = 0.0):
if y == -1: y = x # so, absence of y provides a square matrix
zMatrix = []
for i in xrange(x):
zRow = []
for j in xrange(y):
zRow.append(defaultValue)
zMatrix.append(zRow)
return zMatrix
#------------------------------------------------------
def booleaniseMatrix(myMatrix, threshold = 0):
booleanMatrix = zeroMatrix(len(myMatrix))
for i in xrange(len(myMatrix)):
for j in xrange(len(myMatrix)):
if type(myMatrix[i][j]) == type(0) or type(myMatrix[i][j]) == type(0.0):
if myMatrix[i][j] >= threshold: booleanMatrix[i][j] = 1
else: booleanMatrix[i][j] = 0
else: booleanMatrix[i][j] = myMatrix[i][j]
return booleanMatrix
#------------------------------------------------------
def booleaniseMatrix2(myMatrix, threshold = 0):
print "booleanising matrix"
for i in xrange(len(myMatrix)):
if i % 500 == 0: print "Booleanising row #%i of %i" % (i, len(myMatrix))
for j in xrange(len(myMatrix)):
if type(myMatrix[i][j]) == type(0) or type(myMatrix[i][j]) == type(0.0):
if myMatrix[i][j] >= threshold: myMatrix[i][j] = 1
else: myMatrix[i][j] = 0
return myMatrix
#------------------------------------------------------
def getConfluenceList(inputList, deleteDuplicates = False):
#header = inputList.pop(0)
newList = inputList[:]
outputList = []
for element in newList:
newElement = ['1', element]
outputList.append(newElement)
if deleteDuplicates:
outputList = removeDuplicates(outputList)
#outputList.insert(0, header)
return outputList
#------------------------------------------------------
def fixNodeNameLength(originalName, fixingCharacter = " ", maxLength = 12, lineFeed = " "):
# important for DOT language graphs
nameParts = originalName.split(fixingCharacter)
fixedName = ""
newPart = ""
for part in nameParts:
if len(newPart) < maxLength:
newPart += part + fixingCharacter
else:
fixedName += newPart[:len(newPart) - 1] + lineFeed
newPart = part + fixingCharacter
fixedName += newPart[:len(newPart) - 1]
return fixedName
#------------------------------------------------------
def fixNodeName(originalName):
# important for DOT language graphs
# uppercases should not be a problem, as GVEdit seems to be
# case sensitive
fixedName = "NODE_"
for character in originalName:
if (ord(character) >= ord("a") and ord(character) <= ord("z")) \
or (ord(character) >= ord("A") and ord(character) <= ord("Z")) \
or (ord(character) >= ord("0") and ord(character) <= ord("9")):
fixedName += character
else:
if ord(character) == ord(" "):
fixedName += "_"
else:
fixedName += "_ASCII%i_" % ord(character)
return fixedName
#------------------------------------------------------
def extractVariableFromInfoFile(infoFile, varName = "Variance", defaultSeed = float("nan"), verbose = True):
fileContents = load2stringList(infoFile)
variableOk = True
varName = varName.strip()
for line in fileContents[::-1]: # [::-1] is to search from the end of the file
if varName + " not found" in line[0]:
if verbose: print varName + " not found in previous integration"
variableOk = False
return defaultSeed, variableOk
if varName + " = " in line[0]:
return (double)(line[0].split("=")[1].strip()), variableOk
if verbose: print """the file does not contain any "%s = [float]" line; the default seed will be used.""" % varName
return defaultSeed, variableOk
#------------------------------------------------------
def extractVarianceFromVarFile(varFile, verbose = True, defaultSeed = 0.001):
resultValue, varianceOk = extractVariableFromInfoFile(varFile, varName = "Variance", defaultSeed = defaultSeed, verbose = verbose)
return resultValue, varianceOk
#------------------------------------------------------
def extractKFromKFile(kFile, verbose = True, defaultSeed = 1.0):
resultValue, KOk = extractVariableFromInfoFile(kFile, varName = "K", defaultSeed = defaultSeed, verbose = verbose)
return resultValue, KOk
#------------------------------------------------------
def refillDuplicates(inputList):
changed = False
outputList = inputList[:]
outputList.sort()
i = 0
while i < len(outputList) - 1:
if outputList[i] == outputList[i + 1]:
randomNumber = random.randint(0, len(inputList) - 1)
outputList[i][0] = inputList[randomNumber][0]
changed = True
else: i += 1
return outputList, changed
#------------------------------------------------------
def getRandomList(inputList):
outputList = [-1] * len(inputList) # filling all with -1
lowerList = list(set(extractColumns(inputList, 1)))
listWithId = []
# generating conversionTable
conversionTable = []
i = 0
for i in xrange(len(lowerList)):
conversionTable.append([i, random.random()])
conversionTable = sortByIndex(conversionTable, 1)
conversionTable = extractColumns(conversionTable, 0)
# older conversionTable generator
# while i < len(lowerList):
# randomNumber = random.randint(0, len(lowerList) - 1)
# if not randomNumber in conversionTable:
# conversionTable.append(randomNumber)
# i += 1
# assigning new relations according to conversion table
for i in xrange(len(outputList)):
# switching lower elements
# while keeping structure (distribution of lower elements per higher element)
lowerElement = inputList[i][1]
# improved method, much faster!!
index, listWithId = firstIndex(list = lowerList, listWithId = listWithId, element = lowerElement, method = "binsearch")
indexOfNewElement = conversionTable[index]
newElement = lowerList[indexOfNewElement]
outputList[i] = [inputList[i][0], newElement]
if -1 in outputList:
print "Error while generating the randomised relations table"
sys.exit()
return outputList
#------------------------------------------------------
def getNodeColourList(node,
elementNumber,
ZLimit = 6.0,
subData = None,
extraData = None,
maxAltTextLinesPerSide = 5,
lineFeed = " ",
defaultNodeColour = "#ffff80",
errorNodeColour = "#8080ff", # default is white
minColour = "#00ff00",
middleColour = "#ffffff",
maxColour = "#ff0000",
bgColour = "#ffffd8",
defaultNodeTextColour = "#000000",
nonParetoOpacity = 0.5,
errorNodeTextColour = "#0000ff",
paretoInfo = None):
altText = ""
NValue = -1
nodeColour = defaultNodeColour
nodeFontColour = defaultNodeTextColour
nonParetoNodeTextColour = averageColour(normalisedValue = nonParetoOpacity,
colour1 = bgColour,
colour2 = defaultNodeTextColour)
nodeIsParetoFront = True
try:
if paretoInfo:
# if node == "DAVID_SP_PIR_KEYWORDS_blood coagulation":
# pdb.set_trace()
nodeIsParetoFront = True
if filterByElement(paretoInfo, node)[0][1]:
nodeFontColour = defaultNodeTextColour
else:
nodeIsParetoFront = False
nodeFontColour = nonParetoNodeTextColour
except:
nodeFontColour = errorNodeTextColour
i = elementNumber + 2
try:
if subData:
subDataHigher = subData[0][i][0]
if subDataHigher == node:
nodeColour = ""
NValue = len(subData[0][i][1])
lowerNodeElementRatio = 1.0 / float(NValue)
counter = 0
for lowerElement in subData[0][i][1]:
counter += 1
lowerNodeElementZ = lowerElement[1]
lowerNodeElementColour = extrapolateColour(lowerNodeElementZ,
minValue = -ZLimit,
middleValue = 0.0,
maxValue = ZLimit,
maxColour = maxColour,
middleColour = middleColour,
minColour = minColour)
if not nodeIsParetoFront:
lowerNodeElementColour = averageColour(normalisedValue = nonParetoOpacity,
colour1 = bgColour,
colour2 = lowerNodeElementColour)
lowerNodeElementResult = "%s;%f:" % (lowerNodeElementColour, lowerNodeElementRatio)
nodeColour += lowerNodeElementResult
if maxAltTextLinesPerSide > 0:
lowerNodeElementName = str(lowerElement[0])
lowerElementAltText = "%i) Z = %f, NAME = "%s"" % (counter, lowerNodeElementZ, lowerNodeElementName)
if len(altText) == 0:
altText = lowerElementAltText
else:
if counter > maxAltTextLinesPerSide and counter < NValue - maxAltTextLinesPerSide + 1:
if counter == maxAltTextLinesPerSide + 1: altText += " "
altText += "."
else:
altText += lineFeed + lowerElementAltText
if len(nodeColour) > 0:
nodeColour = nodeColour[:-1] # to remove final ":"
else:
nodeColour = errorNodeColour # blue denotes an error occurred
else:
# in this case, the names do not match
# should search for it, as the list might be in a different order if
# the code has been touched,
# but for the moment it will just paint it in blue ***
nodeColour = errorNodeColour
else:
ZIndex = 2
nodeColour = getNodeColour(node,
extraData = extraData,
colouringVariableIndex = ZIndex,
minValue = -ZLimit,
middleValue = 0,
maxValue = ZLimit,
maxColour = maxColour,
middleColour = middleColour,
minColour = minColour)
if len(nodeColour) > 2**14: nodeColour = nodeColourReduced(nodeColour)
# should give an error when nodeColour is > 2**14 even after nodeColourReduced
# could make shorter numbers in that case
except:
return errorNodeColour, NValue
return nodeColour, NValue, altText, nodeFontColour
#------------------------------------------------------
def extrapolateColour(value = 0.0,
minValue = 0.0,
middleValue = 1.0,
maxValue = 1.0,
minColour = "#00ff00",
middleColour = "#ffffff",
maxColour = "#ff0000"):
resultingColour = middleColour
if value <= minValue:
resultingColour = minColour
if value > minValue and value < middleValue:
if minValue == middleValue:
resultingColour = minColour
else:
normalisedValue = (value - minValue) / (middleValue - minValue)
resultingColour = averageColour(normalisedValue, minColour, middleColour)
if value > middleValue and value < maxValue: # value = middleColour is default already
if middleValue == maxValue:
resultingColour = maxColour
else:
normalisedValue = (value - middleValue) / (maxValue - middleValue)
resultingColour = averageColour(normalisedValue, middleColour, maxColour)
if value >= maxValue:
resultingColour = maxColour
return resultingColour
#------------------------------------------------------
def averageColour(normalisedValue = 0.5, colour1 = "#000000", colour2 = "#ffffff"):
if normalisedValue < 0: normalisedValue = 0
if normalisedValue > 1: normalisedValue = 1
red1, green1, blue1 = divideColour(colour1)
red2, green2, blue2 = divideColour(colour2)
newRed = middleValue(normalisedValue, [0.0, red1], [1.0, red2])
newGreen = middleValue(normalisedValue, [0.0, green1], [1.0, green2])
newBlue = middleValue(normalisedValue, [0.0, blue1], [1.0, blue2])
newColour = hexRGBFromDecimal(newRed, newGreen, newBlue)
return newColour
#------------------------------------------------------
def hexRGBFromDecimal(decRed, decGreen, decBlue):
intRed = int(round(decRed))
intGreen = int(round(decGreen))
intBlue = int(round(decBlue))
if intRed > 255: intRed = 255
if intGreen > 255: intGreen = 255
if intBlue > 255: intBlue = 255
if intRed < 0: intRed = 0
if intGreen < 0: intGreen = 0
if intBlue < 0: intBlue = 0
hexRed = dec2hex(intRed)
hexGreen = dec2hex(intGreen)
hexBlue = dec2hex(intBlue)
hexRGB = "#" + hexRed + hexGreen + hexBlue
return hexRGB
#------------------------------------------------------
def dec2hex(decValue):
# only for values between 2 and 255!!
# decValue must be an integer
hexValue = hex(decValue).split('x')[1]
if len(hexValue) == 1:
hexValue = "0" + hexValue
return hexValue
#------------------------------------------------------
def divideColour(hexColour):
hexRed = hexColour[1:3]
hexGreen = hexColour[3:5]
hexBlue = hexColour[5:7]
decRed = float(int(hexRed, 16))
decGreen = float(int(hexGreen, 16))
decBlue = float(int(hexBlue, 16))
return decRed, decGreen, decBlue
#------------------------------------------------------
def nodeColourReduced(colourList):
splitColours = colourList.split(":")
i = 0
while i < len(splitColours) - 1:
currentColour = splitColours[i].split(";")[0]
nextColour = splitColours[i + 1].split(";")[0]
if currentColour == nextColour:
sizeColour = float(splitColours[i].split(";")[1]) + float(splitColours[i + 1].split(";")[1])
newColour = "%s;%f" % (currentColour, sizeColour)
del splitColours[i]
splitColours[i] = newColour
else: i += 1
newColourList = ""
for i in xrange(len(splitColours)):
newColourList += splitColours[i] + ":"
newColourList = newColourList[:-1]
return newColourList
#------------------------------------------------------
def getNodeColour(node,
defaultColour = "#FFFFFF",
extraData = None,
colouringVariableIndex = 1.0,
minValue = 0.0,
middleValue = 0.5,
maxValue = 1.0,
minColour = "#00ff00",
middleColour = "#ffffff",
maxColour = "#ff0000"):
nodeColour = defaultColour
if extraData:
# this needs to be implemented ****
nodeIndex = -1
for i in xrange(len(extraData)):
if node == extraData[i][0]:
nodeIndex = i
break
if nodeIndex > -1:
nodeColour = extrapolateColour(float(extraData[nodeIndex][colouringVariableIndex]),
minValue = minValue,
middleValue = middleValue,
maxValue = maxValue,
minColour = minColour,
middleColour = middleColour,
maxColour = maxColour)
return nodeColour
#------------------------------------------------------
def getFromIni(iniFile, variableName):
result = ""
if os.path.exists(iniFile):
iniText = load2stringList(iniFile)
for line in iniText:
element = line[0]
if len(element) > 0 and "=" in element and element.strip()[0] != "#":
parts = element.split("=")
if parts[0].strip().lower() == variableName.strip().lower():
result = parts[1].strip()
break
return result
#------------------------------------------------------
def getNodeFontSize(NValue,
NMax = 1000,
NMin = 2,
normalFontSize = 14.0,
maxFontSize = 50.0,
minFontSize = 10.0):
if NMax == NMin: return normalFontSize
if NValue <= 0: return normalFontSize
point1 = [math.log(NMin), minFontSize]
point2 = [math.log(NMax), maxFontSize]
fontSize = middleValue(math.log(NValue), point1, point2)
if fontSize <= minFontSize: return minFontSize
if fontSize >= maxFontSize: return maxFontSize
return fontSize
#------------------------------------------------------
def removeHeader(myList):
if len(myList) > 0:
myList.remove(myList[0])
return myList
#------------------------------------------------------
def load2dictionary(fileName, keyNum, n1, n2 = -1, n3 = -1, n4=-1, n5=-1, splitter = "\t", lineFeed = "\n"):
dic = {}
with open(fileName) as file:
next(file)
for line in file:
if line != lineFeed:
splits=line.split(splitter)
keyField = splits[keyNum].strip()
if n5 >=0 and n4 >=0 and n3>=0 and n2>=0:
dic[keyField]=[splits[n1].strip(), splits[n2].strip(), splits[n3].strip(), splits[n4].strip(), splits[n5].strip()]
else:
if n4 >=0 and n3>=0 and n2>=0:
dic[keyField]=[splits[n1].strip(), splits[n2].strip(), splits[n3].strip(), splits[n4].strip()]
else:
if n3 >= 0 and n2 >=0:
dic[keyField]=[splits[n1].strip(), splits[n2].strip(), splits[n3].strip()]
else:
if n2 >=0:
dic[keyField]=[splits[n1].strip(),splits[n2].strip()]
else:
dic[keyField]=[splits[n1].strip()]
return dic
#------------------------------------------------------
# load any _tab separated values_ file
def load2stringList(fileName, removeCommas = False, splitChar = "\t"):
reader = open(fileName, "r")
fullList = []
for myRow in reader:
myRowStrip = myRow.strip()
if len(myRowStrip) > 0:
thisRow = myRowStrip.split(splitChar)
for i in xrange(len(thisRow)):
thisRow[i] = thisRow[i].strip()
if removeCommas:
for i in xrange(len(thisRow)):
if thisRow[i].endswith('"') and thisRow[i].startswith('"'):
thisRow[i] = thisRow[i][1:len(thisRow[i]) - 1]
fullList.append(thisRow)
return fullList
#------------------------------------------------------
def arrangeSubData(inStats = "",
uFile = "",
relFile = "",
higherElements = None,
relations = None,
ignoreNaNsInFDR = False):
results = []
if not relations:
relations = loadRelationsFile(relFile)
relations = sortByIndex(relations, 0)
statsData = loadStatsDataFile(inStats, FDRasText = ignoreNaNsInFDR)
if not higherElements:
higherElements = load2stringList(uFile, removeCommas = True)
if higherElements[0] == ['id', 'Z', 'n'] \
or higherElements[0] == ['id', 'n', 'Z', 'FDR'] \
or higherElements[0] == ['id', 'n', 'Z', 'FDR', 'X']:
# this means the list comes from SanXoTSqueezer
# so the header and the extra columns have to be removed
higherElements = extractColumns(higherElements[1:], 0)
else:
# only removing extra columns and converting list into text
higherElements = extractColumns(higherElements, 0)
statsData = sortByIndex(statsData, 7)
ZijList = []
for element in statsData:
ZijList.append([element[3], element[7]])
# to be implemented to avoid not a numbers
# # this is a trick to remove "not a number" element fast
# for i in xrange(len(ZijList)):
# if str(ZijList[i][1]).lower() == "nan":
# ZijList[i][1] = sys.float_info.max
# ZijList = sortByIndex(ZijList, 2)
# try:
# NaNindex = stats.firstIndex(ZijList, sys.float_info.max)
# ZijList = ZijList[0:NaNindex - 1]
# except:
# pass
theorList = []
experList = []
N = len(ZijList)
for i in xrange(N):
theorList.append([ZijList[i][0], ZijList[i][1], norm.cdf(float(ZijList[i][1]))])
experList.append([ZijList[i][0], ZijList[i][1], (float(i) + 0.5) / float(N)])
results.append(['Theoretical', theorList])
results.append(['Experimental', experList])
relationsFirstColumn = extractColumns(relations, 0)
relationsSecondColumn = extractColumns(relations, 1)
experListFirstColumn = extractColumns(experList, 0)
for uElement in higherElements:
lowerElementList = []
first = firstIndex(relationsFirstColumn, uElement)
if first > -1: # -1 means it is not in the list
notInList = 0
last = lastIndex(relationsFirstColumn, uElement)
lowerElements = relationsSecondColumn[first:last + 1] # "+1" is to include the last one
for element in lowerElements:
lowerIndex = firstIndex(experListFirstColumn, element)
if lowerIndex > -1: # -1 means it is not in the list
Zlower = experList[lowerIndex][1]
lowerElementList.append([element, Zlower])
else:
notInList += 1
lowerElementList = sortByIndex(lowerElementList, 1)
# now we add the rank/N
# N = len(lowerElementList) [it should coincide]
N = last - first + 1 - notInList
rank = 0.5
for element in lowerElementList:
rankNlower = rank / float(N)
element.append(rankNlower)
rank += 1
results.append([uElement, lowerElementList])
else:
results.append([uElement, None])
return results, ""
#------------------------------------------------------
def createBigTable(data = None):
# used by SanXoTGauss and Sanson
bigTable = []
extraTable = []
header1 = ""
header2 = ""
# data[j][0] contains the name of the category
# each data[j][1][i] contains a list with [id, Zij, rank/N]
for j in xrange(len(data)):
if j == 0:
header1 += str(data[0][0]) + "\t\t\t"
header2 += "id\tZ\tp\t"
for subData in data[0][1]:
bigTable.append(subData)
else:
header1 += str(data[j][0]) + "\t\t\t"
header2 += "id\tZ\trank/N\t"
for i in xrange(len(bigTable)):
if type(data[j][1]) == type([]):
if i < len(data[j][1]):
bigTable[i].extend(data[j][1][i])
if j > 1:
newRow = []
newRow.append(data[j][0])
newRow.extend(data[j][1][i])
extraTable.append(newRow)
if i >= len(data[j][1]):
bigTable[i].extend(['','',''])
else: # NoneType -> this means the uLevel was not present
bigTable[i].extend(['','',''])
header = header1 + "\n" + header2
extraHeader = "idsup\tidinf\tZ\trank/N"
return bigTable, header, extraTable, extraHeader
#------------------------------------------------------
def stringList2inputDataFile_old(input):
result = []
for myRow in input:
# if it is an inputRawDataFile, it should be str - float - float
resultRow = []
resultRow.append(myRow[0]) # identificator, such as raw-scannumber-charge string
# *** next line should be general to avoid any text
if myRow[1].lower() != "neun" and myRow[2].lower != "neun" and myRow[1].lower() != "nan" and myRow[2].lower() != "nan":
resultRow.append(float(myRow[1])) # Xi
resultRow.append(float(myRow[2])) # Vs
result.append(resultRow)
return result
#------------------------------------------------------
def stringList2inputDataFile(input, format = ['s', 'f', 'f'], fillEmptyPositions = False, emptyFiller = ""):
result = []
counter = 0
for myRow in input:
# if it is an inputRawDataFile, it should be str - float - float
if fillEmptyPositions or len(myRow) >= len(format):
resultRow = []
if len(format) > 0:
for i in xrange(len(format)):
if i > len(myRow) - 1:
resultRow.append(emptyFiller)
else:
stringy = myRow[i].strip()
if format[i] == 's':
resultRow.append(stringy)
elif format[i] == 'f' or format[i] == 'i':
if len(stringy) > 0 and \
((stringy[0] >= '0' and stringy[0] <= '9') or \
(stringy[0] == '-' and (stringy[1] >= '0' and stringy[1] <= '9'))):
if format[i] == 'f': resultRow.append(float(stringy))
if format[i] == 'i': resultRow.append(int(stringy))
else:
# if a row that is supposed to contain a float or an int
# is empty, or there is an error while reading it,
# the row is not read but the program keeps going
resultRow = []
break
if len(resultRow) > 0:
result.append(resultRow)
return result
#------------------------------------------------------
def loadInputDataFile(fileName):
result = load2stringList(fileName, removeCommas = True)