-
Notifications
You must be signed in to change notification settings - Fork 42
/
cellbrowser.py
executable file
·2945 lines (2445 loc) · 104 KB
/
cellbrowser.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
#!/usr/bin/env python2
# this library mostly contains functions that convert tab-sep files
# (=single cell expression matrix and meta data) into the binary format that is read by the
# javascript viewer cbWeb/js/cellbrowser.js and cbData.js.
# Helper functions here allow importing data from other tools, e.g. cellranger or scanpy.
# requires at least python2.6, version tested was 2.6.6
# should work with python2.5, not tested
# works on python3, version tested was 3.6.5
import logging, sys, optparse, struct, json, os, string, shutil, gzip, re, unicodedata
import zlib, math, operator, doctest, copy, bisect, array, glob, io, time, subprocess
import hashlib
from distutils import spawn
from collections import namedtuple, OrderedDict
from os.path import join, basename, dirname, isfile, isdir, relpath, abspath, getsize, getmtime
try:
from collections import defaultdict
from collections import Counter
except:
# python2.6 has no defaultdict or Counter yet
from backport_collections import defaultdict # error? -> pip2 install backport-collections
from backport_collections import Counter # error? -> pip2 install backport-collections
# We do not require numpy but numpy is around 30-40% faster in serializing arrays
# So use it if it's present
numpyLoaded = True
try:
import numpy as np
except:
numpyLoaded = False
logging.error("Numpy could not be loaded. The script will work, but it will be 30% slower when processing the matrix.")
# older numpy versions don't have tobytes()
if numpyLoaded:
try:
np.ndarray.tobytes
except:
numpyLoaded = False
logging.error("Numpy version too old. Falling back to normal Python array handling.")
isPy3 = False
if sys.version_info >= (3, 0):
isPy3 = True
# directory to static data files, e.g. gencode tables
dataDir = join(dirname(__file__), "..", "cbData")
defOutDir = os.environ.get("CBOUT")
# ==== functions =====
def setDebug(options):
" activate debugging if needed "
if options.debug:
logging.basicConfig(level=logging.DEBUG)
logging.getLogger().setLevel(logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
logging.getLogger().setLevel(logging.INFO)
def cbBuild_parseArgs(showHelp=False):
" setup logging, parse command line arguments and options. -h shows auto-generated help page "
parser = optparse.OptionParser("""usage: %prog [options] -i cellbrowser.conf -o outputDir - add a dataset to the single cell viewer directory
If you have previously built into the same output directory with the same dataset and the
expression matrix has not changed its filesize, this will be detected and the expression
matrix will not be copied again. This means that an update of a few meta data attributes
is quite quick.
""")
parser.add_option("-d", "--debug", dest="debug", action="store_true",
help="show debug messages")
parser.add_option("-i", "--inConf", dest="inConf", action="append",
help="a cellbrowser.conf file that specifies labels and all input files, default %default, can be specified multiple times")
parser.add_option("-o", "--outDir", dest="outDir", action="store", help="output directory, default can be set through the env. variable CBOUT, current value: %default", default=defOutDir)
parser.add_option("-p", "--port", dest="port", action="store",
help="if build is successful, start an http server on this port and serve the result via http://localhost:port", type="int")
(options, args) = parser.parse_args()
if showHelp:
parser.print_help()
exit(1)
setDebug(options)
return args, options
def cbMake_parseArgs():
" setup logging, parse command line arguments and options. -h shows auto-generated help page "
parser = optparse.OptionParser("usage: %prog [options] outDir - copy all relevant js/css files into outDir, look for datasets in it and create index.html")
parser.add_option("-d", "--debug", dest="debug", action="store_true",
help="show debug messages")
parser.add_option("-o", "--outDir", dest="outDir", action="store", help="output directory, default can be set through the env. variable CBOUT, current value: %default", default=defOutDir)
#parser.add_option("-m", "--meta", dest="meta", action="store",
#help="meta data tsv file, aka sample sheet. One row per sample, first row has headers, first column has sample name."
#)
#parser.add_option("-e", "--matrix", dest="matrix", action="store",
#help="expression matrix file, one gene per row, one sample per column. First column has gene identifiers (Ensembl or symbol), First row has sample names. ")
#parser.add_option("-c", "--coords", dest="coords", action="append", help="tab-sep table with cell coordinates, format: metaId, x, y. Can be specified multiple times, if you have multiple coordinate files.")
(options, args) = parser.parse_args()
if options.outDir==None:
parser.print_help()
exit(1)
setDebug(options)
return args, options
def makeDir(outDir):
if not isdir(outDir):
logging.info("Creating %s" % outDir)
os.makedirs(outDir)
def errAbort(msg):
logging.error(msg)
sys.exit(1)
def iterItems(d):
" wrapper for iteritems for all python versions "
if isPy3:
return d.items()
else:
return d.iteritems()
def lineFileNextRow(inFile, utfHacks=False):
"""
parses tab-sep file with headers in first line
yields collection.namedtuples
strips "#"-prefix from header line
utfHacks forces all chars to latin1 and removes anything that doesn't fit into latin1
"""
if isinstance(inFile, str):
# input file is a string = file name
fh = openFile(inFile)
sep = sepForFile(inFile)
else:
fh = inFile
sep = "\t"
line1 = fh.readline()
line1 = line1.strip("\n").lstrip("#")
if utfHacks:
line1 = line1.decode("latin1")
# skip special chars in meta data and keep only ASCII
line1 = unicodedata.normalize('NFKD', line1).encode('ascii','ignore')
headers = line1.split(sep)
if len(headers)>=255:
errAbort("Cannot read more than 255 columns. Are you sure that this file is in the correct format?"
" It may have the wrong line endings and may require treatment with dos2unix or mac2unix. "
" Or it may be the wrong file type for this input, e.g. an expression matrix instead of a "
" coordinate file.")
headers = [re.sub("[^a-zA-Z0-9_]","_", h) for h in headers]
headers = [re.sub("^_","", h) for h in headers] # remove _ prefix
#headers = [x if x!="" else "noName" for x in headers]
if headers[0]=="": # R does not name the first column by default
headers[0]="rowName"
if "" in headers:
logging.error("Found empty cells in header line of %s" % inFile)
logging.error("This often happens with Excel files. Make sure that the conversion from Excel was done correctly. Use cut -f-lastColumn to fix it.")
assert(False)
filtHeads = []
for h in headers:
if h[0].isdigit():
filtHeads.append("x"+h)
else:
filtHeads.append(h)
headers = filtHeads
Record = namedtuple('tsvRec', headers)
for line in fh:
if line.startswith("#"):
continue
if utfHacks:
line = line.decode("latin1")
# skip special chars in meta data and keep only ASCII
line = unicodedata.normalize('NFKD', line).encode('ascii','ignore')
#line = line.decode("latin1")
# skip special chars in meta data and keep only ASCII
#line = unicodedata.normalize('NFKD', line).encode('ascii','ignore')
line = line.rstrip("\r\n")
#if isPy3:
#fields = line.split(sep, maxsplit=len(headers)-1)
#else:
#fields = string.split(line, sep, maxsplit=len(headers)-1)
fields = line.split(sep)
if sep==",":
fields = [x.lstrip('"').rstrip('"') for x in fields]
try:
rec = Record(*fields)
except Exception as msg:
logging.error("Exception occured while parsing line, %s" % msg)
logging.error("Filename %s" % fh.name)
logging.error("Line was: %s" % line)
logging.error("Does number of fields match headers?")
logging.error("Headers are: %s" % headers)
raise Exception("header count: %d != field count: %d wrong field count in line %s" % (len(headers), len(fields), line))
yield rec
def parseOneColumn(fname, colName):
" return a single column from a tsv as a list "
ifh = open(fname)
sep = sepForFile(fname)
headers = ifh.readline().rstrip("\r\n").split(sep)
colIdx = headers.index(colName)
vals = []
for line in ifh:
row = line.rstrip("\r\n").split(sep)
vals.append(row[colIdx])
return vals
def parseIntoColumns(fname):
" parse tab sep file vertically, return as a list of (headerName, list of values) "
ifh = open(fname)
sep = "\t"
headers = ifh.readline().rstrip("\r\n").split(sep)
colsToGet = range(len(headers))
columns = []
for h in headers:
columns.append([])
for line in ifh:
row = line.rstrip("\r\n").split(sep)
for colIdx in colsToGet:
columns[colIdx].append(row[colIdx])
return zip(headers, columns)
def openFile(fname, mode="rt"):
if fname.endswith(".gz"):
if isPy3:
fh = gzip.open(fname, mode, encoding="latin1")
else:
fh = gzip.open(fname, mode)
else:
if isPy3:
fh = io.open(fname, mode)
else:
fh = open(fname, mode)
return fh
def parseDict(fname):
""" parse text file in format key<tab>value and return as dict key->val """
d = {}
fh = openFile(fname)
sep = "\t"
if fname.endswith(".csv"):
sep = ","
for line in fh:
key, val = line.rstrip("\r\n").split(sep)
d[key] = val
return d
def readGeneToSym(fname):
" given a file with geneId,symbol return a dict geneId -> symbol. Strips anything after . in the geneId "
if fname.lower()=="none":
return None
logging.info("Reading gene,symbol mapping from %s" % fname)
# Jim's files and CellRanger files have no headers, they are just key-value
line1 = open(fname).readline().rstrip("\r\n")
fieldCount = line1.split('\t')
if "geneId" not in line1:
d = parseDict(fname)
# my gencode tables contain a symbol for all genes
# the old format
elif line1=="transcriptId\tgeneId\tsymbol":
for row in lineFileNextRow(fname):
if row.symbol=="":
continue
d[row.geneId.split(".")[0]]=row.symbol
# my new files are smaller and have headers
elif line1=="geneId\tsymbol" or fieldCount==2:
d = {}
for row in lineFileNextRow(fname):
if row.symbol=="":
continue
d[row.geneId.split(".")[0]]=row.symbol
else:
assert(False)
logging.debug("Found symbols for %d genes" % len(d))
return d
def getDecilesList_np(values):
deciles = np.percentile( values, [0,10,20,30,40,50,60,70,80,90,100] )
return deciles
def bytesAndFmt(x):
""" how many bytes do we need to store x values and what is the sprintf
format string for it?
"""
if x > 65535:
assert(False) # field with more than 65k elements or high numbers? Weird meta data.
if x > 255:
return "Uint16", "<H" # see javascript typed array names, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
else:
return "Uint8", "<B"
#def getDecilesWithZeros(numVals):
# """ return a pair of the deciles and their counts.
# Counts is 11 elements long, the first element holds the number of zeros,
# which are treated separately
#
# >>> l = [0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9,10]
# >>> getDecilesWithZeros(l)
# ([1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
# """
# nonZeros = [x for x in numVals if x!=0.0]
#
# zeroCount = len(numVals) - len(nonZeros)
# deciles = getDecilesList_np(nonZeros)
#
# decArr = np.searchsorted(deciles, numVals)
# decCounts(deciles, nonZeros)
#
# decCounts.insert(0, zeroCount)
# return deciles, decCounts, newVals
def findBins(numVals, breakVals):
"""
find the right bin index defined by breakVals for every value in numVals.
Special handling for the last value. The comparison uses "<=". The first
break is assumed to be the minimum of numVals and is therefore ignored.
Also returns an array with the count for every bin.
>>> findBins([1,1,1,2,2,2,3,3,4,4,5,5,6,6], [1, 2,3,5,6])
([0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 3, 3], [6, 2, 4, 2])
"""
breaks = breakVals[1:]
bArr = []
binCounts = [0]*len(breaks)
for x in numVals:
binIdx = bisect.bisect_left(breaks, x)
bArr.append(binIdx)
binCounts[binIdx]+=1
return bArr, binCounts
def countBinsBetweenBreaks(numVals, breakVals):
""" count how many numVals fall into the bins defined by breakVals.
Special handling for the last value. Comparison uses "<=". The first
break is assumed to be the minimum of numVals.
Also returns an array with the bin for every element in numVals
>>> countBinsBetweenBreaks([1,1,1,2,2,2,3,3,4,4,5,5,6,6], [1,2,3,5,6])
([6, 2, 4, 2], [0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 3, 3])
"""
binCounts = []
binCount = 0
i = 1
dArr = []
for x in numVals:
if x <= breakVals[i]:
binCount+=1
else:
binCounts.append(binCount)
binCount = 1
i += 1
dArr.append(i-1)
binCounts.append(binCount)
assert(len(dArr)==len(numVals))
assert(len(binCounts)==len(breakVals)-1)
return binCounts, dArr
def discretizeArray(numVals, fieldMeta):
"""
discretize numeric values based on quantiles.
"""
maxBinCount = 10
counts = Counter(numVals).most_common()
counts.sort() # sort by value, not count
if len(counts) < maxBinCount:
# if we have just a few values, do not do any binning
binCounts = [y for x,y in counts]
values = [x for x,y in counts]
valToBin = {}
for i, x in values:
valToBin[x] = i
dArr = [valToBin[x] for x in numVals]
fieldMeta["binMethod"] = "raw"
fieldMeta["values"] = values
fieldMeta["binCounts"] = binCounts
return dArr, fieldMeta
# ten breaks
breakPercs = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
countLen = len(counts)
breakIndices = [int(round(bp*countLen)) for bp in breakPercs]
# as with all histograms, the last break is always a special case (0-based array)
breakIndices.append(countLen-1)
breakVals = [counts[idx][0] for idx in breakIndices]
dArr, binCounts = findBins(numVals, breakVals)
assert(len(binCounts)==10)
logging.info("Number of values per decile-bin: %s" % binCounts)
fieldMeta["binMethod"] = "quantiles"
fieldMeta["binCounts"] = binCounts
fieldMeta["breaks"] = breakVals
return dArr, fieldMeta
def discretizeNumField(numVals, fieldMeta, numType):
" given a list of numbers, add attributes to fieldMeta that describe the binning scheme "
#digArr, fieldMeta = discretizeArr_uniform(numVals, fieldMeta)
digArr, fieldMeta = discretizeArray(numVals, fieldMeta)
#deciles, binCounts, newVals = getDecilesWithZeros(numVals)
fieldMeta["arrType"] = "uint8"
fieldMeta["_fmt"] = "<B"
return digArr, fieldMeta
def typeForStrings(strings):
""" given a list of strings, determine if they're all ints or floats or strings
"""
floatCount = 0
intCount = 0
for val in strings:
try:
newVal = int(val)
intCount += 1
except:
try:
newVal = float(val)
floatCount += 1
except:
return "string"
if floatCount!=0:
return "float"
return "int"
def guessFieldMeta(valList, fieldMeta, colors, forceEnum):
""" given a list of strings, determine if they're all int, float or
strings. Return fieldMeta, as dict, and a new valList, with the correct python type
- 'type' can be: 'int', 'float', 'enum' or 'uniqueString'
- if int or float: 'deciles' is a list of the deciles
- if uniqueString: 'maxLen' is the length of the longest string
- if enum: 'values' is a list of all possible values
- if colors is not None: 'colors' is a list of the default colors
"""
intCount = 0
floatCount = 0
valCounts = defaultdict(int)
#maxVal = 0
for val in valList:
fieldType = "string"
try:
newVal = int(val)
intCount += 1
floatCount += 1
#maxVal = max(newVal, val)
except:
try:
newVal = float(val)
floatCount += 1
#maxVal = max(newVal, val)
except:
pass
valCounts[val] += 1
valToInt = None
if floatCount==len(valList) and intCount!=len(valList) and len(valCounts) > 10 and not forceEnum:
# field is a floating point number: convert to decile index
numVals = [float(x) for x in valList]
newVals, fieldMeta = discretizeNumField(numVals, fieldMeta, "float")
fieldMeta["type"] = "float"
#fieldMeta["maxVal"] = maxVal
elif intCount==len(valList) and not forceEnum:
# field is an integer: convert to decile index
numVals = [int(x) for x in valList]
newVals, fieldMeta = discretizeNumField(numVals, fieldMeta, "int")
fieldMeta["type"] = "int"
#fieldMeta["maxVal"] = maxVal
elif len(valCounts)==len(valList) and not forceEnum:
# field is a unique string
fieldMeta["type"] = "uniqueString"
maxLen = max([len(x) for x in valList])
fieldMeta["maxSize"] = maxLen
fieldMeta["_fmt"] = "%ds" % (maxLen+1)
newVals = valList
else:
# field is an enum - convert to enum index
fieldMeta["type"] = "enum"
valArr = list(valCounts.keys())
valCounts = list(sorted(valCounts.items(), key=operator.itemgetter(1), reverse=True)) # = (label, count)
if colors!=None:
colArr = []
foundColors = 0
notFound = set()
for val, _ in valCounts:
if val in colors:
colArr.append(colors[val])
foundColors +=1
else:
notFound.add(val)
colArr.append("DDDDDD") # wonder if I should not stop here
if foundColors > 0:
fieldMeta["colors"] = colArr
if len(notFound)!=0:
logging.warn("No default color found for field values %s" % notFound)
fieldMeta["valCounts"] = valCounts
fieldMeta["arrType"], fieldMeta["_fmt"] = bytesAndFmt(len(valArr))
valToInt = dict([(y[0],x) for (x,y) in enumerate(valCounts)]) # dict with value -> index in valCounts
newVals = [valToInt[x] for x in valList] #
#fieldMeta["valCount"] = len(valList)
fieldMeta["diffValCount"] = len(valCounts)
return fieldMeta, newVals
def writeNum(col, packFmt, ofh):
" write a list of numbers to a binary file "
def cleanString(s):
" returns only alphanum characters in string s "
newS = []
for c in s:
if c.isalnum():
newS.append(c)
return "".join(newS)
def runGzip(fname, finalFname=None):
logging.debug("Compressing %s" % fname)
cmd = "gzip -f %s" % fname
runCommand(cmd)
gzipFname = fname+".gz"
if finalFname==None:
return gzipFname
if isfile(finalFname):
os.remove(finalFname)
logging.debug("Renaming %s to %s" % (gzipFname, finalFname))
os.rename(gzipFname, finalFname)
return finalFname
def metaToBin(inConf, outConf, fname, colorFname, outDir, enumFields):
""" convert meta table to binary files. outputs fields.json and one binary file per field.
adds names of metadata fields to outConf and returns outConf
"""
logging.info("Converting to numbers and compressing meta data fields")
makeDir(outDir)
colData = parseIntoColumns(fname)
colors = parseColors(colorFname)
fieldInfo = []
for colIdx, (fieldName, col) in enumerate(colData):
logging.info("Meta data field index %d: '%s'" % (colIdx, fieldName))
forceEnum = False
if enumFields!=None:
forceEnum = (fieldName in enumFields)
cleanFieldName = cleanString(fieldName)
binName = join(outDir, cleanFieldName+".bin")
fieldMeta = OrderedDict()
fieldMeta["name"] = cleanFieldName
fieldMeta["label"] = fieldName
if fieldName=="cluster" or fieldName=="Cluster":
forceEnum=True
fieldMeta, binVals = guessFieldMeta(col, fieldMeta, colors, forceEnum)
fieldType = fieldMeta["type"]
if "metaOpt" in inConf and fieldName in inConf["metaOpt"]:
fieldMeta["opt"] = inConf["metaOpt"][fieldName]
packFmt = fieldMeta["_fmt"]
# write the binary file
binFh = open(binName, "wb")
if fieldMeta["type"]!="uniqueString":
for x in binVals:
binFh.write(struct.pack(packFmt, x))
else:
for x in col:
if isPy3:
binFh.write(bytes("%s\n" % x, encoding="ascii"))
else:
binFh.write("%s\n" % x)
binFh.close()
runGzip(binName)
del fieldMeta["_fmt"]
fieldInfo.append(fieldMeta)
if "type" in fieldMeta:
logging.info(("Type: %(type)s, %(diffValCount)d different values" % fieldMeta))
else:
logging.info(("Type: %(type)s, %(diffValCount)d different values, max size %(maxSize)d " % fieldMeta))
return fieldInfo
def iterLineOffsets(ifh):
""" parse a text file and yield tuples of (line, startOffset, endOffset).
endOffset does not include the newline, but the newline is not stripped from line.
"""
line = True
start = 0
while line!='':
line = ifh.readline()
end = ifh.tell()-1
if line!="":
yield line, start, end
start = ifh.tell()
class MatrixTsvReader:
" open a .tsv file and yield rows via iterRows. gz and csv OK."
def __init__(self, geneToSym=None):
self.geneToSym = geneToSym
def open(self, fname, matType=None):
" return something for iterMatrixTsv "
logging.debug("Opening %s" % fname)
self.fname = fname
if fname.endswith(".gz"):
#ifh = gzip.open(fname)
self.ifh = subprocess.Popen(
['gunzip', '-c', fname],
stdout=subprocess.PIPE,
encoding='utf-8',
).stdout # faster, especially with two CPUs
else:
self.ifh = open(fname, "rU")
self.sep = "\t"
if ".csv" in fname.lower():
self.sep = ","
logging.debug("Field separator is %s" % repr(self.sep))
headLine = self.ifh.readline().rstrip("\r\n")
self.sampleNames = headLine.split(self.sep)[1:]
self.sampleNames = [x.strip('"') for x in self.sampleNames]
assert(len(self.sampleNames)!=0)
logging.debug("Read %d sampleNames, e.g. %s" % (len(self.sampleNames), self.sampleNames[0]))
if matType is None:
self.matType = self.autoDetectMatType(10)
logging.info("Numbers in matrix are of type '%s'", self.matType)
else:
self.matType = matType
def getMatType(self):
return self.matType
def getSampleNames(self):
return self.sampleNames
def autoDetectMatType(self, n):
" check if matrix has 'int' or 'float' data type by looking at the first n genes"
# auto-detect the type of the matrix: int vs float
logging.info("Auto-detecting number type of %s" % self.fname)
geneCount = 0
self.matType = "float" # iterRows needs this attribute
matType = "int"
for geneId, sym, a in self.iterRows():
geneCount+=1
if numpyLoaded:
a_int = a.astype(int)
hasOnlyInts = np.array_equal(a, a_int)
if not hasOnlyInts:
matType = "float"
break
else:
for x in a:
frac, whole = math.modf(x)
if frac != 0.0:
matType = "float"
break
if matType=="float":
break
if geneCount==n:
break
if geneCount==0:
errAbort("empty expression matrix?")
logging.debug("Matrix type is: %s" % matType)
return matType
def iterRows(self):
" yield (geneId, symbol, array) tuples from gene expression file. "
if self.matType == "float":
npType = "float32"
else:
npType = "int32"
skipIds = 0
doneGenes = set()
lineNo = 0
sep = self.sep
sampleCount = len(self.sampleNames)
geneToSym = self.geneToSym
for line in self.ifh:
self.lineLen = len(line)
if isPy3:
gene, rest = line.rstrip("\r\n").split(sep, maxsplit=1)
else:
gene, rest = string.split(line.rstrip("\r\n"), sep, maxsplit=1)
if numpyLoaded:
arr = np.fromstring(rest, dtype=npType, sep=sep, count=sampleCount)
else:
if self.matType=="int":
#a = [int(x) for x in rest.split(sep)]
arr = map(int, rest.split(sep))
else:
#a = [float(x) for x in rest.split(sep)]
arr = map(float, rest.split(sep))
if "|" in gene:
gene, symbol = gene.split("|")
else:
if geneToSym is None:
symbol = gene
else:
symbol = geneToSym.get(gene)
if symbol is None:
skipIds += 1
logging.warn("line %d: %s is not a valid Ensembl gene ID, check geneIdType setting in cellbrowser.conf" % (lineNo, gene))
continue
if symbol.isdigit():
logging.warn("line %d in gene matrix: gene identifier %s is a number. If this is indeed a gene identifier, you can ignore this warning." % (lineNo, symbol))
if symbol in doneGenes:
logging.warn("line %d: Gene %s/%s is duplicated in matrix, using only first occurence" % (lineNo, gene, symbol))
skipIds += 1
continue
doneGenes.add(gene)
lineNo += 1
yield gene, symbol, arr
if skipIds!=0:
logging.warn("Skipped %d expression matrix lines because of duplication/unknown ID" % skipIds)
def iterRowsWithOffsets(self):
" like iterRows, but also return offset and line length "
offset = self.ifh.tell()
for gene, sym, row in self.iterRows():
yield gene, sym, row, offset, self.lineLen
offset = self.ifh.tell()
def getDecilesList(values):
""" given a list of values, return the 10 values that define the 10 ranges for the deciles
"""
if len(values)==0:
return None
valCount = len(values)
binSize = float(valCount-1) / 10.0; # width of each bin, in number of elements, fractions allowed
values = list(sorted(values))
# get deciles from the list of sorted values
deciles = []
pos = 0
for i in range(10): # 10 bins means that we need 10 limits, the last limit is at 90%
pos = int (binSize * i)
if pos > valCount: # this should not happen, but maybe it can, due to floating point issues?
logging.warn("decile exceeds 10, binSize %d, i %d, len(values) %d" % (binSize, i, len(values)))
pos = len(values)
deciles.append ( values[pos] )
return deciles
def findBin(ranges, val):
""" given an array of values, find the index i where ranges[i] < val <= ranges[i+1]
ranges have to be sorted.
This is a dumb brute force implementation - maybe binary search is faster, if ever revisit this again
Someone said up to 10 binary search is not faster.
"""
if val==0: # speedup
return 0
for i in range(0, len(ranges)):
if (val < ranges[i]):
return i
# if doesn't fit in anywhere, return beyond last possible index
return i+1
def discretizeArr_uniform(arr, fieldMeta):
""" given an array of numbers, get min/max, create 10 bins between min and max then
translate the array to bins and return the list of bins
"""
arrMin = min(arr)
arrMax = max(arr)
stepSize = (arrMax-arrMin)/10.0
dArr = [0]*len(arr)
binCounts = [0]*10
for i, x in enumerate(arr):
binIdx = int(round((x - arrMin)/stepSize))
if x == arrMax:
binIdx = 9
assert(binIdx <= 9)
dArr[i] = binIdx
binCounts[binIdx]+=1
fieldMeta["binMethod"] = "uniform"
fieldMeta["minVal"] = arrMin
fieldMeta["maxVal"] = arrMax
fieldMeta["stepSize"] = stepSize
fieldMeta["binCounts"] = binCounts
return dArr, fieldMeta
def digitize_py(arr, matType):
""" calculate deciles ignoring 0s from arr, use these deciles to digitize the whole arr,
return (digArr, zeroCount, bins).
bins is an array of (min, max, count)
There are at most 11 bins and bin0 is just for the value zero.
For bin0, min and max are both 0.0
matType can be "int" or "float".
If it is 'int' and arr has only <= 11 values, will not calculate deciles, but rather just
count the numbers and use them to create bins, one per number.
#>>> digitize_py([1,1,1,1,1,2,3,4,5,6,4,5,5,5,5], "float")
"""
if matType=="int":
valCount = len(set(arr))
if valCount <= 11: # 10 deciles + 0s
counts = Counter(arr).most_common()
counts.sort()
valToIdx = {}
for i, (val, count) in enumerate(counts):
valToIdx[val] = i
digArr = [valToIdx[x] for x in arr]
bins = []
for val, count in counts:
bins.append( (val, val, count) )
return digArr, bins
noZeroArr = [x for x in arr if x!=0]
zeroCount = len(arr) - len(noZeroArr)
deciles = getDecilesList(noZeroArr) # there are 10 limits for the 10 deciles, 0% - 90%
deciles.insert(0, 0) # bin0 is always for the zeros
# we now have 11 limits
assert(len(deciles)<=11)
# digitize and count bins
digArr = []
binCounts = len(deciles)*[0]
for x in arr:
binIdx = findBin(deciles, x)
# bin1 is always empty, so move down all other indices
if binIdx>0:
binIdx-=1
digArr.append(binIdx)
binCounts[binIdx]+=1
# create the bin info
bins = []
if zeroCount!=0:
bins.append( [float(0), float(0), float(zeroCount)])
for i in range(1, len(deciles)):
minVal = deciles[i-1]
maxVal = deciles[i]
count = binCounts[i]
# skip empty bins
#if count!=0:
bins.append( [float(minVal), float(maxVal), float(count)] )
# add the maximum value explicitly, more meaningful
bins[-1][1] = np.amax(arr)
return digArr, bins
def digitizeArr(arr, numType):
if numpyLoaded:
return digitize_np(arr, numType)
else:
return digitize_py(arr, numType)
def binEncode(bins):
" encode a list of at 11 three-tuples into a string of 33 floats (little endian)"
# add (0,0,0) elements to bins until it has 11 elements "
padBins = copy.copy(bins)
for i in range(len(bins), 11):
padBins.append( (0.0, 0.0, 0.0) )
#print len(padBins), padBins, len(padBins)
assert(len(padBins)==11)
strList = []
for xMin, xMax, count in padBins:
strList.append( struct.pack("<f", xMin) )
strList.append( struct.pack("<f", xMax) )
strList.append( struct.pack("<f", count) )
ret = "".join(strList)
assert(len(ret)==11*3*4)
return ret
def digitize_np(arr, matType):
""" hopefully the same as digitize(), but using numpy
#>>> digitize_np([1,2,3,4,5,6,4,1,1,1], "int")
#>>> digitize_np([0,0,0,1,1,1,1,1,2,3,4,5,6,4,5,5,5,5], "float")
#>>> digitize_np([1,1,1,1,1,2,3,4,5,6,4,5,5,5,5], "float")
"""
# meta data comes in as a list
if not type(arr) is np.ndarray:
arr = np.array(arr)
if matType=="int":
# raw counts mode:
# first try if there are enough unique values in the array
# if there are <= 10 values, deciles make no sense,
# so simply enumerate the values and map to bins 0-10
binCounts = np.bincount(arr)
nonZeroCounts = binCounts[np.nonzero(binCounts)] # remove the 0s
if nonZeroCounts.size <= 11:
logging.debug("we have read counts and <11 values: not using quantiles, just enumerating")
posWithValue = np.where(binCounts != 0)[0]
valToBin = {}
bins = []
binIdx = 0
#for val, count in enumerate(binCounts):
#if count!=0:
for val in posWithValue:
count = binCounts[val]
bins.append( (val, val, count) )
valToBin[val] = binIdx
binIdx += 1
# map values to bin indices, from stackoverflow
digArr = np.vectorize(valToBin.__getitem__)(arr)
return digArr, bins
logging.debug("calculating deciles")
# calculate the deciles without the zeros, otherwise
# the 0s completely distort the deciles
#noZero = np.copy(arr)
#nonZeroIndices = np.nonzero(arr)
noZero = arr[np.nonzero(arr)]
# gene not expressed -> do nothing
if noZero.size==0:
logging.debug("expression vector is all zeroes")
return np.zeros(arr.size, dtype=np.int8), [(0.0, 0.0, arr.size)]
deciles = np.percentile( noZero, [0,10,20,30,40,50,60,70,80,90] , interpolation="lower")
# make sure that we always have a bin for the zeros
deciles = np.insert(deciles, 0, 0)
logging.debug("deciles are: %s" % str(deciles))
# now we have 10 limits, defining 11 bins
# but bin1 will always be empty, as there is nothing between the value 0 and the lowest limit
digArr = np.searchsorted(deciles, arr, side="right")
# so we decrease all bin indices that are not 0
np.putmask(digArr, digArr>0, digArr-1)
binCounts = np.bincount(digArr)
bins = []
zeroCount = binCounts[0]
# bin0 is a bit special