-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMAPR_characterizeSet.py
1940 lines (1565 loc) · 52.8 KB
/
MAPR_characterizeSet.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
"""
GeneSet MAPR implementation
Step 03: characterize input set(s)
ie: rank genes & describe connections
For an input set of nodes, rank all nodes in the
network by the density of their connections to
the set. Nodes connected by patterns similar
to connections within the set are ranked higher.
Output the rank and details about common
connection patterns.
author: Greg Linkowski
for KnowEnG by UIUC & NIH
"""
import argparse
import time
import numpy as np
from sklearn import linear_model as lm
import random
import warnings
import sys
import os
import gzip
import re
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Agg')
################################################################
# GLOBAL PARAMETERS
# Level of verbosity (feedback in terminal)
VERBOSITY = 0
# Character used to sepate text in output files
TEXT_DELIM = '\t'
# size the zero-padded matrix file name (match MAPR_networkPrep !)
FNAME_ZPAD = 6
# Data-type for the path matrices (allow room for computation)
MATRIX_DTYPE = np.float32
# end params ##############################
################################################################
# ANCILLARY FUNCTIONS
def readCommandLineFlags():
parser = argparse.ArgumentParser()
parser.add_argument('setsRoot', type=str,
help='parent directory containing input sets')
parser.add_argument('-l', '--length', type=int, default=3,
help='maximum meta-path depth')
parser.add_argument('-v', '--verbose', type=int, default=0,
help='enable verbose output to terminal: 0=none, 2=all')
parser.add_argument('-i', '--ignore', type=str, default='NONE',
help='text file containing list of edge types to ignore')
parser.add_argument('-m', '--numModels', type=int, default=101,
help='number of random null sets to use for comparison')
parser.add_argument('-p', '--plotAUCs', type=bool, default=False,
help='to save plots of AUC curves, set to "True"')
flags = parser.parse_args()
return flags
# end def #################################
def setParamVerbose(newVal):
"""
set the global parameters
:param newVal: bool, the new value
:return:
"""
global VERBOSITY
VERBOSITY = min(max(newVal, 0), 2)
return
# end def #################################
def setParamTextDelim(newVal):
"""
set the global parameters
:param newVal: str, desired text delimiter character
NOTE: an input value of...
'-1' keeps the parameter unchanged
'-2' resets parameter to default
:return:
"""
global TEXT_DELIM
if str(newVal) == '-1':
TEXT_DELIM = TEXT_DELIM
elif str(newVal) == '-2':
TEXT_DELIM = '\t'
else:
TEXT_DELIM = str(newVal)
# end if
return
# end def #################################
def getGeneIndexLists(path, gDict):
# Create index lists for Known, Hidden, Unknown, TrueNeg
gKnown = readFileAsList(path + 'known.txt')
giKnown = convertToIndices(gKnown, gDict)
gHidden = readFileAsList(path + 'concealed.txt')
giHidden = convertToIndices(gHidden, gDict)
giUnknown = [g for g in gDict.values() if g not in giKnown]
giTrueNeg = [g for g in giUnknown if g not in giHidden]
return giKnown, giUnknown, giHidden, giTrueNeg
# end def #################################
def readFileAsList(fName) :
"""
Read in a file as a line-by-line list of items
:param fName: str, path + name of the the sample files
:return: fItems, str list: ordered list of items from file
"""
# ERROR CHECK: verify file exists
if not os.path.isfile(fName) :
print ( "ERROR: Specified file doesn't exist:" +
" {}".format(fName))
sys.exit()
#end if
# The list of items to return
fItems = list()
# Read in from the file
fn = open(fName, "r")
for line in fn :
fItems.append( line.rstrip() )
#end loop
fn.close()
fItems.sort()
return fItems
# end def #################################
def convertToIndices(names, iDict) :
"""
Given a list of names and appropriate dict,
convert to corresponding index values
:param names: str list, names of items to convert
:param iDict: dict,
key, str: names of items
value, int: corresponding index values
:return: indices, int list: index values of the input items
"""
# The item to return
indices = list()
for name in names :
indices.append(iDict[name])
#end loop
return indices
# end def #################################
def aggregateRankFromScore(scoreCols, weights):
# Normalize the columns
# Center each column about the mean
mMean = np.mean(scoreCols, axis=0)
mNormed = np.subtract(scoreCols, mMean)
# Set the L2 norm = 1
mAbsMax = np.amax(np.absolute(mNormed), axis=0)
mAbsMax = np.add(mAbsMax, 0.0001) # so as not to / 0
scoreColsNormed = np.divide(mNormed, mAbsMax)
# numRows = scoreCols.shape[0]
numRows = scoreColsNormed.shape[0]
sumRanks = np.zeros(numRows)
sumScores = np.zeros(numRows)
# For each column
# rank the rows by their score
# sort by score, apply rank, sort by index
# multiply rank by weight & add to sumRanks
# Then sort & rank again
ranker = np.recarray(numRows,
dtype=[('rowIdx', 'i4'), ('score', 'f4'), ('rank', 'f4')])
for i in range(len(weights)):
ranker['rowIdx'] = np.arange(numRows)
ranker['score'] = scoreCols[:, i]
ranker['rank'] = np.zeros(numRows)
ranker.sort(order=['score'])
ranker = ranker[::-1]
ranker['rank'] = np.arange(numRows)
ranker.sort(order=['rowIdx'])
sumRanks = np.add(sumRanks, np.multiply(ranker['rank'], weights[i]))
sumScores = np.add(sumScores, np.multiply(ranker['score'], weights[i]))
# end loop
sNormed = np.subtract(sumScores, np.mean(sumScores))
sAbsMax = np.add(np.amax(np.absolute(sNormed)), 0.000001)
finScores = np.divide(sNormed, sAbsMax)
rankFinal = np.recarray(numRows,
dtype=[('rowIdx', 'i4'), ('score', 'f4'), ('rankSum', 'f4')])
rankFinal['rowIdx'] = np.arange(numRows)
rankFinal['score'] = finScores
rankFinal['rankSum'] = sumRanks
rankFinal.sort(order=['rankSum'])
return rankFinal
# end def #################################
def aggRankFromStandardizedScore(scoreCols, weights):
"""
Get the aggregate rank of each gene from the weighted mean of their standardized scores
over each predictive model/vote. Weights come from the model's ability to separate
the Pos/Neg training data.
:param scoreCols: 2D array (genes, models/votes), as numpy array
:param weights: list/array of weights, one per model/vote
:return:
"""
#### Standardize the scores by column
# using column mean & column standard deviation
cMean = np.reshape(np.mean(scoreCols, axis=0), (1, scoreCols.shape[1]))
cSTD = np.reshape(np.std(scoreCols, axis=0), (1, scoreCols.shape[1]))
scoresStd = np.divide(np.subtract(scoreCols, cMean), np.add(cSTD, 1e-11))
# scoreStd = np.divide( scoreCols, np.add(cSTD, 1e-8))
#### Get the weighted mean
scoresMean = np.sum(np.multiply(scoresStd, np.reshape(weights, (1, len(weights)))), axis=1)
scoresMean = np.divide(scoresMean, np.sum(weights))
#### Return list of genes sorted by rank
ranker = np.recarray(scoreCols.shape[0],
dtype=[('rowIdx', 'i4'), ('score', 'f4'), ('rankSum', 'f4')])
ranker['score'] = scoresMean
ranker['rowIdx'] = np.arange(scoreCols.shape[0])
ranker.sort(order=['score'])
ranker = ranker[::-1]
ranker['rankSum'] = np.arange(scoreCols.shape[0])
ranker.sort(order=['rankSum'])
return ranker
# end def #################################
def checkIfNameHasDuplicate(pathName):
"""
Check if a meta-path name consecutively contains two of the same edge type.
:param pathName: (str) the MP name, types separated by '-'
:return: (bool) True if a duplicate occurs, False otherwise
"""
retBool = False
pv = pathName.split('-')
if len(pv) > 1:
for i in range(1, len(pv)):
if pv[i] == pv[i - 1]:
retBool = True
break
# end if
# end for
# end if
return retBool
# end def #################################
def getGeneAndPathDict(path) :
"""
Get the specified geneDict & pathDict from parameters.txt
:param path: str, path to the samples' parameter.txt file
(parameters.txt tells where the network is stored/named)
:return: geneDict, pathDict
"""
# get the network path & name from the parameters.txt file
if not path.endswith('/') :
path = path + '/'
with open(path + 'parameters.txt', 'r') as fin :
line = fin.readline()
del line
line = fin.readline()
line = line.rstrip()
lv = line.split(TEXT_DELIM)
eName = lv[1]
line = fin.readline()
line = line.rstrip()
lv = line.split(TEXT_DELIM)
ePath = lv[1]
#end with
if VERBOSITY :
print("Reading gene and path dictionaries for {}".format(eName))
geneDict = readGenesFile(ePath, eName)
pathDict = readKeyFile(ePath, eName)
return geneDict, pathDict
# end def #################################
def readGenesFile(path, name) :
"""
Read in the genes.txt file containing the
gene-name headers to the metapath matrices
Pre-reqs: readFileAsIndexDict(fname)
:param path: str, path to the network files
:param name: name, str, name of the network to use
:return: gDict, dict
key, str: name of gene
value, int: row/col index for that gene
"""
fname = name + '_MetaPaths/genes.txt'
if verifyFile(path, name + fname, True) :
# The item to return
gDict = readFileAsIndexDict(fname)
else :
fname = path + name + '/genes.txt'
# The item to return
gDict = readFileAsIndexDict(fname)
#end if
return gDict
# end def #################################
def verifyFile(path, name, quiet) :
"""
ERROR CHECK: verify file exists
:param path: str, path to save the file
:param name: str, name of the file (w/ extension)
:param quiet: bool, whether to quietly return T/F
:return: exists, bool: indicates existence of file
"""
exists = True
# First check the directory
if not (path == '') :
exists = verifyDirectory(path, False, quiet)
# Then look for the file
if not path.endswith('/') :
path = path+'/'
#end if
if not os.path.isfile(path+name) :
if quiet:
exists = False
else :
print ( "ERROR: Specified file doesn't exist:" +
" {}".format(path) )
sys.exit()
#end if
return exists
# end def #################################
def verifyDirectory(path, create, quiet) :
"""
ERROR CHECK: verify directory exists
:param path: str: path to verify
:param create: bool, whether to create missing dir
:param quiet: bool, whether to quietly return T/F
:return: exists, bool: indicates existence of directory
"""
exists = True
if not os.path.isdir(path) :
if create :
print("Creating path: {}".format(path))
os.makedirs(path)
elif quiet :
exists = False
else :
print ( "ERROR: Specified path doesn't exist:" +
" {}".format(path) )
sys.exit()
#end if
return exists
# end def #################################
def readFileAsIndexDict(fName) :
"""
Read in the gene file. File is an ordered list
of genes, where the row number (starting at zero)
corresonds to the index in the matrix/list/etc where
the gene can be found.
:param fName: str, path & name to keep file
:return: iDict, dict:
key, str: gene name as read from file
value, int: index to corresponding array
"""
# ERROR CHECK: verify file exists
if not os.path.isfile(fName) :
print ( "ERROR: Specified file doesn't exist:" +
" {}".format(fName))
sys.exit()
#end if
# Build the dictionary from the text file
iDict = dict()
gf = open(fName, "r")
index = 0
for line in gf :
gene = line.rstrip() # remove "\n"
iDict[gene] = int(index)
index += 1
#end loop
return iDict
# end def #################################
def readKeyFile(path, name) :
"""
Read in the key.txt file regarding the
metapath matrices
:param path: str, path to the network files
:param name: str, name of the network to use
:return: keyDict, dict
key, str: name of metapath
value, tuple: int is matrix/file ID number
bool where True means use matrix transpose
"""
fName = path + name + "_MetaPaths/key.txt"
# ERROR CHECK: verify file exists
if not os.path.isfile(fName) :
print ( "ERROR: Specified file doesn't exist:" +
" {}".format(fName) )
sys.exit()
#end if
# The item to return
keyDict = dict()
# Read in the file
fk = open(fName, "r")
firstLine = True
for line in fk :
# skip the first line
if firstLine :
firstLine = False
continue
#end if
# separate the values
line = line.rstrip()
lk = line.split('\t')
lv = lk[0].split(',')
transpose = False
if lv[1] == "t" :
transpose = True
#end if
# add to the dict
keyDict[lk[1]] = [int(lv[0]), transpose]
#end loop
fk.close()
return keyDict
# end def #################################
def removeInvertedPaths(mpDict) :
"""
Find the number of paths of this type joining
the nodes in the sample
:param mpDict: {str: [int, bool]} dict,
key, str - name of the metapath
value, [int, bool] - which matrix file to use, and
whether to use the transpose (inverse path)
:return: mpList, str list: ordered names of paths available,
less paths that are mirror-images of another
"""
# The item to return
mpList = list()
# Check the keys in the dict
for key in mpDict.keys() :
# If the boolean is True, then the path is an
# inverse of another; only append if false
if not mpDict[key][1] :
mpList.append(key)
#end loop
mpList.sort()
return mpList
# end def #################################
def getFeaturesNeighborhood(path, suffix):
"""
Get the neighborhood features from parameters.txt
:param path: str, path to the samples' parameter.txt file
(parameters.txt tells where the network is stored/named)
:param suffix: str, filename suffix (which version of feature to load)
:return: featVals, featNames
"""
# get the network path & name from the parameters.txt file
if not path.endswith('/'):
path = path + '/'
with open(path + 'parameters.txt', 'r') as fin:
line = fin.readline()
del line
line = fin.readline()
line = line.rstrip()
lv = line.split(TEXT_DELIM)
eName = lv[1]
line = fin.readline()
line = line.rstrip()
lv = line.split(TEXT_DELIM)
ePath = lv[1]
# end with
if VERBOSITY:
print("Reading neighborhood features file for {}".format(eName))
if not ePath.endswith('/'):
ePath = ePath + '/'
if not eName.endswith('/'):
eName = eName + '/'
featVals = np.loadtxt(ePath + eName + 'featNeighbor_' + suffix + '.gz')
featNames = readFileAsList(ePath + eName + 'featNeighbor_Names.txt')
featNames = np.reshape(featNames, (1, len(featNames)))
return featVals, featNames
# end def #################################
def getSubDirectoryList(root) :
"""
Return list of paths to folders in the
given root directory
:param root: str, path where the folders reside
:return: subDirs, str list: sorted list of subdirectories
contains full path: root+subdir
"""
verifyDirectory(root, False, False)
if not root.endswith('/') :
root = root+'/'
subDirs = [(root+d+'/') for d in os.listdir(root) if os.path.isdir(root+d)]
subDirs.sort()
return subDirs
# end def #################################
def normalizeFeatureColumns(featMatrix) :
"""
Normalize each column of the feature matrix
:param featMatrix: matrix containing feature weights
row: gene feature vector
col: each individual feature
:return: featNormed: the normalized copy of the original matrix
"""
# Center each column about the mean
featMean = np.mean(featMatrix, axis=0)
featNormed = np.subtract(featMatrix, featMean)
# Set the L2 norm = 1
featAbsMax = np.minimum(featMean, np.amax(featNormed, axis=0))
featAbsMax = np.add(featAbsMax, 1) # hack so as not to / by 0
featNormed = np.divide(featNormed, featAbsMax)
return featNormed
# end def #################################
def getFeaturesTermsV2(path) :
"""
Get the term weight features from parameters.txt
:param path: str, path to the samples' parameter.txt file
(parameters.txt tells where the network is stored/named)
:return: featVals, featNames
"""
# get the network path & name from the parameters.txt file
if not path.endswith('/') :
path = path + '/'
with open(path + 'parameters.txt', 'r') as fin :
line = fin.readline()
del line
line = fin.readline()
line = line.rstrip()
lv = line.split('\t')
eName = lv[1]
line = fin.readline()
line = line.rstrip()
lv = line.split('\t')
ePath = lv[1]
#end with
if not ePath.endswith('/') :
ePath = ePath + '/'
if eName.endswith('/') :
eName = eName.rstrip('/')
########
# Load the non-gene term raw data matrices
# Read in the key file for terms: key_termNonGene.txt
termKey = readKeyFileSimple(ePath, eName, 'key_termNonGene.txt')
# Count how many genes there are (number rows)
gList = readFileAsList(ePath + eName + '/genes.txt')
gCount = len(gList)
del gList
# Initialize the items to return
featVals = np.zeros( (gCount,0), dtype=np.float32)
featNames = list()
# Append the items from each term dictionary
for e in list(termKey.keys()) :
ftlName = ePath + eName + '_MetaPaths/' + termKey[e] + 'tl.txt'
tList = readFileAsList(ftlName)
tMatrix = getTermMatrix(termKey[e], ePath, eName, gCount, len(tList))
featVals = np.hstack((featVals, tMatrix))
featNames = np.append(featNames, tList)
#end loop
########
# Load the gene-gene network matrices
# Read in the key file for all primary networks: key_primaries.txt
primKey = readKeyFileSimple(ePath, eName, 'key_primaries.txt')
geneKey = dict()
for k in primKey.keys() :
if k in termKey.keys() :
continue
geneKey[k] = (primKey[k], False)
#end for
del termKey, primKey
# Load the gene names
gNames = readFileAsList(ePath + eName + '/genes.txt')
# Append the items from each gene-gene matrix
sortedKeys = list(geneKey.keys())
sortedKeys.sort()
sumMatrix = np.zeros( (len(gNames), len(gNames)), dtype=np.float32)
for e in list(sortedKeys) :
# Normalize the weights for this set of terms
fMatrix = loadPathMatrix(geneKey[e], ePath, eName, len(gNames))
fMatrix = np.divide(fMatrix, np.sum(fMatrix))
sumMatrix = np.add(sumMatrix, fMatrix)
del fMatrix
#end loop
featVals = np.hstack((featVals, sumMatrix))
featNames = np.append(featNames, gNames)
if VERBOSITY == 2 :
sizeGB = featVals.nbytes / 1.0e9
print(" ... total feature vector size, {:.3f} Gb".format(sizeGB))
#end if
return featVals, featNames
# end def #################################
def readKeyFileSimple(path, name, kName):
"""
Read in the key.txt file regarding the metapath matrices
:param path: (str) path to the network files
:param name: (str) name of the network to use
:param kName: (str) name of the keyfile to read
:return: keyDict (dict)
key, str: name of metapath
value, tuple: int is matrix/file ID number
bool where True means use matrix transpose
"""
fName = path + name + "_MetaPaths/" + kName
# ERROR CHECK: verify file exists
if not os.path.isfile(fName):
fName = path + name + '/' + kName
if not os.path.isfile(fName):
print("ERROR: Specified file doesn't exist:" +
" {}".format(fName))
sys.exit()
# end if
# The item to return
keyDict = dict()
# Read in the file
fk = open(fName, "r")
for line in fk:
# separate the values
line = line.rstrip()
if line.startswith('NOTE:'):
continue
lv = line.split('\t')
# add to the dict
keyDict[lv[1]] = lv[0]
# end loop
fk.close()
return keyDict
# end def #################################
def getTermMatrix(mpKeyNum, path, name, nRows, nCols) :
"""
Load the matrix containing the number of paths
of this type which join the nodes in the network
:param mpKeyNum: (int, bool): indicates which matrix file to use
:param path: str, path to the network files
:param name: str, name of the network to use
:param nRows: int, number of rows in new matrix
:param nCols: int, number of columns in new matrix
:return: matrix, int array: num paths between node pairs
"""
# Define the file name for the matrix
preName = (path + name + "_MetaPaths/" +
"{}tm".format(str(mpKeyNum).zfill(FNAME_ZPAD)) )
if os.path.isfile(preName + '.gz') :
fName = (path + name + "_MetaPaths/" +
"{}tm.gz".format(str(mpKeyNum).zfill(FNAME_ZPAD)) )
elif os.path.isfile(preName + '.txt') :
fName = (path + name + "_MetaPaths/" +
"{}tm.txt".format(str(mpKeyNum).zfill(FNAME_ZPAD)) )
else :
# ERROR CHECK: verify file exists
print ( "ERROR: Specified file doesn't exist:" +
"{}".format(preName) )
sys.exit()
#end if
# Allocate the matrix
matrix = np.zeros([nRows, nCols], dtype=MATRIX_DTYPE)
# Read in the file, placing values into matrix
row = 0
with gzip.open(fName, 'rb') as fin :
for line in fin :
line = line.rstrip()
ml = line.split()
# print(line)
# print(ml)
matrix[row,:] = ml[:]
row += 1
#end with
return matrix
# end def #################################
def loadPathMatrix(mpTuple, path, name, sizeOf) :
"""
Load the matrix containing the number of paths
of this type which join the nodes in the network
:param mpTuple: [int, bool]: indicates which matrix file to use
:param path: str, path to the network files
:param name: str, name of the network to use
:param sizeOf: int, number of rows (& cols) in new matrix
:return: int array: num paths between node pairs
"""
preName = (path + name + "_MetaPaths/" +
"{}".format(str(mpTuple[0]).zfill(FNAME_ZPAD)) )
if os.path.isfile(preName + '.gz') :
fName = (preName + '.gz')
elif os.path.isfile(preName + '.txt') :
fName = (preName + '.txt')
else :
# ERROR CHECK: verify file exists
print ( "ERROR: Specified file doesn't exist:" +
" {} .gz/.txt".format(preName) )
sys.exit()
#end if
# Declare the matrix
matrix = np.zeros([sizeOf, sizeOf], dtype=MATRIX_DTYPE)
# Read in the file, placing values into matrix
row = 0
with gzip.open(fName, 'rb') as fin :
for line in fin :
line = line.rstrip()
ml = line.split()
matrix[row,:] = ml[:]
row += 1
#end with
# Convert to transpose if flag==True
if mpTuple[1] :
return np.transpose(matrix)
else :
return matrix
# end def #################################
def readFileColumnAsString(fName, iCol, nSkip):
"""
Read in the desired column from a csv/tsv file
(typically a list of genes), skip N header rows
:param fName: str, path & filename of input
:param iCol: int, index of column to read (! INDEXED AT 0 !)
:param nSkip: int, number of rows to skip at top (ie: header rows)
:return:
"""
# ERROR CHECK: verify file exists
if not os.path.isfile(fName):
print("ERROR: Specified file doesn't exist:" +
" {}".format(fName))
sys.exit()
# end if
# the item to return
theList = list()
# Read in from the file
theFile = open(fName, 'r')
count = 0
firstWarn = True
lvLen = -1
for line in theFile:
# Skip first nSkip number of rows
if count < nSkip:
continue
# end if
line = line.rstrip()
lv = line.split(TEXT_DELIM)
# ERROR CHECK: verify iCol is within range
if (firstWarn == True) and (iCol >= len(lv)):
print("WARNING: File contains {} columns,".format(len(lv)) +
" but col {} was requested.".format(iCol))
print(" Note: Indexing starts at 0.")
print(" Returning last column. ")
iCol = len(lv) - 1
firstWarn = False
# end if
# ERROR CHECK: Warn if column length changes
if (lvLen != len(lv)) and (lvLen >= 0):
print("WARNING: Inconsistent number of columns in file.")
print(" Previous width: {}; Current: {}".format(
lvLen, len(lv)))
# end if
lvLen = len(lv)
theList.append(str(lv[iCol]))
count += 1
# end loop
theFile.close()
return theList
# end def #################################
def countLinesInFile(fName):
"""
Count the number of lines in a file
used to set size of matrices & arrays
:param fName: str, path & filename of input
:return:
cRows, int: total # of lines in the file
cColMin, int: minimum # of columns in the file
cColMax, int: maximum # of columns in the file
"""
# ERROR CHECK: verify file exists
if not os.path.isfile(fName):
print("ERROR: Specified file doesn't exist:" +
" {}".format(fName))
sys.exit()
#end if
cRows = 0
cColMin = -1
cColMax = 0
if fName[-3:0] == '.gz':
with gzip.open(fName, 'r') as fin:
for line in fin:
lv = line.split(TEXT_DELIM)
lineLength = len(lv)
cRows += 1
if cColMax < lineLength:
cColMax = lineLength
if cColMin == -1:
cColMin = lineLength
elif cColMin > lineLength:
cColMin = lineLength
#end if
else:
fin = open(fName, 'r')
for line in fin:
lv = line.split(TEXT_DELIM)
lineLength = len(lv)
cRows += 1
if cColMax < lineLength:
cColMax = lineLength
if cColMin == -1:
cColMin = lineLength
elif cColMin > lineLength:
cColMin = lineLength
#end for
fin.close()
#end if
return cRows, cColMin, cColMax
# end def #################################
def getAUCStats(path, name):
"""
calculate Recall (TPR), FPR, & Precision
:param path: str, path to input file
:param name: str, name of input file
:return:
recall, float:
FPR, float:
precision, float:
nHidden, float:
"""
# Read in the ranked genes
fnConcealed = 'concealed.txt'
if not os.path.isfile(path + fnConcealed):
fnConcealed = 'hidden.txt'
gHidden = readFileColumnAsString(path + fnConcealed, 0, 0)
gHidSet = set(gHidden)
nHidden = len(gHidden)
# In case concealed.txt is empty
if nHidden == 0:
if VERBOSITY > 1 :
print("There are no Concealed Positives to predict in {}".format(path))
return [-1], [-1], [-1], [-1]
# end if