-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMAPR_networkPrep.py
1539 lines (1221 loc) · 39.2 KB
/
MAPR_networkPrep.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 01: pre-process the network
Convert the network edge and node files into
meta-path matrices. Convert indirect
connections into direct edges.
author: Greg Linkowski
for KnowEnG by UIUC & NIH
"""
import argparse
import sys
import os
import re
import math
import gzip
import numpy as np
from shutil import copyfile
################################################################
# GLOBAL PARAMETERS
# Data-type for the path matrices:
MATRIX_DTYPE = np.float32
# Max value when normalizing a meta-path matrix
MATRIX_NORM = 1.0
# Length to pad the matrix file names:
FNAME_ZPAD = 6
# Considering consecutive edges of same type
KEEP_DOUBLE = True
KEEP_TRIPLE = True
# File extension to use when saving the matrix
MATRIX_EXTENSION = '.gz' # '.txt' or '.gz' (gz is compressed)
# Normalize matrix to this value & save as '%u' (if true)
MX_SAVE_AS_INT = True
MX_NORM_AS_INT = 6.5e4
# end params ##############################
################################################################
# ANCILLARY FUNCTIONS
def readCommandLineFlags() :
parser = argparse.ArgumentParser()
parser.add_argument('netEdgeFile', type=str,
help='path & file name of network edge file')
parser.add_argument('-k', '--keep', type=str, default='',
help='path & file name of network keep file')
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('-n', '--networkPath', type=str, default='./networks',
help='output directory to store processed network')
parser.add_argument('-t', '--textSubNets', type=bool, default=False,
help='whether to save separate subnetwork text files')
flags = parser.parse_args()
return flags
#end def #################################
def verifyFile(fName, verbose) :
# Verify file exists
exists = True
if not os.path.isfile(fName) :
if not verbose:
exists = False
else :
print ( "ERROR: Specified file doesn't exist:" +
" {}".format(fName))
sys.exit()
#end if
return exists
#end def #################################
def stripQuotesFromString(inString) :
outString = inString
if len(outString) > 2 :
# strip single quotes
if (outString[0] == "'") and (outString[-1] == "'") :
outString = outString[1:-1]
# strip double quotes
elif (outString[0] == '"') and (outString[-1] == '"') :
outString = outString[1:-1]
#end if
#end if
return outString
#end def #################################
def readKeepFile(fName) :
# Verify keep file exists
if not os.path.isfile(fName) :
print("ERROR: Failed to read keep file: ", fName)
sys.exit()
#end if
# Flags to indicate which sections were seen:
sawSectionGenes = False
sawSectionEdges = False
# The lists to return
humanGenes = list()
keepGenes = list()
loseGenes = list()
keepEdges = list()
indirEdges = list()
tHold = 0.0
cutoffRanges = dict()
# Read the file #TODO: python version check 2 vs 3
# f = open(fname, "rb")
f = open(fName, "r")
# read file line by line
section = 'header'
for line in f :
# line = str(line) #TODO: ever necessary for python 2 ??
line = line.rstrip()
if line == '':
continue
#end if
# split the line by columns
lv = line.split('\t')
# Sections headers (defined by all-caps)
# set the behavior for the lines that follow
if lv[0] == 'GENE TYPES' :
section = 'gene'
sawSectionGenes = True
elif lv[0] == 'EDGE TYPES' :
section = 'edge'
sawSectionEdges = True
elif lv[0] == 'THRESHOLD' :
section = 'threshold'
tHold = float(lv[2])
elif lv[0] == 'CUTOFF RANGE' :
section = 'cutoff'
elif section == 'gene' :
# sort genes between kept & ignored
if (lv[2] == 'keep') or (lv[2] == 'yes') :
keepGenes.append(lv[1])
# if lv[1] == '*' :
# keepGenes.append('[ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]')
# else :
# keepGenes.append(lv[1])
if lv[0].startswith('human') :
humanGenes.append(lv[1])
# if lv[1] == '*' :
# humanGenes.append('[ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]')
# else :
# humanGenes.append(lv[1])
else :
loseGenes.append(lv[1])
#end if
elif section == 'edge' :
# sort kept edges & note indirect edges
if (lv[2] == 'keep') or (lv[2] == 'yes') :
keepEdges.append(lv[0])
if (lv[1] != 'direct') and (lv[1] != 'yes') :
indirEdges.append(lv[0])
elif section == 'cutoff' :
cutoffRanges[lv[0]] = (int(lv[1]), int(lv[2]))
#end if
#end loop
# Error checks
if not sawSectionGenes :
print("ERROR: Keep file is missing section GENE TYPES:" +
" {}".format(fName))
sys.exit()
#end if
if not sawSectionEdges :
print("ERROR: Keep file is missing section EDGE TYPES:" +
" {}".format(fName))
sys.exit()
#end if
for ie in indirEdges :
if ie not in cutoffRanges.keys() :
cutoffRanges[ie] = (0, 1e15)
print("WARNING: Cutoff ranges unspecified for edge type {}".format(ie))
print(" Using default inclusive range 0 to 10^15")
#end for
return humanGenes, keepGenes, loseGenes, keepEdges, indirEdges, cutoffRanges, tHold
#end def #################################
def readEdgeFile(fName) :
# get the number of lines in the file
nLines = sum( 1 for line in open(fName, "r"))
# assign space for edge list
Edges = np.empty( (nLines,4), dtype=np.dtype('object'))
# dictionary to hold Node indices
Nodes = dict()
nodeSet = set()
# Start reading from the file
# df = open(datafile, "rb") #TODO: python version 2 or 3 ?
df = open(fName, "r")
i = 0
for line in df:
# extract the data from the file
# line = line.decode('UTF-8') #TODO: left over from python 2 ??
line = line.rstrip()
lv = line.split('\t')
# insert into the edge list
Edges[i,0] = lv[0]
# Edges[i,0] = str(lv[0], encoding='utf-8')
# print(np.char.decode(Edges[i,0], 'ascii')) #TODO: left over from python 2 ??
Edges[i,1] = lv[1]
Edges[i,2] = lv[2]
Edges[i,3] = lv[3]
# add node locations to dict
if lv[0] in nodeSet :
Nodes[lv[0]].append(i)
else :
Nodes[lv[0]] = list()
Nodes[lv[0]].append(i)
nodeSet.add(lv[0])
#end if
if lv[1] in nodeSet :
Nodes[lv[1]].append(i)
else :
Nodes[lv[1]] = list()
Nodes[lv[1]].append(i)
nodeSet.add(lv[1])
#end if
i += 1
#end loop
# close the data file
df.close()
#TODO: what should be the behavior if using Python 2 ?
# print(Edges[0,:]
# # Decode the edge array from type=bytes to type=str
# if sys.version_info[0] < 3 :
# Edges = np.char.decode(Edges, 'ascii')
return Edges, Nodes
#end def #################################
def applyTermCutoffRanges(edgeList, indirEdges, nodeDict, termCutoffs) :
# the terms to be removed from the network
dropTerms = set()
# the terms to be removed from the network
keepTerms = set()
# the indices of the rows to keep from edgeList
keepIdx = list()
# step through the edge list
i = -1
for row in edgeList :
i += 1
# if an indirect edge, check the size of term
if row[3] in indirEdges :
termSize = len(nodeDict[row[0]])
termMinMax = termCutoffs[row[3]]
if termSize > termMinMax[1] :
dropTerms.add( (row[0], row[3], termSize) )
elif termSize < termMinMax[0] :
dropTerms.add( (row[0], row[3], termSize) )
else :
keepIdx.append(i)
keepTerms.add( (row[0], row[3], termSize) )
# keep all direct edges
else :
keepIdx.append(i)
#end loop
newEdgeList = edgeList[keepIdx,:]
dropTerms = list(dropTerms)
dropTerms.sort()
keepTerms = list(keepTerms)
keepTerms.sort()
return newEdgeList, dropTerms, keepTerms
#end def #################################
def applyKeepLists(edges, lGenes, kEdges, iEdges) :
#TODO: remove or pass skipped edges
keepIndex = list()
kEdgeSet = set(kEdges)
# Note which rows in edge list will be kept
# and skip/discard non-kept edges
for i in range(0, edges.shape[0]) :
if edges[i,3] not in kEdgeSet :
continue
#end if
# list of matches to be found
m0 = list()
m1 = list()
# Check nodes for matches (column 1 & 2)
for gt in lGenes :
m0.append( re.match(gt, edges[i,0]) )
m1.append( re.match(gt, edges[i,1]) )
#end loop
# Skip/discard genes that match the non-keep list
# Check for any match with the non-keep list
if any(match is not None for match in m1) :
continue
#ASSUMPTION: for indirect edges, col 0 contains
# a non-gene node
elif edges[i,3] not in iEdges :
if any(match is not None for match in m0) :
continue
#end if
# Finally, if no objections
# add this to the kept list
keepIndex.append(i)
#end loop
newEdges = edges[keepIndex,:]
return newEdges
#end def #################################
def createNodeLists(edges, aGenes) :
nodeDict = dict()
nodeSet = set()
geneSet = set()
for i in range(0, edges.shape[0]) :
# Add the first node to the dictionary,
# using a set for look-up speed
if edges[i,0] in nodeSet :
nodeDict[edges[i,0]].append(i)
else :
nodeDict[edges[i,0]] = list()
nodeDict[edges[i,0]].append(i)
nodeSet.add(edges[i,0])
#end if
# Add the second node to the dictionary,
# using a set for look-up speed
if edges[i,1] in nodeSet :
nodeDict[edges[i,1]].append(i)
else :
nodeDict[edges[i,1]] = list()
nodeDict[edges[i,1]].append(i)
nodeSet.add(edges[i,1])
#end if
# list of matches to be found
m0 = list()
m1 = list()
# Check nodes for matches (column 1 & 2)
for gt in aGenes :
m0.append( re.match(gt, edges[i,0]) )
m1.append( re.match(gt, edges[i,1]) )
#end loop
# Matches mean node is a gene; add to set
if any(match is not None for match in m0) :
geneSet.add(edges[i,0])
if any(match is not None for match in m1) :
geneSet.add(edges[i,1])
#end if
#end loop
geneList = list(geneSet)
geneList.sort()
return nodeDict, geneList
#end def #################################
def writeModEdgeFilePlus(oPath, oName, nDict, gList, eArray) :
newPath = oPath + oName + '/'
if not os.path.exists(newPath) :
os.makedirs(newPath)
#end if
# Save output: ordered list of genes
# Save output: row indices for each node in edge file
gFile = 'genes.txt'
nFile = 'indices.txt'
gf = open(newPath + gFile, 'w')
nf = open(newPath + nFile, 'w')
# gf = open(newPath + gFile, 'wb') #TODO: left over from python 2 ??
# nf = open(newPath + nFile, 'wb')
firstLine = True
for gene in gList :
if firstLine :
firstLine = False
else :
gf.write("\n")
nf.write("\n")
#end if
gf.write("{}".format(gene))
nf.write("{}\t".format(gene, nDict[gene]))
firstIndex = True
for item in nDict[gene] :
if firstIndex :
firstIndex = False
else :
nf.write(",")
#end if
nf.write("{}".format(item))
#end loop
#end loop
gf.close()
nf.close()
# Save output: list of edge types
eTypes = np.unique(eArray[:,3])
eTypes.sort()
eFile = 'edges.txt'
with open(newPath + eFile, 'w') as ef :
firstLine = True
for et in eTypes :
if firstLine :
firstLine = False
else :
ef.write("\n")
#end if
ef.write("{}".format(et))
#end loop
#end with
# Save output: the network (as an edge list)
oFile = 'network.txt'
with open(newPath + oFile, 'w') as of :
firstLine = True
for i in range(0, eArray.shape[0]) :
if firstLine :
firstLine = False
else :
of.write("\n")
#end if
of.write("{}\t{}\t{}\t{}".format(eArray[i,0],
eArray[i,1], eArray[i,2], eArray[i,3]))
#end loop
#end with
return
#end def #################################
def saveSelectGeneDegrees(oPath, oName, edgeArray, genesAll, humanRegex) :
textDelim = '\t'
# If folder doesn't exist, create it
if not os.path.exists(oPath + oName + "/") :
os.makedirs(oPath + oName + "/")
#end if
# NOTE: Only considering human genes (at least for now)
# Build an index dictionary from the human genes
genesAll = np.unique(genesAll)
genesAll.sort()
gHumanDict = dict()
index = 0
for gene in genesAll :
# Look for matches to regex expression
ma = list()
for exp in humanRegex :
ma.append( re.match(exp, gene) )
# add gene only if one of the matches is positive
if any(match is not None for match in ma) :
gHumanDict[gene] = index
index += 1
#end loop
# Get list of edge types
eTypes = np.unique(edgeArray[:,3])
eTypes.sort()
# Build an index dictionary from the edge types
eDict = dict()
index = 1 # col 0 reserved for 'all'
for et in eTypes :
eDict[et] = index
index += 1
#end loop
# matrix to store degree counts (col 0 reserved for 'all')
degreeMatrix = np.zeros([ len(gHumanDict), len(eTypes)+1 ])
# First, count degrees along SPECIFIED edge types
for row in edgeArray :
# by incrementing the matrix
if row[0] in gHumanDict :
degreeMatrix[ gHumanDict[row[0]], eDict[row[3]] ] += 1
if row[1] in gHumanDict :
degreeMatrix[ gHumanDict[row[1]], eDict[row[3]] ] += 1
#end loop
# Second, sum degrees along ALL edge types
degreeMatrix[:, 0] = np.sum(degreeMatrix, axis=1)
# Open the output file
fname = oPath + oName + '/node-degree.txt'
with open(fname, 'w') as fOut : #TODO 'wb' for python 2 ??
# Write column headers
fOut.write("HEADER{}all".format(textDelim))
for et in eTypes :
fOut.write("{}{}".format(textDelim, et))
# Write the matrix to file
gHumanList = list(gHumanDict.keys())
gHumanList.sort()
for i in range(len(gHumanList)) :
fOut.write( "\n{}".format(gHumanList[i]) )
for j in range(degreeMatrix.shape[1]) :
fOut.write( "{}{:.0f}".format(textDelim, degreeMatrix[i,j]) )
#end loop
#end with
return
#end def #################################
def readFileAsIndexDict(fName) :
verifyFile(fName, True)
# 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 convertMatrixFloatToUInt16(matrix, verbosity) :
maxVal = np.amax(matrix)
minVal = np.amin(matrix)
if maxVal == minVal:
if verbosity > 1:
print(
"WARNING: Uniform {:,}x{:,} matrix , all values = {}".format(matrix.shape[0], matrix.shape[1], maxVal))
# end if
if minVal != 0 :
matrix = np.subtract(matrix, minVal)
maxVal = np.amax(matrix)
if maxVal > MX_NORM_AS_INT :
matrix = np.divide(matrix, (maxVal - minVal))
matrix = np.multiply(matrix, MX_NORM_AS_INT)
#end if
return matrix.astype(np.uint16)
#end def #################################
def buildDirectPathMatrix(eList, gDict, verbosity) :
matrix = np.zeros( (len(gDict), len(gDict)), dtype=np.float32 )
for row in eList :
i = gDict[row[0]]
j = gDict[row[1]]
matrix[i,j] += float(row[2])
matrix[j,i] += float(row[2])
#end for
return convertMatrixFloatToUInt16(matrix, verbosity)
#end def #################################
def saveSubNetworkDirect(snPath, snName, eList) :
snPath = snPath.rstrip('/') + '/'
fnSubNet = snPath + snName
with open(fnSubNet, 'w') as fOut:
firstLine = True
for row in eList:
if firstLine :
firstLine = False
else :
fOut.write('\n')
fOut.write('{}\t{}\t{}'.format(row[0], row[1], row[2]))
#end with
return
# end def #################################
def buildIndirectPathMatrix(eList, nNames, gDict, nDict, verbosity) :
matrix = np.zeros( (len(gDict), len(gDict)), dtype=np.float32 )
for node in nNames :
idxList = nDict[node]
listLen = len(idxList)
for iIdx in range(listLen - 1):
thisRowIdx = idxList[iIdx]
thisGene = eList[thisRowIdx, 1]
thisWeight = float(eList[thisRowIdx, 2])
for jIdx in range((iIdx + 1), listLen):
nextRowIdx = idxList[jIdx]
nextGene = eList[nextRowIdx, 1]
nextWeight = float(eList[nextRowIdx, 2])
i = gDict[thisGene]
j = gDict[nextGene]
placeWeight = thisWeight * nextWeight
matrix[i, j] += placeWeight
matrix[j, i] += placeWeight
# end loop
return convertMatrixFloatToUInt16(matrix, verbosity)
#end def #################################
def saveSubNetworkIndirect(snPath, snName, eList, nNames, nDict) :
snPath = snPath.rstrip('/') + '/'
fnSubNet = snPath + snName
with open(fnSubNet, 'w') as fIn :
firstLine = True
for node in nNames :
idxList = nDict[node]
listLen = len(idxList)
for iIdx in range(listLen - 1) :
thisRowIdx = idxList[iIdx]
thisGene = eList[thisRowIdx, 1]
thisWeight = float(eList[thisRowIdx, 2])
for jIdx in range((iIdx + 1), listLen):
nextRowIdx = idxList[jIdx]
nextGene = eList[nextRowIdx, 1]
nextWeight = float(eList[nextRowIdx, 2])
placeWeight = thisWeight * nextWeight
if firstLine :
firstLine = False
else :
fIn.write('\n')
fIn.write('{}\t{}\t{}'.format(thisGene, nextGene, placeWeight))
#end with
return
# end def #################################
def buildGeneTermMatrix(eList, gDict, verbosity=0) :
nList = np.unique(eList[:,0])
nDict = dict()
idx = -1
for n in nList:
idx += 1
nDict[n] = idx
#end loop
matrix = np.zeros( (len(gDict), len(nList)), dtype=np.float32 )
for row in eList :
i = gDict[row[1]]
j = nDict[row[0]]
matrix[i,j] += float(row[2])
#end loop
return convertMatrixFloatToUInt16(matrix, verbosity), nList
#end def #################################
def saveKeyFile(mDict, path):
"""
save the key file for the metapath matrices
Creates a legend, mapping the path type on the right
to the path matrix file on the left, where 't'
indicates the transpose of that matrix should be used
:param mDict: dict,
key, str: metapath names
value, [int, : corresponding index number for mList
bool] : True means use matrix transpose
:param path: str, path to the folder to save the file
:return:
"""
# If folder doesn't exist, create it
if not os.path.exists(path):
os.makedirs(path)
# end if
# Get the sorted list of all paths
nameList = list(mDict.keys())
nameList.sort()
# This file tells which matrix corresponds to which path
fKey = open(path + "key.txt", "w")
# fKey = open(path+"key.txt", "wb") #TODO: left over from python 2
fKey.write("NOTE: 't' means use matrix transpose\n")
firstLine = True
for name in nameList:
if firstLine:
firstLine = False
else:
fKey.write("\n")
# end if
fKey.write("{}".format(str(mDict[name][0]).zfill(FNAME_ZPAD)))
if mDict[name][1]:
fKey.write(",t")
else:
fKey.write(", ")
fKey.write("\t{}".format(name))
# end loop
fKey.close()
return
# end def #################################
def readKeyFilePP(path):
"""
Read in the key.txt file regarding the metapath matrices
:param path: str, path to the network files
:return: keyDict, dict
key, str: name of metapath
value, tuple: int is matrix/file ID number
bool where True means use matrix transpose
"""
if not path.endswith('_MetaPaths/'):
if path.endswith('/'):
path = path[0:-1] + '_MetaPaths/'
else:
path = path + '_MetaPaths/'
# end if
fName = path + "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")
# fk = open(fName, "rb") #TODO: left over from python 2
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 getPathMatrixV2(mpFName, mpPath, sizeOf) :
preName = mpPath + mpFName
if os.path.isfile(preName) :
fName = preName
elif 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:" +
" {} w/.txt/.gz".format(preName))
sys.exit()
#end if
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
return matrix
#end def #################################
def saveMatrixNumpyV2(matrix, mFileName, mPath, mName, asUint) :
"""
save given matrix as a .npy file
:param matrix: (NxN) list, the values to save
:param mFileName: str, name of the file to save
:param mPath: str, path to the folder to save the file
:param mName: str, name of corresponding meta-path
:param asUint: bool, whether to convert matrix as uint16 b/f saving
:return:
"""
# If folder doesn't exist, create it
if not os.path.exists(mPath) :
os.makedirs(mPath)
#end if
# Matrix prep before saving
# - Warn if matrix contains zero connections #TODO: how to safely skip a 0 matrix ??
# - Convert to uint16 if flag is true (to save space)
# - (otherwise) Normalize according to defaults
maxVal = np.amax(np.amax(matrix))
if maxVal == 0 :
print("WARNING: maximum value == 0 for saved matrix {}".format(mFileName))
print(" Meta-path {} does not connect any nodes.\n".format(mName))
elif asUint :
matrix = convertMatrixFloatToUInt16(matrix, 0)
else :
matrix = np.divide(matrix, maxVal)
matrix = np.multiply(matrix, MATRIX_NORM)
#end if
if mFileName.endswith('.gz') or mFileName.endswith('.txt') :
np.savetxt(mPath + mFileName, matrix, fmt='%u')
else :
np.savetxt(mPath + mFileName + MATRIX_EXTENSION, matrix, fmt='%u')
#end if
return
#end def #################################
def NChooseK(N, K):
"""
Calculate (N choose K)
:param N: int, the size of the overall set
:param K: int, size of the combinations chosen from set
:return: combos, int, number of combinations possible
"""
numer = math.factorial(N)
denom = math.factorial(K) * math.factorial(N - K)
combos = numer / denom
return int(combos)
# end def #################################
def createMPLengthOneV2(pDict, pDir, verbosity):
# Get the list of the primary path matrices
pNames = list(pDict.keys())
pNames.sort()
# Check if metapath key file exists
if verifyFile('{}key.txt'.format(pDir), True):
# check if all expected 1-step paths were created
# exit if they are
mNumExpected = len(pNames)
mDict = readKeyFilePP(pDir)
mp1Count = 0
for mpName in list(mDict.keys()):
if mpName.count('-') == 0:
mp1Count += 1
# end loop
if mp1Count == mNumExpected:
if verbosity:
print("All 1-length paths already computed ...")
return
elif mp1Count >= mNumExpected:
print("ERROR: Uh-oh, more 1-length paths than expected already exist!")
sys.exit()
# end if
if verbosity > 1:
print(" Creating key.txt for length-1 meta-paths")
# Create the metapath dict
mpDict = dict()
for name in pNames:
mpDict[name] = (pDict[name], False)
# end loop
# save the new mp key file
saveKeyFile(mpDict, pDir)
return
# end def #################################
def createMPLengthTwoV2(pDict, pDir, verbosity):
# Get the list of the primary path matrices
pNames = list(pDict.keys())
pNames.sort()
pNum = len(pNames)
# Get the list of all metapaths created thus far
mDict = readKeyFilePP(pDir)
mNum = pNum
# Check if all expected 2-step paths were created
# exit if they are
mNumExpected = math.pow(pNum, 2)
mp2Count = 0
for mpName in list(mDict.keys()):
# print(mpName)
if mpName.count('-') == 1:
mp2Count += 1
# end if
if mp2Count == int(mNumExpected):
if verbosity:
print("All 2-length paths already computed ...")
return
elif mp2Count >= mNumExpected:
print("ERROR: Uh-oh, more 2-length paths than expected already exist!")
sys.exit()
# end if
# Get the matrix dimensions from genes.txt file
sizeOf = 0
pDirAlt = pDir
if pDirAlt.endswith("_MetaPaths/"):
pDirAlt = pDirAlt[:-11] + '/'
with open(pDirAlt + 'genes.txt') as fin:
for line in fin:
sizeOf += 1
# end with
# Multiply each matrix pair